Merge origin/parity/rendering-hud into parity/rendering-be

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-12 15:40:50 +02:00
29 changed files with 3106 additions and 947 deletions
+242 -115
View File
@@ -1,11 +1,14 @@
//! Headless transport for the HUD parity gate: replays each player state
//! through `horizon_client::hud_layout` (crosshair, hotbar, health, mount
//! hearts, experience bar and level) and writes the draw calls in vanilla's
//! GuiGraphicsExtractor terms.
//! Headless transport for the HUD parity gate: replays each case through
//! `horizon_client::hud_layout` and writes the draw calls in vanilla's
//! GuiGraphicsExtractor terms. Case kinds: `decorations` (crosshair,
//! hotbar, health, mount hearts, experience bar and level) and the
//! overlays handled in `kinds`.
#![forbid(unsafe_code)]
use horizon_client::{
hud::{HudAtlas, HudBatch},
hud_layout::{self, GuiDraw, HealthHud, HealthInputs, HeartKind, HotbarInputs},
hud_layout::{self, GuiDraw, HealthHud, HealthInputs, HeartKind, HotbarInputs, IDENTITY, Pose},
lang,
text::Text,
};
use serde_json::{Value, json};
use std::{
@@ -14,6 +17,8 @@ use std::{
path::PathBuf,
};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[path = "hud_fixture/kinds.rs"]
mod kinds;
fn main() -> Result<()> {
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
@@ -21,123 +26,245 @@ 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()
.filter(|l| !l.is_empty())
{
let c: Value = serde_json::from_str(line)?;
let int = |k: &str, d: i64| c[k].as_i64().unwrap_or(d) as i32;
let float = |k: &str, d: f64| c[k].as_f64().unwrap_or(d) as f32;
let (w, h) = (int("width", 0), int("height", 0));
let mode = c["gameMode"].as_str().unwrap_or("survival");
let survival = mode == "survival" || mode == "adventure";
let indicator = c["attackIndicator"].as_str().unwrap_or("OFF");
let partial = float("partial", 0.0);
let effects: Vec<&str> = c["effects"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let has = |e: &str| effects.contains(&e);
let mut draws = Vec::new();
// Spectators only see it over a spectatable target (none here).
if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" {
let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0));
draws.extend(hud_layout::crosshair(w, h, attack, false));
}
if mode != "spectator" {
let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial);
let slots: [Option<f32>; 9] = std::array::from_fn(|i| pop(&c["slots"][i]));
let inputs = HotbarInputs {
selected: int("selected", 0),
right_handed: c["rightHanded"].as_bool().unwrap_or(true),
offhand: !c["offhand"].is_null(),
slots,
offhand_pop: pop(&c["offhand"]).unwrap_or(0.0),
attack: (indicator == "HOTBAR").then(|| float("attackScale", 1.0)),
};
draws.extend(hud_layout::hotbar(w, h, &inputs));
}
let vehicle_hearts = if c.get("vehicleMaxHealth").is_some() {
hud_layout::vehicle_max_hearts(float("vehicleMaxHealth", 0.0))
} else {
0
// State the case reads back besides the draws (e.g. `scopeScale`).
let mut state = serde_json::Map::new();
let draws = match c["kind"].as_str().unwrap_or("decorations") {
"decorations" => decorations(&c, &atlas),
kind => kinds::run(kind, &c, &atlas, &mut state),
};
if survival {
let millis = 1_000_000_000i64;
let mut hud = HealthHud {
last_health: int("lastHealth", 0),
display_health: int("displayHealth", 0),
last_health_time: millis - i64::from(int("lastHealthAgo", 0)),
health_blink_time: i64::from(int("healthBlinkTime", 0)),
};
let kind = if has("minecraft:poison") {
HeartKind::Poisoned
} else if has("minecraft:wither") {
HeartKind::Withered
} else if c["frozen"].as_bool().unwrap_or(false) {
HeartKind::Frozen
} else {
HeartKind::Normal
};
let inputs = HealthInputs {
tick: int("tick", 0),
millis,
health: float("health", 20.0),
max_health: float("maxHealth", 20.0),
absorption: float("absorption", 0.0),
armor: int("armor", 0),
food: int("food", 20),
saturation: float("saturation", 5.0),
kind,
regeneration: has("minecraft:regeneration"),
hunger: has("minecraft:hunger"),
hardcore: c["hardcore"].as_bool().unwrap_or(false),
damage_cooldown: int("damageCooldown", 0) > 0,
air: int("air", 300),
max_air: int("maxAir", 300),
under_water: c["underWater"].as_bool().unwrap_or(false),
vehicle_hearts,
};
draws.extend(hud.layout(&inputs, w, h));
}
if vehicle_hearts > 0 {
draws.extend(hud_layout::vehicle_health(
w,
h,
vehicle_hearts,
float("vehicleHealth", 0.0),
));
}
let width = |s: &str| HudBatch::text_width(&atlas, s) as i32;
let level = if survival { int("xpLevel", 0) } else { 0 };
draws.extend(hud_layout::experience(
w,
h,
float("xpProgress", 0.0),
level,
c["experienceBar"].as_bool().unwrap_or(false),
&width,
));
let draws: Vec<Value> = draws
.iter()
.map(|d| match d {
GuiDraw::Sprite { sprite, x, y, w, h, region } => {
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region})
}
GuiDraw::Text { text, x, y, color, shadow } => {
json!({"type": "text", "text": text, "x": x, "y": y, "color": *color as i32, "shadow": shadow})
}
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]];
json!({"type": "item", "slot": slot, "x": x, "y": y, "seed": seed, "matrix": m})
}
})
.collect();
writeln!(out, "{}", json!({ "draws": draws }))?;
state.insert("draws".into(), json!(encode(&draws)));
writeln!(out, "{}", Value::Object(state))?;
}
Ok(())
}
/// Style runs of styled text: `[text, rgb|null, bold, italic]` per run of
/// equally styled characters, or none for plain text.
fn runs(t: &Text) -> Option<Value> {
let mut out: Vec<(String, Option<u32>, bool, bool)> = Vec::new();
let mut styled = false;
for (ch, s) in t.chars() {
let key = (s.color, s.is_bold(), s.is_italic());
styled |= key != (None, false, false);
match out.last_mut() {
Some(last) if (last.1, last.2, last.3) == key => last.0.push(ch),
_ => 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::<Vec<_>>()
)
})
}
fn encode(draws: &[GuiDraw]) -> Vec<Value> {
let mut stack: Vec<Pose> = vec![IDENTITY];
let mut out = Vec::new();
for d in draws {
let pose = *stack.last().unwrap();
let mut v = match d {
GuiDraw::Push(ops) => {
let mut m = pose;
for op in ops {
hud_layout::pose_apply(&mut m, *op);
}
stack.push(m);
continue;
}
GuiDraw::Pop => {
stack.pop();
continue;
}
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,
} => {
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!({
"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,
} => {
json!({"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": *color as i32})
}
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,
} => {
// 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],
];
out.push(json!({"type": "item", "slot": slot, "x": x, "y": y, "seed": seed, "matrix": m}));
continue;
}
};
if pose != IDENTITY {
v["matrix"] = json!(pose);
}
out.push(v);
}
out
}
fn decorations(c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
let int = |k: &str, d: i64| c[k].as_i64().unwrap_or(d) as i32;
let float = |k: &str, d: f64| c[k].as_f64().unwrap_or(d) as f32;
let (w, h) = (int("width", 0), int("height", 0));
let mode = c["gameMode"].as_str().unwrap_or("survival");
let survival = mode == "survival" || mode == "adventure";
let indicator = c["attackIndicator"].as_str().unwrap_or("OFF");
let partial = float("partial", 0.0);
let effects: Vec<&str> = c["effects"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let has = |e: &str| effects.contains(&e);
let mut draws = Vec::new();
// Spectators only see it over a spectatable target (none here).
if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" {
let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0));
draws.extend(hud_layout::crosshair(w, h, attack, false));
}
if mode != "spectator" {
let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial);
let slots: [Option<f32>; 9] = std::array::from_fn(|i| pop(&c["slots"][i]));
let inputs = HotbarInputs {
selected: int("selected", 0),
right_handed: c["rightHanded"].as_bool().unwrap_or(true),
offhand: !c["offhand"].is_null(),
slots,
offhand_pop: pop(&c["offhand"]).unwrap_or(0.0),
attack: (indicator == "HOTBAR").then(|| float("attackScale", 1.0)),
};
draws.extend(hud_layout::hotbar(w, h, &inputs));
}
let vehicle_hearts = if c.get("vehicleMaxHealth").is_some() {
hud_layout::vehicle_max_hearts(float("vehicleMaxHealth", 0.0))
} else {
0
};
if survival {
let millis = 1_000_000_000i64;
let mut hud = HealthHud {
last_health: int("lastHealth", 0),
display_health: int("displayHealth", 0),
last_health_time: millis - i64::from(int("lastHealthAgo", 0)),
health_blink_time: i64::from(int("healthBlinkTime", 0)),
};
let kind = if has("minecraft:poison") {
HeartKind::Poisoned
} else if has("minecraft:wither") {
HeartKind::Withered
} else if c["frozen"].as_bool().unwrap_or(false) {
HeartKind::Frozen
} else {
HeartKind::Normal
};
let inputs = HealthInputs {
tick: int("tick", 0),
millis,
health: float("health", 20.0),
max_health: float("maxHealth", 20.0),
absorption: float("absorption", 0.0),
armor: int("armor", 0),
food: int("food", 20),
saturation: float("saturation", 5.0),
kind,
regeneration: has("minecraft:regeneration"),
hunger: has("minecraft:hunger"),
hardcore: c["hardcore"].as_bool().unwrap_or(false),
damage_cooldown: int("damageCooldown", 0) > 0,
air: int("air", 300),
max_air: int("maxAir", 300),
under_water: c["underWater"].as_bool().unwrap_or(false),
vehicle_hearts,
};
draws.extend(hud.layout(&inputs, w, h));
}
if vehicle_hearts > 0 {
draws.extend(hud_layout::vehicle_health(
w,
h,
vehicle_hearts,
float("vehicleHealth", 0.0),
));
}
let width = |s: &str| HudBatch::text_width(atlas, s) as i32;
let level = if survival { int("xpLevel", 0) } else { 0 };
draws.extend(hud_layout::experience(
w,
h,
float("xpProgress", 0.0),
level,
c["experienceBar"].as_bool().unwrap_or(false),
&width,
));
draws
}
@@ -0,0 +1,326 @@
//! The overlay case kinds of the HUD parity fixture.
use horizon_client::{
brewing,
chat::{Chat, ChatOptions},
component,
hud::HudAtlas,
hud_layout::{self, GuiDraw},
hud_overlays::{
self, BossBar, CameraOverlays, EffectIcon, HeldName, ItemDecorations, Titles, ToolHighlight,
},
scoreboard::{NumberFormat, RenderType, Scoreboard},
text::{self, Text},
};
use serde_json::Value;
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,
state: &mut serde_json::Map<String, Value>,
) -> Vec<GuiDraw> {
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),
"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),
"decor" => decor(c, atlas),
"overlays" => overlays(c, w, h, state),
"chat" => chat(c, h, atlas),
_ => Vec::new(),
}
}
fn effects(c: &Value, w: i32) -> Vec<GuiDraw> {
let icons: Vec<EffectIcon> = 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<GuiDraw> {
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<GuiDraw> {
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))
}
fn boss(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
let bars: Vec<BossBar> = 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<NumberFormat> {
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<GuiDraw> {
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),
)
}
/// `itemDecorations` for a stack with a count, damage and an item cooldown
/// `elapsed` ticks into `duration` (ItemCooldowns.getCooldownPercent).
fn decor(c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
let count = int(c, "count", 1);
if count <= 0 {
return Vec::new();
}
let cd = &c["cooldown"];
let cooldown = if cd.is_null() {
0.0
} else {
let (duration, elapsed) = (int(cd, "duration", 0), int(cd, "elapsed", 0));
if duration <= elapsed {
0.0 // ItemCooldowns.tick dropped it
} else {
let remaining = duration as f32 - (elapsed as f32 + float(c, "partial", 0.0));
(remaining / duration as f32).clamp(0.0, 1.0)
}
};
let max_damage = if c["unbreakable"].as_bool().unwrap_or(false) {
0
} else {
int(c, "maxDamage", 0)
};
let d = ItemDecorations {
count: count as u32,
count_text: c["countText"].as_str().map(str::to_owned),
bar: hud_overlays::damage_bar(int(c, "damage", 0), max_damage),
cooldown,
};
hud_overlays::item_decorations(int(c, "x", 0), int(c, "y", 0), &d, &atlas.font)
}
/// `Hud.extractCameraOverlays` then `extractSleepOverlay`; the border is
/// static, so only its warning blocks matter.
fn overlays(c: &Value, w: i32, h: i32, state: &mut serde_json::Map<String, Value>) -> Vec<GuiDraw> {
let partial = float(c, "partial", 0.0);
let warning = match &c["border"] {
Value::Null => 0.0,
b => {
// WorldBorder.getDistanceToBorder with the static extent's clamped box.
let max = 29_999_984.0;
let half = b["size"].as_f64().unwrap_or(0.0) / 2.0;
let (cx, cz) = (
b["centerX"].as_f64().unwrap_or(0.0),
b["centerZ"].as_f64().unwrap_or(0.0),
);
let (min_x, max_x) = ((cx - half).clamp(-max, max), (cx + half).clamp(-max, max));
let (min_z, max_z) = ((cz - half).clamp(-max, max), (cz + half).clamp(-max, max));
let (x, z) = (
f64::from(float(c, "camX", 0.0)),
f64::from(float(c, "camZ", 0.0)),
);
let distance = (x - min_x).min(max_x - x).min(z - min_z).min(max_z - z);
hud_overlays::border_warning(
distance as f32,
int(b, "warningBlocks", 5),
int(b, "warningTime", 15),
0.0,
0.0,
)
}
};
let ticks_frozen = int(c, "ticksFrozen", 0);
let inputs = CameraOverlays {
vignette: c["vignette"]
.as_bool()
.unwrap_or(false)
.then(|| (float(c, "vignetteBrightness", 1.0), warning)),
first_person: c["firstPerson"].as_bool().unwrap_or(false),
scoping: c["scoping"].as_bool().unwrap_or(false),
game_time_delta: partial,
equipment: match c["head"].as_str() {
Some("carved_pumpkin") => vec!["misc/pumpkinblur".to_owned()],
_ => Vec::new(),
},
ticks_frozen,
percent_frozen: ticks_frozen.min(140) as f32 / 140.0,
partial,
portal: [
c["portal"][0].as_f64().unwrap_or(0.0) as f32,
c["portal"][1].as_f64().unwrap_or(0.0) as f32,
],
nausea: float(c, "nausea", 0.0),
screen_effect_scale: float(c, "screenEffectScale", 1.0),
};
let mut scope = float(c, "scopeScale", 0.5);
let mut out = hud_overlays::camera_overlays(w, h, &inputs, &mut scope);
out.extend(hud_overlays::sleep_overlay(w, h, int(c, "sleepTimer", 0)));
state.insert("scopeScale".into(), serde_json::json!(scope));
out
}
/// Messages added at their ticks (`Hud.tickCount`), then the chat in
/// background mode at tick `now`.
fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
let option = |k: &str| c[k].as_f64().unwrap_or(0.0);
let mut chat = Chat::default();
chat.options = ChatOptions {
opacity: option("chatOpacity"),
background_opacity: option("textOpacity"),
scale: option("chatScale"),
width: option("chatWidth"),
height_focused: option("chatHeightFocused"),
height_unfocused: option("chatHeightUnfocused"),
line_spacing: option("chatLineSpacing"),
};
for m in c["messages"].as_array().into_iter().flatten() {
// GuiMessageTag indicator colours: systemSinglePlayer and chatError.
let indicator = match m["tag"].as_str() {
Some("system") => Some(13684944),
Some("error") => Some(16733525),
_ => None,
};
chat.add(
atlas,
comp(&m["text"]),
indicator,
m["at"].as_u64().unwrap_or(0),
false,
);
}
chat.layout(h, c["now"].as_u64().unwrap_or(0), false)
}
@@ -0,0 +1,106 @@
//! The player's attack strength (`Player.attackStrengthTicker`,
//! `itemSwapTicker`, `getAttackStrengthScale`, `getCurrentItemAttackStrengthDelay`):
//! the charge the attack indicator shows and attacks scale their damage by.
/// `Attributes.ATTACK_SPEED` base value.
pub const BASE_ATTACK_SPEED: f64 = 4.0;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AttackStrength {
/// `LivingEntity.attackStrengthTicker`.
pub ticker: i32,
/// `LivingEntity.itemSwapTicker`.
pub swap_ticker: i32,
/// `Player.lastItemInMainHand`: the stack as last compared.
last_item: Option<HeldStack>,
}
/// What `ItemStack.matches` / `isSameItem` compare of the main-hand stack:
/// its item id and the rest of the stack (count and components) as a key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct HeldStack {
pub item: String,
pub rest: String,
}
/// `Player.getCurrentItemAttackStrengthDelay` for an ATTACK_SPEED value.
pub fn delay(attack_speed: f64) -> f32 {
(1.0 / attack_speed * 20.0) as f32
}
impl AttackStrength {
/// The attack-strength part of `Player.tick`: both tickers advance, and a
/// main-hand change to a different item resets them
/// (`!ItemStack.matches` and `!ItemStack.isSameItem`).
pub fn tick(&mut self, main_hand: Option<HeldStack>) {
self.ticker += 1;
self.swap_ticker += 1;
if self.last_item != main_hand {
let same_item = match (&self.last_item, &main_hand) {
(Some(a), Some(b)) => a.item == b.item,
(None, None) => true,
_ => false,
};
if !same_item {
self.reset();
}
self.last_item = main_hand;
}
}
/// `resetAttackStrengthTicker`: swinging at nothing, attacking or
/// stopping a block break.
pub fn reset(&mut self) {
self.ticker = 0;
self.swap_ticker = 0;
}
/// `resetOnlyAttackStrengthTicker` (`Player.onAttack`).
pub fn reset_attack(&mut self) {
self.ticker = 0;
}
/// `getAttackStrengthScale(a)` with the ATTACK_SPEED attribute value.
pub fn scale(&self, a: f32, attack_speed: f64) -> f32 {
((self.ticker as f32 + a) / delay(attack_speed)).clamp(0.0, 1.0)
}
/// `getItemSwapScale(a)`.
pub fn swap_scale(&self, a: f32, attack_speed: f64) -> f32 {
((self.swap_ticker as f32 + a) / delay(attack_speed)).clamp(0.0, 1.0)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn held(item: &str, rest: &str) -> Option<HeldStack> {
Some(HeldStack {
item: item.into(),
rest: rest.into(),
})
}
#[test]
fn charges_over_the_attack_delay() {
let mut s = AttackStrength::default();
// A sword's 1.6 attacks per second: 12.5 ticks to full strength.
assert_eq!(delay(1.6), 12.5);
for _ in 0..6 {
s.tick(None);
}
assert_eq!(s.scale(0.25, 1.6), 6.25 / 12.5);
for _ in 0..10 {
s.tick(None);
}
assert_eq!(s.scale(0.0, 1.6), 1.0);
}
#[test]
fn switching_items_resets_but_restacking_does_not() {
let mut s = AttackStrength::default();
s.tick(held("minecraft:stone", "64"));
assert_eq!(s.ticker, 0, "picking up an item resets");
s.tick(held("minecraft:stone", "63"));
assert_eq!(
s.ticker, 1,
"the same item with another count keeps charging"
);
s.tick(held("minecraft:diamond_sword", ""));
assert_eq!((s.ticker, s.swap_ticker), (0, 0));
s.tick(held("minecraft:diamond_sword", ""));
s.reset_attack();
assert_eq!((s.ticker, s.swap_ticker), (0, 1));
}
}
+124 -110
View File
@@ -5,6 +5,7 @@
use crate::{
command::{Dispatcher, ParseResults, Registries, Suggestion},
hud::{HudAtlas, HudBatch, rgba},
hud_layout::{self, GuiDraw, PoseOp},
text::{self, Style, Text},
ui::{EditBox, char_len},
};
@@ -12,15 +13,16 @@ use crate::{
/// GuiMessageTag.systemSinglePlayer's indicator colour.
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
/// The chat options (doubles, as vanilla keeps them).
#[derive(Clone, Copy, Debug)]
pub struct ChatOptions {
pub opacity: f32,
pub background_opacity: f32,
pub scale: f32,
pub width: f32,
pub height_focused: f32,
pub height_unfocused: f32,
pub line_spacing: f32,
pub opacity: f64,
pub background_opacity: f64,
pub scale: f64,
pub width: f64,
pub height_focused: f64,
pub height_unfocused: f64,
pub line_spacing: f64,
}
impl Default for ChatOptions {
fn default() -> Self {
@@ -37,20 +39,21 @@ impl Default for ChatOptions {
}
impl ChatOptions {
/// ChatComponent.getWidth/getHeight.
pub fn width_px(&self) -> f32 {
(self.width * 280.0 + 40.0).floor()
pub fn width_px(&self) -> i32 {
(self.width * 280.0 + 40.0).floor() as i32
}
pub fn height_px(&self, focused: bool) -> f32 {
pub fn height_px(&self, focused: bool) -> i32 {
((if focused {
self.height_focused
} else {
self.height_unfocused
}) * 160.0
+ 20.0)
.floor()
.floor() as i32
}
pub fn line_height(&self) -> f32 {
(9.0 * (self.line_spacing + 1.0)).floor()
/// `getLineHeight`.
pub fn line_height(&self) -> i32 {
(9.0 * (self.line_spacing + 1.0)) as i32
}
}
#[derive(Clone, Debug)]
@@ -59,12 +62,25 @@ struct Message {
content: Text,
indicator: Option<u32>,
}
/// A wrapped line (`GuiMessage.Line`).
#[derive(Clone, Debug)]
struct Line {
added: u64,
content: Text,
indicator: Option<u32>,
}
/// `ChatComponent.AlphaCalculator.timeBased`: opaque for 180 ticks, then
/// fading out quadratically over 20.
fn time_alpha(ticks: u64, added: u64) -> f32 {
let delta = ticks as i64 - added as i64;
let mut t = delta as f64 / 200.0;
t = 1.0 - t;
t *= 10.0;
t = t.clamp(0.0, 1.0);
t *= t;
t as f32
}
#[derive(Default)]
pub struct Chat {
messages: Vec<Message>,
@@ -80,10 +96,11 @@ pub struct Chat {
}
impl Chat {
pub fn lines_per_page(&self, focused: bool) -> usize {
(self.options.height_px(focused) / self.options.line_height().max(1.0)) as usize
(self.options.height_px(focused) / self.options.line_height().max(1)) as usize
}
fn max_width(&self) -> f32 {
(self.options.width_px() / self.options.scale.max(0.01)).floor()
/// The wrapping width, `Mth.floor(getWidth() / getScale())`.
fn max_width(&self) -> i32 {
(f64::from(self.options.width_px()) / self.options.scale).floor() as i32
}
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines.
pub fn add(
@@ -108,7 +125,7 @@ impl Chat {
}
fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) {
let width = self.max_width();
for line in atlas.font.split(&message.content, width) {
for line in atlas.font.wrap_components(&message.content, width) {
if focused && self.scroll > 0 {
self.new_since_scroll = true;
self.scroll_by(1, focused);
@@ -164,116 +181,113 @@ impl Chat {
self.scroll = pos as usize;
}
}
/// ChatComponent.extractRenderState.
pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) {
if self.lines.is_empty() {
return;
/// `ChatComponent.extractRenderState` (background mode unless `focused`)
/// on a screen `height` GUI pixels tall at `Hud.tickCount` `ticks`.
pub fn layout(&self, height: i32, ticks: u64, focused: bool) -> Vec<GuiDraw> {
let total = self.lines.len();
if total == 0 {
return Vec::new();
}
let o = &self.options;
let scale = o.scale;
if scale <= 0.0 {
return;
}
let max_width = (o.width_px() / scale).ceil();
let chat_bottom = ((batch.height - 40.0) / scale).floor();
let text_opacity = o.opacity * 0.9 + 0.1;
let scale = o.scale as f32;
let max_width = hud_layout::ceil(o.width_px() as f32 / scale);
let chat_bottom = hud_layout::floor((height - 40) as f32 / scale);
let text_opacity = o.opacity as f32 * 0.9 + 0.1;
let background_opacity = o.background_opacity as f32;
let entry_height = o.line_height();
let bottom_to_text = (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing).round();
let per_page = self.lines_per_page(focused);
let alpha_of = |line: &Line| -> f32 {
let bottom_to_text =
(8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing + 0.5).floor() as i32;
let alpha_of = |line: &Line| {
if focused {
return 1.0;
1.0
} else {
time_alpha(ticks, line.added)
}
let t =
((1.0 - (ticks.saturating_sub(line.added)) as f64 / 200.0) * 10.0).clamp(0.0, 1.0);
(t * t) as f32
};
let visible = self.lines.len().saturating_sub(self.scroll).min(per_page);
let mut count = 0;
// Pass 1: backgrounds; pass 2: text (same order as vanilla).
let s = |v: f32| v * scale;
for i in (0..visible).rev() {
let line = &self.lines[i + self.scroll];
let alpha = alpha_of(line);
if alpha <= 1.0e-5 {
continue;
}
count += 1;
let bottom = chat_bottom - i as f32 * entry_height;
let top = bottom - entry_height;
batch.fill(
atlas,
0.0,
s(top),
s(max_width + 8.0),
s(entry_height),
rgba(0, 0, 0, (alpha * o.background_opacity * 255.0) as u8),
);
let visible = total
.saturating_sub(self.scroll)
.min(self.lines_per_page(focused));
let lines: Vec<(usize, &Line, f32)> = (0..visible)
.rev()
.map(|i| (i, &self.lines[i + self.scroll]))
.map(|(i, line)| (i, line, alpha_of(line)))
.filter(|(_, _, alpha)| *alpha > 1.0e-5)
.collect();
let mut out = vec![GuiDraw::Push(vec![
PoseOp::Scale(scale, scale),
PoseOp::Translate(4.0, 0.0),
])];
for &(i, _, alpha) in &lines {
let bottom = chat_bottom - i as i32 * entry_height;
out.push(hud_layout::fill(
-4,
bottom - entry_height,
max_width + 4 + 4,
bottom,
hud_layout::as8(alpha * background_opacity) << 24,
));
}
for i in (0..visible).rev() {
let line = &self.lines[i + self.scroll];
let alpha = alpha_of(line);
if alpha <= 1.0e-5 {
continue;
for &(i, line, alpha) in &lines {
let bottom = chat_bottom - i as i32 * entry_height;
let opacity = alpha * text_opacity;
let color = hud_layout::white(opacity);
if color >> 24 != 0 {
out.push(GuiDraw::Text {
text: line.content.clone(),
x: 0,
y: bottom - bottom_to_text,
color,
shadow: true,
});
}
let bottom = chat_bottom - i as f32 * entry_height;
let top = bottom - entry_height;
let text_top = bottom - bottom_to_text;
let a = (alpha * text_opacity * 255.0) as u8;
if let Some(c) = line.indicator {
batch.fill(
atlas,
0.0,
s(top),
s(2.0),
s(entry_height),
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, a),
);
}
if a > 3 {
batch.text_styled(
atlas,
&line.content,
s(4.0),
s(text_top),
rgba(255, 255, 255, a),
true,
);
if let Some(indicator) = line.indicator {
let color = hud_layout::as8(opacity) << 24 | indicator & 0xFF_FFFF;
out.push(hud_layout::fill(
-4,
bottom - entry_height,
-2,
bottom,
color,
));
}
}
// Scroll bar while focused and scrolled content exists.
if focused && count > 0 {
let total = self.lines.len() as f32;
let chat_height = count as f32 * entry_height;
let virtual_height = total * entry_height;
if focused {
let count = lines.len() as i32;
let chat_height = count * entry_height;
let virtual_height = total as i32 * entry_height;
let y = self.scroll as i32 * chat_height / total as i32 - chat_bottom;
let height = chat_height * chat_height / virtual_height;
if virtual_height != chat_height {
let y = self.scroll as f32 * chat_height / total - chat_bottom;
let height = chat_height * chat_height / virtual_height;
let alpha = if y > 0.0 { 170 } else { 96 };
let c = if self.new_since_scroll {
let alpha: u32 = if y > 0 { 170 } else { 96 };
let color = if self.new_since_scroll {
0xCC3333
} else {
0x3333AA
};
let x = max_width + 4.0 + 4.0;
batch.fill(
atlas,
s(x),
s(-y - height),
s(2.0),
s(height),
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, alpha),
);
batch.fill(
atlas,
s(x + 1.0),
s(-y - height),
s(1.0),
s(height),
rgba(0xCC, 0xCC, 0xCC, alpha),
);
let x = max_width + 4;
out.push(hud_layout::fill(
x,
-y,
x + 2,
-y - height,
alpha << 24 | color,
));
out.push(hud_layout::fill(
x + 2,
-y,
x + 1,
-y - height,
alpha << 24 | 0xCCCCCC,
));
}
}
out.push(GuiDraw::Pop);
out
}
/// Draws [`Chat::layout`] into the HUD batch.
pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) {
let draws = self.layout(batch.height as i32, ticks, focused);
hud_layout::paint(batch, atlas, &draws);
}
/// Plain text of the newest messages (for tests and the control socket).
pub fn recent_lines(&self, n: usize) -> Vec<String> {
+28 -18
View File
@@ -152,6 +152,23 @@ impl Parser<'_> {
Err("unterminated string".into())
}
}
/// The style fields of a component object.
fn object_style(o: &serde_json::Map<String, Value>) -> Style {
let mut style = Style::default();
if let Some(c) = o.get("color").and_then(Value::as_str) {
style.color = named_color(c).or_else(|| {
c.strip_prefix('#')
.and_then(|h| u32::from_str_radix(h, 16).ok())
});
}
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
style.bold = flag("bold");
style.italic = flag("italic");
style.underlined = flag("underlined");
style.strikethrough = flag("strikethrough");
style.obfuscated = flag("obfuscated");
style
}
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
/// are resolved by `resolve` (ComponentUtils.updateForEntity).
pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
@@ -165,30 +182,23 @@ pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
return Text::empty();
};
let mut base = to_text(first, resolve);
let style = base
.spans
.first()
.map(|s| s.style.clone())
.unwrap_or_default();
// The siblings take the first component's own style, even when
// its text is empty.
let style = match first {
Value::Object(o) => object_style(o),
_ => base
.spans
.first()
.map(|s| s.style.clone())
.unwrap_or_default(),
};
for sibling in rest {
base.push(to_text(sibling, resolve).with_style(&style));
}
base
}
Value::Object(o) => {
let mut style = Style::default();
if let Some(c) = o.get("color").and_then(Value::as_str) {
style.color = named_color(c).or_else(|| {
c.strip_prefix('#')
.and_then(|h| u32::from_str_radix(h, 16).ok())
});
}
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
style.bold = flag("bold");
style.italic = flag("italic");
style.underlined = flag("underlined");
style.strikethrough = flag("strikethrough");
style.obfuscated = flag("obfuscated");
let style = object_style(o);
let content = if let Some(t) = o.get("text") {
match t {
Value::String(s) => Text::literal(s.clone()),
+66
View File
@@ -451,6 +451,72 @@ impl Font {
.sum::<f32>()
.ceil()
}
/// `StringSplitter.splitLines`: each line and whether it continues a
/// wrapped one. A line breaks at a `\n`, or once a character overflows
/// `max_width` (never the first visible one) at the last space so far, or
/// before that character; the `\n` or space at the break is dropped.
pub fn split_lines(&self, t: &Text, max_width: f32) -> Vec<(Text, bool)> {
let max_width = max_width.max(1.0);
let chars: Vec<(char, &Style)> = t.chars().collect();
let n = chars.len();
let mut out = Vec::new();
let (mut start, mut wrapped, mut force_new_line) = (0, false, false);
loop {
// LineBreakFinder over what is left.
let (mut width, mut had_visible, mut last_space) = (0.0f32, false, None);
let mut split = None;
for (i, &(c, style)) in chars.iter().enumerate().skip(start) {
if c == '\n' {
split = Some(i);
break;
}
if c == ' ' {
last_space = Some(i);
}
let advance = self.advance(c, style);
width += advance;
if !had_visible || width <= max_width {
had_visible |= advance != 0.0;
} else {
split = Some(last_space.unwrap_or(i));
break;
}
}
let Some(at) = split else { break };
let new_line = chars[at].0 == '\n';
let skip = usize::from(new_line || chars[at].0 == ' ');
force_new_line = new_line;
out.push((t.slice(start, at), wrapped));
wrapped = !new_line;
start = at + skip;
}
if start < n {
out.push((t.slice(start, n), wrapped));
} else if force_new_line {
out.push((Text::empty(), false));
}
out
}
/// `ComponentRenderUtils.wrapComponents`: the split lines, wrapped ones
/// indented by an unstyled space; one empty line for empty text.
pub fn wrap_components(&self, t: &Text, max_width: i32) -> Vec<Text> {
let lines: Vec<Text> = self
.split_lines(t, max_width as f32)
.into_iter()
.map(|(line, wrapped)| {
if wrapped {
Text::literal(" ").append(line)
} else {
line
}
})
.collect();
if lines.is_empty() {
vec![Text::empty()]
} else {
lines
}
}
/// StringSplitter.splitLines: wrap at the last space that fits (or
/// mid-word when none does); `\n` always breaks. Styles are kept.
pub fn split(&self, t: &Text, max_width: f32) -> Vec<Text> {
+38 -30
View File
@@ -110,7 +110,7 @@ use horizon_client::{
environment::Environment,
gfx::{Frame, Renderer},
hud::{HudAtlas, HudBatch, rgba},
hud_layout,
hud_layout, hud_overlays,
items::{ItemStack, Items},
keymapping::KeyAction,
light::LightTables,
@@ -637,6 +637,8 @@ struct Game<'a> {
/// The source of a command run through /execute (the player otherwise).
command_source: Option<commands::execute::Source>,
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<ExperienceOrb>,
@@ -2724,7 +2726,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();
@@ -2864,26 +2866,30 @@ impl Game<'_> {
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
// special renderers included), then the decorations.
self.draw_item_model(batch, stack, x, y);
let atlas = &self.res.atlas;
if stack.count > 1 {
let text = stack.count.to_string();
let w = HudBatch::text_width(atlas, &text);
batch.text(atlas, &text, x + 17.0 - w, y + 9.0, u32::MAX, true);
}
if let Some(info) = self.res.items.get(&stack.item)
&& info.max_damage > 0
&& stack.damage > 0
{
let f = 1.0 - stack.damage as f32 / info.max_damage as f32;
let width = (13.0 * f).round();
let hue = f / 3.0;
let (r, g) = (
(255.0 * (1.0 - hue * 3.0).clamp(0.0, 1.0)) as u8,
(255.0 * (hue * 3.0).clamp(0.0, 1.0)) as u8,
);
batch.fill(atlas, x + 2.0, y + 13.0, 13.0, 2.0, rgba(0, 0, 0, 255));
batch.fill(atlas, x + 2.0, y + 13.0, width, 1.0, rgba(r, g, 0, 255));
}
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
// moved to (x, y). Horizon tracks no item cooldowns to shade yet.
let max_damage = self
.res
.items
.get(&stack.item)
.map_or(0, |info| info.max_damage as i32);
let decorations = hud_overlays::ItemDecorations {
count: stack.count,
count_text: None,
bar: hud_overlays::damage_bar(stack.damage as i32, max_damage),
cooldown: 0.0,
};
let mut draws = vec![hud_layout::GuiDraw::Push(vec![
hud_layout::PoseOp::Translate(x, y),
])];
draws.extend(hud_overlays::item_decorations(
0,
0,
&decorations,
&self.res.atlas.font,
));
draws.push(hud_layout::GuiDraw::Pop);
hud_layout::paint(batch, &self.res.atlas, &draws);
}
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
let mut batch = HudBatch::new(size);
@@ -2951,8 +2957,12 @@ 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);
// Hud.extractSleepOverlay, under the sidebar, titles and chat.
if let Some((_, ticks)) = self.sleeping {
let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32);
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
}
self.draw_titles(&mut batch);
self.draw_scoreboard(&mut batch);
self.draw_subtitles(&mut batch);
@@ -3022,6 +3032,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
@@ -3123,12 +3136,6 @@ impl Game<'_> {
batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true);
}
self.draw_chat(&mut batch);
let atlas = &self.res.atlas;
if let Some((_, ticks)) = self.sleeping {
// Gui sleep overlay fading in over 100 ticks.
let a = ((ticks as f32 / 100.0).min(1.0) * 204.0) as u8;
batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 32, a));
}
match self.screen {
Screen::Paused => self.draw_pause_menu(&mut batch),
Screen::Dead => self.draw_death_screen(&mut batch),
@@ -8057,6 +8064,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(),
+16 -59
View File
@@ -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<hud_overlays::BossBar>) {
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),
});
}
}
}
+1 -1
View File
@@ -511,7 +511,7 @@ impl Game<'_> {
return;
};
screen.resize(batch.width, batch.height);
let bg = self.ui.chat.options.background_opacity;
let bg = self.ui.chat.options.background_opacity as f32;
screen.draw(
batch,
&self.res.atlas,
+1 -1
View File
@@ -685,7 +685,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::collections::HashMap<String, String>> =
std::sync::OnceLock::new();
let map = RARITY.get_or_init(|| {
@@ -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);
+26 -24
View File
@@ -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 {
+12 -17
View File
@@ -8,7 +8,8 @@ use horizon_client::{
BobState, CameraFluid, FovPlayer, HurtBob, UseItem, bob_matrix, field_of_view_modifier,
},
fog::{FogType, fog_type},
hud::{HudBatch, rgba},
hud::HudBatch,
hud_layout, hud_overlays,
};
/// `Abilities.walkingSpeed`.
@@ -145,26 +146,20 @@ impl Game<'_> {
self.audio
.play("minecraft:item.spyglass.stop_using", at, 1.0, 1.0);
}
/// `Hud.extractCameraOverlays`: the scope, its size easing from 0.5 to
/// 1.125 at half a step per tick of frame time.
/// `Hud.extractCameraOverlays`: the spyglass scope, its size easing
/// towards 1.125 by half the frame's game ticks and reset to 0.5 while
/// not scoping in first person.
pub(super) fn draw_spyglass(&mut self, batch: &mut HudBatch) {
self.scope_scale += 0.5 * self.frame_ticks * (1.125 - self.scope_scale);
if !self.camera_type.first_person() {
return;
}
if !self.scoping() {
self.scope_scale = 0.5;
return;
}
self.scope_scale += (1.125 - self.scope_scale) * (0.5 * self.frame_ticks).min(1.0);
let atlas = &self.res.atlas;
let (w, h) = (batch.width, batch.height);
let src = w.min(h);
let ratio = (w / src).min(h / src) * self.scope_scale;
let (sw, sh) = ((src * ratio).floor(), (src * ratio).floor());
let (left, top) = (((w - sw) / 2.0).floor(), ((h - sh) / 2.0).floor());
let (right, bottom) = (left + sw, top + sh);
batch.sprite_scaled(atlas, "misc/spyglass_scope", left, top, sw, sh, u32::MAX);
let black = rgba(0, 0, 0, 255);
batch.fill(atlas, 0.0, bottom, w, h - bottom, black);
batch.fill(atlas, 0.0, 0.0, w, top, black);
batch.fill(atlas, 0.0, top, left, bottom - top, black);
batch.fill(atlas, right, top, w - right, bottom - top, black);
let draws =
hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale);
hud_layout::paint(batch, &self.res.atlas, &draws);
}
}
+1 -2
View File
@@ -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]) {
+5 -17
View File
@@ -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)
}
+21 -46
View File
@@ -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};
@@ -563,52 +564,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<hud_overlays::EffectIcon> = 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) {
+10 -33
View File
@@ -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<hud_overlays::BossBar>) {
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) {
+31 -10
View File
@@ -2,7 +2,6 @@
//! campfire smoke and rain splashes (`ClientLevel.tickWeatherEffects`).
use super::{Dim, Game};
use horizon_client::fog::{FogData, FogInputs, FogType, fog_type, update_rain_fog};
use horizon_client::screen_effects::{ScreenInputs, ScreenQuad, lightmap_brightness};
use horizon_client::{
animate_tick::{AnimateContext, animate_tick, campfire_particles},
biome::Biomes,
@@ -11,6 +10,10 @@ use horizon_client::{
particles::{ParticleLevel, ParticleOptions, ParticleType},
world::World,
};
use horizon_client::{
hud_overlays,
screen_effects::{ScreenInputs, ScreenQuad, lightmap_brightness},
};
use horizon_core::random::{LegacyRandom, RandomSource};
/// The first motion-blocking block at or below `from` (Heightmap MOTION_BLOCKING), plus one.
@@ -140,12 +143,33 @@ impl Game<'_> {
fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water;
let water =
(in_water && !spectator).then(|| (self.eye_brightness(eye), self.yaw, self.pitch));
let camera_overlays = match &self.armor[0] {
Some(stack) if &*stack.item == "minecraft:carved_pumpkin" => {
vec!["misc/pumpkinblur".to_owned()]
}
_ => Vec::new(),
// Hud.extractCameraOverlays; the spyglass scope (and its easing) is
// drawn on the HUD by draw_spyglass.
let fx = &self.res.screen_fx;
let overlays = hud_overlays::CameraOverlays {
vignette: self
.settings
.vignette
.then_some((fx.vignette_brightness, 0.0)),
first_person: self.camera_type.first_person(),
scoping: self.scoping(),
game_time_delta: 0.0,
equipment: match &self.armor[0] {
Some(stack) if &*stack.item == "minecraft:carved_pumpkin" => {
vec!["misc/pumpkinblur".to_owned()]
}
_ => Vec::new(),
},
ticks_frozen: 0,
percent_frozen: 0.0,
partial,
portal: [fx.o_portal, fx.portal],
nausea: 0.0,
screen_effect_scale: 1.0,
};
let mut scope = self.scope_scale;
let gui_overlays =
hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope);
self.res.screen_fx.build(&ScreenInputs {
sprites: &self.res.atlas.sprites,
aspect: size[0] as f32 / size[1].max(1) as f32,
@@ -153,10 +177,7 @@ impl Game<'_> {
block_overlay,
water,
on_fire: false,
camera_overlays,
frozen: 0.0,
vignette: true,
border_warning: None,
gui_overlays: &gui_overlays,
})
}
/// `Lightmap.getBrightness(getMaxLocalRawBrightness(eye))`.
+12 -79
View File
@@ -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);
}
}
+58 -158
View File
@@ -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<Text>,
pub subtitle: Option<Text>,
pub time: i32,
pub fade_in: i32,
pub stay: i32,
pub fade_out: i32,
pub overlay: Option<Text>,
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<HeldName> {
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)]
}
+11 -25
View File
@@ -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<'_> {
@@ -69,12 +70,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<hud_overlays::BossBar>) {
let Some(p) = self.player.as_ref() else {
return y;
return;
};
let atlas = &self.res.atlas;
for m in self
.mobs
.iter()
@@ -83,36 +83,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| {
+337 -60
View File
@@ -1,26 +1,109 @@
//! Layout of vanilla's `Hud` decorations as draw calls (`GuiGraphicsExtractor`
//! blits and text): the hotbar with its selection, off-hand slot, items and
//! Layout of vanilla's `Hud` as draw calls (`GuiGraphicsExtractor` blits,
//! fills and text): the hotbar with its selection, off-hand slot, items and
//! attack indicator, the crosshair, armour, hearts, food, air bubbles, mount
//! hearts and the experience bar and level. Computed without drawing so the
//! parity fixture can compare them with the vanilla client.
//! hearts and the experience bar, plus the draw-call types and colour
//! helpers the other layouts share (`hud_overlays`, `chat`). Computed without
//! drawing so the parity fixture can compare them with the vanilla client.
use crate::{font::Font, text::Text};
use horizon_core::random::{LegacyRandom, RandomSource};
use std::borrow::Cow;
/// A `Matrix3x2fStack` operation applied to a copy of the current pose.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PoseOp {
Translate(f32, f32),
Scale(f32, f32),
}
/// A JOML `Matrix3x2f` as `[m00, m01, m10, m11, m20, m21]`.
pub type Pose = [f32; 6];
pub const IDENTITY: Pose = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
/// Applies `op` like JOML's `translate` / `scale` (same float order).
pub fn pose_apply(m: &mut Pose, op: PoseOp) {
match op {
PoseOp::Translate(x, y) => {
m[4] += m[0] * x + m[2] * y;
m[5] += m[1] * x + m[3] * y;
}
PoseOp::Scale(x, y) => {
m[0] *= x;
m[1] *= x;
m[2] *= y;
m[3] *= y;
}
}
}
/// The render pipeline of a texture blit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Blend {
/// `GUI_TEXTURED`.
Textured,
/// `VIGNETTE`: `dst * (1 - src)`.
Vignette,
/// `GUI_NAUSEA_OVERLAY`: additive.
Nausea,
}
impl Blend {
pub fn pipeline(self) -> &'static str {
match self {
Blend::Textured => "pipeline/gui_textured",
Blend::Vignette => "pipeline/vignette",
Blend::Nausea => "pipeline/gui_nausea_overlay",
}
}
}
/// One `GuiGraphicsExtractor` call.
#[derive(Clone, Debug, PartialEq)]
pub enum GuiDraw {
/// `blitSprite(sprite, x, y, w, h)`; `region` = (spriteW, spriteH, u, v)
/// for the partial overload.
/// `blitSprite(sprite, x, y, w, h, color)`; `region` = (spriteW,
/// spriteH, u, v) for the partial overload.
Sprite {
sprite: &'static str,
sprite: Cow<'static, str>,
x: i32,
y: i32,
w: i32,
h: i32,
region: Option<[i32; 4]>,
color: u32,
},
/// `blitSprite(pipeline, TextureAtlasSprite, ...)` with a block atlas
/// sprite (the nether portal overlay).
AtlasSprite {
sprite: Cow<'static, str>,
x: i32,
y: i32,
w: i32,
h: i32,
color: u32,
},
/// `blit(pipeline, texture, x, y, u, v, w, h, srcW, srcH, texW, texH,
/// color)`; `texture` is the path under `textures/` without `.png`.
Blit {
texture: Cow<'static, str>,
blend: Blend,
x: i32,
y: i32,
w: i32,
h: i32,
uv: [f32; 2],
src: [i32; 2],
tex: [i32; 2],
color: u32,
},
/// `fill(x0, y0, x1, y1, color)` with the corners sorted.
Fill {
x0: i32,
y0: i32,
x1: i32,
y1: i32,
color: u32,
},
/// `text(font, text, x, y, argb, dropShadow)`.
Text {
text: String,
text: Text,
x: i32,
y: i32,
color: u32,
@@ -36,17 +119,134 @@ pub enum GuiDraw {
scale: [f32; 2],
pivot: [f32; 2],
},
/// `pose().pushMatrix()` followed by `ops`.
Push(Vec<PoseOp>),
/// `pose().popMatrix()`.
Pop,
}
pub const WHITE: u32 = 0xFFFF_FFFF;
fn sprite(sprite: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw {
GuiDraw::Sprite {
sprite,
sprite: Cow::Borrowed(sprite),
x,
y,
w,
h,
region: None,
color: WHITE,
}
}
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],
y: at[1],
w,
h,
region: Some([size[0], size[1], uv[0], uv[1]]),
color: WHITE,
}
}
/// `graphics.fill`: the corners are sorted.
pub fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: u32) -> GuiDraw {
GuiDraw::Fill {
x0: x0.min(x1),
y0: y0.min(y1),
x1: x0.max(x1),
y1: y0.max(y1),
color,
}
}
/// `graphics.text`: dropped when fully transparent.
fn text(out: &mut Vec<GuiDraw>, text: Text, x: i32, y: i32, color: u32, shadow: bool) {
if color >> 24 != 0 {
out.push(GuiDraw::Text {
text,
x,
y,
color,
shadow,
});
}
}
/// `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 };
color_from_float(a, 0.0, 0.0, 0.0)
}
/// `Mth.floor`.
pub fn floor(x: f32) -> i32 {
let i = x as i32;
if x < i as f32 { i - 1 } else { i }
}
/// `Mth.ceil`.
pub fn ceil(x: f32) -> i32 {
let i = x as i32;
if x > i as f32 { i + 1 } else { i }
}
/// `ARGB.as8BitChannel`.
pub fn as8(v: f32) -> u32 {
floor(v * 255.0) as u32
}
/// `ARGB.white(float)`.
pub fn white(alpha: f32) -> u32 {
(as8(alpha) << 24) | 0xFF_FFFF
}
/// `ARGB.colorFromFloat`.
pub fn color_from_float(a: f32, r: f32, g: f32, b: f32) -> u32 {
argb(as8(a), as8(r), as8(g), as8(b))
}
/// `ARGB.color(a, r, g, b)`.
pub fn argb(a: u32, r: u32, g: u32, b: u32) -> u32 {
(a & 255) << 24 | (r & 255) << 16 | (g & 255) << 8 | (b & 255)
}
/// `ARGB.multiply`.
pub fn multiply(l: u32, r: u32) -> u32 {
if l == WHITE {
return r;
}
if r == WHITE {
return l;
}
let c = |s: u32| ((l >> s) & 255) * ((r >> s) & 255) / 255;
argb(c(24), c(16), c(8), c(0))
}
/// `Mth.lerpDiscrete`.
pub fn lerp_discrete(alpha: f32, p0: i32, p1: i32) -> i32 {
p0 + floor(alpha * (p1 - p0 - 1) as f32) + i32::from(alpha > 0.0)
}
/// `Mth.hsvToArgb`.
pub fn hsv_to_argb(hue: f32, saturation: f32, value: f32, alpha: u32) -> u32 {
let h = (hue * 6.0) as i32 % 6;
let f = hue * 6.0 - h as f32;
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) as i32).clamp(0, 255) as u32;
argb(alpha, c(r), c(g), c(b))
}
/// `Font.width` of styled text.
pub fn width(font: &Font, t: &Text) -> i32 {
font.width_text(t) as i32
}
/// `Hud.extractItemHotbar` inputs.
pub struct HotbarInputs {
@@ -153,14 +353,14 @@ pub fn hotbar(w: i32, h: i32, i: &HotbarInputs) -> Vec<GuiDraw> {
18,
18,
));
out.push(GuiDraw::Sprite {
sprite: "hud/hotbar_attack_indicator_progress",
x,
y: y + 18 - progress,
w: 18,
h: progress,
region: Some([18, 18, 0, 18 - progress]),
});
out.push(region(
"hud/hotbar_attack_indicator_progress",
[18, 18],
[0, 18 - progress],
[x, y + 18 - progress],
18,
progress,
));
}
out
}
@@ -183,14 +383,14 @@ pub fn crosshair(w: i32, h: i32, attack: Option<f32>, full: bool) -> Vec<GuiDraw
16,
4,
));
out.push(GuiDraw::Sprite {
sprite: "hud/crosshair_attack_indicator_progress",
x,
y,
w: progress,
h: 4,
region: Some([16, 4, 0, 0]),
});
out.push(region(
"hud/crosshair_attack_indicator_progress",
[16, 4],
[0, 0],
[x, y],
progress,
4,
));
}
}
out
@@ -212,14 +412,14 @@ pub fn experience(
let filled = (progress * 183.0) as i32;
out.push(sprite("hud/experience_bar_background", left, top, 182, 5));
if filled > 0 {
out.push(GuiDraw::Sprite {
sprite: "hud/experience_bar_progress",
x: left,
y: top,
w: filled,
h: 5,
region: Some([182, 5, 0, 0]),
});
out.push(region(
"hud/experience_bar_progress",
[182, 5],
[0, 0],
[left, top],
filled,
5,
));
}
}
if level > 0 {
@@ -227,21 +427,16 @@ 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)] {
out.push(GuiDraw::Text {
text: text.clone(),
x: x + dx,
y: y + dy,
color: 0xFF00_0000,
shadow: false,
});
self::text(
&mut out,
Text::literal(&text),
x + dx,
y + dy,
0xFF00_0000,
false,
);
}
out.push(GuiDraw::Text {
text,
x,
y,
color: 0xFF80_FF20,
shadow: false,
});
self::text(&mut out, Text::literal(text), x, y, 0xFF80_FF20, false);
}
out
}
@@ -394,12 +589,6 @@ fn heart(
table[usize::from(hardcore) * 4 + usize::from(half) * 2 + usize::from(blink)]
}
fn ceil(x: f32) -> i32 {
// Mth.ceil.
let i = x as i32;
if x > i as f32 { i + 1 } else { i }
}
impl HealthHud {
/// `Hud.extractPlayerHealth` for a screen of `w` x `h` GUI pixels.
pub fn layout(&mut self, i: &HealthInputs, w: i32, h: i32) -> Vec<GuiDraw> {
@@ -554,10 +743,14 @@ impl HealthHud {
}
}
/// Draws the sprite and text calls with the HUD batch; items are left to the
/// caller (they need the item renderer).
/// Draws the calls with the HUD batch under their poses; items are left to
/// the caller (they need the item renderer) and so are the vignette and
/// nausea blits (their blending needs the screen-effect pipeline).
pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, draws: &[GuiDraw]) {
let mut stack = vec![IDENTITY];
for d in draws {
let start = batch.vertices.len();
let pose = *stack.last().unwrap_or(&IDENTITY);
match d {
GuiDraw::Sprite {
sprite,
@@ -566,6 +759,7 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
w,
h,
region,
color,
} => {
let Some(mut r) = atlas.sprites.get(&format!("gui/sprites/{sprite}")).copied()
else {
@@ -580,7 +774,66 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
r.u0 = u0;
r.v0 = v0;
}
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, u32::MAX);
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, abgr(*color));
}
GuiDraw::AtlasSprite {
sprite,
x,
y,
w,
h,
color,
} => {
batch.sprite_scaled(
atlas,
sprite,
*x as f32,
*y as f32,
*w as f32,
*h as f32,
abgr(*color),
);
}
GuiDraw::Blit {
texture,
blend: Blend::Textured,
x,
y,
w,
h,
uv,
src,
tex,
color,
} => {
let Some(mut r) = atlas.sprites.get(texture.as_ref()).copied() else {
continue;
};
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
let u0 = r.u0 + du * uv[0] / tex[0] as f32;
let v0 = r.v0 + dv * uv[1] / tex[1] as f32;
r.u1 = r.u0 + du * (uv[0] + src[0] as f32) / tex[0] as f32;
r.v1 = r.v0 + dv * (uv[1] + src[1] as f32) / tex[1] as f32;
r.u0 = u0;
r.v0 = v0;
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, abgr(*color));
}
GuiDraw::Blit { .. } | GuiDraw::Item { .. } => {}
GuiDraw::Fill {
x0,
y0,
x1,
y1,
color,
} => {
batch.fill(
atlas,
*x0 as f32,
*y0 as f32,
(x1 - x0) as f32,
(y1 - y0) as f32,
abgr(*color),
);
}
GuiDraw::Text {
text,
@@ -589,11 +842,35 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
color,
shadow,
} => {
let [a, r, g, b] = color.to_be_bytes();
let rgba = crate::hud::rgba(r, g, b, a);
batch.text(atlas, text, *x as f32, *y as f32, rgba, *shadow);
batch.text_styled(atlas, text, *x as f32, *y as f32, abgr(*color), *shadow);
}
GuiDraw::Push(ops) => {
let mut m = pose;
for op in ops {
pose_apply(&mut m, *op);
}
stack.push(m);
}
GuiDraw::Pop => {
if stack.len() > 1 {
stack.pop();
}
}
}
if pose != IDENTITY {
for v in &mut batch.vertices[start..] {
let [x, y] = v.pos;
v.pos = [
pose[0] * x + pose[2] * y + pose[4],
pose[1] * x + pose[3] * y + pose[5],
];
}
GuiDraw::Item { .. } => {}
}
}
}
/// An ARGB colour as the HUD batch's packed RGBA.
pub fn abgr(color: u32) -> u32 {
let [a, r, g, b] = color.to_be_bytes();
crate::hud::rgba(r, g, b, a)
}
+899
View File
@@ -0,0 +1,899 @@
//! The `Hud` overlays 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`), the selected item name (`extractSelectedItemName`
//! and its `toolHighlightTimer`), boss bars (`BossHealthOverlay`), the jump
//! bar (`JumpableVehicleBar`), the scoreboard sidebar, item decorations
//! (`GuiGraphicsExtractor.itemDecorations`), the camera overlays and the
//! sleep overlay.
use crate::{
font::Font,
hud_layout::{
Blend, GuiDraw, PoseOp, color_from_float, 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<GuiDraw>, 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<GuiDraw>,
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<T>(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/<id>`.
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<GuiDraw> {
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<Text>,
pub subtitle: Option<Text>,
pub time: i32,
pub fade_in: i32,
pub stay: i32,
pub fade_out: i32,
pub overlay: Option<Text>,
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<GuiDraw> {
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<GuiDraw> {
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<HeldName>,
}
impl ToolHighlight {
/// The selected-item part of `Hud.tick`; `display_time` is the
/// `notificationDisplayTime` option.
pub fn tick(&mut self, selected: Option<HeldName>, 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<GuiDraw> {
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
}
}
/// 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<GuiDraw> {
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<GuiDraw>, 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<GuiDraw> {
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<Item = char>, 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<u16>, Vec<u16>) = (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<GuiDraw> {
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
}
/// What `GuiGraphicsExtractor.itemDecorations` draws over a stack.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ItemDecorations {
pub count: u32,
/// The text shown instead of the count, if any.
pub count_text: Option<String>,
/// `isBarVisible`: `getBarWidth` and `getBarColor` (RGB).
pub bar: Option<(i32, u32)>,
/// `ItemCooldowns.getCooldownPercent` of the stack.
pub cooldown: f32,
}
/// `Item.getBarWidth` and `getBarColor` for a damaged stack (`isDamaged`).
pub fn damage_bar(damage: i32, max_damage: i32) -> Option<(i32, u32)> {
if max_damage <= 0 || damage <= 0 {
return None;
}
let width = (13.0 - damage as f32 * 13.0 / max_damage as f32)
.round()
.clamp(0.0, 13.0) as i32;
let health = ((max_damage as f32 - damage as f32) / max_damage as f32).max(0.0);
Some((width, hsv_to_argb(health / 3.0, 1.0, 1.0, 0)))
}
/// `GuiGraphicsExtractor.itemDecorations` for a non-empty stack at (x, y):
/// the durability bar, the cooldown shade and the count.
pub fn item_decorations(x: i32, y: i32, d: &ItemDecorations, font: &Font) -> Vec<GuiDraw> {
let mut out = vec![GuiDraw::Push(Vec::new())];
if let Some((width, color)) = d.bar {
let (left, top) = (x + 2, y + 13);
out.push(fill(left, top, left + 13, top + 2, 0xFF00_0000));
out.push(fill(left, top, left + width, top + 1, color | 0xFF00_0000));
}
if d.cooldown > 0.0 {
let top = y + crate::hud_layout::floor(16.0 * (1.0 - d.cooldown));
let bottom = top + crate::hud_layout::ceil(16.0 * d.cooldown);
out.push(fill(x, top, x + 16, bottom, 0x7FFF_FFFF));
}
if d.count != 1 || d.count_text.is_some() {
let amount = d.count_text.clone().unwrap_or_else(|| d.count.to_string());
let w = font.width(&amount) as i32;
text(
&mut out,
Text::literal(amount),
x + 19 - 2 - w,
y + 6 + 3,
crate::hud_layout::WHITE,
true,
);
}
out.push(GuiDraw::Pop);
out
}
/// A full-screen `graphics.blit` of `textures/<texture>.png`.
fn screen_blit(
w: i32,
h: i32,
texture: impl Into<Cow<'static, str>>,
blend: Blend,
color: u32,
) -> GuiDraw {
GuiDraw::Blit {
texture: texture.into(),
blend,
x: 0,
y: 0,
w,
h,
uv: [0.0, 0.0],
src: [w, h],
tex: [w, h],
color,
}
}
/// `Hud.extractVignette`: `brightness` is `vignetteBrightness` and
/// `border_warning` the world border warning strength (0 when far).
pub fn vignette(w: i32, h: i32, brightness: f32, border_warning: f32) -> GuiDraw {
let brightness = brightness.clamp(0.0, 1.0);
let color = if border_warning > 0.0 {
let warning = border_warning.clamp(0.0, 1.0);
let red = brightness * (1.0 - warning);
let green_blue = brightness + (1.0 - brightness) * warning;
color_from_float(1.0, red, green_blue, green_blue)
} else {
color_from_float(1.0, brightness, brightness, brightness)
};
screen_blit(w, h, "misc/vignette", Blend::Vignette, color)
}
/// The border warning strength of `extractVignette` for a camera
/// `distance` from a border with `warning_blocks`, `warning_time`, its
/// `lerp_speed` and how far its size still has to move.
pub fn border_warning(
distance: f32,
warning_blocks: i32,
warning_time: i32,
lerp_speed: f64,
size_left: f64,
) -> f32 {
let moving = (lerp_speed * f64::from(warning_time)).min(size_left.abs());
let warning_distance = f64::from(warning_blocks).max(moving);
if f64::from(distance) < warning_distance {
1.0 - (f64::from(distance) / warning_distance) as f32
} else {
0.0
}
}
/// `Hud.extractSpyglassOverlay`.
pub fn spyglass(w: i32, h: i32, scale: f32) -> Vec<GuiDraw> {
let src = w.min(h) as f32;
let ratio = (w as f32 / src).min(h as f32 / src) * scale;
let width = crate::hud_layout::floor(src * ratio);
let height = crate::hud_layout::floor(src * ratio);
let left = (w - width) / 2;
let top = (h - height) / 2;
let (right, bottom) = (left + width, top + height);
vec![
GuiDraw::Blit {
texture: Cow::Borrowed("misc/spyglass_scope"),
blend: Blend::Textured,
x: left,
y: top,
w: width,
h: height,
uv: [0.0, 0.0],
src: [width, height],
tex: [width, height],
color: crate::hud_layout::WHITE,
},
fill(0, bottom, w, h, 0xFF00_0000),
fill(0, 0, w, top, 0xFF00_0000),
fill(0, top, left, bottom, 0xFF00_0000),
fill(right, top, w, bottom, 0xFF00_0000),
]
}
/// `Hud.extractPortalOverlay`: the nether portal block sprite over the screen.
pub fn portal_overlay(w: i32, h: i32, mut alpha: f32) -> GuiDraw {
if alpha < 1.0 {
alpha *= alpha;
alpha *= alpha;
alpha = alpha * 0.8 + 0.2;
}
GuiDraw::AtlasSprite {
sprite: Cow::Borrowed("block/nether_portal"),
x: 0,
y: 0,
w,
h,
color: white(alpha),
}
}
/// `Hud.extractConfusionOverlay`: the nausea swirl scaled about the centre.
pub fn confusion_overlay(w: i32, h: i32, strength: f32) -> Vec<GuiDraw> {
let size = 2.0 + strength * (1.0 - 2.0);
let (cx, cy) = (w as f32 / 2.0, h as f32 / 2.0);
vec![
GuiDraw::Push(vec![
PoseOp::Translate(cx, cy),
PoseOp::Scale(size, size),
PoseOp::Translate(-cx, -cy),
]),
screen_blit(
w,
h,
"misc/nausea",
Blend::Nausea,
color_from_float(1.0, 0.2 * strength, 0.4 * strength, 0.2 * strength),
),
GuiDraw::Pop,
]
}
/// What `Hud.extractCameraOverlays` reads.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct CameraOverlays {
/// `Options.vignette`: `vignetteBrightness` and the border warning strength.
pub vignette: Option<(f32, f32)>,
pub first_person: bool,
/// `LocalPlayer.isScoping`.
pub scoping: bool,
/// `DeltaTracker.getGameTimeDeltaTicks`.
pub game_time_delta: f32,
/// `Equippable.cameraOverlay` textures (`misc/pumpkinblur`) of the worn
/// items in `EquipmentSlot` order.
pub equipment: Vec<String>,
/// `getTicksFrozen` and `getPercentFrozen`.
pub ticks_frozen: i32,
pub percent_frozen: f32,
/// The partial tick and `oPortalEffectIntensity` / `portalEffectIntensity`.
pub partial: f32,
pub portal: [f32; 2],
/// `getEffectBlendFactor(NAUSEA, partial)` and `Options.screenEffectScale`.
pub nausea: f32,
pub screen_effect_scale: f32,
}
/// `Hud.extractCameraOverlays`, easing `scope_scale` (`Hud.scopeScale`).
pub fn camera_overlays(w: i32, h: i32, i: &CameraOverlays, scope_scale: &mut f32) -> Vec<GuiDraw> {
let mut out = Vec::new();
if let Some((brightness, warning)) = i.vignette {
out.push(vignette(w, h, brightness, warning));
}
*scope_scale += 0.5 * i.game_time_delta * (1.125 - *scope_scale);
if i.first_person {
if i.scoping {
out.extend(spyglass(w, h, *scope_scale));
} else {
*scope_scale = 0.5;
for texture in &i.equipment {
out.push(screen_blit(
w,
h,
texture.clone(),
Blend::Textured,
crate::hud_layout::WHITE,
));
}
}
}
if i.ticks_frozen > 0 {
out.push(screen_blit(
w,
h,
"misc/powder_snow_outline",
Blend::Textured,
white(i.percent_frozen),
));
}
let portal = i.portal[0] + i.partial * (i.portal[1] - i.portal[0]);
if portal > 0.0 {
out.push(portal_overlay(w, h, portal));
} else if i.nausea > 0.0 && i.screen_effect_scale < 1.0 {
out.extend(confusion_overlay(
w,
h,
i.nausea * (1.0 - i.screen_effect_scale),
));
}
out
}
/// `Hud.extractSleepOverlay`.
pub fn sleep_overlay(w: i32, h: i32, sleep_timer: i32) -> Vec<GuiDraw> {
if sleep_timer <= 0 {
return Vec::new();
}
let timer = sleep_timer as f32;
let mut amount = timer / 100.0;
if amount > 1.0 {
amount = 1.0 - (timer - 100.0) / 10.0;
}
let color = (((220.0 * amount) as i32) << 24) as u32 | 0x10_1020;
vec![fill(0, 0, w, h, color)]
}
+2
View File
@@ -6,6 +6,7 @@ pub mod ambience;
pub mod animate_tick;
pub mod assets;
pub mod atlas_sources;
pub mod attack_strength;
pub mod attribute_updates;
pub mod audio;
pub mod auto_jump;
@@ -46,6 +47,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;
+41 -48
View File
@@ -1,9 +1,10 @@
//! Full-screen camera effects drawn between the world and the HUD:
//! `ScreenEffectRenderer` (in-wall block texture, underwater overlay, fire)
//! and the `Hud` camera overlays (vignette, pumpkin blur, powder-snow
//! and the full-screen `Hud` camera overlays laid out by
//! `hud_overlays::camera_overlays` (vignette, pumpkin blur, powder-snow
//! outline, nether portal swirl). Positions are clip-space quads; textures
//! come from the shared 2D atlas and may repeat.
use crate::hud::Rect;
use crate::{hud::Rect, hud_layout::GuiDraw};
use std::collections::HashMap;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -40,14 +41,9 @@ pub struct ScreenInputs<'a> {
/// Eye in water: (lightmap brightness at the eye, yaw, pitch).
pub water: Option<(f32, f32, f32)>,
pub on_fire: bool,
/// Equipment camera overlays (`Equippable.cameraOverlay`, e.g. `misc/pumpkinblur`).
pub camera_overlays: Vec<String>,
/// `Player.getPercentFrozen`.
pub frozen: f32,
/// `Options.vignette`.
pub vignette: bool,
/// Distance to the world border and its warning distance, when close.
pub border_warning: Option<f32>,
/// `Hud.extractCameraOverlays` draws: the full-screen blits become
/// screen quads (the spyglass, its fills and the nausea swirl do not).
pub gui_overlays: &'a [GuiDraw],
}
/// Effect state advanced every tick.
@@ -170,43 +166,43 @@ impl ScreenEffects {
}),
blend,
};
if input.vignette
&& let Some(rect) = sprite("misc/vignette")
{
let b = self.vignette_brightness.clamp(0.0, 1.0);
let color = match input.border_warning {
Some(w) if w > 0.0 => {
let w = w.clamp(0.0, 1.0);
let red = b * (1.0 - w);
let gb = b + (1.0 - b) * w;
[red, gb, gb, 1.0]
let rgba = |c: u32| {
let [a, r, g, b] = c.to_be_bytes();
[r, g, b, a].map(|v| f32::from(v) / 255.0)
};
for d in input.gui_overlays {
match d {
GuiDraw::Blit {
texture,
blend,
x: 0,
y: 0,
color,
..
} if *blend != crate::hud_layout::Blend::Nausea
&& texture != "misc/spyglass_scope" =>
{
let blend = if *blend == crate::hud_layout::Blend::Vignette {
Blend::Vignette
} else {
Blend::Alpha
};
if let Some(rect) = sprite(texture) {
out.push(gui(rect, rgba(*color), blend));
}
}
_ => [b, b, b, 1.0],
};
out.push(gui(rect, color, Blend::Vignette));
}
for overlay in &input.camera_overlays {
if let Some(rect) = sprite(overlay) {
out.push(gui(rect, [1.0; 4], Blend::Alpha));
GuiDraw::AtlasSprite {
sprite: name,
color,
..
} => {
if let Some(rect) = sprite(name) {
out.push(gui(rect, rgba(*color), Blend::Alpha));
}
}
_ => {}
}
}
if input.frozen > 0.0
&& let Some(rect) = sprite("misc/powder_snow_outline")
{
out.push(gui(rect, [1.0, 1.0, 1.0, input.frozen], Blend::Alpha));
}
let portal = self.o_portal + (self.portal - self.o_portal) * input.partial;
if portal > 0.0
&& let Some(rect) = sprite("block/nether_portal")
{
let mut a = portal;
if a < 1.0 {
a *= a;
a *= a;
a = a * 0.8 + 0.2;
}
out.push(gui(rect, [1.0, 1.0, 1.0, a], Blend::Alpha));
}
out
}
}
@@ -254,10 +250,7 @@ mod tests {
block_overlay: None,
water: Some((1.0, 0.0, 0.0)),
on_fire: false,
camera_overlays: vec![],
frozen: 0.0,
vignette: true,
border_warning: None,
gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)],
};
let quads = e.build(&input);
assert_eq!(quads.len(), 1);
+16 -7
View File
@@ -475,15 +475,24 @@ 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,
background_opacity: self.text_background_opacity,
scale: self.chat_scale,
width: self.chat_width,
height_focused: self.chat_height_focused,
height_unfocused: self.chat_height_unfocused,
line_spacing: self.chat_line_spacing,
opacity: f64::from(self.chat_opacity),
background_opacity: f64::from(self.text_background_opacity),
scale: f64::from(self.chat_scale),
width: f64::from(self.chat_width),
height_focused: f64::from(self.chat_height_focused),
height_unfocused: f64::from(self.chat_height_unfocused),
line_spacing: f64::from(self.chat_line_spacing),
}
}
}
@@ -43,19 +43,22 @@ import org.joml.Matrix3x2f;
import org.joml.Matrix3x2fStack;
/**
* Original oracle for the in-game HUD decorations: runs vanilla's own Hud
* methods (extractItemHotbar, extractPlayerHealth, extractVehicleHealth,
* extractCrosshair) and ExperienceBar / ContextualBar on a stand-in client
* (Unsafe-allocated Minecraft, options, game mode, window and level) and a
* player whose state getters answer from the case, and records every
* GuiGraphicsExtractor blit, text and item call.
* Oracle for the in-game HUD: runs vanilla's own Hud methods (hotbar,
* crosshair, health, mount, experience, effects, titles and the action bar,
* the selected item name, the sidebar, camera and sleep overlays and
* Hud.tick), BossHealthOverlay, JumpableVehicleBar, ChatComponent and
* GuiGraphicsExtractor.itemDecorations on a stand-in client (Unsafe-allocated
* Minecraft, options, game mode, window and level) and a player whose state
* getters answer from the case, and records every GuiGraphicsExtractor blit,
* fill, text and item call. See tools/test_hud_parity.py for the case kinds.
*
* Input lines: case JSON. Output lines: {case, draws:[...]} or {case, error}.
* Input lines: case JSON. Output lines: {case, draws:[...], state...} or {case, error}.
*/
public final class VanillaHudOracle {
static Object unsafe;
static Method allocate;
static JsonObject c;
static Font FONT;
static IdentityHashMap<ItemStack, Integer> slots = new IdentityHashMap<>();
@SuppressWarnings("unchecked")
@@ -84,9 +87,41 @@ public final class VanillaHudOracle {
unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value);
}
static void putStatic(Class<?> owner, String name, Object value) throws Exception {
Field f = field(owner, name);
var u = unsafe.getClass();
Object base = u.getMethod("staticFieldBase", Field.class).invoke(unsafe, f);
long offset = (long) u.getMethod("staticFieldOffset", Field.class).invoke(unsafe, f);
u.getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, base, offset, value);
}
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 <T> OptionInstance<T> option(T value) throws Exception {
@SuppressWarnings("unchecked") OptionInstance<T> o = alloc(OptionInstance.class);
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);
return m;
}
/** A player whose HUD-facing getters answer from the case. */
public static final class Actor extends LocalPlayer {
@@ -94,6 +129,7 @@ public final class VanillaHudOracle {
Entity vehicle;
FoodData food;
ItemStack offhand = ItemStack.EMPTY;
List<net.minecraft.world.effect.MobEffectInstance> 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<Attribute> a) { return a == Attributes.MAX_HEALTH ? f("maxHealth", 20) : 0.0; }
@@ -101,9 +137,10 @@ public final class VanillaHudOracle {
@Override public int getArmorValue() { return i("armor", 0); }
@Override public FoodData getFoodData() { return food; }
@Override public boolean hasEffect(Holder<MobEffect> 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<net.minecraft.world.effect.MobEffectInstance> 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); }
@@ -114,6 +151,23 @@ 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 ItemStack getItemBySlot(net.minecraft.world.entity.EquipmentSlot slot) {
return slot == net.minecraft.world.entity.EquipmentSlot.HEAD && c.has("head") && !c.get("head").isJsonNull()
? new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(c.get("head").getAsString()))) : ItemStack.EMPTY;
}
@Override public int getTicksFrozen() { return i("ticksFrozen", 0); }
@Override public boolean isScoping() { return b("scoping"); }
@Override public float getEffectBlendFactor(Holder<MobEffect> effect, float partial) {
return effect.is(net.minecraft.world.effect.MobEffects.NAUSEA) ? f("nausea", 0) : 0.0F;
}
@Override public int getSleepTimer() { return i("sleepTimer", 0); }
@Override public void playSound(net.minecraft.sounds.SoundEvent sound, float volume, float pitch) { }
}
@@ -134,6 +188,16 @@ public final class VanillaHudOracle {
@Override public int guiHeight() { return i("height", 0); }
@Override public Matrix3x2fStack pose() { return stack; }
@Override public void nextStratum() { }
/** Adds the pose when it is not the identity. */
JsonObject posed(JsonObject o, org.joml.Matrix3x2fc m) {
if (!m.equals(new Matrix3x2f())) {
var a = new JsonArray();
for (float v : new float[] {m.m00(), m.m01(), m.m10(), m.m11(), m.m20(), m.m21()}) a.add(v);
o.add("matrix", a);
}
draws.add(o);
return o;
}
void sprite(Identifier id, int x, int y, int w, int h, int[] region, int color) {
var o = new JsonObject();
o.addProperty("type", "sprite");
@@ -145,20 +209,86 @@ public final class VanillaHudOracle {
o.add("region", r);
}
o.addProperty("color", color);
draws.add(o);
posed(o, stack);
}
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { sprite(id, x, y, w, h, null, color); }
@Override public void blitSprite(RenderPipeline p, Identifier id, int sw, int sh, int u, int v, int x, int y, int w, int h, int color) {
sprite(id, x, y, w, h, new int[] {sw, sh, u, v}, color);
}
@Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) {
@Override public void blitSprite(RenderPipeline p, net.minecraft.client.renderer.texture.TextureAtlasSprite s, int x, int y, int w, int h, int color) {
var o = new JsonObject();
o.addProperty("type", "atlas");
o.addProperty("sprite", s.contents().name().getPath());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
o.addProperty("color", color);
posed(o, stack);
}
@Override public void blit(RenderPipeline p, Identifier texture, int x, int y, float u, float v, int w, int h, int srcW, int srcH, int texW, int texH, int color) {
var o = new JsonObject();
o.addProperty("type", "blit");
o.addProperty("texture", texture.getPath());
o.addProperty("pipeline", p.getLocation().getPath());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
var uv = new JsonArray(); uv.add(u); uv.add(v); o.add("uv", uv);
var src = new JsonArray(); src.add(srcW); src.add(srcH); o.add("src", src);
var tex = new JsonArray(); tex.add(texW); tex.add(texH); o.add("tex", tex);
o.addProperty("color", color);
posed(o, stack);
}
@Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) {
var o = new JsonObject();
o.addProperty("type", "fill");
o.addProperty("x0", Math.min(x0, x1)); o.addProperty("y0", Math.min(y0, y1));
o.addProperty("x1", Math.max(x0, x1)); o.addProperty("y1", Math.max(y0, y1));
o.addProperty("color", color);
posed(o, stack);
}
void text(FormattedCharSequence str, int x, int y, int color, boolean shadow, org.joml.Matrix3x2fc pose) {
var o = new JsonObject();
o.addProperty("type", "text");
var sb = new StringBuilder();
str.accept((index, style, cp) -> { sb.appendCodePoint(cp); return true; });
var runs = new JsonArray();
boolean[] styled = {false};
str.accept((index, style, cp) -> {
sb.appendCodePoint(cp);
Integer rgb = style.getColor() == null ? null : style.getColor().getValue();
boolean bold = style.isBold(), italic = style.isItalic();
styled[0] |= rgb != null || bold || italic;
JsonArray last = runs.isEmpty() ? null : runs.get(runs.size() - 1).getAsJsonArray();
if (last != null && java.util.Objects.equals(last.get(1).isJsonNull() ? null : last.get(1).getAsInt(), rgb)
&& last.get(2).getAsBoolean() == bold && last.get(3).getAsBoolean() == italic) {
last.set(0, new JsonPrimitive(last.get(0).getAsString() + new String(Character.toChars(cp))));
} else {
var run = new JsonArray();
run.add(new String(Character.toChars(cp)));
if (rgb == null) run.add(JsonNull.INSTANCE); else run.add(rgb);
run.add(bold); run.add(italic);
runs.add(run);
}
return true;
});
o.addProperty("text", sb.toString());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow);
draws.add(o);
if (styled[0]) o.add("runs", runs);
posed(o, pose);
}
@Override public void text(Font font, FormattedCharSequence str, int x, int y, int color, boolean shadow) {
if (net.minecraft.util.ARGB.alpha(color) != 0) text(str, x, y, color, shadow, stack);
}
/** The chat's text collector: text at the parameters' pose and opacity. */
@Override public net.minecraft.client.gui.ActiveTextCollector textRenderer(GuiGraphicsExtractor.HoveredTextEffects effects, java.util.function.Consumer<net.minecraft.network.chat.Style> consumer) {
var self = this;
return new net.minecraft.client.gui.ActiveTextCollector() {
Parameters parameters = new Parameters(new Matrix3x2f(stack), 1.0F, null);
@Override public Parameters defaultParameters() { return parameters; }
@Override public void defaultParameters(Parameters p) { parameters = p; }
@Override public void accept(net.minecraft.client.gui.TextAlignment alignment, int anchorX, int y, Parameters p, FormattedCharSequence text) {
int left = alignment.calculateLeft(anchorX, FONT, text);
if (net.minecraft.util.ARGB.as8BitChannel(p.opacity()) != 0)
self.text(text, left, y, net.minecraft.util.ARGB.white(p.opacity()), true, p.pose());
}
@Override public void acceptScrolling(net.minecraft.network.chat.Component m, int cx, int l, int r, int t, int b, Parameters p) { }
};
}
@Override public void item(LivingEntity owner, ItemStack stack, int x, int y, int seed) {
var o = new JsonObject();
@@ -171,7 +301,11 @@ public final class VanillaHudOracle {
o.add("matrix", a);
draws.add(o);
}
@Override public void itemDecorations(Font font, ItemStack stack, int x, int y, String count) { }
/** Off for the hotbar cases (Horizon draws the decorations with the item). */
boolean realDecorations;
@Override public void itemDecorations(Font font, ItemStack stack, int x, int y, String count) {
if (realDecorations) super.itemDecorations(font, stack, x, y, count);
}
}
public static void main(String[] args) throws Exception {
@@ -180,13 +314,21 @@ public final class VanillaHudOracle {
unsafeField.setAccessible(true);
unsafe = unsafeField.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
Font font = ParityFont.create(ParityFont.resources());
Font font = FONT = ParityFont.create(ParityFont.resources());
Method hotbar = Hud.class.getDeclaredMethod("extractItemHotbar", GuiGraphicsExtractor.class, DeltaTracker.class);
Method health = Hud.class.getDeclaredMethod("extractPlayerHealth", GuiGraphicsExtractor.class);
Method vehicle = Hud.class.getDeclaredMethod("extractVehicleHealth", GuiGraphicsExtractor.class);
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 cameraOverlays = hudMethod("extractCameraOverlays", GuiGraphicsExtractor.class, DeltaTracker.class);
Method sleep = hudMethod("extractSleepOverlay", GuiGraphicsExtractor.class, DeltaTracker.class);
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);
@@ -207,6 +349,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));
@@ -219,7 +362,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());
@@ -240,17 +383,21 @@ 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);
var gui = alloc(net.minecraft.client.gui.Gui.class);
put(mc, Minecraft.class, "gui", gui);
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());
@@ -259,25 +406,197 @@ 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);
put(capture, GuiGraphicsExtractor.class, "pose", capture.stack);
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<Identifier>());
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<Identifier>());
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);
}
case "boss" -> {
var overlay = new net.minecraft.client.gui.components.BossHealthOverlay(mc);
@SuppressWarnings("unchecked") var events = (Map<UUID, net.minecraft.client.gui.components.LerpingBossEvent>)
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);
}
case "decor" -> {
var stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(c.get("item").getAsString())));
stack.setCount(i("count", 1));
stack.setDamageValue(i("damage", 0));
if (b("unbreakable")) stack.set(net.minecraft.core.component.DataComponents.UNBREAKABLE, net.minecraft.util.Unit.INSTANCE);
var cooldowns = new net.minecraft.world.item.ItemCooldowns();
put(actor, net.minecraft.world.entity.player.Player.class, "cooldowns", cooldowns);
if (c.has("cooldown") && !c.get("cooldown").isJsonNull()) {
var cd = c.getAsJsonObject("cooldown");
cooldowns.addCooldown(stack, cd.get("duration").getAsInt());
for (int n = cd.get("elapsed").getAsInt(); n > 0; n--) cooldowns.tick();
}
var timer = alloc(DeltaTracker.Timer.class);
put(timer, DeltaTracker.Timer.class, "deltaTickResidual", partial);
put(mc, Minecraft.class, "deltaTracker", timer);
capture.realDecorations = true;
capture.itemDecorations(font, stack, i("x", 0), i("y", 0), c.has("countText") ? c.get("countText").getAsString() : null);
}
case "overlays" -> {
put(options, Options.class, "vignette", option(b("vignette")));
put(options, Options.class, "cameraType", b("firstPerson") ? net.minecraft.client.CameraType.FIRST_PERSON : net.minecraft.client.CameraType.THIRD_PERSON_BACK);
put(options, Options.class, "screenEffectScale", option((double) f("screenEffectScale", 1)));
var border = new net.minecraft.world.level.border.WorldBorder();
if (c.has("border") && !c.get("border").isJsonNull()) {
var bo = c.getAsJsonObject("border");
border.setCenter(bo.get("centerX").getAsDouble(), bo.get("centerZ").getAsDouble());
border.setSize(bo.get("size").getAsDouble());
border.setWarningBlocks(bo.get("warningBlocks").getAsInt());
border.setWarningTime(bo.get("warningTime").getAsInt());
}
put(clientLevel, ClientLevel.class, "worldBorder", border);
put(mc, Minecraft.class, "level", clientLevel);
put(actor, Entity.class, "position", new net.minecraft.world.phys.Vec3(f("camX", 0), 64, f("camZ", 0)));
actor.oPortalEffectIntensity = c.getAsJsonArray("portal").get(0).getAsFloat();
actor.portalEffectIntensity = c.getAsJsonArray("portal").get(1).getAsFloat();
put(hud, Hud.class, "vignetteBrightness", f("vignetteBrightness", 1));
put(hud, Hud.class, "scopeScale", f("scopeScale", 0.5F));
// The nether portal particle sprite, as the block model set would give it.
var contents = alloc(net.minecraft.client.renderer.texture.SpriteContents.class);
put(contents, net.minecraft.client.renderer.texture.SpriteContents.class, "name", Identifier.withDefaultNamespace("block/nether_portal"));
var sprite = alloc(net.minecraft.client.renderer.texture.TextureAtlasSprite.class);
put(sprite, net.minecraft.client.renderer.texture.TextureAtlasSprite.class, "contents", contents);
var material = new net.minecraft.client.resources.model.sprite.Material.Baked(sprite, false);
var model = (net.minecraft.client.renderer.block.dispatch.BlockStateModel) Proxy.newProxyInstance(Actor.class.getClassLoader(),
new Class<?>[] {net.minecraft.client.renderer.block.dispatch.BlockStateModel.class},
(proxy, method, a) -> method.getName().equals("particleMaterial") ? material : null);
var models = alloc(net.minecraft.client.resources.model.ModelManager.class);
put(models, net.minecraft.client.resources.model.ModelManager.class, "blockStateModelSet",
new net.minecraft.client.renderer.block.BlockStateModelSet(Map.of(), model));
put(mc, Minecraft.class, "modelManager", models);
cameraOverlays.invoke(hud, capture, delta);
sleep.invoke(hud, capture, delta);
result.addProperty("scopeScale", (float) field(Hud.class, "scopeScale").get(hud));
}
case "chat" -> {
for (String o : new String[] {"chatScale", "chatWidth", "chatOpacity", "chatLineSpacing", "chatHeightUnfocused", "chatHeightFocused"})
put(options, Options.class, o, option(c.get(o).getAsDouble()));
put(options, Options.class, "chatColors", option(true));
putStatic(Minecraft.class, "instance", mc);
put(gui, net.minecraft.client.gui.Gui.class, "hud", hud);
var listener = alloc(net.minecraft.client.multiplayer.chat.ChatListener.class);
put(listener, net.minecraft.client.multiplayer.chat.ChatListener.class, "delayedMessageQueue", new ArrayDeque<>());
put(gui, net.minecraft.client.gui.Gui.class, "chatListener", listener);
var C = net.minecraft.client.gui.components.ChatComponent.class;
put(chat, C, "minecraft", mc);
put(chat, C, "allMessages", new ArrayList<>());
put(chat, C, "trimmedMessages", new ArrayList<>());
put(chat, C, "visibleMessageFilter", (java.util.function.Predicate<?>) m -> true);
for (var e : c.getAsJsonArray("messages")) {
var m = e.getAsJsonObject();
put(hud, Hud.class, "tickCount", m.get("at").getAsInt());
var text = comp(m.get("text"));
switch (m.get("tag").isJsonNull() ? "" : m.get("tag").getAsString()) {
case "system" -> chat.addClientSystemMessage(text);
case "error" -> chat.addPlayerMessage(text, null, net.minecraft.client.multiplayer.chat.GuiMessageTag.chatError());
default -> chat.addPlayerMessage(text, null, null);
}
}
chat.extractRenderState(capture, font, i("now", 0), 0, 0, net.minecraft.client.gui.components.ChatComponent.DisplayMode.BACKGROUND, false);
}
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;
+243
View File
@@ -0,0 +1,243 @@
"""Random HUD cases for test_hud_parity.py, one generator per case kind."""
EFFECTS = ['minecraft:poison', 'minecraft:wither', 'minecraft:regeneration', 'minecraft:hunger', 'minecraft:speed']
def decorations(rng, n):
max_health = rng.choice([20.0, 20.0, 6.0, 40.0, 33.0, 100.0])
health = rng.choice([max_health, round(rng.uniform(0, max_health), 2), 1.0, 0.5, 3.0])
air_max = 300
under = rng.random() < 0.3
air = rng.choice([air_max, rng.randint(-20, air_max), 0, 1, 29, 30, 31, 299]) if under or rng.random() < 0.2 else air_max
case = {
'width': rng.choice([427, 320, 480, 640, 961]), 'height': rng.choice([240, 255, 270, 360, 501]),
'gameMode': rng.choice(['survival'] * 5 + ['adventure', 'creative', 'spectator']),
'crosshair': rng.random() < 0.7,
'attackIndicator': rng.choice(['OFF', 'CROSSHAIR', 'HOTBAR']),
'attackScale': rng.choice([1.0, round(rng.random(), 3), 0.0, 0.999]),
'selected': rng.randint(0, 8), 'rightHanded': rng.random() < 0.7,
'slots': [rng.choice([None, 0, 0, 3, 5]) if rng.random() < 0.6 else None for _ in range(9)],
'offhand': rng.choice([None, None, 0, 4]), 'partial': round(rng.random(), 3),
'health': health, 'maxHealth': max_health,
'absorption': rng.choice([0.0, 0.0, 4.0, 3.5, 17.0, 40.0]),
'armor': rng.choice([0, 0, 1, 7, 20, 13]), 'food': rng.randint(0, 20),
'saturation': rng.choice([0.0, 5.0, 0.0]),
'effects': [e for e in EFFECTS if rng.random() < 0.15], 'frozen': rng.random() < 0.08,
'hardcore': rng.random() < 0.2, 'damageCooldown': rng.choice([0, 0, 10]),
'air': air, 'maxAir': air_max, 'underWater': under,
'tick': rng.randint(0, 100000), 'lastHealth': rng.randint(0, 40), 'displayHealth': rng.randint(0, 40),
'lastHealthAgo': rng.choice([0, 500, 5000]), 'healthBlinkTime': 0,
'xpProgress': rng.choice([0.0, round(rng.random(), 4), 0.999]), 'xpLevel': rng.choice([0, 1, 7, 30, 123, 4000]),
'experienceBar': rng.random() < 0.8,
}
if case['damageCooldown'] and rng.random() < 0.5:
case['healthBlinkTime'] = case['tick'] + rng.randint(1, 20)
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}
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}
# Items for the decorations: id and max damage (0 = not damageable), checked by the oracle's own stacks.
DECOR_ITEMS = [('diamond_sword', 1561), ('bow', 384), ('shield', 336), ('flint_and_steel', 64), ('elytra', 432),
('stone', 0), ('ender_pearl', 0), ('apple', 0)]
def decor(rng, n):
"""GuiGraphicsExtractor.itemDecorations: count, durability bar and cooldown shade."""
item, max_damage = rng.choice(DECOR_ITEMS)
case = {'x': rng.randint(-20, 400), 'y': rng.randint(-20, 300), 'item': item, 'maxDamage': max_damage,
'count': rng.choice([1, 1, 2, 16, 64, 99, 0, 10, 127]),
'damage': rng.choice([0, 0, 1, max_damage // 2, max_damage - 1, max_damage, rng.randint(0, max(max_damage, 1))]) if max_damage else 0,
'unbreakable': rng.random() < 0.1, 'partial': round(rng.random(), 3)}
if rng.random() < 0.4:
duration = rng.choice([1, 2, 7, 20, 100, 200])
case['cooldown'] = {'duration': duration, 'elapsed': rng.choice([0, 1, duration - 1, duration, rng.randint(0, duration)])}
if rng.random() < 0.1:
case['countText'] = rng.choice(['', '+', '1/2', 'x9'])
return case
def overlays(rng, n):
"""Camera overlays (vignette and border warning, spyglass, pumpkin, powder snow, portal, nausea) and sleep."""
case = {**screen(rng), 'vignette': rng.random() < 0.7,
'vignetteBrightness': rng.choice([1.0, 0.0, 0.5, round(rng.random(), 4), 1.3, -0.2]),
'firstPerson': rng.random() < 0.8, 'scoping': rng.random() < 0.2,
'scopeScale': rng.choice([0.5, 1.125, round(rng.uniform(0.5, 1.125), 4)]), 'partial': round(rng.random(), 3),
'head': rng.choice([None, None, 'carved_pumpkin', 'diamond_helmet']),
'ticksFrozen': rng.choice([0, 0, 0, 1, 70, 139, 140, 300]),
'portal': rng.choice([[0.0, 0.0], [0.0, 0.0], [0.0, 0.0125], [0.5, 0.5125], [1.0, 1.0], [0.05, 0.0], [round(rng.random(), 3)] * 2]),
'nausea': rng.choice([0.0, 0.0, 1.0, 0.25, round(rng.random(), 3)]),
'screenEffectScale': rng.choice([1.0, 0.0, 0.5, round(rng.random(), 3)]),
'sleepTimer': rng.choice([0, 0, 0, 1, 50, 100, 101, 105, 110, 111])}
if rng.random() < 0.4:
size = rng.choice([10.0, 50.0, 200.0, 1000.0])
case['border'] = {'centerX': rng.choice([0.0, 100.5]), 'centerZ': rng.choice([0.0, -30.25]), 'size': size,
'warningBlocks': rng.choice([0, 5, 20, 100]), 'warningTime': rng.choice([0, 15])}
case['camX'] = round(rng.uniform(-150, 250), 2)
case['camZ'] = round(rng.uniform(-150, 150), 2)
return case
WORDS = ['hello', 'world', 'a', 'Minecraft', 'supercalifragilisticexpialidocious', 'x' * 70, 'ok!', 'Ünïcödé', '★', '']
def chat_text(rng):
words = [rng.choice(WORDS) for _ in range(rng.choice([1, 2, 5, 12, 30]))]
text = rng.choice([' ', ' ', ' ', ' ', '\n']).join(words)
if rng.random() < 0.1:
text = rng.choice([' ', '\n']) + text + rng.choice(['', ' ', '\n'])
if rng.random() < 0.3:
cut = rng.randint(0, len(text))
return [{'text': text[:cut], 'color': rng.choice(['red', 'gold', 'aqua'])},
{'text': text[cut:], 'bold': rng.random() < 0.5, 'italic': rng.random() < 0.3}]
return {'text': text}
def chat(rng, n):
"""Messages wrapped to the chat width and fading 200 ticks after they arrive."""
count = rng.choice([1, 2, 5, 10, 30, 120])
now = rng.randint(200, 2000)
messages = []
for _ in range(count):
at = rng.choice([now, now - 1, now - 179, now - 180, now - 190, now - 199, now - 200, now - 500, rng.randint(now - 260, now + 5)])
messages.append({'text': chat_text(rng), 'at': at, 'tag': rng.choice([None, None, 'system', 'error'])})
messages.sort(key=lambda m: m['at'])
return {**screen(rng), 'now': now, 'messages': messages,
'chatScale': rng.choice([1.0, 1.0, 0.5, 0.0 + 0.75, 0.25]), 'chatWidth': rng.choice([1.0, 1.0, 0.5, 0.0, 0.3]),
'chatOpacity': rng.choice([1.0, 0.5, 0.0, 0.25]), 'textOpacity': rng.choice([0.5, 0.0, 1.0, 0.25]),
'chatLineSpacing': rng.choice([0.0, 0.0, 0.5, 1.0, 0.25]), 'chatHeightUnfocused': rng.choice([70 / 160, 1.0, 0.0, 0.5]),
'chatHeightFocused': 1.0}
# 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,
'decor': decor,
'overlays': overlays,
'chat': chat,
}
+81 -54
View File
@@ -1,15 +1,31 @@
#!/usr/bin/env python3
"""Compare the in-game HUD decorations with the vanilla 26.3 client's Hud.
"""Compare the in-game HUD with the vanilla 26.3 client's Hud.
The Java oracle (VanillaHudOracle) runs vanilla's own Hud.extractCrosshair,
extractItemHotbar, extractPlayerHealth, extractVehicleHealth, ExperienceBar
and ContextualBar.extractExperienceLevel on a stand-in client whose player
answers from the case, and records every blit (sprite, position, size,
partial region), text call (string, position, colour, shadow) and hotbar
item (slot, position, seed, pose). `examples/hud_fixture` lays out the same
state with `horizon_client::hud_layout`; the ordered call lists must agree.
The Java oracle (VanillaHudOracle) runs vanilla's own code on a stand-in
client whose player answers from the case, and records every
GuiGraphicsExtractor blit (sprite, texture, position, size, region, colour,
pose), fill, text call (string, style runs, position, colour, shadow, pose)
and hotbar item (slot, position, seed, pose). `examples/hud_fixture` lays
out the same state with `horizon_client::hud_layout`, `hud_overlays` and
`chat`; the ordered call lists (and any state read back) must agree.
test_hud_parity.py [--count N] [--detail N]
Case kinds (`tools/hud_parity_cases.py`), drawn round-robin:
decorations extractCrosshair, extractItemHotbar, extractPlayerHealth,
extractVehicleHealth, ExperienceBar and the level
effects extractEffects (MobEffectInstance order, blinking icons)
title setTitle/setTimes/setOverlayMessage and Hud.tick, then
extractOverlayMessage and extractTitle (fades, backdrops)
selected Hud.tick's tool highlight, then extractSelectedItemName
boss BossHealthOverlay
jump JumpableVehicleBar
sidebar displayScoreboardSidebar (teams, number formats)
decor GuiGraphicsExtractor.itemDecorations (count, bar, cooldown)
overlays extractCameraOverlays (vignette, spyglass and scopeScale,
pumpkin, powder snow, portal, nausea) and extractSleepOverlay
chat ChatComponent: wrapping (StringSplitter, indents), fades,
tags, scale, width, height and spacing options
test_hud_parity.py [--count N] [--detail N] [--kind K]
"""
import argparse
import json
@@ -20,62 +36,69 @@ import sys
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
from .hud_parity_cases import KINDS
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
from hud_parity_cases import KINDS
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
EFFECTS = ['minecraft:poison', 'minecraft:wither', 'minecraft:regeneration', 'minecraft:hunger', 'minecraft:speed']
def cases(count):
def cases(count, kinds):
rng = random.Random(0x485544)
out = []
for n in range(count):
max_health = rng.choice([20.0, 20.0, 6.0, 40.0, 33.0, 100.0])
health = rng.choice([max_health, round(rng.uniform(0, max_health), 2), 1.0, 0.5, 3.0])
air_max = 300
under = rng.random() < 0.3
air = rng.choice([air_max, rng.randint(-20, air_max), 0, 1, 29, 30, 31, 299]) if under or rng.random() < 0.2 else air_max
case = {
'width': rng.choice([427, 320, 480, 640, 961]), 'height': rng.choice([240, 255, 270, 360, 501]),
'gameMode': rng.choice(['survival'] * 5 + ['adventure', 'creative', 'spectator']),
'crosshair': rng.random() < 0.7,
'attackIndicator': rng.choice(['OFF', 'CROSSHAIR', 'HOTBAR']),
'attackScale': rng.choice([1.0, round(rng.random(), 3), 0.0, 0.999]),
'selected': rng.randint(0, 8), 'rightHanded': rng.random() < 0.7,
'slots': [rng.choice([None, 0, 0, 3, 5]) if rng.random() < 0.6 else None for _ in range(9)],
'offhand': rng.choice([None, None, 0, 4]), 'partial': round(rng.random(), 3),
'health': health, 'maxHealth': max_health,
'absorption': rng.choice([0.0, 0.0, 4.0, 3.5, 17.0, 40.0]),
'armor': rng.choice([0, 0, 1, 7, 20, 13]), 'food': rng.randint(0, 20),
'saturation': rng.choice([0.0, 5.0, 0.0]),
'effects': [e for e in EFFECTS if rng.random() < 0.15], 'frozen': rng.random() < 0.08,
'hardcore': rng.random() < 0.2, 'damageCooldown': rng.choice([0, 0, 10]),
'air': air, 'maxAir': air_max, 'underWater': under,
'tick': rng.randint(0, 100000), 'lastHealth': rng.randint(0, 40), 'displayHealth': rng.randint(0, 40),
'lastHealthAgo': rng.choice([0, 500, 5000]), 'healthBlinkTime': 0,
'xpProgress': rng.choice([0.0, round(rng.random(), 4), 0.999]), 'xpLevel': rng.choice([0, 1, 7, 30, 123, 4000]),
'experienceBar': rng.random() < 0.8,
}
if case['damageCooldown'] and rng.random() < 0.5:
case['healthBlinkTime'] = case['tick'] + rng.randint(1, 20)
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)
kind = kinds[n % len(kinds)]
case = KINDS[kind](rng, n)
case['kind'] = kind
out.append(case)
return out
def close(p, q):
if (isinstance(p, float) or isinstance(q, float)) and not isinstance(p, bool) and not isinstance(q, bool):
return abs(p - q) <= 1e-4 * (1 + abs(p))
return p == q
IDENTITY = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
def normal(d):
d = dict(d)
d.setdefault('matrix', IDENTITY)
if d['type'] == 'sprite':
d.setdefault('region', None)
if d['type'] == 'text':
d.setdefault('runs', None)
return d
def same(x, y):
if x.keys() != y.keys():
return False
for k in x:
p, q = x[k], y[k]
if isinstance(p, list) and isinstance(q, list):
if len(p) != len(q) or not all(close(a, b) for a, b in zip(p, q)):
return False
elif not close(p, q):
return False
return True
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=600)
parser.add_argument('--count', type=int, default=2200)
parser.add_argument('--detail', type=int, default=3)
parser.add_argument('--kind', action='append', choices=sorted(KINDS), help='only these kinds (repeatable)')
args = parser.parse_args()
kinds = args.kind or list(KINDS)
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-hud-parity'; build.mkdir(parents=True, exist_ok=True)
resources = lab.LOCAL / 'horizon-client' / '26.3'
chosen = cases(args.count)
chosen = cases(args.count, kinds)
inputs = build / 'inputs.jsonl'; inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
classes = build / 'classes'; classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
@@ -95,27 +118,31 @@ def main():
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust)
errors, bad = [], []
totals = {}
for v, r in zip(vanilla, rust):
kind = v['case']['kind']
totals.setdefault(kind, [0, 0])[1] += 1
if 'error' in v:
errors.append(v['error']); continue
a = [{k: x for k, x in d.items() if k != 'color' or d['type'] == 'text'} for d in v['draws']]
for d in a:
if d['type'] == 'sprite':
d.setdefault('region', None)
b = r['draws']
def same(x, y):
if x.keys() != y.keys():
return False
return all(
(all(abs(p - q) <= 1e-4 * (1 + abs(p)) for p, q in zip(x[k], y[k])) if k == 'matrix' else x[k] == y[k]) for k in x)
a = [normal(d) for d in v['draws']]
b = [normal(d) for d in r['draws']]
# State the case reads back besides the draws.
for key in v.keys() - {'case', 'draws'}:
if key not in r or not close(v[key], r[key]):
a = a + [{'type': 'state', key: v[key]}]
b = b + [{'type': 'state', key: r.get(key)}]
if len(a) != len(b) or not all(same(x, y) for x, y in zip(a, b)):
first = next((i for i, (x, y) in enumerate(zip(a, b)) if not same(x, y)), min(len(a), len(b)))
bad.append((v['case'], first, a[first:first + 2], b[first:first + 2], len(a), len(b)))
else:
totals[kind][0] += 1
for e in sorted(set(errors))[:5]:
print('ORACLE ERROR', e)
for case, i, a, b, la, lb in bad[:args.detail]:
print('MISMATCH', json.dumps(case))
print(f' at call {i} ({la} vanilla, {lb} Horizon calls)\n vanilla {a}\n horizon {b}')
for kind, (ok, n) in sorted(totals.items()):
print(f' {kind:12} {ok}/{n}')
print(f'{len(vanilla) - len(bad) - len(errors)}/{len(vanilla)} HUD states match; {len(errors)} oracle errors')
if bad or errors:
sys.exit(1)