Compare the chat with vanilla's ChatComponent
The chat cases add messages (with the system and error tags) at given Hud ticks and draw ChatComponent in background mode: wrapping, the 200-tick fade, scale, width, height, spacing and opacity options. Horizon's chat now wraps like StringSplitter.splitLines and ComponentRenderUtils.wrapComponents (the indent on wrapped lines, breaks at the last space, a dropped newline or space), keeps the options as doubles and draws through a layout with vanilla's fills and text offsets. A component list whose first part has empty text now still passes its style to the rest. The harness runs 200 cases per kind. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
//! The overlay case kinds of the HUD parity fixture.
|
||||
use horizon_client::{
|
||||
brewing, component,
|
||||
brewing,
|
||||
chat::{Chat, ChatOptions},
|
||||
component,
|
||||
hud::HudAtlas,
|
||||
hud_layout::{self, GuiDraw},
|
||||
hud_overlays::{
|
||||
@@ -46,6 +48,7 @@ pub fn run(
|
||||
"sidebar" => sidebar(c, w, h, atlas),
|
||||
"decor" => decor(c, atlas),
|
||||
"overlays" => overlays(c, w, h, state),
|
||||
"chat" => chat(c, h, atlas),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -289,3 +292,35 @@ fn overlays(c: &Value, w: i32, h: i32, state: &mut serde_json::Map<String, Value
|
||||
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)
|
||||
}
|
||||
|
||||
+124
-110
@@ -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> {
|
||||
|
||||
@@ -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()),
|
||||
|
||||
@@ -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> {
|
||||
|
||||
@@ -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,9 +1,8 @@
|
||||
//! 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, the experience and jump bars, status effect icons, camera
|
||||
//! overlays, titles and the action bar, the selected item name, boss bars,
|
||||
//! the scoreboard sidebar, chat and item decorations. Computed without
|
||||
//! 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};
|
||||
@@ -190,6 +189,11 @@ 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
|
||||
@@ -585,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> {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
//! The `Hud` overlays above the hotbar and decorations, laid out as
|
||||
//! [`GuiDraw`] calls like [`crate::hud_layout`]: status effect icons
|
||||
//! (`extractEffects`), titles and the action bar (`extractTitle`,
|
||||
//! `extractOverlayMessage` and the title timers of `Hud.tick`), and the
|
||||
//! selected item name (`extractSelectedItemName` and its `toolHighlightTimer`).
|
||||
//! 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::{
|
||||
@@ -635,12 +638,6 @@ pub fn sidebar(
|
||||
out
|
||||
}
|
||||
|
||||
/// `Mth.ceil`.
|
||||
fn ceil(x: f32) -> i32 {
|
||||
let i = x as i32;
|
||||
if x > i as f32 { i + 1 } else { i }
|
||||
}
|
||||
|
||||
/// What `GuiGraphicsExtractor.itemDecorations` draws over a stack.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ItemDecorations {
|
||||
@@ -676,7 +673,7 @@ pub fn item_decorations(x: i32, y: i32, d: &ItemDecorations, font: &Font) -> Vec
|
||||
}
|
||||
if d.cooldown > 0.0 {
|
||||
let top = y + crate::hud_layout::floor(16.0 * (1.0 - d.cooldown));
|
||||
let bottom = top + ceil(16.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() {
|
||||
|
||||
@@ -486,13 +486,13 @@ impl Settings {
|
||||
}
|
||||
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,14 +43,16 @@ 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;
|
||||
@@ -85,6 +87,14 @@ 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(); }
|
||||
@@ -385,7 +395,8 @@ public final class VanillaHudOracle {
|
||||
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledWidth", i("width", 0));
|
||||
put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledHeight", i("height", 0));
|
||||
put(mc, Minecraft.class, "window", window);
|
||||
put(mc, Minecraft.class, "gui", alloc(net.minecraft.client.gui.Gui.class));
|
||||
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);
|
||||
@@ -558,6 +569,32 @@ public final class VanillaHudOracle {
|
||||
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());
|
||||
}
|
||||
result.add("draws", capture.draws);
|
||||
|
||||
@@ -196,6 +196,38 @@ def overlays(rng, n):
|
||||
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,
|
||||
@@ -207,4 +239,5 @@ KINDS = {
|
||||
'sidebar': sidebar,
|
||||
'decor': decor,
|
||||
'overlays': overlays,
|
||||
'chat': chat,
|
||||
}
|
||||
|
||||
+23
-15
@@ -1,21 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the in-game HUD with the vanilla 26.3 client's Hud.
|
||||
|
||||
The Java oracle (VanillaHudOracle) runs vanilla's own Hud methods
|
||||
(extractCrosshair, extractItemHotbar, extractPlayerHealth,
|
||||
extractVehicleHealth, extractEffects, extractCameraOverlays, extractTitle,
|
||||
extractOverlayMessage, extractSelectedItemName, the scoreboard sidebar and
|
||||
Hud.tick), BossHealthOverlay, ChatComponent, the contextual bars and
|
||||
GuiGraphicsExtractor.itemDecorations on a stand-in client whose player
|
||||
answers from the case, and records every 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`; 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.
|
||||
|
||||
Each case has a `kind` (decorations, effects, title, selected, boss,
|
||||
sidebar, jump, decor, overlays, chat); timing kinds replay events tick by
|
||||
tick (title fades, the action bar, the selected item name, chat fades).
|
||||
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]
|
||||
"""
|
||||
@@ -81,7 +89,7 @@ def same(x, y):
|
||||
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user