diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/hud_fixture/kinds.rs index 52abd73a0..fef5be327 100644 --- a/crates/horizon-client/examples/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/hud_fixture/kinds.rs @@ -3,7 +3,8 @@ use horizon_client::{ brewing, component, hud::HudAtlas, hud_layout::{self, GuiDraw}, - hud_overlays::{self, EffectIcon, HeldName, Titles, ToolHighlight}, + hud_overlays::{self, BossBar, EffectIcon, HeldName, Titles, ToolHighlight}, + scoreboard::{NumberFormat, RenderType, Scoreboard}, text::{self, Text}, }; use serde_json::Value; @@ -33,6 +34,9 @@ pub fn run(kind: &str, c: &Value, atlas: &HudAtlas) -> Vec { "effects" => effects(c, w), "title" => title(c, w, h, atlas), "selected" => selected(c, w, h, atlas), + "boss" => boss(c, w, h, atlas), + "jump" => hud_overlays::jump_bar(w, h, int(c, "cooldown", 0), float(c, "jumpScale", 0.0)), + "sidebar" => sidebar(c, w, h, atlas), _ => Vec::new(), } } @@ -115,3 +119,71 @@ fn selected(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { let can_hurt = mode == "survival" || mode == "adventure"; highlight.draw(w, h, can_hurt, &atlas.font, background(c)) } + +fn boss(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { + let bars: Vec = c["bars"] + .as_array() + .into_iter() + .flatten() + .map(|b| BossBar { + name: comp(&b["name"]), + progress: b["progress"].as_f64().unwrap_or(0.0) as f32, + color: b["color"].as_u64().unwrap_or(0) as usize, + overlay: b["overlay"].as_u64().unwrap_or(0) as usize, + }) + .collect(); + hud_overlays::boss_overlay(w, h, &bars, &atlas.font) +} + +/// A `NumberFormat` from the case: null, `{type: blank}`, `{type: fixed, +/// value}` or `{type: styled, style}`. +fn number_format(v: &Value) -> Option { + match v["type"].as_str()? { + "blank" => Some(NumberFormat::Blank), + "fixed" => Some(NumberFormat::Fixed(v["value"].clone())), + "styled" => Some(NumberFormat::Styled(v["style"].clone())), + other => panic!("unknown number format {other}"), + } +} + +fn sidebar(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { + let mut board = Scoreboard::default(); + let o = &c["objective"]; + board.add_objective( + "sidebar", + "dummy", + o["display"].clone(), + RenderType::Integer, + false, + number_format(&o["format"]), + ); + for s in c["scores"].as_array().into_iter().flatten() { + let owner = s["owner"].as_str().unwrap_or(""); + let score = board.score_mut(owner, "sidebar"); + score.value = s["value"].as_i64().unwrap_or(0) as i32; + score.display = (!s["display"].is_null()).then(|| s["display"].clone()); + score.number_format = number_format(&s["format"]); + } + for t in c["teams"].as_array().into_iter().flatten() { + let name = t["name"].as_str().unwrap_or(""); + let team = board.add_team(name); + team.prefix = t["prefix"].clone(); + team.suffix = t["suffix"].clone(); + team.color = t["color"].as_str().map(str::to_owned); + for m in t["members"].as_array().into_iter().flatten() { + board.add_to_team(m.as_str().unwrap_or(""), name); + } + } + let opacity = c["textOpacity"].as_f64().unwrap_or(0.5); + let chat_only = c["chatOnly"].as_bool().unwrap_or(true); + let objective = board.objective("sidebar").expect("objective").clone(); + hud_overlays::sidebar( + w, + h, + &board, + &objective, + &atlas.font, + hud_layout::background_color(chat_only, opacity, 0.3), + hud_layout::background_color(chat_only, opacity, 0.4), + ) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5a1608282..96e326d3f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2931,8 +2931,7 @@ impl Game<'_> { } self.draw_effect_icons(&mut batch); // Hud: the action bar and titles draw over the hotbar (nextStratum). - self.draw_boss_bar(&mut batch); - self.draw_custom_bossbars(&mut batch, 12.0 + 19.0 * self.builtin_bar_count() as f32); + self.draw_boss_bars(&mut batch); self.draw_titles(&mut batch); self.draw_scoreboard(&mut batch); self.draw_subtitles(&mut batch); diff --git a/crates/horizon-client/src/game/bossbars.rs b/crates/horizon-client/src/game/bossbars.rs index 2863546ac..ec7b72632 100644 --- a/crates/horizon-client/src/game/bossbars.rs +++ b/crates/horizon-client/src/game/bossbars.rs @@ -4,10 +4,9 @@ use super::{ commands::{R, err}, }; use horizon_client::{ - bossbar::BossBars, + bossbar::{self, BossBars}, command::{Arg, Context}, - hud::{HudBatch, rgba}, - save, + hud_overlays, save, scoreboard::{self as sb, Comp, comp_text}, scoreboard_cmd::format_list, text::Text, @@ -334,26 +333,10 @@ impl Game<'_> { Ok(self.resolve_component(value)) } - /// How many boss bars the dragon and withers already show. - pub(super) fn builtin_bar_count(&self) -> usize { - let dragon = usize::from(self.dragon.is_some() && self.dim == super::Dim::End); - let withers = self.player.as_ref().map_or(0, |p| { - self.mobs - .iter() - .filter(|m| { - m.species() == horizon_client::mobs::Species::Wither - && m.alive() - && m.position.distance_squared(p.position) <= 64.0 * 64.0 - }) - .count() - }); - dragon + withers - } // ---- drawing ------------------------------------------------------------------ - /// `BossHealthOverlay`: the visible custom bars under the built-in ones. - pub(super) fn draw_custom_bossbars(&self, batch: &mut HudBatch, mut y: f32) { - let atlas = &self.res.atlas; + /// The visible custom bars (`/bossbar`), after the built-in ones. + pub(super) fn custom_bossbars(&self, bars: &mut Vec) { for b in self .bosses .bars @@ -361,44 +344,18 @@ impl Game<'_> { .iter() .filter(|b| b.visible && b.player) { - if y >= batch.height / 3.0 { - break; - } - let x = (batch.width / 2.0 - 91.0).floor(); - let sprite = |kind: &str| format!("gui/sprites/boss_bar/{kind}"); - batch.sprite(atlas, &sprite(&format!("{}_background", b.color)), x, y); - if b.progress() > 0.0 { - batch.sprite_part( - atlas, - &sprite(&format!("{}_progress", b.color)), - x, - y, - b.progress(), - ); - } - if b.style != "progress" { - batch.sprite(atlas, &sprite(&format!("{}_background", b.style)), x, y); - if b.progress() > 0.0 { - batch.sprite_part( - atlas, - &sprite(&format!("{}_progress", b.style)), - x, - y, - b.progress(), - ); - } - } - let name = comp_text(&b.name); - let w = atlas.font.width_text(&name); - batch.text_styled( - atlas, - &name, - (batch.width / 2.0 - w / 2.0).floor(), - y - 9.0, - rgba(255, 255, 255, 255), - true, - ); - y += 19.0; + bars.push(hud_overlays::BossBar { + name: comp_text(&b.name), + progress: b.progress(), + color: bossbar::COLORS + .iter() + .position(|c| *c == b.color) + .unwrap_or(0), + overlay: bossbar::STYLES + .iter() + .position(|s| *s == b.style) + .unwrap_or(0), + }); } } } diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index be4b4ec1f..063c57d97 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -8,9 +8,11 @@ //! exit portal, the egg and the next gateway; and its rendering and boss bar. use super::{Dim, Game}; use horizon_client::{ - hud::{HudBatch, rgba}, + hud::HudBatch, + hud_layout, hud_overlays, mesher::Vertex, particles::{ParticleOptions, ParticleType}, + text::Text, }; use horizon_core::{ geometry::{Aabb, Vec3}, @@ -1839,30 +1841,30 @@ impl Game<'_> { }); self.breath_clouds.append(&mut clouds); } - /// The boss bar (`BossHealthOverlay`): name and the pink progress bar. - pub(super) fn draw_boss_bar(&self, batch: &mut HudBatch) { - let dragon = self.dragon.as_ref().filter(|_| self.dim == Dim::End); - let y = self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 }); - self.draw_raid_bar(batch, y); - let Some(d) = dragon else { - return; - }; - let atlas = &self.res.atlas; - let x = (batch.width / 2.0 - 91.0).floor(); - let y = 12.0; - batch.sprite(atlas, "gui/sprites/boss_bar/pink_background", x, y); - let progress = (d.health / MAX_HEALTH).clamp(0.0, 1.0); - batch.sprite_part(atlas, "gui/sprites/boss_bar/pink_progress", x, y, progress); - let name = self.translate("entity.minecraft.ender_dragon", "Ender Dragon"); - let w = HudBatch::text_width(atlas, &name); - batch.text( - atlas, - &name, - (batch.width / 2.0 - w / 2.0).floor(), - y - 9.0, - rgba(255, 255, 255, 255), - true, + /// `BossHealthOverlay`: the dragon's pink bar, then the withers', the + /// raids' and the custom bars, in that order. + pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) { + let mut bars = Vec::new(); + if let Some(d) = self.dragon.as_ref().filter(|_| self.dim == Dim::End) { + bars.push(hud_overlays::BossBar { + name: Text::literal( + self.translate("entity.minecraft.ender_dragon", "Ender Dragon"), + ), + progress: (d.health / MAX_HEALTH).clamp(0.0, 1.0), + color: 0, + overlay: 0, + }); + } + self.wither_bars(&mut bars); + self.raid_bars(&mut bars); + self.custom_bossbars(&mut bars); + let draws = hud_overlays::boss_overlay( + batch.width as i32, + batch.height as i32, + &bars, + &self.res.atlas.font, ); + hud_layout::paint(batch, &self.res.atlas, &draws); } /// `music.dragon` while the boss bar plays music. pub(super) fn boss_music(&self) -> bool { diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 9f6ce609b..2d987ea28 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -466,23 +466,11 @@ impl Game<'_> { let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); if m.extra.saddled { - let x = (w / 2 - 91) as f32; - let y = (h - 29) as f32; - batch.sprite(atlas, "gui/sprites/hud/jump_bar_background", x, y); - if self.mount.jump_ticks < 0 { - batch.sprite(atlas, "gui/sprites/hud/jump_bar_cooldown", x, y); - } else { - let filled = (self.mount.jump_scale * 183.0).floor(); - if filled > 0.0 { - batch.sprite_part( - atlas, - "gui/sprites/hud/jump_bar_progress", - x, - y, - filled / 182.0, - ); - } - } + // JumpableVehicleBar: the cooldown shows while the jump recharges. + let cooldown = i32::from(self.mount.jump_ticks < 0); + let draws = + horizon_client::hud_overlays::jump_bar(w, h, cooldown, self.mount.jump_scale); + horizon_client::hud_layout::paint(batch, atlas, &draws); } (hearts, m.extra.saddled) } diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 91c454ce8..d2fbb6566 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -4,9 +4,10 @@ use super::{Dim, Game}; use horizon_client::mobs::villager as mobs_villager; use horizon_client::{ effects::EffectInstance, - hud::{HudBatch, rgba}, + hud_overlays, mobs::{Mob, Species, data, raider}, raid::{self, Action, BarName, RaidLevel, RaiderInfo, RaiderType, Raids, Spawn}, + text::Text, }; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::collections::{HashMap, HashSet}; @@ -746,31 +747,12 @@ impl Game<'_> { } } - /// The raid boss bars (`BossHealthOverlay`): a red notched bar with the - /// raid's title. Returns the next free row. - pub(super) fn draw_raid_bar(&self, batch: &mut HudBatch, mut y: f32) -> f32 { - let atlas = &self.res.atlas; + /// The raid boss bars: red and notched in tens, with the raid's title. + pub(super) fn raid_bars(&self, bars: &mut Vec) { for raid in self.raiding.raids.map.values() { if !raid.bar.visible || !raid.bar.player || raid.is_stopped() { continue; } - let x = (batch.width / 2.0 - 91.0).floor(); - batch.sprite(atlas, "gui/sprites/boss_bar/red_background", x, y); - batch.sprite(atlas, "gui/sprites/boss_bar/notched_10_background", x, y); - let p = raid.bar.progress; - // Mth.lerpDiscrete(progress, 0, 182). - let width = (p * 181.0).floor() as i32 + i32::from(p > 0.0); - if width > 0 { - let fraction = width as f32 / 182.0; - batch.sprite_part(atlas, "gui/sprites/boss_bar/red_progress", x, y, fraction); - batch.sprite_part( - atlas, - "gui/sprites/boss_bar/notched_10_progress", - x, - y, - fraction, - ); - } let title = self.translate("event.minecraft.raid", "Raid"); let name = match raid.bar.name { BarName::Raid => title, @@ -789,18 +771,13 @@ impl Game<'_> { self.translate("event.minecraft.raid.defeat.full", "Raid - Defeat") } }; - let w = HudBatch::text_width(atlas, &name); - batch.text( - atlas, - &name, - (batch.width / 2.0 - w / 2.0).floor(), - y - 9.0, - rgba(255, 255, 255, 255), - true, - ); - y += 19.0; + bars.push(hud_overlays::BossBar { + name: Text::literal(name), + progress: raid.bar.progress, + color: 2, + overlay: 2, + }); } - y } /// A firework a villager launches to celebrate (`CelebrateVillagersSurvivedRaid`). pub(super) fn villager_firework(&mut self, at: [f64; 3], color: usize, flight: u8) { diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index d6962d674..987ea7d14 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -8,9 +8,10 @@ use horizon_client::{ Context, args::{IntRange, Selector}, }, - hud::{HudBatch, rgba}, + hud::HudBatch, + hud_layout, hud_overlays, save::{self, uuid_from_text, uuid_text}, - scoreboard::{self as sb, Comp, NumberFormat, Scoreboard, literal}, + scoreboard::{self as sb, Comp, Scoreboard, literal}, scoreboard_cmd::{self, Env, Holder}, text::Text, }; @@ -478,84 +479,16 @@ impl Game<'_> { else { return; }; - let atlas = &self.res.atlas; - let default_format = NumberFormat::sidebar_default(); - let format = objective.format_or_default(default_format); - let mut entries: Vec<_> = board - .list_scores(&objective.name) - .into_iter() - .filter(|e| !e.is_hidden()) - .collect(); - // Highest score first, then names case-insensitively. - entries.sort_by(|a, b| { - b.value - .cmp(&a.value) - .then_with(|| a.owner.to_lowercase().cmp(&b.owner.to_lowercase())) - }); - entries.truncate(15); - let rows: Vec<(Text, Text, f32)> = entries - .iter() - .map(|e| { - let name = match board.players_team(&e.owner) { - Some(t) => t.formatted_name(e.owner_name()), - None => e.owner_name(), - }; - let score = e.format_value(&format); - let width = atlas.font.width_text(&score); - (name, score, width) - }) - .collect(); - let title = objective.display_text(); - let title_width = atlas.font.width_text(&title); - let spacer = atlas.font.width(": "); - let mut biggest = title_width; - for (name, _, score_width) in &rows { - let extra = if *score_width > 0.0 { - spacer + score_width - } else { - 0.0 - }; - biggest = biggest.max(atlas.font.width_text(name) + extra); - } - let count = rows.len() as f32; - let height = count * 9.0; - let (w, h) = (batch.width, batch.height); - let bottom = (h / 2.0).trunc() + (height / 3.0).trunc(); - let left = w - biggest - 3.0; - let right = w - 3.0 + 2.0; - let body = rgba(0, 0, 0, (0.3 * 255.0) as u8); - let header = rgba(0, 0, 0, (0.4 * 255.0) as u8); - let top = bottom - count * 9.0; - batch.fill( - atlas, - left - 2.0, - top - 9.0 - 1.0, - right - (left - 2.0), - 9.0, - header, + let draws = hud_overlays::sidebar( + batch.width as i32, + batch.height as i32, + board, + objective, + &self.res.atlas.font, + self.settings.text_background(0.3), + self.settings.text_background(0.4), ); - batch.fill( - atlas, - left - 2.0, - top - 1.0, - right - (left - 2.0), - bottom - (top - 1.0), - body, - ); - let white = rgba(255, 255, 255, 255); - batch.text_styled( - atlas, - &title, - left + (biggest / 2.0).trunc() - (title_width / 2.0).trunc(), - top - 9.0, - white, - false, - ); - for (i, (name, score, score_width)) in rows.iter().enumerate() { - let y = bottom - (count - i as f32) * 9.0; - batch.text_styled(atlas, name, left, y, white, false); - batch.text_styled(atlas, score, right - score_width, y, white, false); - } + hud_layout::paint(batch, &self.res.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index 3668e5f9f..09ddc2b5f 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -2,9 +2,10 @@ //! its boss bar, and its skulls hitting and exploding. use super::Game; use horizon_client::{ - hud::{HudBatch, rgba}, + hud_overlays, mobs::{Damage, DamageKind, Species, Who}, projectiles::{Projectile, ProjectileKind}, + text::Text, }; impl Game<'_> { @@ -74,12 +75,11 @@ impl Game<'_> { } Ok(()) } - /// The wither boss bars (purple, below the dragon's), within range. - pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) -> f32 { + /// The wither boss bars (purple), within range. + pub(super) fn wither_bars(&self, bars: &mut Vec) { let Some(p) = self.player.as_ref() else { - return y; + return; }; - let atlas = &self.res.atlas; for m in self .mobs .iter() @@ -88,36 +88,22 @@ impl Game<'_> { if m.position.distance_squared(p.position) > 64.0 * 64.0 { continue; } - let x = (batch.width / 2.0 - 91.0).floor(); let progress = if m.extra.counter > 0 { 1.0 - m.extra.counter as f32 / horizon_client::mobs::wither::INVULNERABLE as f32 } else { (m.health / m.attrs.max_health).clamp(0.0, 1.0) }; - batch.sprite(atlas, "gui/sprites/boss_bar/purple_background", x, y); - batch.sprite_part( - atlas, - "gui/sprites/boss_bar/purple_progress", - x, - y, - progress, - ); let name = m .custom_name .clone() .unwrap_or_else(|| self.translate("entity.minecraft.wither", "Wither")); - let w = HudBatch::text_width(atlas, &name); - batch.text( - atlas, - &name, - (batch.width / 2.0 - w / 2.0).floor(), - y - 9.0, - rgba(255, 255, 255, 255), - true, - ); - y += 19.0; + bars.push(hud_overlays::BossBar { + name: Text::literal(name), + progress, + color: 5, + overlay: 0, + }); } - y } pub(super) fn wither_near(&self) -> bool { self.player.as_ref().is_some_and(|p| { diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index ec77a639b..8c554898a 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -435,3 +435,200 @@ impl ToolHighlight { out } } + +/// One `LerpingBossEvent` as `BossHealthOverlay` draws it. +#[derive(Clone, Debug, PartialEq)] +pub struct BossBar { + pub name: Text, + /// `getProgress()` (the lerped value). + pub progress: f32, + /// `BossBarColor` ordinal: pink, blue, red, green, yellow, purple, white. + pub color: usize, + /// `BossBarOverlay` ordinal: progress, notched_6, _10, _12, _20. + pub overlay: usize, +} +const BOSS_COLORS: [&str; 7] = ["pink", "blue", "red", "green", "yellow", "purple", "white"]; +const BOSS_OVERLAYS: [&str; 5] = [ + "progress", + "notched_6", + "notched_10", + "notched_12", + "notched_20", +]; + +/// `BossHealthOverlay.extractRenderState`: the bars in event order, 19 pixels +/// apart from y = 12 until a third of the screen height. +pub fn boss_overlay(w: i32, h: i32, bars: &[BossBar], font: &Font) -> Vec { + let mut out = Vec::new(); + let mut y_offset = 12; + for bar in bars { + let x_left = w / 2 - 91; + let part = |out: &mut Vec, width: i32, kind: &str| { + let sprite = |name: String| GuiDraw::Sprite { + sprite: Cow::Owned(format!("boss_bar/{name}_{kind}")), + x: x_left, + y: y_offset, + w: width, + h: 5, + region: Some([182, 5, 0, 0]), + color: crate::hud_layout::WHITE, + }; + out.push(sprite(BOSS_COLORS[bar.color].to_owned())); + if bar.overlay != 0 { + out.push(sprite(BOSS_OVERLAYS[bar.overlay].to_owned())); + } + }; + part(&mut out, 182, "background"); + let progress = crate::hud_layout::lerp_discrete(bar.progress, 0, 182); + if progress > 0 { + part(&mut out, progress, "progress"); + } + let width = width(font, &bar.name); + text( + &mut out, + bar.name.clone(), + w / 2 - width / 2, + y_offset - 9, + crate::hud_layout::WHITE, + true, + ); + y_offset += 10 + 9; + if y_offset >= h / 3 { + break; + } + } + out +} + +/// `JumpableVehicleBar.extractBackground`: `cooldown` is the mount's jump +/// cooldown and `scale` the player's `getJumpRidingScale()`. +pub fn jump_bar(w: i32, h: i32, cooldown: i32, scale: f32) -> Vec { + let (left, top) = ((w - 182) / 2, h - 24 - 5); + let sprite = |name: &'static str, width: i32, region: Option<[i32; 4]>| GuiDraw::Sprite { + sprite: Cow::Borrowed(name), + x: left, + y: top, + w: width, + h: 5, + region, + color: crate::hud_layout::WHITE, + }; + let mut out = vec![sprite("hud/jump_bar_background", 182, None)]; + if cooldown > 0 { + out.push(sprite("hud/jump_bar_cooldown", 182, None)); + } else { + let progress = crate::hud_layout::lerp_discrete(scale, 0, 182); + if progress > 0 { + out.push(sprite( + "hud/jump_bar_progress", + progress, + Some([182, 5, 0, 0]), + )); + } + } + out +} + +/// `String.CASE_INSENSITIVE_ORDER` over UTF-16 code units. +pub fn compare_ignore_case(a: &str, b: &str) -> Ordering { + fn single(mut it: impl Iterator, c: char) -> char { + match (it.next(), it.next()) { + (Some(m), None) => m, + _ => c, + } + } + let unit = |u: u16| char::from_u32(u32::from(u)); + let (x, y): (Vec, Vec) = (a.encode_utf16().collect(), b.encode_utf16().collect()); + for (&p, &q) in x.iter().zip(&y) { + if p == q { + continue; + } + let (Some(c1), Some(c2)) = (unit(p), unit(q)) else { + return p.cmp(&q); + }; + let (u1, u2) = (single(c1.to_uppercase(), c1), single(c2.to_uppercase(), c2)); + if u1 != u2 { + let (l1, l2) = (single(u1.to_lowercase(), u1), single(u2.to_lowercase(), u2)); + if l1 != l2 { + return (l1 as u32).cmp(&(l2 as u32)); + } + } + } + x.len().cmp(&y.len()) +} + +/// `Hud.displayScoreboardSidebar` for `objective`; `background` and +/// `header` are `Options.getBackgroundColor(0.3F)` and `(0.4F)`. +pub fn sidebar( + w: i32, + h: i32, + board: &crate::scoreboard::Scoreboard, + objective: &crate::scoreboard::Objective, + font: &Font, + background: u32, + header: u32, +) -> Vec { + use crate::scoreboard::NumberFormat; + let format = objective.format_or_default(NumberFormat::sidebar_default()); + let mut entries: Vec<_> = board + .list_scores(&objective.name) + .into_iter() + .filter(|e| !e.is_hidden()) + .collect(); + // SCORE_DISPLAY_ORDER: highest value first, then owners case-insensitively. + java_sort(&mut entries, |a, b| { + b.value + .cmp(&a.value) + .then_with(|| compare_ignore_case(&a.owner, &b.owner)) + }); + entries.truncate(15); + let rows: Vec<(Text, Text, i32)> = entries + .iter() + .map(|e| { + let name = match board.players_team(&e.owner) { + Some(team) => team.formatted_name(e.owner_name()), + None => e.owner_name(), + }; + let score = e.format_value(&format); + let score_width = width(font, &score); + (name, score, score_width) + }) + .collect(); + let title = objective.display_text(); + let title_width = width(font, &title); + let spacer = font.width(": ") as i32; + let mut biggest = title_width; + for (name, _, score_width) in &rows { + let extra = if *score_width > 0 { + spacer + score_width + } else { + 0 + }; + biggest = biggest.max(width(font, name) + extra); + } + let count = rows.len() as i32; + let height = count * 9; + let bottom = h / 2 + height / 3; + let left = w - biggest - 3; + let right = w - 3 + 2; + let header_y = bottom - count * 9; + let mut out = vec![ + fill(left - 2, header_y - 9 - 1, right, header_y - 1, header), + fill(left - 2, header_y - 1, right, bottom, background), + ]; + let white = crate::hud_layout::WHITE; + text( + &mut out, + title, + left + biggest / 2 - title_width / 2, + header_y - 9, + white, + false, + ); + for (i, (name, score, score_width)) in rows.into_iter().enumerate() { + let y = bottom - (count - i as i32) * 9; + text(&mut out, name, left, y, white, false); + text(&mut out, score, right - score_width, y, white, false); + } + out +} 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 65cc4cecf..9b22bb327 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java @@ -96,6 +96,17 @@ public final class VanillaHudOracle { put(o, OptionInstance.class, "value", value); return o; } + static net.minecraft.network.chat.numbers.NumberFormat numberFormat(JsonElement e) { + if (e == null || e.isJsonNull()) return null; + var o = e.getAsJsonObject(); + return switch (o.get("type").getAsString()) { + case "blank" -> net.minecraft.network.chat.numbers.BlankFormat.INSTANCE; + case "fixed" -> new net.minecraft.network.chat.numbers.FixedFormat(comp(o.get("value"))); + case "styled" -> new net.minecraft.network.chat.numbers.StyledFormat( + net.minecraft.network.chat.Style.Serializer.MAP_CODEC.codec().parse(com.mojang.serialization.JsonOps.INSTANCE, o.get("style")).getOrThrow()); + default -> throw new IllegalArgumentException(o.toString()); + }; + } static Method hudMethod(String name, Class... params) throws Exception { Method m = Hud.class.getDeclaredMethod(name, params); m.setAccessible(true); @@ -130,6 +141,13 @@ public final class VanillaHudOracle { @Override public float getAttackStrengthScale(float a) { return f("attackScale", 1); } @Override public Level level() { return level; } @Override public boolean isSpectator() { return false; } + @Override public net.minecraft.world.entity.PlayerRideableJumping jumpableVehicle() { + return (net.minecraft.world.entity.PlayerRideableJumping) Proxy.newProxyInstance(Actor.class.getClassLoader(), + new Class[] {net.minecraft.world.entity.PlayerRideableJumping.class}, + (proxy, method, a) -> method.getName().equals("getJumpCooldown") ? i("cooldown", 0) + : method.getReturnType() == boolean.class ? false : method.getReturnType() == float.class ? 0.0F : null); + } + @Override public float getJumpRidingScale() { return f("jumpScale", 0); } @Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { } } @@ -284,6 +302,7 @@ public final class VanillaHudOracle { Method overlayMessage = hudMethod("extractOverlayMessage", GuiGraphicsExtractor.class, DeltaTracker.class); Method selectedName = hudMethod("extractSelectedItemName", GuiGraphicsExtractor.class); Method tick = hudMethod("tick"); + Method sidebar = hudMethod("displayScoreboardSidebar", GuiGraphicsExtractor.class, net.minecraft.world.scores.Objective.class); Method level = Class.forName("net.minecraft.client.gui.contextualbar.ContextualBar") .getDeclaredMethod("extractExperienceLevel", GuiGraphicsExtractor.class, Font.class, int.class); level.setAccessible(true); @@ -431,6 +450,43 @@ public final class VanillaHudOracle { } selectedName.invoke(hud, capture); } + case "boss" -> { + var overlay = new net.minecraft.client.gui.components.BossHealthOverlay(mc); + @SuppressWarnings("unchecked") var events = (Map) + field(net.minecraft.client.gui.components.BossHealthOverlay.class, "events").get(overlay); + for (var e : c.getAsJsonArray("bars")) { + var o = e.getAsJsonObject(); + var id = UUID.randomUUID(); + events.put(id, new net.minecraft.client.gui.components.LerpingBossEvent(id, comp(o.get("name")), o.get("progress").getAsFloat(), + net.minecraft.world.BossEvent.BossBarColor.values()[o.get("color").getAsInt()], + net.minecraft.world.BossEvent.BossBarOverlay.values()[o.get("overlay").getAsInt()], false, false, false)); + } + overlay.extractRenderState(capture); + } + case "jump" -> new net.minecraft.client.gui.contextualbar.JumpableVehicleBar(mc).extractBackground(capture, delta); + case "sidebar" -> { + var board = new net.minecraft.world.scores.Scoreboard(); + var o = c.getAsJsonObject("objective"); + var objective = board.addObjective("sidebar", net.minecraft.world.scores.criteria.ObjectiveCriteria.DUMMY, comp(o.get("display")), + net.minecraft.world.scores.criteria.ObjectiveCriteria.RenderType.INTEGER, false, numberFormat(o.get("format"))); + for (var e : c.getAsJsonArray("scores")) { + var sc = e.getAsJsonObject(); + var access = board.getOrCreatePlayerScore(net.minecraft.world.scores.ScoreHolder.forNameOnly(sc.get("owner").getAsString()), objective); + access.set(sc.get("value").getAsInt()); + if (!sc.get("display").isJsonNull()) access.display(comp(sc.get("display"))); + access.numberFormatOverride(numberFormat(sc.get("format"))); + } + for (var e : c.getAsJsonArray("teams")) { + var t = e.getAsJsonObject(); + var team = board.addPlayerTeam(t.get("name").getAsString()); + team.setPlayerPrefix(comp(t.get("prefix"))); + team.setPlayerSuffix(comp(t.get("suffix"))); + team.setColor(t.get("color").isJsonNull() ? Optional.empty() + : Optional.of(net.minecraft.world.scores.TeamColor.byName(t.get("color").getAsString()))); + for (var m : t.getAsJsonArray("members")) board.addPlayerToTeam(m.getAsString(), team); + } + sidebar.invoke(hud, capture, objective); + } default -> throw new IllegalArgumentException(c.get("kind").getAsString()); } result.add("draws", capture.draws); diff --git a/tools/hud_parity_cases.py b/tools/hud_parity_cases.py index b3ebebdb7..98dc7ab21 100644 --- a/tools/hud_parity_cases.py +++ b/tools/hud_parity_cases.py @@ -115,10 +115,51 @@ def selected(rng, n): 'displayTime': rng.choice([1.0, 1.0, 0.5, 2.0, 0.123]), 'steps': steps} + +def boss(rng, n): + bars = [] + for _ in range(rng.choice([1, 1, 2, 3, 5, 9])): + progress = rng.choice([0.0, 1.0, 0.5, 0.001, 0.999, 1 / 182, round(rng.random(), 4)]) + bars.append({'name': rng.choice(TITLES), 'progress': progress, 'color': rng.randrange(7), 'overlay': rng.randrange(5)}) + return {**screen(rng), 'bars': bars} + + +def jump(rng, n): + return {**screen(rng), 'cooldown': rng.choice([0, 0, 0, 1, 10]), + 'jumpScale': rng.choice([0.0, 1.0, 0.4, 0.001, round(rng.random(), 4)])} + + +OWNERS = ['Alex', 'steve', 'Zed', 'bob', 'Bobby', 'ÉLodie', 'élan', '#hidden', 'x', 'LongPlayerName_123', 'Mia', '_under'] +FORMATS = [None, None, None, {'type': 'blank'}, {'type': 'fixed', 'value': {'text': 'FIX', 'color': 'aqua'}}, + {'type': 'styled', 'style': {'color': 'gold', 'bold': True}}, {'type': 'styled', 'style': {}}] + + +def sidebar(rng, n): + """An objective with scores, display names, number formats and teams.""" + owners = rng.sample(OWNERS, rng.randint(0, len(OWNERS))) + if rng.random() < 0.3: # more rows than the 15 shown + owners += [f'p{i}' for i in range(rng.randint(5, 20))] + scores = [{'owner': o, 'value': rng.choice([0, 1, -1, 7, 7, 100, 2147483647, -2147483648, rng.randint(-50, 50)]), + 'display': rng.choice([None, None, None, {'text': 'Shown ' + o, 'color': 'green'}]), + 'format': rng.choice(FORMATS)} for o in owners] + teams = [] + for t in range(rng.choice([0, 0, 1, 2])): + teams.append({'name': f'team{t}', 'prefix': rng.choice([{'text': ''}, {'text': '[A] '}, {'text': '<', 'color': 'red'}]), + 'suffix': rng.choice([{'text': ''}, {'text': ' *'}]), + 'color': rng.choice([None, 'red', 'blue', 'gold', 'white']), + 'members': [o for o in owners if rng.random() < 0.3]}) + return {**screen(rng), **backdrop(rng), + 'objective': {'display': rng.choice(TITLES + [{'text': 'Kills'}]), 'format': rng.choice(FORMATS)}, + 'scores': scores, 'teams': teams} + + # Generators by kind: (rng, index) -> case. Cases are drawn round-robin. KINDS = { 'decorations': decorations, 'effects': effects, 'title': title, 'selected': selected, + 'boss': boss, + 'jump': jump, + 'sidebar': sidebar, }