Compare the resource pack screen's drawing with vanilla

horizon_client::pack_screen ports PackSelectionScreen, its two
TransferableSelectionLists and the ConfirmScreen of an incompatible pack as
vanilla's state machine (clicks, wheel, search typing, focus, selection,
scroll) and gives its GUI calls; screen_draw holds the widgets (StringWidget,
MultiLineTextWidget, Button, a font-aware EditBox port) and StringSplitter's
line splitting with legacy codes. Pack components keep their legacy codes and
style fields. tools/test_pack_screen_parity.py runs a real
PackSelectionScreen through the same actions: 1500/1500 cases match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 06:07:04 +02:00
parent d6fd90a347
commit a7606c4ad4
7 changed files with 2564 additions and 25 deletions
@@ -0,0 +1,163 @@
//! The resource pack screen for tools/test_pack_screen_parity.py: reads one
//! JSON case per line (packs, selection, GUI size, actions, mouse), runs
//! `horizon_client::pack_screen` through the actions and writes the shown
//! screen's GUI calls in the oracle's JSON form.
//!
//! usage: pack_screen_fixture RESOURCES CASES OUTPUT
use horizon_client::{
hud::HudAtlas,
lang,
pack_screen::{Compat, PackInfo, PackScreen, Source},
packs::{self, Position},
screen_draw::{Draw, Measure},
text::Text,
};
use serde_json::{Value, json};
use std::{fmt::Write as _, fs, path::PathBuf};
/// Styled runs: [text, rgb or null, bold, italic, underlined, strikethrough, obfuscated].
pub fn runs(t: &Text) -> Value {
let mut out: Vec<(String, Option<u32>, [bool; 5])> = Vec::new();
for (c, s) in t.chars() {
let f = [
s.bold,
s.italic,
s.underlined,
s.strikethrough,
s.obfuscated,
]
.map(|b| b == Some(true));
match out.last_mut() {
Some(last) if last.1 == s.color && last.2 == f => last.0.push(c),
_ => out.push((c.to_string(), s.color, f)),
}
}
Value::Array(
out.into_iter()
.map(|(t, c, f)| json!([t, c, f[0], f[1], f[2], f[3], f[4]]))
.collect(),
)
}
pub fn encode(draws: &[Draw]) -> Value {
Value::Array(
draws
.iter()
.map(|d| match d {
Draw::Sprite { sprite, x, y, w, h, color } => {
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "color": color})
}
Draw::Blit { texture, x, y, w, h, u, v, src, tex, color } => json!({"type": "blit", "texture": texture,
"x": x, "y": y, "w": w, "h": h, "u": u, "v": v, "srcW": src[0], "srcH": src[1], "texW": tex[0],
"texH": tex[1], "color": color}),
Draw::Fill { x0, y0, x1, y1, color } => {
json!({"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color})
}
Draw::Highlight { x0, y0, x1, y1 } => json!({"type": "highlight", "x0": x0, "y0": y0, "x1": x1, "y1": y1}),
Draw::Text { text, x, y, color, shadow } => {
json!({"type": "text", "runs": runs(text), "x": x, "y": y, "color": color, "shadow": shadow})
}
Draw::Scissor { x0, y0, x1, y1 } => json!({"type": "scissor", "x0": x0, "y0": y0, "x1": x1, "y1": y1}),
Draw::NoScissor => json!({"type": "noscissor"}),
Draw::Tooltip { lines, x, y } => {
json!({"type": "tooltip", "lines": lines.iter().map(runs).collect::<Vec<_>>(), "x": x, "y": y})
}
})
.collect(),
)
}
fn main() -> horizon_client::Result<()> {
let args: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
let [root, inputs, output] = args.as_slice() else {
return Err("usage: pack_screen_fixture RESOURCES CASES OUTPUT".into());
};
let atlas = HudAtlas::build(root)?;
lang::set(lang::Language::load(&[root], lang::DEFAULT));
let m = Measure(&atlas.font);
let mut out = String::new();
for line in fs::read_to_string(inputs)?
.lines()
.filter(|l| !l.is_empty())
{
let c: Value = serde_json::from_str(line)?;
let int = |v: &Value| v.as_i64().unwrap_or(0) as i32;
let packs: Vec<PackInfo> = c["packs"]
.as_array()
.into_iter()
.flatten()
.map(|p| {
let (description, description_style) = packs::component_root(&p["description"]);
PackInfo {
id: p["id"].as_str().unwrap_or_default().to_owned(),
title: packs::component_root(&p["title"]).0,
description,
description_style,
source: match p["source"].as_str() {
Some("builtin") => Source::BuiltIn,
Some("world") => Source::World,
Some("server") => Source::Server,
Some("feature") => Source::Feature,
_ => Source::Default,
},
compat: match p["compat"].as_str() {
Some("old") => Compat::TooOld,
Some("new") => Compat::TooNew,
Some("unknown") => Compat::Unknown,
_ => Compat::Compatible,
},
icon: p["icon"].as_bool().unwrap_or(false),
required: p["required"].as_bool().unwrap_or(false),
position: if p["position"] == "top" {
Position::Top
} else {
Position::Bottom
},
fixed: p["fixed"].as_bool().unwrap_or(false),
}
})
.collect();
let selected: Vec<String> = c["selected"]
.as_array()
.into_iter()
.flatten()
.filter_map(|s| s.as_str().map(str::to_owned))
.collect();
let mut screen = PackScreen::new(
&m,
int(&c["width"]),
int(&c["height"]),
c["inWorld"] == true,
packs,
&selected,
);
for a in c["actions"].as_array().into_iter().flatten() {
let f = |k: &str| a[k].as_f64().unwrap_or(0.0);
match a["type"].as_str().unwrap_or_default() {
"click" => {
screen.click(&m, f("x"), f("y"));
}
"scroll" => screen.scroll(f("x"), f("y"), f("amount")),
"type" => screen.type_text(&m, a["text"].as_str().unwrap_or_default()),
"erase" => screen.erase(&m, f("count") as isize),
_ => {}
}
if std::env::var_os("PACK_DEBUG").is_some() {
eprintln!("{a} -> {}", screen.debug());
}
}
let mouse = (int(&c["mouse"][0]), int(&c["mouse"][1]));
let draws = screen.draw(&m, mouse, c["blink"].as_u64().unwrap_or(0));
let screen_name = if screen.confirming() {
"confirm"
} else {
"packs"
};
writeln!(
out,
"{}",
json!({"screen": screen_name, "draws": encode(&draws)})
)?;
}
fs::write(output, out)?;
Ok(())
}
+2
View File
@@ -77,6 +77,7 @@ pub mod net;
pub mod options_file;
pub mod options_fixes;
pub mod options_ui;
pub mod pack_screen;
pub mod packs;
pub mod particles;
pub mod patrol;
@@ -89,6 +90,7 @@ pub mod recipe_book_screen;
pub mod save;
pub mod scoreboard;
pub mod scoreboard_cmd;
pub mod screen_draw;
pub mod screen_effects;
pub mod screen_layout;
pub mod sculk;
+915
View File
@@ -0,0 +1,915 @@
//! The resource pack screen (`PackSelectionScreen` with its two
//! `TransferableSelectionList`s, search box and buttons) and the
//! `ConfirmScreen` an incompatible pack opens, as vanilla's state machine:
//! clicks, the mouse wheel and typing change the selection model, the lists'
//! entries, scroll, selection and focus as the vanilla widgets do, and
//! [`PackScreen::draw`] gives the screen's GUI calls. The game shows it;
//! tools/test_pack_screen_parity.py compares it with vanilla.
use crate::{
packs::{Position, Selectable, SelectionModel},
screen_draw::{self as d, Draw, Measure, TextField},
text::{Style, Text},
};
/// `PackCompatibility`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Compat {
Compatible,
TooOld,
TooNew,
Unknown,
}
impl Compat {
fn key(self) -> &'static str {
match self {
Compat::TooOld => "old",
Compat::TooNew => "new",
Compat::Unknown => "unknown",
Compat::Compatible => "compatible",
}
}
}
/// `PackSource`: how the description is decorated.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Source {
Default,
BuiltIn,
Feature,
World,
Server,
}
/// A pack as the screen shows it.
#[derive(Clone, Debug)]
pub struct PackInfo {
pub id: String,
pub title: Text,
pub description: Text,
/// The description component's own (root) style.
pub description_style: Style,
pub source: Source,
pub compat: Compat,
/// Whether the pack has a `pack.png`.
pub icon: bool,
pub required: bool,
pub position: Position,
pub fixed: bool,
}
impl PackInfo {
pub fn selectable(&self) -> Selectable {
Selectable {
id: self.id.clone(),
required: self.required,
position: self.position,
fixed: self.fixed,
compatible: self.compat == Compat::Compatible,
}
}
/// `PackSource.decorate` merged with the entry's grey
/// (`getExtendedDescription`, `ComponentUtils.mergeStyles`), and the style of
/// its root, which the ellipsis of a cut description takes.
fn extended_description(&self) -> (Text, Style) {
let gray = Style::color(0x808080);
let key = match self.source {
Source::Default => {
let mut root = self.description_style.clone();
root.inherit(&gray);
return (self.description.clone().with_style(&gray), root);
}
Source::BuiltIn => "pack.source.builtin",
Source::Feature => "pack.source.feature",
Source::World => "pack.source.world",
Source::Server => "pack.source.server",
};
let t = Text::translate(
"pack.nameAndSource",
&[self.description.clone(), Text::translate(key, &[])],
)
.with_color(d::GRAY);
(t, Style::color(d::GRAY))
}
}
/// `PackSelectionScreen.loadPackIcon`'s texture for a pack with an icon.
pub fn icon_texture(id: &str) -> String {
let sanitized: String = id
.to_lowercase()
.chars()
.map(|c| {
if c.is_ascii_lowercase() || c.is_ascii_digit() || "_-./".contains(c) {
c
} else {
'_'
}
})
.collect();
let bytes: Vec<u8> = id.encode_utf16().flat_map(u16::to_le_bytes).collect();
let hash: String = crate::skins::sha1(&bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect();
format!("pack/{sanitized}/{hash}/icon")
}
#[derive(Clone, Debug, PartialEq)]
enum Row {
Header,
Pack(String),
}
#[derive(Clone, Debug)]
struct Entry {
row: Row,
y: i32,
height: i32,
}
/// A `TransferableSelectionList`.
#[derive(Clone, Debug)]
struct List {
selected_side: bool,
x: i32,
y: i32,
width: i32,
height: i32,
scroll: f64,
entries: Vec<Entry>,
/// `getSelected`, an index into `entries`.
selected: Option<usize>,
/// The list has a focused child (possibly an entry it no longer holds).
focused: bool,
}
impl List {
fn new(selected_side: bool, height: i32) -> Self {
Self {
selected_side,
x: 0,
y: 33,
width: 200,
height,
scroll: 0.0,
entries: Vec::new(),
selected: None,
focused: false,
}
}
fn bottom(&self) -> i32 {
self.y + self.height
}
fn row_left(&self) -> i32 {
self.x + self.width / 2 - self.row_width() / 2
}
fn row_width(&self) -> i32 {
self.width - 4
}
fn content_height(&self) -> i32 {
self.entries.iter().map(|e| e.height).sum::<i32>() + 4
}
fn max_scroll(&self) -> i32 {
(self.content_height() - self.height).max(0)
}
fn scrollable(&self) -> bool {
self.max_scroll() > 0
}
/// `TransferableSelectionList.Entry.getWidth`.
fn entry_width(&self) -> i32 {
self.row_width() - if self.scrollable() { 6 } else { 0 }
}
fn next_y(&self) -> i32 {
self.y + 2 - self.scroll as i32 + self.entries.iter().map(|e| e.height).sum::<i32>()
}
fn add(&mut self, row: Row, height: i32) {
let y = self.next_y();
self.entries.push(Entry { row, y, height });
}
fn reposition(&mut self) {
let mut y = self.y + 2 - self.scroll as i32;
for e in &mut self.entries {
e.y = y;
y += e.height;
}
}
fn set_scroll(&mut self, v: f64) {
self.scroll = v.clamp(0.0, self.max_scroll() as f64);
self.reposition();
}
fn scroll_to(&mut self, i: usize) {
let e = &self.entries[i];
let top = e.y - self.y - 2;
if top < 0 {
self.set_scroll(self.scroll + top as f64);
}
let e = &self.entries[i];
let bottom = self.bottom() - e.y - e.height - 2;
if bottom < 0 {
self.set_scroll(self.scroll - bottom as f64);
}
}
fn set_selected(&mut self, i: Option<usize>) {
self.selected = i;
if let Some(i) = i {
let e = &self.entries[i];
let top = e.y + 2 < self.y;
let bottom = e.y + 2 + e.height - 4 > self.bottom();
if top || bottom {
self.scroll_to(i);
}
}
}
fn update_size(&mut self, width: i32, height: i32, x: i32, y: i32) {
self.width = width;
self.height = height;
self.x = x;
self.y = y;
self.reposition();
if let Some(i) = self.selected {
self.scroll_to(i);
}
self.set_scroll(self.scroll);
}
fn is_over(&self, x: f64, y: f64) -> bool {
x >= self.x as f64
&& y >= self.y as f64
&& x < (self.x + self.width) as f64
&& y < self.bottom() as f64
}
/// `getEntryAtPosition`.
fn entry_at(&self, x: i32, y: i32) -> Option<usize> {
let (left, w) = (self.row_left(), self.entry_width());
self.entries
.iter()
.position(|e| x >= left && x < left + w && y >= e.y && y < e.y + e.height)
}
fn scroll_bar_x(&self) -> i32 {
self.x + self.width - 6
}
fn scroller_height(&self) -> i32 {
((self.height * self.height) as f32 / self.content_height() as f32) as i32
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Focus {
None,
Search,
List(usize),
/// Open Pack Folder (0) or Done (1).
Button(usize),
}
/// The open `ConfirmScreen` for an incompatible pack.
#[derive(Clone, Debug)]
struct Confirm {
id: String,
title: Text,
message: Text,
}
/// What a click on the screen asks the game to do.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Action {
None,
/// The Open Pack Folder button.
OpenFolder,
/// The Done button (`onClose`: commit).
Done,
}
/// The pack screen and its state.
#[derive(Clone, Debug)]
pub struct PackScreen {
pub width: i32,
pub height: i32,
pub in_world: bool,
pub packs: Vec<PackInfo>,
pub model: SelectionModel,
search: TextField,
focus: Focus,
/// 0: available, 1: selected.
lists: [List; 2],
confirm: Option<Confirm>,
/// The selection changed since the screen opened.
pub changed: bool,
}
fn tr(key: &str) -> Text {
Text::translate(key, &[])
}
impl PackScreen {
/// `PackSelectionScreen.init`: the lists filled, the search box focused.
pub fn new(
m: &Measure,
width: i32,
height: i32,
in_world: bool,
packs: Vec<PackInfo>,
selected: &[String],
) -> Self {
let model = SelectionModel::new(packs.iter().map(PackInfo::selectable).collect(), selected);
let mut search = TextField::new(0, 0, 200, 15);
search.hint = Some(tr("gui.packSelection.search").with_style(&Style {
color: Some(d::GRAY),
italic: Some(true),
..Style::default()
}));
let mut s = Self {
width,
height,
in_world,
packs,
model,
search,
focus: Focus::None,
lists: [List::new(false, height - 66), List::new(true, height - 66)],
confirm: None,
changed: false,
};
s.reposition(m);
s.populate(None);
s.set_focus(Focus::Search);
s
}
fn info(&self, id: &str) -> Option<&PackInfo> {
self.packs.iter().find(|p| p.id == id)
}
/// The header layout: title, drop info and search box, centred.
fn header(&self, m: &Measure) -> [(i32, i32); 3] {
let tw = m.width(&tr("resourcePack.title"));
let dw = m.width(&tr("pack.dropInfo"));
let col = tw.max(dw).max(200);
let frame = self.width.max(col);
let lx = (0.5 * (frame - col) as f32) as i32;
let cell = |w: i32| lx + (0.5 * (col - w) as f32) as i32;
[(cell(tw), 4), (cell(dw), 17), (cell(200), 30)]
}
/// The footer's two buttons.
fn footer(&self) -> [(i32, i32); 2] {
let frame = self.width.max(308);
let x = (0.5 * (frame - 308) as f32) as i32;
let y = self.height - 33 + (0.5f32 * 13.0).round() as i32;
[(x, y), (x + 158, y)]
}
/// `repositionElements`.
fn reposition(&mut self, m: &Measure) {
let (sx, sy) = self.header(m)[2];
self.search.x = sx;
self.search.y = sy;
let content = self.height - 49 - 33;
let w = self.width;
self.lists[0].update_size(200, content, w / 2 - 15 - 200, 49);
self.lists[1].update_size(200, content, w / 2 + 15, 49);
}
/// `AbstractContainerEventHandler.setFocused` on the screen.
fn set_focus(&mut self, f: Focus) {
if self.focus == f {
return;
}
match self.focus {
Focus::Search => self.search.focused = false,
Focus::List(i) => self.lists[i].focused = false,
Focus::None | Focus::Button(_) => {}
}
if f == Focus::Search {
self.search.focused = true;
}
self.focus = f;
}
fn shown(&self, side: usize) -> Vec<String> {
let value = self.search.value.to_lowercase();
let blank = self.search.value.trim().is_empty()
&& self.search.value.chars().all(char::is_whitespace);
let list = if side == 1 {
&self.model.selected
} else {
&self.model.unselected
};
list.iter()
.filter(|p| {
blank
|| p.id.to_lowercase().contains(&value)
|| self.info(&p.id).is_some_and(|i| {
i.title.plain().to_lowercase().contains(&value)
|| i.description.plain().to_lowercase().contains(&value)
})
})
.map(|p| p.id.clone())
.collect()
}
/// `TransferableSelectionList.updateList`.
fn update_list(&mut self, side: usize, ids: Vec<String>, transferred: Option<&str>) {
let l = &mut self.lists[side];
l.entries.clear();
l.selected = None;
l.add(Row::Header, 13);
l.set_selected(None);
for id in ids {
let hit = transferred == Some(id.as_str());
self.lists[side].add(Row::Pack(id), 36);
if hit {
self.set_focus(Focus::List(side));
let l = &mut self.lists[side];
l.focused = true;
let i = l.entries.len() - 1;
l.set_selected(Some(i));
}
}
let l = &mut self.lists[side];
l.set_scroll(l.scroll);
}
/// `populateLists`: both lists, then again through the search filter.
fn populate(&mut self, transferred: Option<&str>) {
let all = |m: &SelectionModel, side: bool| -> Vec<String> {
(if side { &m.selected } else { &m.unselected })
.iter()
.map(|p| p.id.clone())
.collect()
};
self.update_list(1, all(&self.model, true), transferred);
self.update_list(0, all(&self.model, false), transferred);
self.filter(transferred);
}
/// `updateFilteredEntries`.
fn filter(&mut self, transferred: Option<&str>) {
let (sel, avail) = (self.shown(1), self.shown(0));
self.update_list(1, sel, transferred);
self.update_list(0, avail, transferred);
}
/// The pack's index in its model list.
fn model_index(&self, side: usize, id: &str) -> Option<usize> {
let list = if side == 1 {
&self.model.selected
} else {
&self.model.unselected
};
list.iter().position(|p| p.id == id)
}
fn flags(&self, side: usize, id: &str) -> (bool, bool, bool, bool) {
let Some(i) = self.model_index(side, id) else {
return (false, false, false, false);
};
let s = side == 1;
(
self.model.can_select(s, i),
self.model.can_unselect(s, i),
self.model.can_move_up(s, i),
self.model.can_move_down(s, i),
)
}
fn overlay(&self, id: &str) -> bool {
self.info(id).is_none_or(|p| !p.fixed || !p.required)
}
/// A left click (`Screen.mouseClicked`).
pub fn click(&mut self, m: &Measure, x: f64, y: f64) -> Action {
if self.confirm.is_some() {
return self.confirm_click(m, x, y);
}
if self.search.contains(x, y) {
self.search.click(m, x, false);
self.set_focus(Focus::Search);
return Action::None;
}
for side in 0..2 {
if !self.lists[side].is_over(x, y) {
continue;
}
let l = &self.lists[side];
let scrolling = l.scrollable()
&& x >= l.scroll_bar_x() as f64
&& x <= (l.scroll_bar_x() + 6) as f64
&& y >= l.y as f64
&& y < l.bottom() as f64;
let hit = l.entry_at(x as i32, y as i32);
let mut took = false;
if let Some(i) = hit {
took = true;
match l.entries[i].row.clone() {
Row::Header => {
let l = &mut self.lists[side];
l.focused = true;
l.set_selected(Some(i));
}
Row::Pack(id) => {
let current = self.entry_click(m, side, i, &id, x as i32, y as i32);
if self.lists[side]
.entries
.iter()
.any(|e| e.row == Row::Pack(id.clone()))
{
let l = &mut self.lists[side];
l.focused = true;
if current {
l.set_selected(Some(i));
}
}
}
}
}
if took || scrolling {
self.set_focus(Focus::List(side));
}
return Action::None;
}
for (i, (bx, by)) in self.footer().into_iter().enumerate() {
if x >= bx as f64 && y >= by as f64 && x < (bx + 150) as f64 && y < (by + 20) as f64 {
self.set_focus(Focus::Button(i));
return if i == 0 {
Action::OpenFolder
} else {
Action::Done
};
}
}
Action::None
}
/// `PackEntry.mouseClicked`; true when the entry clicked is still the
/// list's own (nothing was repopulated).
fn entry_click(
&mut self,
m: &Measure,
side: usize,
i: usize,
id: &str,
x: i32,
y: i32,
) -> bool {
if !self.overlay(id) {
return true;
}
let e = &self.lists[side].entries[i];
let (cx, cy) = (self.lists[side].row_left() + 2, e.y + 2);
let (rx, ry) = (x - cx, y - cy);
let (sel, unsel, up, down) = self.flags(side, id);
let icon = (0..32).contains(&rx) && (0..32).contains(&ry);
let left = (0..16).contains(&rx) && (0..32).contains(&ry);
let top_right = (16..32).contains(&rx) && (0..16).contains(&ry);
let bottom_right = (16..32).contains(&rx) && (16..32).contains(&ry);
let index = self.model_index(side, id).unwrap_or(0);
let s = side == 1;
if sel && icon {
if self
.info(id)
.is_some_and(|p| p.compat != Compat::Compatible)
{
self.open_confirm(id);
return true;
}
self.model.activate(s, index, true);
} else if unsel && left {
self.model.activate(s, index, false);
} else if up && top_right {
self.model.move_by(s, index, true);
} else if down && bottom_right {
self.model.move_by(s, index, false);
} else {
return true;
}
self.changed = true;
self.populate(Some(id));
let _ = m;
false
}
/// `handlePackSelection` of an incompatible pack: the ConfirmScreen
/// (the pack screen loses its focus as `Gui.setScreen` clears it).
fn open_confirm(&mut self, id: &str) {
let compat = self.info(id).map_or(Compat::Unknown, |p| p.compat);
self.set_focus(Focus::None);
for l in &mut self.lists {
l.focused = false;
}
self.confirm = Some(Confirm {
id: id.to_owned(),
title: tr("pack.incompatible.confirm.title"),
message: tr(&format!("pack.incompatible.confirm.{}", compat.key())),
});
}
/// The ConfirmScreen's layout: title, message lines and the two buttons.
fn confirm_layout(
&self,
m: &Measure,
c: &Confirm,
) -> ((i32, i32), (Vec<(Text, i32)>, i32, i32), [(i32, i32); 2]) {
let max = self.width - 50;
let lines = d::label_lines(m, &c.message, max, 15, &Style::default());
let mw = d::label_width(&lines, max);
let mh = lines.len() as i32 * 9;
let tw = m.width(&c.title);
let col = tw.max(mw).max(304);
let total = 9 + 8 + mh + 8 + 36;
let lx = (0.5 * (self.width - col) as f32) as i32;
let ly = (0.5 * (self.height - total) as f32) as i32;
let cell = |w: i32| lx + (0.5 * (col - w) as f32) as i32;
let by = ly + 9 + 8 + mh + 8 + 16;
let bx = cell(304);
(
(cell(tw), ly),
(lines, cell(mw), ly + 17),
[(bx, by), (bx + 154, by)],
)
}
fn confirm_click(&mut self, m: &Measure, x: f64, y: f64) -> Action {
let Some(c) = self.confirm.clone() else {
return Action::None;
};
let (_, _, buttons) = self.confirm_layout(m, &c);
for (i, (bx, by)) in buttons.into_iter().enumerate() {
if x >= bx as f64 && y >= by as f64 && x < (bx + 150) as f64 && y < (by + 20) as f64 {
// The callback: back to the pack screen (repositioned), then select.
self.confirm = None;
self.reposition(m);
if i == 0
&& let Some(index) = self.model_index(0, &c.id)
{
self.model.activate(false, index, true);
self.changed = true;
self.populate(Some(&c.id));
}
return Action::None;
}
}
Action::None
}
/// The focus, the lists' rows, scroll and selection (for debugging).
pub fn debug(&self) -> String {
format!(
"{:?} {:?}",
self.focus,
self.lists
.iter()
.map(|l| (
l.scroll,
l.selected,
l.focused,
l.entries.iter().map(|e| e.y).collect::<Vec<_>>()
))
.collect::<Vec<_>>()
)
}
/// Whether the confirmation screen is shown.
pub fn confirming(&self) -> bool {
self.confirm.is_some()
}
/// Escape on the confirmation screen answers no.
pub fn cancel_confirm(&mut self, m: &Measure) -> bool {
if self.confirm.take().is_some() {
self.reposition(m);
return true;
}
false
}
/// The mouse wheel (`AbstractScrollArea.mouseScrolled`).
pub fn scroll(&mut self, x: f64, y: f64, amount: f64) {
if self.confirm.is_some() || self.search.contains(x, y) {
return;
}
for l in &mut self.lists {
if l.is_over(x, y) {
l.set_scroll(l.scroll - amount * 18.0);
return;
}
}
}
/// Typed text, when the search box has the focus.
pub fn type_text(&mut self, m: &Measure, s: &str) {
if self.confirm.is_none() && self.focus == Focus::Search && self.search.insert_text(m, s) {
self.filter(None);
}
}
/// Backspace in the search box.
pub fn erase(&mut self, m: &Measure, count: isize) {
if self.confirm.is_none()
&& self.focus == Focus::Search
&& self.search.delete_chars(m, -count)
{
self.filter(None);
}
}
pub fn search_focused(&self) -> bool {
self.confirm.is_none() && self.focus == Focus::Search
}
/// Resize (`Screen.init` on a new size: `repositionElements`).
pub fn resize(&mut self, m: &Measure, width: i32, height: i32) {
self.width = width;
self.height = height;
self.reposition(m);
}
/// `PackSelectionModel.commit`: the selection as options.txt stores it.
pub fn commit(&self) -> Vec<String> {
self.model.commit()
}
/// The shown screen's calls (`Screen.extractRenderState`); `blink_ms`
/// is the time since the search box took the focus.
pub fn draw(&self, m: &Measure, mouse: (i32, i32), blink_ms: u64) -> Vec<Draw> {
let mut out = Vec::new();
if let Some(c) = &self.confirm {
let ((tx, ty), (lines, mx, my), buttons) = self.confirm_layout(m, c);
d::string_widget(&mut out, m, &c.title, tx, ty, 0);
d::label(&mut out, &lines, mx, my, self.width - 50, true);
for ((bx, by), key) in buttons.into_iter().zip(["gui.yes", "gui.no"]) {
let hover = d::inside(mouse, bx, by, 150, 20);
d::button(&mut out, m, &tr(key), bx, by, 150, 20, true, hover);
}
return out;
}
let [(tx, ty), (dx, dy), _] = self.header(m);
d::string_widget(&mut out, m, &tr("resourcePack.title"), tx, ty, 0);
d::string_widget(
&mut out,
m,
&tr("pack.dropInfo").with_color(d::GRAY),
dx,
dy,
0,
);
self.search.draw(&mut out, m, blink_ms, None);
for side in 0..2 {
self.draw_list(&mut out, m, side, mouse);
}
for (i, (bx, by)) in self.footer().into_iter().enumerate() {
let hover = d::inside(mouse, bx, by, 150, 20);
let label = tr(if i == 0 {
"pack.openFolder"
} else {
"gui.done"
});
d::button(
&mut out,
m,
&label,
bx,
by,
150,
20,
true,
hover || self.focus == Focus::Button(i),
);
if i == 0 && hover {
d::tooltip(&mut out, m, &tr("pack.folderInfo"), mouse);
}
}
out
}
fn draw_list(&self, out: &mut Vec<Draw>, m: &Measure, side: usize, mouse: (i32, i32)) {
let l = &self.lists[side];
let hovered = if l.is_over(mouse.0 as f64, mouse.1 as f64) {
l.entry_at(mouse.0, mouse.1)
} else {
None
};
let prefix = if self.in_world { "inworld_" } else { "" };
let right = l.x + l.width;
d::blit(
out,
&format!("textures/gui/{prefix}menu_list_background.png"),
l.x,
l.y,
(right as f32, (l.bottom() + l.scroll as i32) as f32),
l.width,
l.height,
[32, 32],
);
out.push(Draw::Scissor {
x0: l.x.clamp(0, self.width),
y0: l.y.clamp(0, self.height),
x1: right.clamp(0, self.width),
y1: l.bottom().clamp(0, self.height),
});
let (left, w) = (l.row_left(), l.entry_width());
let narrow = if l.scrollable() { 6 } else { 0 };
for (i, e) in l.entries.iter().enumerate() {
if e.y + e.height < l.y || e.y > l.bottom() {
continue;
}
if l.selected == Some(i) {
let color = if l.focused { -1 } else { -8355712 };
d::fill(out, left, e.y, left + w, e.y + e.height, color);
d::fill(
out,
left + 1,
e.y + 1,
left + w - 1,
e.y + e.height - 1,
-16777216,
);
}
let (cx, cy) = (left + 2, e.y + 2);
match &e.row {
Row::Header => {
let key = if l.selected_side {
"pack.selected.title"
} else {
"pack.available.title"
};
let t = tr(key).with_style(&Style {
underlined: Some(true),
bold: Some(true),
..Style::default()
});
let tw = m.width(&t);
d::text(
out,
t,
left + w / 2 - tw / 2,
cy + (e.height - 4) / 2 - 4,
-1,
true,
);
}
Row::Pack(id) => {
let Some(p) = self.info(id) else { continue };
if p.compat != Compat::Compatible {
d::fill(
out,
cx - 1,
cy - 1,
cx + w - 4 + 1,
cy + e.height - 4 + 1,
-8978432,
);
}
let icon = if p.icon {
icon_texture(id)
} else {
"textures/misc/unknown_pack.png".into()
};
d::blit(out, &icon, cx, cy, (0.0, 0.0), 32, 32, [32, 32]);
let (mut name, (mut desc, mut desc_style)) =
(p.title.clone(), p.extended_description());
let focus_hover = l.selected == Some(i) && l.focused;
if self.overlay(id) && (hovered == Some(i) || focus_hover) {
d::fill(out, cx, cy, cx + 32, cy + 32, -1601138544);
let (rx, ry) = (mouse.0 - cx, mouse.1 - cy);
if p.compat != Compat::Compatible {
name = tr("pack.incompatible");
desc = tr(&format!("pack.incompatible.{}", p.compat.key()))
.with_color(d::GRAY);
desc_style = Style::color(d::GRAY);
}
let (sel, unsel, up, down) = self.flags(side, id);
let quarter = |x0: i32, x1: i32, y0: i32, y1: i32| {
(x0..x1).contains(&rx) && (y0..y1).contains(&ry)
};
let mut arrow = |name: &str, on: bool| {
let s = if on {
format!("transferable_list/{name}_highlighted")
} else {
format!("transferable_list/{name}")
};
d::sprite(out, &s, cx, cy, 32, 32);
};
if sel {
arrow("select", quarter(0, 32, 0, 32));
} else {
if unsel {
arrow("unselect", quarter(0, 16, 0, 32));
}
if up {
arrow("move_up", quarter(16, 32, 0, 16));
}
if down {
arrow("move_down", quarter(16, 32, 16, 32));
}
}
}
let max = 157 - narrow;
d::string_widget(out, m, &name, cx + 34, cy + 1, max);
let lines = d::label_lines(m, &desc, max, 2, &desc_style);
d::label(out, &lines, cx + 34, cy + 12, max, false);
}
}
}
out.push(Draw::NoScissor);
d::blit(
out,
&format!("textures/gui/{prefix}header_separator.png"),
l.x,
l.y - 2,
(0.0, 0.0),
l.width,
2,
[32, 2],
);
d::blit(
out,
&format!("textures/gui/{prefix}footer_separator.png"),
l.x,
l.bottom(),
(0.0, 0.0),
l.width,
2,
[32, 2],
);
if l.scrollable() {
let sh = l.scroller_height().clamp(32, l.height - 8);
let sy = (l.scroll as i32 * (l.height - sh) / l.max_scroll() + l.y).max(l.y);
d::sprite(
out,
"widget/scroller_background",
l.scroll_bar_x(),
l.y,
6,
l.height,
);
d::sprite(out, "widget/scroller", l.scroll_bar_x(), sy, 6, sh);
}
}
}
+69 -25
View File
@@ -4,6 +4,7 @@
//! and an overlay resource root that layers the enabled packs over the
//! vanilla resources (later packs win), so every loader sees one tree.
pub mod pattern;
use crate::text::Style;
use crate::{text::Text, zip::Zip};
use pattern::Pattern;
use std::{
@@ -53,47 +54,90 @@ impl Filter {
&& self.path.as_ref().is_none_or(|p| p.is_match(path))
}
}
/// A minimal text component from JSON (strings, `text`, `translate`, arrays).
/// A text component from JSON (strings, `text`, `translate`, arrays, `extra`
/// and the style fields), legacy `§` codes resolved as the font does.
pub fn component(v: &serde_json::Value) -> Text {
component_root(v).0.resolve_legacy()
}
/// The component, its legacy codes left in place (each span is a
/// component's contents and style), and its root style (`Component.getStyle`).
pub fn component_root(v: &serde_json::Value) -> (Text, Style) {
let mut out = Text::empty();
let root = build(v, &Style::default(), &mut out);
(out, root)
}
fn style_of(o: &serde_json::Map<String, serde_json::Value>) -> Style {
let flag = |k: &str| o.get(k).and_then(|b| b.as_bool());
Style {
color: o.get("color").and_then(|c| c.as_str()).and_then(|c| {
crate::text::named_color(c).or_else(|| {
c.strip_prefix('#')
.and_then(|h| u32::from_str_radix(h, 16).ok())
})
}),
bold: flag("bold"),
italic: flag("italic"),
underlined: flag("underlined"),
strikethrough: flag("strikethrough"),
obfuscated: flag("obfuscated"),
..Style::default()
}
}
/// Appends `v` under `parent`'s style; returns the component's own style.
fn build(v: &serde_json::Value, parent: &Style, out: &mut Text) -> Style {
match v {
serde_json::Value::String(s) => Text::legacy(s),
serde_json::Value::Array(a) => {
let mut t = Text::empty();
for e in a {
t.push(component(e));
let Some(first) = a.first() else {
return Style::default();
};
let own = build(first, parent, out);
let mut style = own.clone();
style.inherit(parent);
for e in &a[1..] {
build(e, &style, out);
}
t
own
}
serde_json::Value::Object(o) => {
let mut t = if let Some(s) = o.get("text").and_then(|s| s.as_str()) {
Text::legacy(s)
let own = style_of(o);
let mut style = own.clone();
style.inherit(parent);
if let Some(s) = o.get("text").and_then(|s| s.as_str()) {
out.push(Text::styled(s, style.clone()));
} else if let Some(k) = o.get("translate").and_then(|s| s.as_str()) {
let args: Vec<Text> = o
.get("with")
.and_then(|w| w.as_array())
.map(|a| a.iter().map(component).collect())
.unwrap_or_default();
Text::translate(k, &args)
} else {
Text::empty()
};
if let Some(extra) = o.get("extra") {
t.push(component(extra));
out.push(Text::translate(k, &args).with_style(&style));
}
if let Some(c) = o.get("color").and_then(|c| c.as_str()) {
let rgb = crate::text::named_color(c).or_else(|| {
c.strip_prefix('#')
.and_then(|h| u32::from_str_radix(h, 16).ok())
});
if let Some(rgb) = rgb {
t = t.with_color(rgb);
match o.get("extra") {
Some(serde_json::Value::Array(extra)) => {
for e in extra {
build(e, &style, out);
}
}
Some(e) => {
build(e, &style, out);
}
None => {}
}
t
own
}
serde_json::Value::Number(n) => Text::literal(n.to_string()),
serde_json::Value::Bool(b) => Text::literal(b.to_string()),
serde_json::Value::Null => Text::empty(),
serde_json::Value::String(s) => {
out.push(Text::styled(s.as_str(), parent.clone()));
Style::default()
}
serde_json::Value::Number(n) => {
out.push(Text::styled(n.to_string(), parent.clone()));
Style::default()
}
serde_json::Value::Bool(b) => {
out.push(Text::styled(b.to_string(), parent.clone()));
Style::default()
}
serde_json::Value::Null => Style::default(),
}
}
fn format_of(v: &serde_json::Value) -> Option<(i64, i64)> {
+840
View File
@@ -0,0 +1,840 @@
//! Menu screens as the `GuiGraphicsExtractor` calls vanilla's widgets make
//! (sprites, texture blits, fills, text highlight, text, scissor and the
//! tooltip), with ports of the widgets that make them: `StringWidget`,
//! `MultiLineTextWidget`, `Button`, `EditBox` (a font-aware port, scrolling
//! included) and the label layouts. The screen layouts built on them
//! (`pack_screen`) are compared with vanilla's calls by the parity harnesses;
//! [`paint`] draws them with the HUD batch.
use crate::{
font::Font,
hud::{HudAtlas, HudBatch},
text::{Style, Text},
};
/// One GUI call.
#[derive(Clone, Debug, PartialEq)]
pub enum Draw {
/// `blitSprite`, the id without its namespace.
Sprite {
sprite: String,
x: i32,
y: i32,
w: i32,
h: i32,
color: i32,
},
/// `blit` of a texture region; `texture` is the full path (`textures/…png`).
Blit {
texture: String,
x: i32,
y: i32,
w: i32,
h: i32,
u: f32,
v: f32,
src: [i32; 2],
tex: [i32; 2],
color: i32,
},
/// `fill`, corners sorted.
Fill {
x0: i32,
y0: i32,
x1: i32,
y1: i32,
color: i32,
},
/// `textHighlight`.
Highlight {
x0: i32,
y0: i32,
x1: i32,
y1: i32,
},
Text {
text: Text,
x: i32,
y: i32,
color: i32,
shadow: bool,
},
/// `enableScissor`, `disableScissor`.
Scissor {
x0: i32,
y0: i32,
x1: i32,
y1: i32,
},
NoScissor,
/// `setTooltipForNextFrame`: the split lines and the mouse.
Tooltip {
lines: Vec<Text>,
x: i32,
y: i32,
},
}
pub const WHITE: i32 = -1;
pub const GRAY: u32 = 0xAAAAAA;
pub const DARK_GRAY: u32 = 0x555555;
pub fn fill(out: &mut Vec<Draw>, x0: i32, y0: i32, x1: i32, y1: i32, color: i32) {
out.push(Draw::Fill {
x0: x0.min(x1),
y0: y0.min(y1),
x1: x0.max(x1),
y1: y0.max(y1),
color,
});
}
pub fn sprite(out: &mut Vec<Draw>, sprite: &str, x: i32, y: i32, w: i32, h: i32) {
out.push(Draw::Sprite {
sprite: sprite.to_owned(),
x,
y,
w,
h,
color: WHITE,
});
}
/// `blit(pipeline, texture, x, y, u, v, w, h, texW, texH)`.
pub fn blit(
out: &mut Vec<Draw>,
texture: &str,
x: i32,
y: i32,
uv: (f32, f32),
w: i32,
h: i32,
tex: [i32; 2],
) {
out.push(Draw::Blit {
texture: texture.to_owned(),
x,
y,
w,
h,
u: uv.0,
v: uv.1,
src: [w, h],
tex,
color: WHITE,
});
}
/// `graphics.text`: dropped when fully transparent; legacy codes resolved.
pub fn text(out: &mut Vec<Draw>, text: Text, x: i32, y: i32, color: i32, shadow: bool) {
if (color as u32) >> 24 != 0 {
out.push(Draw::Text {
text: text.resolve_legacy(),
x,
y,
color,
shadow,
});
}
}
/// `StringDecomposer.iterateFormatted`: the drawn characters of `contents`,
/// with their index in it and their style; legacy `§` codes restyle what
/// follows them, `§r` returns to `reset`.
pub fn formatted(contents: &str, current: &Style, reset: &Style) -> Vec<(usize, char, Style)> {
let chars: Vec<char> = contents.chars().collect();
let mut style = current.clone();
let mut out = Vec::new();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c == '§' {
let Some(code) = chars.get(i + 1) else { break };
let code = code.to_ascii_lowercase();
if let Some(c) = crate::text::COLORS.iter().find(|c| c.0 == code) {
style = Style {
color: Some(c.2),
bold: Some(false),
italic: Some(false),
underlined: Some(false),
strikethrough: Some(false),
obfuscated: Some(false),
..style
};
} else {
match code {
'k' => style.obfuscated = Some(true),
'l' => style.bold = Some(true),
'm' => style.strikethrough = Some(true),
'n' => style.underlined = Some(true),
'o' => style.italic = Some(true),
'r' => style = reset.clone(),
_ => {}
}
}
i += 2;
continue;
}
out.push((i, c, style.clone()));
i += 1;
}
out
}
/// Text measurement as vanilla's `Font` and `StringSplitter` do it, on
/// text whose spans may hold legacy `§` codes (each span is a component's
/// contents and style).
pub struct Measure<'a>(pub &'a Font);
impl Measure<'_> {
/// `Font.width`.
pub fn width(&self, t: &Text) -> i32 {
self.0.width_text(&t.resolve_legacy()) as i32
}
pub fn width_str(&self, s: &str) -> i32 {
self.0.width(s) as i32
}
/// `StringSplitter.headByWidth`: the leading characters whose widths sum to at most `max`.
pub fn head(&self, t: &Text, max: i32) -> Text {
let mut left = max as f32;
let mut out = Text::empty();
for span in &t.spans {
let mut end = None;
let mut position = 0;
for (i, c, style) in formatted(&span.text, &span.style, &span.style) {
left -= self.0.advance(c, &style);
if left >= 0.0 {
position = i + 1;
} else {
end = Some(position);
break;
}
}
match end {
Some(p) => {
out.push(Text::styled(
span.text.chars().take(p).collect::<String>(),
span.style.clone(),
));
return out;
}
None => out.push(Text::styled(span.text.clone(), span.style.clone())),
}
}
t.clone()
}
/// `Font.plainSubstrByWidth`, from the start or (`tail`) the end, in characters.
pub fn plain(&self, s: &str, max: i32, tail: bool) -> usize {
if tail {
self.0.fit_reverse(s, max as f32)
} else {
self.0.fit(s, max as f32)
}
}
/// `StringSplitter.splitLines` (`Font.split`): breaks at a newline, or
/// at the last space (else the character) once the width is exceeded;
/// the rest of a broken part takes the style found at the break, legacy
/// codes counted from the root style.
pub fn split(&self, t: &Text, max: i32) -> Vec<Text> {
let max = (max as f32).max(1.0);
let mut parts: Vec<(Vec<char>, Style)> = t
.spans
.iter()
.filter(|s| !s.text.is_empty())
.map(|s| (s.text.chars().collect(), s.style.clone()))
.collect();
let mut lines = Vec::new();
let mut force_new_line = false;
let root = Style::default();
'restart: loop {
let (mut width, mut had_visible) = (0.0f32, false);
let (mut last_space, mut last_space_style) = (None::<usize>, Style::default());
let mut offset = 0;
for (pi, (contents, style)) in parts.iter().enumerate() {
let s: String = contents.iter().collect();
for (i, c, st) in formatted(&s, style, &root) {
let at = i + offset;
let brk = if c == '\n' {
Some((at, st.clone()))
} else {
if c == ' ' {
last_space = Some(at);
last_space_style = st.clone();
}
let w = self.0.advance(c, &st);
width += w;
if !had_visible || width <= max {
had_visible |= w != 0.0;
None
} else {
Some(match last_space {
Some(p) => (p, last_space_style.clone()),
None => (at, st.clone()),
})
}
};
if let Some((at, split_style)) = brk {
let flat: Vec<char> =
parts.iter().flat_map(|p| p.0.iter().copied()).collect();
let first = flat.get(at).copied().unwrap_or(' ');
let new_line = first == '\n';
let skip = usize::from(new_line || first == ' ');
force_new_line = new_line;
// FlatComponents.splitAt.
let mut line = Text::empty();
let mut position = at;
let mut rest = Vec::new();
let mut in_skip = false;
let mut done = false;
for (contents, style) in parts.drain(..) {
if done {
rest.push((contents, style));
continue;
}
let size = contents.len();
if !in_skip {
if position > size {
line.push(Text::styled(
contents.iter().collect::<String>(),
style,
));
position -= size;
continue;
}
let before: String = contents[..position].iter().collect();
if !before.is_empty() {
line.push(Text::styled(before, style.clone()));
}
position += skip;
in_skip = true;
}
if position <= size {
if position < size {
rest.push((contents[position..].to_vec(), split_style.clone()));
}
done = true;
continue;
}
position -= size;
}
let _ = pi;
parts = rest;
lines.push(line);
continue 'restart;
}
}
offset += contents.len();
}
break;
}
if !parts.is_empty() {
let mut line = Text::empty();
for (contents, style) in parts {
line.push(Text::styled(contents.iter().collect::<String>(), style));
}
lines.push(line);
} else if force_new_line {
lines.push(Text::empty());
}
lines
}
}
/// `TextAlignment.CENTER.calculateLeft`.
pub fn center_left(anchor: i32, width: i32) -> i32 {
anchor - width / 2
}
/// `ComponentRenderUtils.clipText`: as much as fits before an unstyled "...".
pub fn clip(m: &Measure, t: &Text, width: i32) -> Text {
m.head(t, width - m.width_str("..."))
.append(Text::literal("..."))
}
/// `StringWidget` (CLAMPED) at its position: its single line, clipped when wider than `max_width`.
pub fn string_widget(
out: &mut Vec<Draw>,
m: &Measure,
message: &Text,
x: i32,
y: i32,
max_width: i32,
) {
let w = m.width(message);
let max = if max_width > 0 { max_width } else { w };
let line = if w > max {
clip(m, message, max)
} else {
message.clone()
};
text(out, line, x, y, WHITE, true);
}
/// `MultiLineLabel.create(font, maxWidth, maxRows, message)`: the lines and their widths;
/// the last kept line gets "..." in `ellipsis` (the message's own style) when rows were cut.
pub fn label_lines(
m: &Measure,
message: &Text,
max_width: i32,
max_rows: usize,
ellipsis: &Style,
) -> Vec<(Text, i32)> {
let split = m.split(message, max_width);
let n = split.len().min(max_rows);
let mut out = Vec::new();
for (i, line) in split.iter().take(n).enumerate() {
if i == n - 1 && n == max_rows && n != split.len() {
let clipped = m.head(line, m.width(line) - m.width_str("..."));
let with = clipped.append(Text::styled("...", ellipsis.clone()));
let w = m.width(&with);
out.push((with, w));
} else {
out.push((line.clone(), m.width(line)));
}
}
out
}
/// `MultiLineTextWidget.getWidth`.
pub fn label_width(lines: &[(Text, i32)], max_width: i32) -> i32 {
lines.iter().map(|l| l.1).max().unwrap_or(0).min(max_width)
}
/// `MultiLineTextWidget.visitLines`.
pub fn label(
out: &mut Vec<Draw>,
lines: &[(Text, i32)],
x: i32,
y: i32,
max_width: i32,
centered: bool,
) {
let mid = x + label_width(lines, max_width) / 2;
for (i, (line, w)) in lines.iter().enumerate() {
let left = if centered { center_left(mid, *w) } else { x };
text(out, line.clone(), left, y + 9 * i as i32, WHITE, true);
}
}
/// `Button` (`extractDefaultSprite` and the label over its contents, which
/// must fit: scrolling labels depend on the clock).
pub fn button(
out: &mut Vec<Draw>,
m: &Measure,
label: &Text,
x: i32,
y: i32,
w: i32,
h: i32,
active: bool,
highlighted: bool,
) {
let sprite_id = if !active {
"widget/button_disabled"
} else if highlighted {
"widget/button_highlighted"
} else {
"widget/button"
};
sprite(out, sprite_id, x, y, w, h);
let (left, right) = (x + 2, x + w - 2);
let lw = m.width(label);
let top = (y + y + h - 9) / 2 + 1;
let cx = ((left + right) / 2).clamp(left + lw / 2, right - lw / 2);
text(out, label.clone(), center_left(cx, lw), top, WHITE, true);
}
/// `Tooltip.splitTooltip` of a widget's tooltip, shown under the mouse.
pub fn tooltip(out: &mut Vec<Draw>, m: &Measure, message: &Text, mouse: (i32, i32)) {
out.push(Draw::Tooltip {
lines: m.split(message, 170),
x: mouse.0,
y: mouse.1,
});
}
/// `AbstractWidget.areCoordinatesInRectangle`.
pub fn inside(mouse: (i32, i32), x: i32, y: i32, w: i32, h: i32) -> bool {
mouse.0 >= x && mouse.1 >= y && mouse.0 < x + w && mouse.1 < y + h
}
/// Vanilla's `EditBox`: value, cursor, selection and the first shown
/// character, which follows the cursor as `scrollTo` moves it. Positions
/// are in characters.
#[derive(Clone, Debug)]
pub struct TextField {
pub value: String,
pub cursor: usize,
pub highlight: usize,
pub display: usize,
pub max_length: usize,
pub bordered: bool,
pub x: i32,
pub y: i32,
pub width: i32,
pub height: i32,
pub focused: bool,
pub text_color: i32,
pub text_shadow: bool,
pub hint: Option<Text>,
pub suggestion: Option<String>,
}
fn chars(s: &str) -> usize {
s.chars().count()
}
fn sub(s: &str, from: usize, to: usize) -> String {
s.chars().skip(from).take(to.saturating_sub(from)).collect()
}
impl TextField {
pub fn new(x: i32, y: i32, width: i32, height: i32) -> Self {
Self {
value: String::new(),
cursor: 0,
highlight: 0,
display: 0,
max_length: 32,
bordered: true,
x,
y,
width,
height,
focused: false,
text_color: -2039584,
text_shadow: true,
hint: None,
suggestion: None,
}
}
pub fn inner_width(&self) -> i32 {
if self.bordered {
self.width - 8
} else {
self.width
}
}
fn text_x(&self) -> i32 {
self.x + if self.bordered { 4 } else { 0 }
}
fn text_y(&self) -> i32 {
if self.bordered {
self.y + (self.height - 8) / 2
} else {
self.y
}
}
/// `setValue`.
pub fn set_value(&mut self, m: &Measure, value: &str) {
self.value = value.chars().take(self.max_length).collect();
self.move_cursor_to(m, chars(&self.value), false);
self.set_highlight(m, self.cursor);
}
/// `insertText`: replaces the selection within the maximum length. True
/// when the value changed (its responder runs).
pub fn insert_text(&mut self, m: &Measure, input: &str) -> bool {
let (start, end) = (
self.cursor.min(self.highlight),
self.cursor.max(self.highlight),
);
let room = self.max_length as isize - chars(&self.value) as isize + (end - start) as isize;
if room <= 0 {
return false;
}
let filtered: String = input
.chars()
.filter(|c| *c >= ' ' && *c != '\u{7f}' && *c != '§')
.collect();
let insert: String = filtered.chars().take(room as usize).collect();
let n = chars(&insert);
self.value = format!(
"{}{}{}",
sub(&self.value, 0, start),
insert,
sub(&self.value, end, chars(&self.value))
);
self.set_cursor(m, start + n);
self.set_highlight(m, self.cursor);
true
}
/// `deleteChars(dir)`: the selection, or `dir` characters from the cursor.
pub fn delete_chars(&mut self, m: &Measure, dir: isize) -> bool {
if self.value.is_empty() {
return false;
}
if self.highlight != self.cursor {
return self.insert_text(m, "");
}
let pos = (self.cursor as isize + dir).clamp(0, chars(&self.value) as isize) as usize;
let (start, end) = (pos.min(self.cursor), pos.max(self.cursor));
if start == end {
return false;
}
self.value = format!(
"{}{}",
sub(&self.value, 0, start),
sub(&self.value, end, chars(&self.value))
);
self.set_cursor(m, start);
self.move_cursor_to(m, start, false);
true
}
pub fn move_cursor_to(&mut self, m: &Measure, pos: usize, extend: bool) {
self.set_cursor(m, pos);
if !extend {
self.set_highlight(m, self.cursor);
}
}
fn set_cursor(&mut self, m: &Measure, pos: usize) {
self.cursor = pos.min(chars(&self.value));
self.scroll_to(m, self.cursor);
}
fn set_highlight(&mut self, m: &Measure, pos: usize) {
self.highlight = pos.min(chars(&self.value));
self.scroll_to(m, self.highlight);
}
fn scroll_to(&mut self, m: &Measure, pos: usize) {
let len = chars(&self.value);
self.display = self.display.min(len);
let inner = self.inner_width();
let rest = sub(&self.value, self.display, len);
let last = m.plain(&rest, inner, false) + self.display;
let mut display = self.display as isize;
if pos == self.display {
display -= m.plain(&self.value, inner, true) as isize;
}
if pos > last {
display += (pos - last) as isize;
} else if pos as isize <= display {
display = pos as isize;
}
self.display = display.clamp(0, len as isize) as usize;
}
/// `onClick`: the cursor where the mouse is (`findClickedPositionInText`).
pub fn click(&mut self, m: &Measure, x: f64, extend: bool) {
let pos = (x.floor() as i32 - self.text_x()).min(self.inner_width());
let rest = sub(&self.value, self.display, chars(&self.value));
let at = self.display + m.plain(&rest, pos, false);
self.move_cursor_to(m, at, extend);
}
pub fn contains(&self, x: f64, y: f64) -> bool {
x >= self.x as f64
&& y >= self.y as f64
&& x < (self.x + self.width) as f64
&& y < (self.y + self.height) as f64
}
/// `extractWidgetRenderState`; `blink_ms` is the time since the field
/// was focused, `format` styles a substring starting at a character index.
pub fn draw(
&self,
out: &mut Vec<Draw>,
m: &Measure,
blink_ms: u64,
format: Option<&dyn Fn(&str, usize) -> Text>,
) {
if self.bordered {
let s = if self.focused {
"widget/text_field_highlighted"
} else {
"widget/text_field"
};
sprite(out, s, self.x, self.y, self.width, self.height);
}
let color = self.text_color;
let len = chars(&self.value);
let rest = sub(&self.value, self.display, len);
let shown_len = m.plain(&rest, self.inner_width(), false);
let displayed = sub(&rest, 0, shown_len);
let rel_cursor = self.cursor as isize - self.display as isize;
let on_screen = rel_cursor >= 0 && rel_cursor <= shown_len as isize;
let show_cursor = self.focused && (blink_ms / 300).is_multiple_of(2) && on_screen;
let (tx, ty) = (self.text_x(), self.text_y());
let mut draw_x = tx;
let rel_highlight =
(self.highlight as isize - self.display as isize).clamp(0, shown_len as isize) as usize;
let styled = |s: String, offset: usize| match format {
Some(f) => f(&s, offset),
None => Text::literal(s),
};
if !displayed.is_empty() {
let half = if on_screen {
sub(&displayed, 0, rel_cursor as usize)
} else {
displayed.clone()
};
let t = styled(half, self.display);
let w = m.width(&t);
text(out, t, draw_x, ty, color, self.text_shadow);
draw_x += w + 1;
}
let insert = self.cursor < len || len >= self.max_length;
let mut cursor_x = draw_x;
if !on_screen {
cursor_x = if rel_cursor > 0 { tx + self.width } else { tx };
} else if insert {
cursor_x -= 1;
draw_x -= 1;
}
if !displayed.is_empty() && on_screen && (rel_cursor as usize) < shown_len {
let t = styled(sub(&displayed, rel_cursor as usize, shown_len), self.cursor);
text(out, t, draw_x, ty, color, self.text_shadow);
}
if let Some(hint) = &self.hint
&& displayed.is_empty()
&& !self.focused
{
text(out, hint.clone(), draw_x, ty, color, true);
}
if !insert && let Some(s) = &self.suggestion {
text(
out,
Text::literal(s.clone()),
cursor_x - 1,
ty,
-8355712,
self.text_shadow,
);
}
if rel_highlight as isize != rel_cursor {
let hx = tx + m.width_str(&sub(&displayed, 0, rel_highlight));
let right = self.x + self.width;
out.push(Draw::Highlight {
x0: cursor_x.min(right),
y0: ty - 1,
x1: (hx - 1).min(right),
y1: ty + 1 + 9,
});
}
if show_cursor {
if insert {
fill(out, cursor_x, ty - 1, cursor_x + 1, ty + 10, color);
} else {
text(
out,
Text::literal("_"),
cursor_x,
ty,
color,
self.text_shadow,
);
}
}
}
}
/// Draws the calls with the HUD batch: sprites nine-sliced, textures from
/// the atlas (`textures/gui/x.png` is `gui/x`; tiled textures from their
/// corner), scissor clipping, and the tooltip at the mouse.
pub fn paint(batch: &mut HudBatch, atlas: &HudAtlas, draws: &[Draw]) {
let mut clip: Option<(usize, [i32; 4])> = None;
let mut tooltip = None;
for d in draws {
match d {
Draw::Sprite {
sprite,
x,
y,
w,
h,
color,
} => crate::ui::nine_slice(
batch,
atlas,
&format!("gui/sprites/{sprite}"),
*x as f32,
*y as f32,
*w as f32,
*h as f32,
crate::hud_layout::abgr(*color as u32),
),
Draw::Blit {
texture,
x,
y,
w,
h,
u,
v,
src,
tex,
color,
} => {
let key = texture
.trim_start_matches("textures/")
.trim_end_matches(".png");
let key = if atlas.sprites.contains_key(key) {
key
} else {
"misc/unknown_pack"
};
let color = crate::hud_layout::abgr(*color as u32);
if src[0] == tex[0] && src[1] == tex[1]
|| (*u == 0.0 && *v == 0.0 && src[0] <= tex[0] && src[1] <= tex[1])
{
if let Some(mut r) = atlas.sprites.get(key).copied() {
let (du, dv) = (r.u1 - r.u0, r.v1 - r.v0);
r.u1 = r.u0 + du * src[0] as f32 / tex[0] as f32;
r.v1 = r.v0 + dv * src[1] as f32 / tex[1] as f32;
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, color);
}
} else {
crate::ui::tiled(
batch,
atlas,
key,
*x as f32,
*y as f32,
*w as f32,
*h as f32,
tex[0] as f32,
color,
);
}
}
Draw::Fill {
x0,
y0,
x1,
y1,
color,
} => batch.fill(
atlas,
*x0 as f32,
*y0 as f32,
(x1 - x0) as f32,
(y1 - y0) as f32,
crate::hud_layout::abgr(*color as u32),
),
Draw::Highlight { x0, y0, x1, y1 } => {
let (a, b) = ((*x0).min(*x1), (*x0).max(*x1));
batch.fill(
atlas,
a as f32,
*y0 as f32,
(b - a) as f32,
(y1 - y0) as f32,
crate::hud::rgba(0, 0, 255, 128),
);
}
Draw::Text {
text,
x,
y,
color,
shadow,
} => {
batch.text_styled(
atlas,
text,
*x as f32,
*y as f32,
crate::hud_layout::abgr(*color as u32),
*shadow,
);
}
Draw::Scissor { x0, y0, x1, y1 } => {
clip = Some((batch.vertices.len(), [*x0, *y0, *x1, *y1]))
}
Draw::NoScissor => {
if let Some((start, [x0, y0, x1, y1])) = clip.take() {
batch.clip_since(start, x0 as f32, y0 as f32, x1 as f32, y1 as f32);
}
}
Draw::Tooltip { lines, x, y } => {
tooltip = Some((lines.clone(), (*x as f32, *y as f32)))
}
}
}
if let Some((lines, at)) = tooltip {
crate::ui::tooltip(batch, atlas, &lines, at);
}
}
@@ -0,0 +1,395 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
import com.mojang.serialization.JsonOps;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.client.InputType;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ActiveTextCollector;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.gui.TextAlignment;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.WidgetTooltipHolder;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner;
import net.minecraft.client.gui.screens.packs.PackSelectionScreen;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.input.MouseButtonInfo;
import net.minecraft.client.sounds.SoundManager;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.PackLocationInfo;
import net.minecraft.server.packs.PackSelectionConfig;
import net.minecraft.server.packs.repository.Pack;
import net.minecraft.server.packs.repository.PackCompatibility;
import net.minecraft.server.packs.repository.PackRepository;
import net.minecraft.server.packs.repository.PackSource;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.util.Util;
import net.minecraft.world.flag.FeatureFlagSet;
import net.minecraft.world.inventory.tooltip.TooltipComponent;
import org.joml.Matrix3x2f;
import org.joml.Matrix3x2fStack;
/**
* Original oracle for the resource pack screen's drawing: a real
* PackSelectionScreen over a PackRepository of the case's packs (titles,
* descriptions, sources, compatibility, required, positions, icons), driven
* by the case's clicks, typing in the search box and mouse wheel, with the
* ConfirmScreen an incompatible pack opens (a stand-in Gui switches screens
* as Gui.setScreen does: the old screen loses focus, the new one is
* initialised or repositioned). The screen shown at the end is drawn
* (Screen.extractRenderState: its widgets, then the tooltip) and every
* GuiGraphicsExtractor call is recorded.
*
* Input lines: case JSON. Output lines: {screen, draws} or {error}.
*/
public final class VanillaPackScreenOracle {
static Object unsafe;
static Method allocate;
static Font font;
@SuppressWarnings("unchecked")
static <T> T alloc(Class<T> type) throws Exception {
return (T) allocate.invoke(unsafe, type);
}
static Field field(Class<?> owner, String name) throws Exception {
Field f = owner.getDeclaredField(name);
f.setAccessible(true);
return f;
}
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 Object call(Object target, Class<?> owner, String name) throws Exception {
Method m = owner.getDeclaredMethod(name);
m.setAccessible(true);
return m.invoke(target);
}
/** Styled runs: [text, rgb or null, bold, italic, underlined, strikethrough, obfuscated]. */
static JsonArray runs(FormattedCharSequence s) {
var runs = new JsonArray();
s.accept((index, style, cp) -> {
Integer rgb = style.getColor() == null ? null : style.getColor().getValue();
boolean[] flags = {style.isBold(), style.isItalic(), style.isUnderlined(), style.isStrikethrough(), style.isObfuscated()};
JsonArray last = runs.isEmpty() ? null : runs.get(runs.size() - 1).getAsJsonArray();
boolean same = last != null && Objects.equals(last.get(1).isJsonNull() ? null : last.get(1).getAsInt(), rgb);
for (int i = 0; same && i < 5; i++) same = last.get(2 + i).getAsBoolean() == flags[i];
if (same) {
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);
for (boolean f : flags) run.add(f);
runs.add(run);
}
return true;
});
return runs;
}
/** Records every GuiGraphicsExtractor call. */
public static final class Capture extends GuiGraphicsExtractor {
JsonArray draws;
Matrix3x2fStack stack;
int width, height;
private Capture() { super(null, null, 0, 0); }
@Override public int guiWidth() { return width; }
@Override public int guiHeight() { return height; }
@Override public Matrix3x2fStack pose() { return stack; }
@Override public void nextStratum() { add("stratum"); }
@Override public void requestCursor(com.mojang.blaze3d.platform.cursor.CursorType type) { }
@Override public boolean containsPointInScissor(int x, int y) { return true; }
JsonObject add(String type) {
var o = new JsonObject();
o.addProperty("type", type);
if (!stack.equals(new Matrix3x2f())) {
var a = new JsonArray();
for (float v : new float[] {stack.m00(), stack.m01(), stack.m10(), stack.m11(), stack.m20(), stack.m21()}) a.add(v);
o.add("matrix", a);
}
draws.add(o);
return o;
}
@Override public void enableScissor(int x0, int y0, int x1, int y1) {
var o = add("scissor");
o.addProperty("x0", x0); o.addProperty("y0", y0); o.addProperty("x1", x1); o.addProperty("y1", y1);
}
@Override public void disableScissor() { add("noscissor"); }
@Override public void fill(RenderPipeline p, int x0, int y0, int x1, int y1, int color) {
var o = add("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);
}
@Override public void textHighlight(int x0, int y0, int x1, int y1, boolean invert) {
var o = add("highlight");
o.addProperty("x0", x0); o.addProperty("y0", y0); o.addProperty("x1", x1); o.addProperty("y1", y1);
}
@Override public void blitSprite(RenderPipeline p, Identifier id, int x, int y, int w, int h, int color) {
var o = add("sprite");
o.addProperty("sprite", id.getPath());
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
o.addProperty("color", color);
}
@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", x); o.addProperty("y", y); o.addProperty("w", w); o.addProperty("h", h);
o.addProperty("u", u); o.addProperty("v", v);
o.addProperty("srcW", srcW); o.addProperty("srcH", srcH); o.addProperty("texW", texW); o.addProperty("texH", texH);
o.addProperty("color", color);
}
void text(FormattedCharSequence str, int x, int y, int color, boolean shadow) {
var o = add("text");
o.add("runs", runs(str));
o.addProperty("x", x); o.addProperty("y", y); o.addProperty("color", color); o.addProperty("shadow", shadow);
}
@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);
}
ActiveTextCollector collector(float opacity) {
var self = this;
return new ActiveTextCollector() {
Parameters parameters = new Parameters(new Matrix3x2f(stack), opacity, null);
@Override public Parameters defaultParameters() { return parameters; }
@Override public void defaultParameters(Parameters p) { parameters = p; }
@Override public void accept(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);
}
@Override public void acceptScrolling(Component m, int cx, int l, int r, int t, int b, Parameters p) {
defaultScrollingHelper(m, cx, l, r, t, b, font.width(m), 9, p);
}
};
}
@Override public ActiveTextCollector textRendererForWidget(AbstractWidget owner, GuiGraphicsExtractor.HoveredTextEffects effects) {
return collector(owner.getAlpha());
}
@Override public ActiveTextCollector textRenderer(GuiGraphicsExtractor.HoveredTextEffects effects, java.util.function.Consumer<net.minecraft.network.chat.Style> consumer) {
return collector(1.0F);
}
@Override public void setTooltipForNextFrame(Font font, List<FormattedCharSequence> lines, Optional<TooltipComponent> image,
ClientTooltipPositioner positioner, int x, int y, boolean replace, Identifier style) {
var o = add("tooltip");
var a = new JsonArray();
for (var l : lines) a.add(runs(l));
o.add("lines", a);
o.addProperty("x", x); o.addProperty("y", y);
}
}
/** The window's text input area: not tracked. */
static final class NoTextInput extends com.mojang.blaze3d.platform.TextInputManager {
NoTextInput() { super(null); }
@Override public void setTextInputArea(int x0, int y0, int x1, int y1) { }
@Override public void onTextInputFocusChange(Object owner, boolean focused) { }
@Override public void startTextInput(Object owner) { }
@Override public void stopTextInput(Object owner) { }
@Override public void stopTextInput() { }
}
/** Sounds are not played. */
public static final class NoSound extends SoundManager {
private NoSound() { super(null); }
@Override public net.minecraft.client.sounds.SoundEngine.PlayResult play(net.minecraft.client.resources.sounds.SoundInstance instance) { return null; }
}
/** No input method editor. */
public static final class NoKeyboard extends net.minecraft.client.KeyboardHandler {
private NoKeyboard() { super(null); }
@Override public void resubmitLastPreeditEvent(net.minecraft.client.gui.components.events.GuiEventListener e) { }
}
/** Gui.setScreen without the window: the screen shown, focus cleared on the old one. */
public static final class StubGui extends Gui {
Screen current;
int width, height;
private StubGui() { super(null, null, null); }
@Override public void setScreen(Screen screen) {
try {
if (current != null) {
current.clearFocus();
current.removed();
}
current = screen;
screen.added();
show(screen, width, height);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override public Screen screen() { return current; }
}
/** Screen.init(width, height) without narration. */
static void show(Screen screen, int width, int height) throws Exception {
screen.width = width;
screen.height = height;
if (!(boolean) field(Screen.class, "initialized").get(screen)) {
call(screen, Screen.class, "init");
Method m = Screen.class.getDeclaredMethod("setInitialFocus");
m.setAccessible(true);
m.invoke(screen);
} else {
Method m = screen.getClass().getDeclaredMethod("repositionElements");
m.setAccessible(true);
m.invoke(screen);
}
put(screen, Screen.class, "initialized", true);
}
static Component component(JsonElement e) {
return ComponentSerialization.CODEC.parse(JsonOps.INSTANCE, e).getOrThrow();
}
static Pack pack(JsonObject o) {
String id = o.get("id").getAsString();
PackSource source = switch (o.get("source").getAsString()) {
case "builtin" -> PackSource.BUILT_IN;
case "world" -> PackSource.WORLD;
case "server" -> PackSource.SERVER;
case "feature" -> PackSource.FEATURE;
default -> PackSource.DEFAULT;
};
var location = new PackLocationInfo(id, component(o.get("title")), source, Optional.empty());
var compatibility = switch (o.get("compat").getAsString()) {
case "old" -> PackCompatibility.TOO_OLD;
case "new" -> PackCompatibility.TOO_NEW;
case "unknown" -> PackCompatibility.UNKNOWN;
default -> PackCompatibility.COMPATIBLE;
};
var metadata = new Pack.Metadata(component(o.get("description")), compatibility, FeatureFlagSet.of(), List.of());
var config = new PackSelectionConfig(o.get("required").getAsBoolean(),
o.get("position").getAsString().equals("top") ? Pack.Position.TOP : Pack.Position.BOTTOM, o.get("fixed").getAsBoolean());
return new Pack(location, null, metadata, config);
}
static JsonObject run(JsonObject c, Minecraft mc, StubGui gui) throws Exception {
int width = c.get("width").getAsInt(), height = c.get("height").getAsInt();
gui.width = width;
gui.height = height;
gui.current = null;
put(mc, Minecraft.class, "level", c.get("inWorld").getAsBoolean() ? alloc(net.minecraft.client.multiplayer.ClientLevel.class) : null);
List<Pack> packs = new ArrayList<>();
Map<String, Boolean> icons = new HashMap<>();
for (var p : c.getAsJsonArray("packs")) {
packs.add(pack(p.getAsJsonObject()));
icons.put(p.getAsJsonObject().get("id").getAsString(), p.getAsJsonObject().get("icon").getAsBoolean());
}
var repository = new PackRepository(consumer -> packs.forEach(consumer));
repository.reload();
List<String> initial = new ArrayList<>();
for (var s : c.getAsJsonArray("selected")) initial.add(s.getAsString());
repository.setSelected(initial);
var screen = new PackSelectionScreen(repository, r -> { }, Path.of(c.get("dir").getAsString()), Component.translatable("resourcePack.title"));
gui.setScreen(screen);
// PackSelectionScreen.loadPackIcon: a pack with a pack.png gets its own texture.
@SuppressWarnings("unchecked")
var iconMap = (Map<String, Identifier>) field(PackSelectionScreen.class, "packIcons").get(screen);
iconMap.clear();
for (var e : icons.entrySet()) {
String id = e.getKey();
iconMap.put(id, e.getValue()
? Identifier.withDefaultNamespace("pack/" + Util.sanitizeName(id, Identifier::validPathChar) + "/" + com.google.common.hash.Hashing.sha1().hashUnencodedChars(id) + "/icon")
: Identifier.withDefaultNamespace("textures/misc/unknown_pack.png"));
}
var search = (EditBox) field(PackSelectionScreen.class, "search").get(screen);
var info = new MouseButtonInfo(1, 0);
for (var a : c.getAsJsonArray("actions")) {
var o = a.getAsJsonObject();
Screen s = gui.current;
switch (o.get("type").getAsString()) {
case "click" -> {
var event = new MouseButtonEvent(o.get("x").getAsDouble(), o.get("y").getAsDouble(), info);
// Never press Open Pack Folder: it opens a file manager.
if (s.getChildAt(event.x(), event.y()).orElse(null) instanceof net.minecraft.client.gui.components.Button b
&& b.getMessage().getString().equals(Component.translatable("pack.openFolder").getString())) {
throw new IllegalArgumentException("click on Open Pack Folder");
}
s.mouseClicked(event, false);
if (gui.current == s) s.mouseReleased(event);
}
case "scroll" -> s.mouseScrolled(o.get("x").getAsDouble(), o.get("y").getAsDouble(), 0.0, o.get("amount").getAsDouble());
case "type" -> { if (s == screen && screen.getFocused() == search) search.insertText(o.get("text").getAsString()); }
case "erase" -> { if (s == screen && screen.getFocused() == search) search.deleteChars(-o.get("count").getAsInt()); }
default -> throw new IllegalArgumentException(o.toString());
}
}
Screen shown = gui.current;
for (var w : shown.children()) {
if (w instanceof AbstractWidget widget) {
var holder = (WidgetTooltipHolder) field(AbstractWidget.class, "tooltip").get(widget);
put(holder, WidgetTooltipHolder.class, "wasDisplayed", widget.isMouseOver(c.getAsJsonArray("mouse").get(0).getAsInt(), c.getAsJsonArray("mouse").get(1).getAsInt()));
put(holder, WidgetTooltipHolder.class, "displayStartTime", Util.getMillis() - 1000L);
}
}
if (shown == screen) put(search, EditBox.class, "focusedTime", Util.getMillis() - c.get("blink").getAsLong());
var g = alloc(Capture.class);
g.draws = new JsonArray();
g.stack = new Matrix3x2fStack(16);
g.width = width;
g.height = height;
shown.extractRenderState(g, c.getAsJsonArray("mouse").get(0).getAsInt(), c.getAsJsonArray("mouse").get(1).getAsInt(), 1.0F);
var result = new JsonObject();
result.addProperty("screen", shown == screen ? "packs" : shown instanceof ConfirmScreen ? "confirm" : shown.getClass().getSimpleName());
result.add("draws", g.draws);
return result;
}
public static void main(String[] args) throws Exception {
ParityData.init();
var unsafeField = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe");
unsafeField.setAccessible(true);
unsafe = unsafeField.get(null);
allocate = unsafe.getClass().getMethod("allocateInstance", Class.class);
font = ParityFont.create(ParityFont.resources());
Minecraft mc = alloc(Minecraft.class);
put(mc, Minecraft.class, "font", font);
put(mc, Minecraft.class, "lastInputType", InputType.MOUSE);
put(mc, Minecraft.class, "textInputManager", new NoTextInput());
put(mc, Minecraft.class, "soundManager", alloc(NoSound.class));
put(mc, Minecraft.class, "keyboardHandler", alloc(NoKeyboard.class));
var gui = alloc(StubGui.class);
put(mc, Minecraft.class, "gui", gui);
field(Minecraft.class, "instance").set(null, mc);
var gson = new Gson();
var out = new StringBuilder();
for (String line : Files.readAllLines(Path.of(args[0]))) {
if (line.isBlank()) continue;
var c = JsonParser.parseString(line).getAsJsonObject();
JsonObject result;
try {
result = run(c, mc, gui);
} catch (Throwable error) {
Throwable cause = error;
while (cause.getCause() != null) cause = cause.getCause();
var sw = new java.io.StringWriter();
cause.printStackTrace(new java.io.PrintWriter(sw));
result = new JsonObject();
result.addProperty("error", sw.toString().lines().limit(10).reduce("", (a, b) -> a + b + " | "));
}
out.append(gson.toJson(result)).append('\n');
}
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
}
}
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
"""Compare the resource pack screen's drawing with the vanilla client's.
Each case is a pack repository (titles and descriptions as text components,
with legacy formatting codes, colours and styles; pack sources; compatible,
too old, too new or unknown packs; required, fixed and positioned packs;
icons), an initial selection, a GUI size, in a world or not, and what the
player does: clicks on the lists (an entry's icon arrows, an entry, a
header, the scroll bar, empty space), on the search box, typing and erasing
in it, the mouse wheel over the lists, and the ConfirmScreen an incompatible
pack opens (yes, no, or left open). The Java oracle
(VanillaPackScreenOracle) runs a real PackSelectionScreen through these and
records every GuiGraphicsExtractor call of the screen shown at the end
(widgets, list backgrounds, scissor, separators, scroll bars, entries with
their incompatibility tint, hover overlay and arrows, the selection
outline, the search box, the buttons and their tooltip);
examples/pack_screen_fixture runs horizon_client::pack_screen, which the
game's pack screen is, through the same actions. The call lists must agree.
test_pack_screen_parity.py [--count N] [--detail N]
"""
import argparse
import json
import os
import random
import subprocess
import sys
try:
from . import interaction_lab as lib, lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import interaction_lab as lib
import lab
import test_rust_parity as base
import test_model_baking_parity as baking
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
IDS = ['vanilla', 'programmer_art', 'file/Faithful.zip', 'file/alpha', 'file/Zeta pack', 'file/zeta', 'file/é', 'file/0',
'server', 'world', 'fabric', 'file/a.zip', 'file/A.zip', 'file/b', 'file/HC', 'file/Stay True 1.21.zip']
WORDS = ['Faithful', 'pack', 'textures', 'the', 'default', 'look', 'of', 'Minecraft', 'x32', 'by', 'Vattic',
'Programmer', 'Art', 'resolution', 'a', 'very', 'loooooooooooooooooooooongword', '§4red', '§lbold§r', '1.21', '!',
'Stay', 'True', 'é', 'Ünïcödé']
COLORS = ['red', 'gold', 'aqua', 'gray', '#12AB34', 'dark_purple', 'yellow']
def words(rng, lo, hi):
return ' '.join(rng.choice(WORDS) for _ in range(rng.randint(lo, hi)))
def component(rng, lo, hi):
kind = rng.random()
if kind < 0.45:
return words(rng, lo, hi)
if kind < 0.6:
return words(rng, lo, hi) + '\n' + words(rng, 1, hi)
if kind < 0.85:
part = {'text': words(rng, lo, hi)}
for key in ('bold', 'italic', 'underlined'):
if rng.random() < 0.2:
part[key] = True
if rng.random() < 0.6:
part['color'] = rng.choice(COLORS)
if rng.random() < 0.4:
part['extra'] = [{'text': ' ' + words(rng, 1, 4), 'color': rng.choice(COLORS)}]
return part
return [words(rng, 1, 3), {'text': ' ' + words(rng, lo, hi), 'color': rng.choice(COLORS)}]
def cases(count):
rng = random.Random(0x50534352)
out = []
for n in range(count):
width, height = rng.choice([(320, 240), (427, 240), (480, 270), (640, 360), (854, 480), (400, 160), (570, 320)])
ids = rng.sample(IDS, rng.randint(1, 14))
packs = []
for i in ids:
packs.append({'id': i, 'title': component(rng, 1, 3) if rng.random() < 0.8 else i,
'description': component(rng, 0, 14),
'source': rng.choice(['default'] * 4 + ['builtin', 'world', 'server', 'feature']),
'compat': rng.choice(['compatible'] * 5 + ['old', 'new', 'unknown']),
'required': rng.random() < 0.15, 'position': rng.choice(['top', 'top', 'bottom']),
'fixed': rng.random() < 0.15, 'icon': rng.random() < 0.4})
selected = rng.sample(ids, rng.randint(0, len(ids)))
cx = width // 2
left, right = cx - 15 - 200, cx + 15
top, bottom = 49, height - 33
def point():
r = rng.random()
if r < 0.6:
x0 = rng.choice([left, right])
row = rng.randint(0, 9)
y = top + 2 + 13 + 36 * row + rng.randint(-2, 35)
x = x0 + rng.choice([rng.randint(0, 40), rng.randint(0, 200), rng.randint(2, 36), rng.randint(194, 199)])
return x, min(y, bottom - 1)
if r < 0.7:
return rng.randint(cx - 100, cx + 99), rng.randint(30, 44)
if r < 0.8:
return rng.choice([left, right]) + rng.randint(0, 199), rng.randint(top, top + 16)
return rng.randint(0, width - 1), rng.randint(0, bottom - 1)
def safe(x, y):
# Not the Open Pack Folder button: vanilla would open the folder.
return not (cx - 154 <= x < cx - 4 and height - 26 <= y < height - 6)
actions = []
for _ in range(rng.choice([0, 1, 2, 4, 8, 14])):
r = rng.random()
if r < 0.7:
x, y = point() if r < 0.6 else (rng.randint(cx - 160, cx + 160), rng.randint(height // 2 - 30, height // 2 + 60))
if safe(x, y):
actions.append({'type': 'click', 'x': x, 'y': y})
elif r < 0.8:
x, y = point()
actions.append({'type': 'scroll', 'x': x, 'y': y, 'amount': rng.choice([-3, -1, 1, 2, 0.5])})
elif r < 0.93:
actions.append({'type': 'type', 'text': rng.choice(['a', 'e', 'pack', 'file', 'Faith', 'z', ' ', 'zzz', 'x32 by'])})
else:
actions.append({'type': 'erase', 'count': rng.randint(1, 4)})
mouse = rng.choice([point(), point(), point(), (rng.randint(0, width - 1), rng.randint(0, height - 1)),
(rng.randint(cx - 154, cx + 154), height - 26 + rng.randint(0, 19)),
(rng.randint(cx - 160, cx + 160), rng.randint(height // 2 - 30, height // 2 + 60))])
out.append({'width': width, 'height': height, 'inWorld': rng.random() < 0.3, 'packs': packs, 'selected': selected,
'actions': actions, 'mouse': list(mouse), 'blink': rng.choice([0, 100, 400, 650])})
return out
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--count', type=int, default=3000)
parser.add_argument('--detail', type=int, default=3)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'pack-screen-parity'; build.mkdir(parents=True, exist_ok=True)
(build / 'resourcepacks').mkdir(exist_ok=True)
chosen = cases(args.count)
for c in chosen:
c['dir'] = str(build / 'resourcepacks')
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]))
def run(command, name):
with (build / (name + '.log')).open('w') as log:
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
if result.returncode:
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, '-d', classes,
*(PARITY / f'{n}.java' for n in ('ParityData', 'ParityFont', 'VanillaPackScreenOracle'))], 'compile-java')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaPackScreenOracle',
inputs, build / 'vanilla.jsonl'], 'vanilla')
lib.cargo_example('horizon-client', 'pack_screen_fixture', lib.RESOURCES, inputs, build / 'rust.jsonl')
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust) == len(chosen), (len(vanilla), len(rust), len(chosen))
errors = [v['error'] for v in vanilla if 'error' in v]
bad = []
for c, v, r in zip(chosen, vanilla, rust):
if 'error' in v or v == r:
continue
bad.append((c, v, r))
for e in sorted(set(errors))[:5]:
print('ORACLE ERROR', e[:1500])
for c, v, r in bad[:args.detail]:
brief = {k: c[k] for k in ('width', 'height', 'inWorld', 'selected', 'actions', 'mouse', 'blink')}
print('MISMATCH', json.dumps(brief)[:1500])
if v.get('screen') != r.get('screen'):
print(f' screen: vanilla {v.get("screen")} | horizon {r.get("screen")}')
a, b = v.get('draws', []), r.get('draws', [])
i = next((i for i in range(max(len(a), len(b))) if i >= len(a) or i >= len(b) or a[i] != b[i]), None)
if i is not None:
print(f' call {i}: vanilla {json.dumps(a[i]) if i < len(a) else None}')
print(f' call {i}: horizon {json.dumps(b[i]) if i < len(b) else None}')
print(f'{len(chosen) - len(bad) - len(errors)}/{len(chosen)} pack screens match; {len(errors)} oracle errors')
if bad or errors:
sys.exit(1)
print('pack screen parity ok')
if __name__ == '__main__':
main()