From b5c0bf7859fcab6f5ecb6ae704eecd9bbd6603e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 12 Oct 2026 17:38:25 +0200 Subject: [PATCH] Draw the loom and crafter screens as the vanilla client does LoomScreen.extractBackground (slot icons, scroller, pattern buttons with their swatches and tooltip, the result banner or the six-layer error) and CrafterScreen's background, disabled slots and redstone arrow become screen_layout calls the game paints. A new harness runs vanilla's screens on stand-in menus and compares 1,600 call lists. Co-Authored-By: Claude Opus 5.5 --- .../examples/screen_layout_fixture.rs | 138 +++++++++ crates/horizon-client/src/game/loom.rs | 239 ++++++++------- .../src/game/machines/crafter.rs | 55 ++-- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/screen_layout.rs | 265 ++++++++++++++++ .../parity/VanillaLoomScreenOracle.java | 282 ++++++++++++++++++ tools/test_screen_layout_parity.py | 119 ++++++++ 7 files changed, 963 insertions(+), 136 deletions(-) create mode 100644 crates/horizon-client/examples/screen_layout_fixture.rs create mode 100644 crates/horizon-client/src/screen_layout.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLoomScreenOracle.java create mode 100644 tools/test_screen_layout_parity.py diff --git a/crates/horizon-client/examples/screen_layout_fixture.rs b/crates/horizon-client/examples/screen_layout_fixture.rs new file mode 100644 index 000000000..f364037ab --- /dev/null +++ b/crates/horizon-client/examples/screen_layout_fixture.rs @@ -0,0 +1,138 @@ +//! Loom and crafter screen drawing for tools/test_screen_layout_parity.py: +//! reads one JSON case per line and prints the `horizon_client::screen_layout` +//! calls in the format of `VanillaLoomScreenOracle`. +//! +//! usage: screen_layout_fixture RESOURCES INPUT OUTPUT +use horizon_client::{ + banner::{BannerLayer, Banners, banner_color}, + screen_layout::{self, CrafterView, LoomView, ScreenDraw}, +}; +use serde_json::{Value, json}; +use std::{fs, path::Path, sync::Arc}; + +fn draw_json(d: &ScreenDraw) -> Value { + let round = |v: f32| ((v * 1e6).round() / 1e6) as f64; + match d { + ScreenDraw::Gradient { x1, y1 } => json!({"t": "gradient", "x1": x1, "y1": y1}), + ScreenDraw::Blit { + texture, + x, + y, + w, + h, + tw, + th, + } => { + json!({"t": "blit", "texture": texture, "x": x, "y": y, "w": w, "h": h, "u": 0.0, "v": 0.0, "tw": tw, "th": th}) + } + ScreenDraw::Sprite { id, x, y, w, h } => { + json!({"t": "sprite", "id": id, "x": x, "y": y, "w": w, "h": h}) + } + ScreenDraw::Banner { + base, + layers, + x0, + y0, + x1, + y1, + } => { + let layers: Vec = layers + .iter() + .map(|l| json!([&*l.pattern, &*l.color])) + .collect(); + json!({"t": "banner", "base": base, "layers": layers, "x0": x0, "y0": y0, "x1": x1, "y1": y1}) + } + ScreenDraw::Tooltip { key } => json!({"t": "tooltip", "key": key}), + ScreenDraw::SpriteOf { id } => { + json!({"t": "sprite_of", "id": id.trim_start_matches("minecraft:")}) + } + ScreenDraw::Fill { + x0, + y0, + x1, + y1, + color, + } => json!({"t": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color}), + ScreenDraw::Atlas { x0, y0, x1, y1, uv } => json!({ + "t": "atlas", "x0": x0, "y0": y0, "x1": x1, "y1": y1, + "u0": round(uv[0]), "u1": round(uv[1]), "v0": round(uv[2]), "v1": round(uv[3]) + }), + } +} + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: screen_layout_fixture RESOURCES INPUT OUTPUT"; + let banners = Banners::load(Path::new(args.get(1).ok_or(usage)?)); + let input = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let mut out = String::new(); + for line in input.lines().filter(|l| !l.trim().is_empty()) { + let c: Value = serde_json::from_str(line)?; + let int = |k: &str| c[k].as_i64().unwrap_or(0) as i32; + let draws = if c["screen"] == "loom" { + let patterns: Vec> = c["patterns"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| p.as_str().map(Arc::from)) + .collect(); + let layers: Vec = c["resultLayers"] + .as_array() + .into_iter() + .flatten() + .map(|l| BannerLayer::new(l[0].as_str().unwrap_or(""), l[1].as_str().unwrap_or(""))) + .collect(); + let base = c["result"] + .as_str() + .and_then(banner_color) + .unwrap_or("white"); + let dye = c["dyeStack"] + .as_str() + .and_then(|d| d.strip_prefix("minecraft:")?.strip_suffix("_dye")) + .unwrap_or("white"); + let view = LoomView { + width: int("width"), + height: int("height"), + left: int("left"), + top: int("top"), + has_banner: c["banner"].is_string(), + has_dye: c["dye"].is_string(), + has_pattern: c["pattern"].is_string(), + patterns: &patterns, + selected: int("selected"), + display: c["display"].as_bool().unwrap_or(false), + has_max: c["hasMax"].as_bool().unwrap_or(false), + scroll: c["scroll"].as_f64().unwrap_or(0.0) as f32, + start_row: int("startRow") as usize, + result: c.get("resultLayers").map(|_| (base, layers.as_slice())), + dye, + mouse: (int("mouseX") as f32, int("mouseY") as f32), + }; + screen_layout::loom(&view, &banners) + } else { + let mut disabled = [false; 9]; + for (i, d) in c["disabled"] + .as_array() + .into_iter() + .flatten() + .enumerate() + .take(9) + { + disabled[i] = d.as_bool().unwrap_or(false); + } + screen_layout::crafter(&CrafterView { + width: int("width"), + height: int("height"), + left: int("left"), + top: int("top"), + disabled, + powered: c["powered"].as_bool().unwrap_or(false), + }) + }; + let list: Vec = draws.iter().map(draw_json).collect(); + out += &json!({ "draws": list }).to_string(); + out.push('\n'); + } + fs::write(args.get(3).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index 561713d8a..759d6e0da 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -7,6 +7,7 @@ use horizon_client::{ banner::{self, BannerLayer}, hud::{HudBatch, Rect, rgba}, items::ItemStack, + screen_layout::{self, LoomView, ScreenDraw}, }; use std::sync::Arc; @@ -32,9 +33,6 @@ impl LoomState { fn offscreen_rows(&self) -> i32 { self.total_rows() as i32 - 4 } - fn scroll_active(&self) -> bool { - self.display && self.patterns.len() > 16 - } /// `startRow` for a scroller position. fn row_for(&self, offs: f32) -> usize { ((offs * self.offscreen_rows() as f32 + 0.5) as i32).max(0) as usize @@ -209,8 +207,116 @@ impl Game<'_> { ); } } - /// `LoomScreen.extractBackground` after the background; returns the - /// pattern name tooltip of the hovered button. + /// Paints `screen_layout` calls at the menu origin (ox, oy): the container + /// background and the dimmed world are drawn by the caller. + pub(super) fn paint_screen( + &self, + batch: &mut HudBatch, + ox: f32, + oy: f32, + draws: &[ScreenDraw], + background: bool, + ) -> Option> { + let atlas = &self.res.atlas; + let mut tooltip = None; + let mut sheet: Option = None; + for d in draws { + match d { + ScreenDraw::Gradient { .. } => {} + ScreenDraw::Blit { + texture, + x, + y, + w, + h, + tw, + th, + } => { + if background { + let name = texture + .trim_start_matches("textures/") + .trim_end_matches(".png"); + batch.sprite_region( + atlas, + name, + [ox + *x as f32, oy + *y as f32, *w as f32, *h as f32], + *tw as f32, + *th as f32, + ); + } + } + ScreenDraw::Sprite { id, x, y, .. } => batch.sprite( + atlas, + &format!("gui/sprites/{id}"), + ox + *x as f32, + oy + *y as f32, + ), + ScreenDraw::Banner { + base, + layers, + x0, + y0, + x1, + y1, + } => self.draw_flag( + batch, + [ + ox + *x0 as f32, + oy + *y0 as f32, + (x1 - x0) as f32, + (y1 - y0) as f32, + ], + base, + layers, + ), + ScreenDraw::Tooltip { key } => { + tooltip = Some(vec![(self.translate(key, key), u32::MAX)]); + } + ScreenDraw::SpriteOf { id } => sheet = Some(id.clone()), + ScreenDraw::Fill { + x0, + y0, + x1, + y1, + color, + } => { + let c = *color as u32; + batch.fill( + atlas, + ox + *x0 as f32, + oy + *y0 as f32, + (x1 - x0) as f32, + (y1 - y0) as f32, + rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, (c >> 24) as u8), + ); + } + ScreenDraw::Atlas { x0, y0, x1, y1, uv } => { + if let Some(r) = sheet.as_ref().and_then(|n| atlas.sprites.get(n)).copied() { + let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0); + let part = Rect { + u0: r.u0 + uv[0] * du, + u1: r.u0 + uv[1] * du, + v0: r.v0 + uv[2] * dv, + v1: r.v0 + uv[3] * dv, + w: (x1 - x0) as u32, + h: (y1 - y0) as u32, + }; + batch.rect_uv( + ox + *x0 as f32, + oy + *y0 as f32, + (x1 - x0) as f32, + (y1 - y0) as f32, + part, + u32::MAX, + ); + } + } + } + } + tooltip + } + /// `LoomScreen.extractBackground` after the background (the verified + /// `screen_layout::loom`); returns the hovered pattern's tooltip. pub(super) fn draw_loom( &mut self, batch: &mut HudBatch, @@ -220,102 +326,35 @@ impl Game<'_> { ) -> Option> { let s = self.station.as_ref()?; let l = &s.loom; - let atlas = &self.res.atlas; - for (i, icon) in ["banner", "dye", "banner_pattern"].iter().enumerate() { - if s.inputs[i].is_none() { - let pos = [(13.0, 26.0), (33.0, 26.0), (23.0, 45.0)][i]; - batch.sprite( - atlas, - &format!("gui/sprites/container/slot/{icon}"), - ox + pos.0, - oy + pos.1, - ); - } - } - let scroller = if l.scroll_active() { - "scroller" - } else { - "scroller_disabled" - }; - batch.sprite( - atlas, - &format!("gui/sprites/container/loom/{scroller}"), - ox + 119.0, - oy + 13.0 + (41.0 * l.scroll).floor(), - ); - let result = s.result.clone(); - let (display, has_max, start_row, selected) = - (l.display, l.has_max, l.start_row, l.selected); - let patterns = l.patterns.clone(); let dye = s.inputs[1] .as_ref() - .and_then(|d| self.res.stations.banners.loom_dye(&self.res.items, d)) - .unwrap_or_else(|| Arc::from("white")); - if let Some(result) = result.filter(|_| !has_max) - && let Some(base) = banner::banner_color(&result.item) - { - self.draw_flag( - batch, - [ox + 141.0, oy + 8.0, 20.0, 40.0], - base, - banner::layers(&result), - ); - } else if has_max { - batch.sprite( - &self.res.atlas, - "gui/sprites/container/loom/error", - ox + 138.0, - oy + 52.0, - ); - } - let mut tooltip = None; - if display { - let atlas = &self.res.atlas; - for row in 0..4 { - for column in 0..4 { - let index = (row + start_row) * 4 + column; - let Some(pattern) = patterns.get(index) else { - return tooltip; - }; - let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); - let hover = inside(local, x, y, BUTTON, BUTTON); - let sprite = if selected == Some(index) { - "pattern_selected" - } else if hover { - let key = self - .res - .stations - .banners - .layer_key(&BannerLayer::new(pattern, &dye)); - tooltip = Some(vec![(self.translate(&key, &key), u32::MAX)]); - "pattern_highlighted" - } else { - "pattern" - }; - batch.sprite( - atlas, - &format!("gui/sprites/container/loom/{sprite}"), - ox + x, - oy + y, - ); - // extractBannerOnButton: a 5x10 grey cloth with the pattern. - batch.fill( - atlas, - ox + x + 4.0, - oy + y + 2.0, - 5.0, - 10.0, - dye_color("gray"), - ); - let texture = self.res.stations.banners.banner_texture(pattern); - if let Some(r) = atlas.sprites.get(&texture).copied() { - let uv = sub_rect(r, [0.0, 1.0, 21.0, 40.0]); - batch.rect_uv(ox + x + 4.0, oy + y + 2.0, 5.0, 10.0, uv, u32::MAX); - } - } - } - } - tooltip + .and_then(|d| self.res.items.get(&d.item)) + .and_then(|i| i.dye.clone()) + .unwrap_or_else(|| "white".to_owned()); + let result = s + .result + .as_ref() + .and_then(|r| Some((banner::banner_color(&r.item)?, banner::layers(r)))); + let view = LoomView { + width: 176, + height: 166, + left: 0, + top: 0, + has_banner: s.inputs[0].is_some(), + has_dye: s.inputs[1].is_some(), + has_pattern: s.inputs[2].is_some(), + patterns: &l.patterns, + selected: l.selected.map_or(-1, |i| i as i32), + display: l.display, + has_max: l.has_max, + scroll: l.scroll, + start_row: l.start_row, + result, + dye: &dye, + mouse: local, + }; + let draws = screen_layout::loom(&view, &self.res.stations.banners); + self.paint_screen(batch, ox, oy, &draws, false) } } @@ -334,7 +373,6 @@ mod tests { }; // 40 patterns = 10 rows, 6 off screen. assert_eq!(l.offscreen_rows(), 6); - assert!(l.scroll_active()); assert_eq!(l.row_for(0.0), 0); assert_eq!(l.row_for(1.0), 6); assert_eq!(l.row_for(0.5), 3); @@ -348,7 +386,6 @@ mod tests { display: true, ..Default::default() }; - assert!(!l.scroll_active()); assert_eq!(l.offscreen_rows(), 0); } } diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 32b28ad70..bd103bdfc 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -232,57 +232,42 @@ impl Game<'_> { _ => None, } } - /// `CrafterScreen`'s background, title, disabled slots and powered arrow. + /// `CrafterScreen`'s background, disabled slots and powered arrow (the + /// verified `screen_layout::crafter`) and its centred title. pub(in crate::game) fn draw_crafter_screen(&self, batch: &mut HudBatch, ox: f32, oy: f32) { let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else { return; }; + let powered = self + .container + .map(|k| self.world.block(k.0, k.1, k.2)) + .is_some_and(|state| self.containers().prop(state, "triggered") == Some("true")); + let draws = + horizon_client::screen_layout::crafter(&horizon_client::screen_layout::CrafterView { + width: 176, + height: 166, + left: 0, + top: 0, + disabled: c.disabled, + powered, + }); + // The background goes first, then the labels, then the slot decorations. + let (background, rest) = draws.split_at(2.min(draws.len())); + self.paint_screen(batch, ox, oy, background, true); let atlas = &self.res.atlas; - batch.sprite_region( - atlas, - "gui/container/crafter", - [ox, oy, 176.0, 166.0], - 256.0, - 256.0, - ); let grey = rgba(64, 64, 64, 255); let title = self.container_title(self.translate("container.crafter", "Crafter")); let tw = HudBatch::text_width(atlas, &title); batch.text( atlas, &title, - ox + (176.0 - tw) / 2.0, + ox + ((176.0 - tw) / 2.0).trunc(), oy + 6.0, grey, false, ); batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false); - for slot in 0..9 { - if c.disabled[slot] { - let (x, y) = self.crafter_slot_position(300 + slot).unwrap_or_default(); - batch.sprite( - atlas, - "gui/sprites/container/crafter/disabled_slot", - ox + x - 1.0, - oy + y - 1.0, - ); - } - } - let powered = self - .container - .map(|k| self.world.block(k.0, k.1, k.2)) - .is_some_and(|state| self.containers().prop(state, "triggered") == Some("true")); - let arrow = if powered { - "powered_redstone" - } else { - "unpowered_redstone" - }; - batch.sprite( - atlas, - &format!("gui/sprites/container/crafter/{arrow}"), - ox + 97.0, - oy + 35.0, - ); + self.paint_screen(batch, ox, oy, rest, true); } /// `gui.togglable_slot` over an empty, enabled grid slot. pub(in crate::game) fn crafter_tooltip(&self, slot: usize) -> Option { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index c3b63dca8..beb39729e 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -87,6 +87,7 @@ pub mod save; pub mod scoreboard; pub mod scoreboard_cmd; pub mod screen_effects; +pub mod screen_layout; pub mod sculk; pub mod settings; pub mod shadows; diff --git a/crates/horizon-client/src/screen_layout.rs b/crates/horizon-client/src/screen_layout.rs new file mode 100644 index 000000000..c627e6b4a --- /dev/null +++ b/crates/horizon-client/src/screen_layout.rs @@ -0,0 +1,265 @@ +//! The loom and crafter screens' own drawing as `GuiGraphicsExtractor` calls: +//! `LoomScreen.extractBackground` (slot icons, the scroller, the pattern +//! buttons with their banner swatches and tooltip, the result banner or the +//! six-layer error) and `CrafterScreen`'s background, disabled slots and +//! redstone arrow. Computed without drawing so `tools/test_screen_layout_parity.py` +//! can compare them with the vanilla client; the game paints the same calls. +use crate::banner::{self, BannerLayer, Banners}; +use std::sync::Arc; + +/// One call a screen makes. +#[derive(Clone, Debug, PartialEq)] +pub enum ScreenDraw { + /// `fillGradient(0, 0, width, height, ..)`: the dimmed world behind a menu. + Gradient { x1: i32, y1: i32 }, + /// `blit(texture, x, y, 0, 0, w, h, tw, th)`: a container background. + Blit { + texture: &'static str, + x: i32, + y: i32, + w: i32, + h: i32, + tw: i32, + th: i32, + }, + /// `blitSprite(sprite, x, y, w, h)` of a GUI sprite. + Sprite { + id: String, + x: i32, + y: i32, + w: i32, + h: i32, + }, + /// `bannerPattern(flag, base, layers, x0, y0, x1, y1)`: the result preview. + Banner { + base: String, + layers: Vec, + x0: i32, + y0: i32, + x1: i32, + y1: i32, + }, + /// `setTooltipForNextFrame` with a translation key. + Tooltip { key: String }, + /// `getSprite(id)`: the atlas sprite the following `Atlas` blit uses. + SpriteOf { id: String }, + /// `fill(x0, y0, x1, y1, argb)`. + Fill { + x0: i32, + y0: i32, + x1: i32, + y1: i32, + color: i32, + }, + /// `blit(atlas, x0, y0, x1, y1, u0, u1, v0, v1)` with the UVs as fractions + /// of the sprite named by the last `SpriteOf`. + Atlas { + x0: i32, + y0: i32, + x1: i32, + y1: i32, + uv: [f32; 4], + }, +} + +/// What `LoomScreen.extractBackground` reads. +pub struct LoomView<'a> { + pub width: i32, + pub height: i32, + pub left: i32, + pub top: i32, + pub has_banner: bool, + pub has_dye: bool, + pub has_pattern: bool, + /// `menu.getSelectablePatterns()`. + pub patterns: &'a [Arc], + /// `menu.getSelectedBannerPatternIndex()`. + pub selected: i32, + pub display: bool, + pub has_max: bool, + pub scroll: f32, + pub start_row: usize, + /// The result banner's colour and layers (`resultBannerPatterns`). + pub result: Option<(&'a str, &'a [BannerLayer])>, + /// The dye stack's colour (`DataComponents.DYE`, white without one). + pub dye: &'a str, + pub mouse: (f32, f32), +} + +/// `DyeColor.getTextureDiffuseColor` as an opaque ARGB int. +fn diffuse(dye: &str) -> i32 { + (banner::dye_rgb(dye) | 0xFF00_0000) as i32 +} + +fn sprite(id: &str, x: i32, y: i32, w: i32, h: i32) -> ScreenDraw { + ScreenDraw::Sprite { + id: id.to_owned(), + x, + y, + w, + h, + } +} + +/// `LoomScreen.extractBackground`. +pub fn loom(v: &LoomView, banners: &Banners) -> Vec { + let (xo, yo) = (v.left, v.top); + let mut out = vec![ + ScreenDraw::Gradient { + x1: v.width, + y1: v.height, + }, + ScreenDraw::Blit { + texture: "textures/gui/container/loom.png", + x: xo, + y: yo, + w: 176, + h: 166, + tw: 256, + th: 256, + }, + ]; + for (has, icon, x, y) in [ + (v.has_banner, "banner", 13, 26), + (v.has_dye, "dye", 33, 26), + (v.has_pattern, "banner_pattern", 23, 45), + ] { + if !has { + out.push(sprite( + &format!("container/slot/{icon}"), + xo + x, + yo + y, + 16, + 16, + )); + } + } + let sy = (41.0 * v.scroll) as i32; + let active = v.display && v.patterns.len() > 16; + out.push(sprite( + if active { + "container/loom/scroller" + } else { + "container/loom/scroller_disabled" + }, + xo + 119, + yo + 13 + sy, + 12, + 15, + )); + match v.result { + Some((base, layers)) if !v.has_max => out.push(ScreenDraw::Banner { + base: base.to_owned(), + layers: layers.to_vec(), + x0: xo + 141, + y0: yo + 8, + x1: xo + 161, + y1: yo + 48, + }), + _ if v.has_max => out.push(sprite("container/loom/error", xo + 138, yo + 52, 26, 26)), + _ => {} + } + if v.display { + let (x, y) = (xo + 60, yo + 13); + 'rows: for row in 0..4 { + for column in 0..4 { + let index = (row + v.start_row) * 4 + column; + let Some(pattern) = v.patterns.get(index) else { + break 'rows; + }; + let (px, py) = (x + column as i32 * 14, y + row as i32 * 14); + let (mx, my) = v.mouse; + let highlighted = mx >= px as f32 + && my >= py as f32 + && mx < (px + 14) as f32 + && my < (py + 14) as f32; + let button = if index as i32 == v.selected { + "container/loom/pattern_selected" + } else if highlighted { + out.push(ScreenDraw::Tooltip { + key: banners.layer_key(&BannerLayer::new(pattern, v.dye)), + }); + "container/loom/pattern_highlighted" + } else { + "container/loom/pattern" + }; + out.push(sprite(button, px, py, 14, 14)); + // extractBannerOnButton: a grey 5x10 swatch with the pattern's front. + out.push(ScreenDraw::SpriteOf { + id: banners.banner_texture(pattern), + }); + let (bx, by) = (px + 4, py + 2); + out.push(ScreenDraw::Fill { + x0: bx, + y0: by, + x1: bx + 5, + y1: by + 10, + color: diffuse("gray"), + }); + let v0 = 1.0 / 64.0; + out.push(ScreenDraw::Atlas { + x0: bx, + y0: by, + x1: bx + 5, + y1: by + 10, + uv: [0.0, 21.0 / 64.0, v0, v0 + 40.0 / 64.0], + }); + } + } + } + out +} + +/// What `CrafterScreen` draws besides the generic container parts. +pub struct CrafterView { + pub width: i32, + pub height: i32, + pub left: i32, + pub top: i32, + pub disabled: [bool; 9], + pub powered: bool, +} + +/// `CrafterScreen.extractBackground`, the disabled slots of `extractSlot` +/// and `extractRedstone`. +pub fn crafter(v: &CrafterView) -> Vec { + let mut out = vec![ + ScreenDraw::Gradient { + x1: v.width, + y1: v.height, + }, + ScreenDraw::Blit { + texture: "textures/gui/container/crafter.png", + x: (v.width - 176) / 2, + y: (v.height - 166) / 2, + w: 176, + h: 166, + tw: 256, + th: 256, + }, + ]; + for (i, disabled) in v.disabled.iter().enumerate() { + if *disabled { + let (x, y) = (26 + (i % 3) as i32 * 18, 17 + (i / 3) as i32 * 18); + out.push(sprite( + "container/crafter/disabled_slot", + v.left + x - 1, + v.top + y - 1, + 18, + 18, + )); + } + } + out.push(sprite( + if v.powered { + "container/crafter/powered_redstone" + } else { + "container/crafter/unpowered_redstone" + }, + v.width / 2 + 9, + v.height / 2 - 48, + 16, + 16, + )); + out +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLoomScreenOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLoomScreenOracle.java new file mode 100644 index 000000000..105329c1d --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLoomScreenOracle.java @@ -0,0 +1,282 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import com.mojang.renderpearl.api.pipeline.RenderPipeline; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.gui.GuiGraphicsExtractor; +import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen; +import net.minecraft.client.gui.screens.inventory.CrafterScreen; +import net.minecraft.client.gui.screens.inventory.LoomScreen; +import net.minecraft.client.model.object.banner.BannerFlagModel; +import net.minecraft.client.renderer.texture.SpriteContents; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.sprite.SpriteId; +import net.minecraft.core.Holder; +import net.minecraft.core.NonNullList; +import net.minecraft.core.component.DataComponents; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.core.registries.Registries; +import net.minecraft.network.chat.Component; +import net.minecraft.network.chat.contents.TranslatableContents; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.world.SimpleContainer; +import net.minecraft.world.inventory.*; +import net.minecraft.world.item.DyeColor; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.block.entity.BannerPattern; +import net.minecraft.world.level.block.entity.BannerPatternLayers; +import org.joml.Matrix3x2fStack; + +/** + * Original oracle for the loom and crafter screens' own drawing: vanilla's + * LoomScreen.extractBackground (slot icons, scroller, pattern buttons with + * their banner swatches and tooltips, the result banner or the six-layer + * error) and CrafterScreen's background, disabled slots and redstone arrow, + * on screens and menus whose fields come from the case, recording every + * GuiGraphicsExtractor call they make. + */ +public final class VanillaLoomScreenOracle { + static Object unsafe; + static Method allocate; + static JsonObject c; + + @SuppressWarnings("unchecked") + static T alloc(Class type) throws Exception { + return (T) allocate.invoke(unsafe, type); + } + + static void put(Object target, Class owner, String name, Object value) throws Exception { + Field f = owner.getDeclaredField(name); + long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f); + Class t = f.getType(); + String setter = t == int.class ? "putInt" : t == boolean.class ? "putBoolean" : t == float.class ? "putFloat" : t == long.class ? "putLong" : "putObject"; + Class param = t.isPrimitive() ? t : Object.class; + unsafe.getClass().getMethod(setter, Object.class, long.class, param).invoke(unsafe, target, offset, value); + } + + static net.minecraft.client.Minecraft mc; + + /** A stand-in client: Screen.extractBackground only asks its HUD for deferred subtitles (none). */ + static net.minecraft.client.Minecraft minecraft() throws Exception { + if (mc == null) { + mc = alloc(net.minecraft.client.Minecraft.class); + var gui = alloc(net.minecraft.client.gui.Gui.class); + put(gui, net.minecraft.client.gui.Gui.class, "hud", alloc(net.minecraft.client.gui.Hud.class)); + put(mc, net.minecraft.client.Minecraft.class, "gui", gui); + } + return mc; + } + + static float round(float v) { + return Math.round(v * 1e6f) / 1e6f; + } + + /** Records the screens' GuiGraphicsExtractor calls. */ + public static final class Capture extends GuiGraphicsExtractor { + JsonArray draws; + Matrix3x2fStack stack; + Map names = new IdentityHashMap<>(); + private Capture() { super(null, null, 0, 0); } + @Override public int guiWidth() { return c.get("width").getAsInt(); } + @Override public int guiHeight() { return c.get("height").getAsInt(); } + @Override public Matrix3x2fStack pose() { return stack; } + @Override public void nextStratum() { } + @Override public void requestCursor(com.mojang.blaze3d.platform.cursor.CursorType type) { } + JsonObject add(String type) { + var o = new JsonObject(); + o.addProperty("t", type); + draws.add(o); + return o; + } + int tx(int x) { return x + Math.round(stack.m20()); } + int ty(int y) { return y + Math.round(stack.m21()); } + @Override public void fillGradient(int x0, int y0, int x1, int y1, int c1, int c2) { + var o = add("gradient"); + o.addProperty("x1", x1); o.addProperty("y1", y1); + } + @Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) { + var o = add("fill"); + o.addProperty("x0", tx(Math.min(x0, x1))); o.addProperty("y0", ty(Math.min(y0, y1))); + o.addProperty("x1", tx(Math.max(x0, x1))); o.addProperty("y1", ty(Math.max(y0, y1))); + o.addProperty("color", color); + } + @Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) { + var o = add("sprite"); + o.addProperty("id", id.getPath()); + o.addProperty("x", tx(x)); o.addProperty("y", ty(y)); o.addProperty("w", w); o.addProperty("h", h); + } + @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 = add("blit"); + o.addProperty("texture", texture.getPath()); + o.addProperty("x", tx(x)); o.addProperty("y", ty(y)); o.addProperty("w", w); o.addProperty("h", h); + o.addProperty("u", u); o.addProperty("v", v); o.addProperty("tw", texW); o.addProperty("th", texH); + } + @Override public void blit(Identifier location, int x0, int y0, int x1, int y1, float u0, float u1, float v0, float v1) { + var o = add("atlas"); + o.addProperty("x0", tx(x0)); o.addProperty("y0", ty(y0)); o.addProperty("x1", tx(x1)); o.addProperty("y1", ty(y1)); + o.addProperty("u0", round(u0)); o.addProperty("u1", round(u1)); o.addProperty("v0", round(v0)); o.addProperty("v1", round(v1)); + } + /** A stand-in sprite spanning the whole texture: the UVs a screen picks are then fractions of it. */ + @Override public TextureAtlasSprite getSprite(SpriteId id) { + try { + TextureAtlasSprite s = alloc(TextureAtlasSprite.class); + put(s, TextureAtlasSprite.class, "atlasLocation", id.atlasLocation()); + put(s, TextureAtlasSprite.class, "u0", 0f); + put(s, TextureAtlasSprite.class, "u1", 1f); + put(s, TextureAtlasSprite.class, "v0", 0f); + put(s, TextureAtlasSprite.class, "v1", 1f); + var o = add("sprite_of"); + o.addProperty("id", id.texture().getPath()); + return s; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + @Override public void bannerPattern(BannerFlagModel flag, DyeColor base, BannerPatternLayers layers, int x0, int y0, int x1, int y1) { + var o = add("banner"); + o.addProperty("base", base.getSerializedName()); + var a = new JsonArray(); + for (var layer : layers.layers()) { + var l = new JsonArray(); + l.add(layer.pattern().unwrapKey().orElseThrow().identifier().toString()); + l.add(layer.color().getSerializedName()); + a.add(l); + } + o.add("layers", a); + o.addProperty("x0", x0); o.addProperty("y0", y0); o.addProperty("x1", x1); o.addProperty("y1", y1); + } + @Override public void setTooltipForNextFrame(Component text, int x, int y) { + var o = add("tooltip"); + o.addProperty("key", text.getContents() instanceof TranslatableContents t ? t.getKey() : text.getString()); + } + } + + static Holder pattern(String id) { + return ParityData.access.lookupOrThrow(Registries.BANNER_PATTERN).getOrThrow(ResourceKey.create(Registries.BANNER_PATTERN, Identifier.parse(id))); + } + + static BannerPatternLayers layers(JsonArray list) { + var b = new BannerPatternLayers.Builder(); + for (var l : list) { + var p = l.getAsJsonArray(); + b.add(pattern(p.get(0).getAsString()), DyeColor.byName(p.get(1).getAsString(), DyeColor.WHITE)); + } + return b.build(); + } + + static Slot slot(String item, int x, int y) { + var container = new SimpleContainer(1); + if (item != null) container.setItem(0, new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(item)))); + return new Slot(container, 0, x, y); + } + + static String opt(String key) { + return c.has(key) && !c.get(key).isJsonNull() ? c.get(key).getAsString() : null; + } + + static void loom(Capture g) throws Exception { + LoomMenu menu = alloc(LoomMenu.class); + put(menu, LoomMenu.class, "bannerSlot", slot(opt("banner"), 13, 26)); + put(menu, LoomMenu.class, "dyeSlot", slot(opt("dye"), 33, 26)); + put(menu, LoomMenu.class, "patternSlot", slot(opt("pattern"), 23, 45)); + put(menu, LoomMenu.class, "resultSlot", slot(opt("result"), 143, 57)); + List> patterns = new ArrayList<>(); + for (var p : c.getAsJsonArray("patterns")) patterns.add(pattern(p.getAsString())); + put(menu, LoomMenu.class, "selectablePatterns", patterns); + DataSlot selected = DataSlot.standalone(); + selected.set(c.get("selected").getAsInt()); + put(menu, LoomMenu.class, "selectedBannerPatternIndex", selected); + LoomScreen screen = alloc(LoomScreen.class); + put(screen, net.minecraft.client.gui.screens.Screen.class, "minecraft", minecraft()); + put(screen, AbstractContainerScreen.class, "menu", menu); + put(screen, AbstractContainerScreen.class, "imageWidth", 176); + put(screen, AbstractContainerScreen.class, "imageHeight", 166); + put(screen, AbstractContainerScreen.class, "leftPos", c.get("left").getAsInt()); + put(screen, AbstractContainerScreen.class, "topPos", c.get("top").getAsInt()); + put(screen, net.minecraft.client.gui.screens.Screen.class, "width", c.get("width").getAsInt()); + put(screen, net.minecraft.client.gui.screens.Screen.class, "height", c.get("height").getAsInt()); + put(screen, LoomScreen.class, "displayPatterns", c.get("display").getAsBoolean()); + put(screen, LoomScreen.class, "hasMaxPatterns", c.get("hasMax").getAsBoolean()); + put(screen, LoomScreen.class, "scrollOffs", c.get("scroll").getAsFloat()); + put(screen, LoomScreen.class, "startRow", c.get("startRow").getAsInt()); + put(screen, LoomScreen.class, "resultBannerPatterns", c.has("resultLayers") ? layers(c.getAsJsonArray("resultLayers")) : null); + ItemStack dye = opt("dyeStack") == null ? ItemStack.EMPTY : new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.parse(opt("dyeStack")))); + put(screen, LoomScreen.class, "dyeStack", dye); + try { + screen.extractBackground(g, c.get("mouseX").getAsInt(), c.get("mouseY").getAsInt(), 0f); + } catch (NullPointerException e) { + // Lighting setup for the items after the background: no game renderer here. + if (System.getenv("ORACLE_TRACE") != null) e.printStackTrace(); + } + } + + static void crafter(Capture g) throws Exception { + CrafterMenu menu = alloc(CrafterMenu.class); + var data = new SimpleContainerData(10); + var disabled = c.getAsJsonArray("disabled"); + for (int i = 0; i < 9; i++) data.set(i, disabled.get(i).getAsBoolean() ? 1 : 0); + data.set(9, c.get("powered").getAsBoolean() ? 1 : 0); + put(menu, CrafterMenu.class, "containerData", data); + CrafterScreen screen = alloc(CrafterScreen.class); + put(screen, net.minecraft.client.gui.screens.Screen.class, "minecraft", minecraft()); + put(screen, AbstractContainerScreen.class, "menu", menu); + put(screen, AbstractContainerScreen.class, "imageWidth", 176); + put(screen, AbstractContainerScreen.class, "imageHeight", 166); + int left = c.get("left").getAsInt(), top = c.get("top").getAsInt(); + put(screen, AbstractContainerScreen.class, "leftPos", left); + put(screen, AbstractContainerScreen.class, "topPos", top); + put(screen, net.minecraft.client.gui.screens.Screen.class, "width", c.get("width").getAsInt()); + put(screen, net.minecraft.client.gui.screens.Screen.class, "height", c.get("height").getAsInt()); + screen.extractBackground(g, 0, 0, 0f); + // AbstractContainerScreen.extractSlots: the slots under the menu's offset. + g.stack.pushMatrix(); + g.stack.translate(left, top); + Method extractSlot = CrafterScreen.class.getDeclaredMethod("extractSlot", GuiGraphicsExtractor.class, Slot.class, int.class, int.class); + extractSlot.setAccessible(true); + for (int y = 0; y < 3; y++) { + for (int x = 0; x < 3; x++) { + int i = x + y * 3; + if (!disabled.get(i).getAsBoolean()) continue; + var slot = new CrafterSlot(new SimpleContainer(9), i, 26 + x * 18, 17 + y * 18, menu); + put(slot, Slot.class, "index", i); + extractSlot.invoke(screen, g, slot, -100, -100); + } + } + g.stack.popMatrix(); + Method redstone = CrafterScreen.class.getDeclaredMethod("extractRedstone", GuiGraphicsExtractor.class); + redstone.setAccessible(true); + redstone.invoke(screen, g); + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + field.setAccessible(true); + unsafe = field.get(null); + allocate = unsafe.getClass().getMethod("allocateInstance", Class.class); + var out = new StringBuilder(); + for (String line : Files.readAllLines(Path.of(args[0]))) { + if (line.isBlank()) continue; + c = JsonParser.parseString(line).getAsJsonObject(); + var result = new JsonObject(); + try { + var g = alloc(Capture.class); + g.draws = new JsonArray(); + g.stack = new Matrix3x2fStack(16); + put(g, GuiGraphicsExtractor.class, "pose", g.stack); + if (c.get("screen").getAsString().equals("loom")) loom(g); else crafter(g); + result.add("draws", g.draws); + } catch (Throwable e) { + Throwable t = e instanceof InvocationTargetException ite ? ite.getCause() : e; + result.addProperty("error", t.toString()); + if (System.getenv("ORACLE_TRACE") != null) t.printStackTrace(); + } + out.append(result).append('\n'); + } + Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8); + } +} diff --git a/tools/test_screen_layout_parity.py b/tools/test_screen_layout_parity.py new file mode 100644 index 000000000..d488716f6 --- /dev/null +++ b/tools/test_screen_layout_parity.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Compare the loom and crafter screens' drawing with the vanilla client's. + +The Java oracle (VanillaLoomScreenOracle) runs LoomScreen.extractBackground on +a loom screen and menu whose state comes from the case (inputs present, the +selectable patterns, the selected one, the scroller, the result banner or +the six-layer error, the mouse over a pattern button) and CrafterScreen's +background, disabled slots and redstone arrow, recording every +GuiGraphicsExtractor call; examples/screen_layout_fixture lays out the same +state with horizon_client::screen_layout, which the game paints. The ordered +call lists must agree. +""" +import argparse +import json +import os +import random +import subprocess +import sys +try: + from . import interaction_lab as lib, test_model_baking_parity as baking, test_rust_parity as base +except ImportError: + import interaction_lab as lib + import test_model_baking_parity as baking + import test_rust_parity as base + +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] + + +def no_item_required(): + root = lib.RESOURCES / 'data/minecraft/tags/banner_pattern' + out = [] + for v in json.loads((root / 'no_item_required.json').read_text())['values']: + out.append(v) + return out + + +def cases(count, seed): + rng = random.Random(seed) + common = no_item_required() + special = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/banner_pattern').glob('*.json')) + out = [] + for n in range(count): + width = rng.choice([320, 427, 480, 640, 961, 175]) + height = rng.choice([240, 255, 360, 501, 165]) + left, top = (width - 176) // 2, (height - 166) // 2 + if n % 4 == 3: + out.append({'screen': 'crafter', 'width': width, 'height': height, 'left': left, 'top': top, + 'disabled': [rng.random() < 0.3 for _ in range(9)], 'powered': rng.random() < 0.5}) + continue + patterns = rng.choice([common, common, [rng.choice(special)], rng.sample(special, 3), []]) + rows = -(-len(patterns) // 4) + scroll = rng.choice([0.0, 0.0, 1.0, round(rng.random(), 4)]) + start = max(int(scroll * max(rows - 4, 0) + 0.5), 0) if rng.random() < 0.8 else rng.randrange(0, max(rows, 1)) + case = {'screen': 'loom', 'width': width, 'height': height, 'left': left, 'top': top, + 'banner': rng.choice(['minecraft:white_banner', 'minecraft:red_banner', None]), + 'dye': rng.choice(['minecraft:red_dye', 'minecraft:blue_dye', None]), + 'pattern': rng.choice(['minecraft:creeper_banner_pattern', None, None]), + 'patterns': patterns, 'selected': rng.choice([-1, 0, 1, 5, 20, len(patterns) - 1]), + 'display': rng.random() < 0.75, 'hasMax': rng.random() < 0.15, 'scroll': scroll, 'startRow': start, + 'dyeStack': rng.choice(['minecraft:%s_dye' % rng.choice(DYES), None]), + 'mouseX': left + 60 + rng.randrange(-3, 60), 'mouseY': top + 13 + rng.randrange(-3, 60)} + if rng.random() < 0.6: + case['result'] = 'minecraft:%s_banner' % rng.choice(DYES) + case['resultLayers'] = [[rng.choice(common), rng.choice(DYES)] for _ in range(rng.choice([1, 2, 6, 7]))] + out.append(case) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--count', type=int, default=1600) + parser.add_argument('--seed', type=int, default=3) + parser.add_argument('--detail', type=int, default=2) + args = parser.parse_args() + lock, jars, _ = base.verify_artifacts() + work = lib.work_dir('screen-layout-parity') + classes = work / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + chosen = cases(args.count, args.seed) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in chosen)) + done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps, + '-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in ('ParityData', 'VanillaLoomScreenOracle'))], + capture_output=True, text=True) + if done.returncode: + print(done.stderr[-4000:]) + sys.exit('javac failed') + run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaLoomScreenOracle', + str(work / 'cases.jsonl'), str(work / 'native.jsonl')], capture_output=True, text=True) + if run.returncode: + print(run.stderr[-4000:]) + sys.exit('oracle failed') + lib.cargo_example('horizon-client', 'screen_layout_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.jsonl') + native = [json.loads(l) for l in (work / 'native.jsonl').read_text().splitlines()] + rust = [json.loads(l) for l in (work / 'rust.jsonl').read_text().splitlines()] + assert len(native) == len(rust) == len(chosen) + bad, errors = {}, 0 + for case, a, b in zip(chosen, native, rust): + if 'error' in a: + errors += 1 + print('oracle error', a['error']) + continue + if a['draws'] != b['draws']: + bad.setdefault(case['screen'], []).append((case, a['draws'], b['draws'])) + for screen, entries in bad.items(): + print(f'{screen}: {len(entries)} differing') + for case, a, b in entries[:args.detail]: + i = next((k for k, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b))) + print(' case ', json.dumps(case)[:400]) + print(' native', a[i] if i < len(a) else '-') + print(' rust ', b[i] if i < len(b) else '-') + total = sum(len(v) for v in bad.values()) + print(f'{len(chosen) - total - errors}/{len(chosen)} screens match ({errors} oracle errors)') + raise SystemExit(1 if total or errors else 0) + + +if __name__ == '__main__': + main()