The recipe book draws as vanilla's widgets do; test_recipe_book_render_parity
horizon_client::recipe_book_screen lays out RecipeBookComponent's drawing (background, search EditBox, tab buttons, the filter CycleButton, the page of RecipeButtons with its number and arrows, the alternatives overlay, tooltips) and GhostSlots as vanilla's GUI calls with their poses, and the game paints them. The new harness builds vanilla's widgets for 600 random states (VanillaRecipeBookScreenOracle) and compares every call: 600/600. Ingredients keep their HolderSet order (tags in TagLoader order), which is how the overlay and ghost slots cycle; the book centres over the menu on narrow screens as widthTooNarrow does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,263 @@
|
||||
//! The recipe book's drawing, for tools/test_recipe_book_render_parity.py:
|
||||
//! reads one JSON case per line (book type, GUI size, tabs, search box,
|
||||
//! filter, recipe collections and page, overlay, ghost slots, cycling index,
|
||||
//! mouse) and writes the calls `horizon_client::recipe_book_screen` makes,
|
||||
//! in the oracle's JSON form.
|
||||
//!
|
||||
//! usage: recipe_book_render_fixture RESOURCES CASES OUTPUT
|
||||
use horizon_client::{
|
||||
crafting::Recipes,
|
||||
hud::{HudAtlas, HudBatch},
|
||||
items::{ItemStack, Items},
|
||||
lang,
|
||||
recipe_book::{Book, BookType, Entry},
|
||||
recipe_book_screen::{
|
||||
ButtonView, Call, GhostView, ItemCall, OverlayRecipe, OverlayView, Run, Screen, Search,
|
||||
TabView, draw, overlay_cells, overlay_origin,
|
||||
},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{fmt::Write as _, fs, path::Path};
|
||||
|
||||
fn runs(r: &[Run]) -> Value {
|
||||
Value::Array(
|
||||
r.iter()
|
||||
.map(|r| json!([r.text, r.color, r.italic]))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
fn round(v: f32) -> f32 {
|
||||
(v * 1e4).round() / 1e4
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let usage = "usage: recipe_book_render_fixture RESOURCES CASES OUTPUT";
|
||||
let root = Path::new(args.get(1).ok_or(usage)?);
|
||||
let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?;
|
||||
let items = Items::catalog(root)?;
|
||||
let recipes = Recipes::load(root, &items)?;
|
||||
let book = Book::build(&recipes, &items);
|
||||
let atlas = HudAtlas::build(root)?;
|
||||
let root_buf = root.to_path_buf();
|
||||
lang::set(lang::Language::load(&[&root_buf], lang::DEFAULT));
|
||||
let translate = |key: &str| lang::get(key);
|
||||
let text_width = |s: &str| HudBatch::text_width(&atlas, s) as i32;
|
||||
let mut out = String::new();
|
||||
for line in cases.lines() {
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let int = |v: &Value| v.as_i64().unwrap_or(0) as i32;
|
||||
let kind = match case["type"].as_str().unwrap_or_default() {
|
||||
"crafting" => BookType::Crafting,
|
||||
"furnace" => BookType::Furnace,
|
||||
"blast_furnace" => BookType::BlastFurnace,
|
||||
_ => BookType::Smoker,
|
||||
};
|
||||
let filtering = case["filtering"].as_bool().unwrap_or(false);
|
||||
let tab_list = kind.tabs();
|
||||
let tabs: Vec<TabView> = case["tabs"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|t| {
|
||||
let (a, b) = tab_list[t["tab"].as_u64().unwrap_or(0) as usize].icons();
|
||||
TabView {
|
||||
icons: (a.to_owned(), b.map(str::to_owned)),
|
||||
selected: t["selected"].as_bool().unwrap_or(false),
|
||||
anim: t["anim"].as_f64().unwrap_or(0.0) as f32,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let s = &case["search"];
|
||||
let search = Search {
|
||||
value: s["value"].as_str().unwrap_or_default().to_owned(),
|
||||
cursor: s["cursor"].as_u64().unwrap_or(0) as usize,
|
||||
highlight: s["highlight"].as_u64().unwrap_or(0) as usize,
|
||||
display: s["display"].as_u64().unwrap_or(0) as usize,
|
||||
focused: s["focused"].as_bool().unwrap_or(false),
|
||||
blink_ms: s["blink"].as_u64().unwrap_or(0),
|
||||
};
|
||||
// Each collection's recipes and craftable flags.
|
||||
let collections: Vec<Vec<(&Entry, bool)>> = case["collections"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|c| {
|
||||
c["recipes"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|r| Some((book.entry(r[0].as_str()?)?, r[1].as_bool()?)))
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
let page = case["page"].as_u64().unwrap_or(0) as usize;
|
||||
let pages = collections.len().div_ceil(20);
|
||||
let anims = case["buttonAnims"].as_array().cloned().unwrap_or_default();
|
||||
let shown = &collections[(20 * page).min(collections.len())..];
|
||||
let buttons: Vec<ButtonView> = shown
|
||||
.iter()
|
||||
.take(20)
|
||||
.enumerate()
|
||||
.map(|(i, c)| ButtonView {
|
||||
has_craftable: c.iter().any(|e| e.1),
|
||||
entries: c
|
||||
.iter()
|
||||
.filter(|e| e.1 || !filtering)
|
||||
.map(|e| vec![e.0.result.clone()])
|
||||
.collect(),
|
||||
anim: anims.get(i).and_then(Value::as_f64).unwrap_or(0.0) as f32,
|
||||
})
|
||||
.collect();
|
||||
let (xo, yo) = Screen {
|
||||
book: kind,
|
||||
width: int(&case["width"]),
|
||||
height: int(&case["height"]),
|
||||
narrow: case["narrow"].as_bool().unwrap_or(false),
|
||||
mouse: (0, 0),
|
||||
index: 0,
|
||||
filtering,
|
||||
search: &search,
|
||||
tabs: &[],
|
||||
buttons: &[],
|
||||
page,
|
||||
pages,
|
||||
overlay: None,
|
||||
ghost: None,
|
||||
translate: &translate,
|
||||
text_width: &text_width,
|
||||
}
|
||||
.origin();
|
||||
let overlay = case["overlay"].as_u64().map(|i| {
|
||||
let i = i as usize;
|
||||
let c = &shown[i];
|
||||
let mut recipes: Vec<OverlayRecipe> = c
|
||||
.iter()
|
||||
.filter(|e| e.1)
|
||||
.map(|e| OverlayRecipe {
|
||||
craftable: true,
|
||||
cells: overlay_cells(&book, e.0),
|
||||
})
|
||||
.collect();
|
||||
if !filtering {
|
||||
recipes.extend(c.iter().filter(|e| !e.1).map(|e| OverlayRecipe {
|
||||
craftable: false,
|
||||
cells: overlay_cells(&book, e.0),
|
||||
}));
|
||||
}
|
||||
let (x, y) = overlay_origin(
|
||||
xo + 11 + 25 * (i as i32 % 5),
|
||||
yo + 31 + 25 * (i as i32 / 5),
|
||||
recipes.len(),
|
||||
xo,
|
||||
yo,
|
||||
);
|
||||
OverlayView { x, y, recipes }
|
||||
});
|
||||
let ghosts: Vec<GhostView> = case["ghost"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|g| GhostView {
|
||||
x: int(&g["x"]),
|
||||
y: int(&g["y"]),
|
||||
result: g["result"].as_bool().unwrap_or(false),
|
||||
items: g["items"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(Value::as_str)
|
||||
.map(|i| ItemStack::new(i, 1))
|
||||
.collect(),
|
||||
})
|
||||
.collect();
|
||||
let screen = Screen {
|
||||
book: kind,
|
||||
width: int(&case["width"]),
|
||||
height: int(&case["height"]),
|
||||
narrow: case["narrow"].as_bool().unwrap_or(false),
|
||||
mouse: (int(&case["mouse"][0]), int(&case["mouse"][1])),
|
||||
index: case["index"].as_u64().unwrap_or(0) as usize,
|
||||
filtering,
|
||||
search: &search,
|
||||
tabs: &tabs,
|
||||
buttons: &buttons,
|
||||
page,
|
||||
pages,
|
||||
overlay: overlay.as_ref(),
|
||||
ghost: case.get("ghost").map(|_| {
|
||||
(
|
||||
int(&case["left"]),
|
||||
int(&case["top"]),
|
||||
case["big"].as_bool().unwrap_or(false),
|
||||
ghosts.as_slice(),
|
||||
)
|
||||
}),
|
||||
translate: &translate,
|
||||
text_width: &text_width,
|
||||
};
|
||||
let draws: Vec<Value> = draw(&screen)
|
||||
.into_iter()
|
||||
.filter_map(|d| {
|
||||
let m: Vec<f32> = d.pose.iter().map(|v| round(*v)).collect();
|
||||
let mut o = match d.call {
|
||||
Call::Blit {
|
||||
texture,
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
u,
|
||||
v,
|
||||
tw,
|
||||
th,
|
||||
} => json!({"t": "blit", "texture": texture, "x": x, "y": y, "w": w, "h": h,
|
||||
"u": u, "v": v, "tw": tw, "th": th}),
|
||||
Call::Sprite { id, x, y, w, h } => {
|
||||
json!({"t": "sprite", "id": id, "x": x, "y": y, "w": w, "h": h})
|
||||
}
|
||||
Call::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => json!({"t": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": color}),
|
||||
Call::Highlight { x0, y0, x1, y1 } => {
|
||||
json!({"t": "highlight", "x0": x0, "y0": y0, "x1": x1, "y1": y1})
|
||||
}
|
||||
Call::Text {
|
||||
runs: r,
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
} => json!({"t": "text", "runs": runs(&r), "x": x, "y": y, "color": color, "shadow": shadow}),
|
||||
Call::Item { call, stack, x, y } => {
|
||||
if stack.count == 0 || &*stack.item == "minecraft:air" {
|
||||
return None;
|
||||
}
|
||||
let t = match call {
|
||||
ItemCall::Item => "item",
|
||||
ItemCall::Fake => "fake",
|
||||
ItemCall::Decorations => "decorations",
|
||||
};
|
||||
json!({"t": t, "id": &*stack.item, "count": stack.count, "x": x, "y": y})
|
||||
}
|
||||
Call::Tooltip(lines) => {
|
||||
json!({"t": "tooltip", "lines": lines.iter().map(|l| runs(l)).collect::<Vec<_>>()})
|
||||
}
|
||||
Call::ItemTooltip { stack, more } => {
|
||||
json!({"t": "item_tooltip", "id": &*stack.item, "more": more})
|
||||
}
|
||||
Call::Stratum => json!({"t": "stratum"}),
|
||||
};
|
||||
o["m"] = json!(m);
|
||||
Some(o)
|
||||
})
|
||||
.collect();
|
||||
let _ = writeln!(out, "{}", json!({ "draws": draws }));
|
||||
}
|
||||
fs::write(args.get(3).ok_or(usage)?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -24,17 +24,26 @@ const FIREWORK_COLORS: [u32; 16] = [
|
||||
11_250_603, 2_651_799, 8_073_150, 2_437_522, 5_320_730, 3_887_386, 11_743_532, 1_973_019,
|
||||
];
|
||||
|
||||
/// A set of accepted items (expanded from an item, list or tag).
|
||||
/// A set of accepted items (expanded from an item, list or tag), and the
|
||||
/// items in its `HolderSet` order (`Ingredient.display`'s `TagSlotDisplay`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Ingredient(pub HashSet<String>);
|
||||
pub struct Ingredient(pub HashSet<String>, pub Vec<String>);
|
||||
impl Ingredient {
|
||||
/// The items of a list, in order.
|
||||
pub fn of(items: Vec<String>) -> Self {
|
||||
Self(items.iter().cloned().collect(), items)
|
||||
}
|
||||
fn parse(v: &Value, items: &Items) -> Option<Self> {
|
||||
let mut set = HashSet::new();
|
||||
let mut list: Vec<String> = Vec::new();
|
||||
let mut add = |s: &str| {
|
||||
if let Some(tag) = s.strip_prefix('#') {
|
||||
set.extend(items.item_tags.get(tag).into_iter().flatten().cloned());
|
||||
} else {
|
||||
set.insert(s.to_owned());
|
||||
let more: Vec<String> = match s.strip_prefix('#') {
|
||||
Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(),
|
||||
None => vec![s.to_owned()],
|
||||
};
|
||||
for i in more {
|
||||
if !list.contains(&i) {
|
||||
list.push(i);
|
||||
}
|
||||
}
|
||||
};
|
||||
match v {
|
||||
@@ -50,7 +59,7 @@ impl Ingredient {
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
(!set.is_empty()).then_some(Self(set))
|
||||
(!list.is_empty()).then(|| Self::of(list))
|
||||
}
|
||||
pub fn test(&self, stack: &ItemStack) -> bool {
|
||||
self.0.contains(&*stack.item)
|
||||
@@ -1525,7 +1534,7 @@ mod tests {
|
||||
use crate::banner::BannerLayer;
|
||||
|
||||
fn ingredient(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
fn patterned(item: &str) -> ItemStack {
|
||||
let mut s = ItemStack::new(item, 1);
|
||||
|
||||
@@ -2930,6 +2930,10 @@ impl Game<'_> {
|
||||
// `GuiGraphics.renderItem`: the resolved item model (tints, foil and
|
||||
// special renderers included), then the decorations.
|
||||
self.draw_item_model(batch, stack, x, y);
|
||||
self.draw_item_decorations(batch, stack, x, y);
|
||||
}
|
||||
/// `GuiGraphicsExtractor.itemDecorations`: the count and damage bar.
|
||||
fn draw_item_decorations(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
|
||||
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
|
||||
// moved to (x, y). Horizon tracks no item cooldowns to shade yet.
|
||||
let max_damage = self
|
||||
|
||||
@@ -11,6 +11,11 @@ use horizon_client::{
|
||||
items::ItemStack,
|
||||
menu::place::{PostPlace, Stacked},
|
||||
recipe_book::{Book, BookType, ClientBook, Collection, Display, Entry, Tab},
|
||||
recipe_book_screen::{
|
||||
self as screen, ButtonView, Call, Drawn, GhostView, ItemCall, OverlayRecipe, OverlayView,
|
||||
Screen as Layout, Search, TabView,
|
||||
},
|
||||
text::{Style, Text},
|
||||
ui::EditBox,
|
||||
};
|
||||
use std::{
|
||||
@@ -444,9 +449,12 @@ impl Game<'_> {
|
||||
|
||||
// ---- geometry ----
|
||||
|
||||
/// `RecipeBookComponent.getXOrigin` / `getYOrigin` (`widthTooNarrow`
|
||||
/// centres the book over the menu).
|
||||
fn book_origin(&self, batch: &HudBatch) -> (f32, f32) {
|
||||
let offset = if batch.width < NARROW { 0.0 } else { 86.0 };
|
||||
(
|
||||
((batch.width - WIDTH) / 2.0).floor() - 86.0,
|
||||
((batch.width - WIDTH) / 2.0).floor() - offset,
|
||||
((batch.height - HEIGHT) / 2.0).floor(),
|
||||
)
|
||||
}
|
||||
@@ -623,25 +631,9 @@ impl Game<'_> {
|
||||
let mut entries: Vec<(usize, bool)> =
|
||||
button.entries.iter().copied().filter(|e| e.1).collect();
|
||||
entries.extend(button.entries.iter().copied().filter(|e| !e.1));
|
||||
let total = entries.len();
|
||||
let maxrow = if total <= 16 { 4 } else { 5 };
|
||||
let rows = total.div_ceil(maxrow);
|
||||
let (mut x, mut y) = (bx, by);
|
||||
let (center_x, center_y) = (xo + WIDTH / 2.0, yo + 13.0 + HEIGHT / 2.0);
|
||||
let right = x + (total.min(maxrow) * 25) as f32;
|
||||
let max_left = center_x + 50.0;
|
||||
if right > max_left {
|
||||
x -= 25.0 * ((right - max_left) / 25.0).floor();
|
||||
}
|
||||
let bottom = y + rows as f32 * 25.0;
|
||||
let max_bottom = center_y + 50.0;
|
||||
if bottom > max_bottom {
|
||||
y -= 25.0 * ((bottom - max_bottom) / 25.0).ceil();
|
||||
}
|
||||
let max_top = center_y - 100.0;
|
||||
if y < max_top {
|
||||
y -= 25.0 * ((y - max_top) / 25.0).ceil();
|
||||
}
|
||||
let (x, y) =
|
||||
screen::overlay_origin(bx as i32, by as i32, entries.len(), xo as i32, yo as i32);
|
||||
let (x, y) = (x as f32, y as f32);
|
||||
self.recipe_ui.overlay = Some(Overlay { x, y, entries });
|
||||
}
|
||||
|
||||
@@ -821,359 +813,293 @@ impl Game<'_> {
|
||||
use winit::keyboard::KeyCode;
|
||||
self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight)
|
||||
}
|
||||
/// `GhostSlots.extractRenderState`, among the container's slots.
|
||||
fn draw_ghost(&mut self, batch: &mut HudBatch, book_type: BookType) {
|
||||
if self.recipe_ui.ghost.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Ghosts show only while their slots are empty.
|
||||
let (ox, oy) = self.inventory_origin(batch);
|
||||
let step = self.swap_index();
|
||||
let big_result = book_type != BookType::Crafting || self.craft_size == 3;
|
||||
let ghosts: Vec<(usize, ItemStack, bool)> = self
|
||||
let ghosts: Vec<GhostView> = self
|
||||
.recipe_ui
|
||||
.ghost
|
||||
.iter()
|
||||
.filter(|g| !g.items.is_empty())
|
||||
.map(|g| (g.slot, g.items[step % g.items.len()].clone(), g.result))
|
||||
.map(|g| {
|
||||
let (sx, sy) = self.slot_position(g.slot);
|
||||
GhostView {
|
||||
x: sx as i32,
|
||||
y: sy as i32,
|
||||
items: g.items.clone(),
|
||||
result: g.result,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
for (slot, stack, result) in ghosts {
|
||||
let (sx, sy) = self.slot_position(slot);
|
||||
let (x, y) = (ox + sx, oy + sy);
|
||||
let atlas = &self.res.atlas;
|
||||
let red = rgba(255, 0, 0, 0x30);
|
||||
if result && big_result {
|
||||
batch.fill(atlas, x - 4.0, y - 4.0, 24.0, 24.0, red);
|
||||
} else {
|
||||
batch.fill(atlas, x, y, 16.0, 16.0, red);
|
||||
}
|
||||
self.draw_item(batch, &stack, x, y);
|
||||
batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 0x30));
|
||||
}
|
||||
let calls = screen::ghost(self.swap_index(), ox as i32, oy as i32, big_result, &ghosts);
|
||||
self.paint_book(batch, &calls);
|
||||
}
|
||||
/// `RecipeBookComponent.extractRenderState` and `extractTooltip`, laid
|
||||
/// out by `horizon_client::recipe_book_screen`.
|
||||
fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) {
|
||||
let (xo, yo) = self.book_origin(batch);
|
||||
let cursor = self.cursor;
|
||||
let atlas_name = "gui/recipe_book";
|
||||
// Background: the 147x166 page at (1, 1) of the texture.
|
||||
if let Some(r) = self.res.atlas.sprites.get(atlas_name).copied() {
|
||||
batch.rect_uv(
|
||||
xo,
|
||||
yo,
|
||||
WIDTH,
|
||||
HEIGHT,
|
||||
sub_rect(r, [1.0, 1.0, WIDTH, HEIGHT]),
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
// Search box.
|
||||
if let Some(search) = self.recipe_ui.search.as_mut() {
|
||||
search.x = xo + 25.0;
|
||||
search.y = yo + 13.0;
|
||||
search.draw(batch, &self.res.atlas, None);
|
||||
if search.value.is_empty() && !search.focused {
|
||||
let hint = self
|
||||
.res
|
||||
.stations
|
||||
.enchantments
|
||||
.translate("gui.recipebook.search_hint")
|
||||
.unwrap_or("Search...")
|
||||
.to_owned();
|
||||
batch.text(
|
||||
&self.res.atlas,
|
||||
&hint,
|
||||
search.text_x(),
|
||||
search.text_y(),
|
||||
rgba(170, 170, 170, 255),
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
// Tabs.
|
||||
let tabs = self.recipe_ui.view.tabs.clone();
|
||||
let current = self
|
||||
.recipe_ui
|
||||
.tab
|
||||
.filter(|t| tabs.contains(t))
|
||||
.unwrap_or(Tab::Search);
|
||||
let frame = self.frame_ticks;
|
||||
for (n, tab) in tabs.iter().enumerate() {
|
||||
let (x, y) = self.tab_pos(xo, yo, n);
|
||||
let selected = *tab == current;
|
||||
let name = if selected { "tab_selected" } else { "tab" };
|
||||
let sx = if selected { x - 2.0 } else { x };
|
||||
let start = batch.vertices.len();
|
||||
batch.sprite(&self.res.atlas, &sprite(name), sx, y);
|
||||
let (a, b) = tab.icons();
|
||||
let shift = if selected { -2.0 } else { 0.0 };
|
||||
match b {
|
||||
Some(b) => {
|
||||
self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0);
|
||||
self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0);
|
||||
let atlas = &self.res.atlas;
|
||||
let search = match self.recipe_ui.search.as_mut() {
|
||||
Some(edit) => {
|
||||
// The box's place, for clicks and typing.
|
||||
edit.x = xo + 25.0;
|
||||
edit.y = yo + 13.0;
|
||||
let (display, blink_ms) = edit.view_state(atlas);
|
||||
Search {
|
||||
value: edit.value.clone(),
|
||||
cursor: edit.cursor,
|
||||
highlight: edit.highlight,
|
||||
display,
|
||||
focused: edit.focused,
|
||||
blink_ms,
|
||||
}
|
||||
None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0),
|
||||
}
|
||||
if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) {
|
||||
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
|
||||
batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze);
|
||||
entry.1 -= frame;
|
||||
None => Search::default(),
|
||||
};
|
||||
let ui = &self.recipe_ui;
|
||||
let current = ui
|
||||
.tab
|
||||
.filter(|t| ui.view.tabs.contains(t))
|
||||
.unwrap_or(Tab::Search);
|
||||
let tabs: Vec<TabView> = ui
|
||||
.view
|
||||
.tabs
|
||||
.iter()
|
||||
.map(|tab| {
|
||||
let (a, b) = tab.icons();
|
||||
TabView {
|
||||
icons: (a.to_owned(), b.map(str::to_owned)),
|
||||
selected: *tab == current,
|
||||
anim: ui
|
||||
.tab_anim
|
||||
.iter()
|
||||
.find(|e| e.0 == *tab)
|
||||
.map_or(0.0, |e| e.1),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let pages = ui.view.buttons.len().div_ceil(20);
|
||||
let first = ui.page * 20;
|
||||
let (buttons, overlay) = match ui.book.as_ref() {
|
||||
Some(book) => {
|
||||
let buttons: Vec<ButtonView> = ui
|
||||
.view
|
||||
.buttons
|
||||
.iter()
|
||||
.enumerate()
|
||||
.skip(first)
|
||||
.take(20)
|
||||
.map(|(n, b)| ButtonView {
|
||||
has_craftable: b.craftable(),
|
||||
entries: b
|
||||
.entries
|
||||
.iter()
|
||||
.map(|e| vec![book.entries[e.0].result.clone()])
|
||||
.collect(),
|
||||
anim: ui
|
||||
.button_anim
|
||||
.iter()
|
||||
.find(|e| e.0 == n)
|
||||
.map_or(0.0, |e| e.1),
|
||||
})
|
||||
.collect();
|
||||
let overlay = ui.overlay.as_ref().map(|o| OverlayView {
|
||||
x: o.x as i32,
|
||||
y: o.y as i32,
|
||||
recipes: o
|
||||
.entries
|
||||
.iter()
|
||||
.map(|&(i, craftable)| OverlayRecipe {
|
||||
craftable,
|
||||
cells: screen::overlay_cells(book, &book.entries[i]),
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
(buttons, overlay)
|
||||
}
|
||||
None => (Vec::new(), None),
|
||||
};
|
||||
let translate = |key: &str| self.translate(key, key);
|
||||
let text_width = |s: &str| HudBatch::text_width(atlas, s) as i32;
|
||||
let layout = Layout {
|
||||
book: book_type,
|
||||
width: batch.width as i32,
|
||||
height: batch.height as i32,
|
||||
narrow: batch.width < NARROW,
|
||||
mouse: (cursor.0.floor() as i32, cursor.1.floor() as i32),
|
||||
index: self.swap_index(),
|
||||
filtering: self.book_filtering(book_type),
|
||||
search: &search,
|
||||
tabs: &tabs,
|
||||
buttons: &buttons,
|
||||
page: ui.page,
|
||||
pages,
|
||||
overlay: overlay.as_ref(),
|
||||
ghost: None,
|
||||
translate: &translate,
|
||||
text_width: &text_width,
|
||||
};
|
||||
let calls = screen::draw(&layout);
|
||||
let tooltip = self.paint_book(batch, &calls);
|
||||
// The squeeze animations run down with the frames.
|
||||
let frame = self.frame_ticks;
|
||||
for e in &mut self.recipe_ui.tab_anim {
|
||||
e.1 -= frame;
|
||||
}
|
||||
for e in &mut self.recipe_ui.button_anim {
|
||||
e.1 -= frame;
|
||||
}
|
||||
self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0);
|
||||
// Craftable filter.
|
||||
let filtering = self.book_filtering(book_type);
|
||||
let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0);
|
||||
let prefix = if book_type == BookType::Crafting {
|
||||
""
|
||||
} else {
|
||||
"furnace_"
|
||||
};
|
||||
let state = if filtering {
|
||||
"filter_enabled"
|
||||
} else {
|
||||
"filter_disabled"
|
||||
};
|
||||
let name = format!("{prefix}{state}{}", if hover { "_highlighted" } else { "" });
|
||||
batch.sprite(&self.res.atlas, &sprite(&name), xo + 110.0, yo + 12.0);
|
||||
// Recipe buttons.
|
||||
let buttons = self.recipe_ui.view.buttons.clone();
|
||||
let pages = buttons.len().div_ceil(20);
|
||||
let step = self.swap_index();
|
||||
let first = self.recipe_ui.page * 20;
|
||||
let mut tooltip: Option<Vec<(String, u32)>> = None;
|
||||
let overlay_open = self.recipe_ui.overlay.is_some();
|
||||
for n in 0..20 {
|
||||
let Some(button) = buttons.get(first + n) else {
|
||||
break;
|
||||
};
|
||||
let (x, y) = Self::button_pos(xo, yo, n);
|
||||
let anim_start = batch.vertices.len();
|
||||
let many = button.entries.len() > 1;
|
||||
let name = match (button.craftable(), many) {
|
||||
(true, true) => "slot_many_craftable",
|
||||
(true, false) => "slot_craftable",
|
||||
(false, true) => "slot_many_uncraftable",
|
||||
(false, false) => "slot_uncraftable",
|
||||
};
|
||||
batch.sprite(&self.res.atlas, &sprite(name), x, y);
|
||||
let shown = button.entries[step % button.entries.len()].0;
|
||||
let Some(stack) = self
|
||||
.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.map(|b| ItemStack::new(&b.entries[shown].result.item, 1))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let same_result = button.entries.iter().all(|e| {
|
||||
self.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.is_some_and(|b| b.entries[e.0].result.item == b.entries[shown].result.item)
|
||||
});
|
||||
let mut offset = 4.0;
|
||||
if many && same_result {
|
||||
self.draw_item_plain(batch, &stack, x + offset + 1.0, y + offset + 1.0);
|
||||
offset -= 1.0;
|
||||
}
|
||||
self.draw_item_plain(batch, &stack, x + offset, y + offset);
|
||||
if let Some(entry) = self
|
||||
.recipe_ui
|
||||
.button_anim
|
||||
.iter_mut()
|
||||
.find(|e| e.0 == first + n)
|
||||
{
|
||||
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
|
||||
batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze);
|
||||
entry.1 -= self.frame_ticks;
|
||||
}
|
||||
if inside(cursor, x, y, 25.0, 25.0) && !overlay_open {
|
||||
let mut lines = self.stack_tooltip(&stack);
|
||||
if many {
|
||||
lines.push((
|
||||
self.translate("gui.recipebook.moreRecipes", "Right Click for More"),
|
||||
u32::MAX,
|
||||
));
|
||||
}
|
||||
tooltip = Some(lines);
|
||||
}
|
||||
}
|
||||
self.recipe_ui.button_anim.retain(|e| e.1 > 0.0);
|
||||
// Page arrows and number.
|
||||
if pages > 1 {
|
||||
let page_text = self
|
||||
.translate("gui.recipebook.page", "%s/%s")
|
||||
.replacen("%s", &(self.recipe_ui.page + 1).to_string(), 1)
|
||||
.replacen("%s", &pages.to_string(), 1);
|
||||
let w = HudBatch::text_width(&self.res.atlas, &page_text);
|
||||
batch.text(
|
||||
&self.res.atlas,
|
||||
&page_text,
|
||||
xo - (w / 2.0).floor() + 73.0,
|
||||
yo + 141.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
if self.recipe_ui.page + 1 < pages {
|
||||
let hover = inside(cursor, xo + 93.0, yo + 137.0, 12.0, 17.0);
|
||||
let name = if hover {
|
||||
"page_forward_highlighted"
|
||||
} else {
|
||||
"page_forward"
|
||||
};
|
||||
batch.sprite(&self.res.atlas, &sprite(name), xo + 93.0, yo + 137.0);
|
||||
if hover {
|
||||
tooltip = Some(vec![(
|
||||
self.translate("gui.recipebook.next_page", "Next Page"),
|
||||
u32::MAX,
|
||||
)]);
|
||||
}
|
||||
}
|
||||
if self.recipe_ui.page > 0 {
|
||||
let hover = inside(cursor, xo + 38.0, yo + 137.0, 12.0, 17.0);
|
||||
let name = if hover {
|
||||
"page_backward_highlighted"
|
||||
} else {
|
||||
"page_backward"
|
||||
};
|
||||
batch.sprite(&self.res.atlas, &sprite(name), xo + 38.0, yo + 137.0);
|
||||
if hover {
|
||||
tooltip = Some(vec![(
|
||||
self.translate("gui.recipebook.previous_page", "Previous Page"),
|
||||
u32::MAX,
|
||||
)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0) {
|
||||
let key = if !filtering {
|
||||
"gui.recipebook.toggleRecipes.all"
|
||||
} else {
|
||||
match book_type {
|
||||
BookType::Crafting => "gui.recipebook.toggleRecipes.craftable",
|
||||
BookType::Furnace => "gui.recipebook.toggleRecipes.smeltable",
|
||||
BookType::BlastFurnace => "gui.recipebook.toggleRecipes.blastable",
|
||||
BookType::Smoker => "gui.recipebook.toggleRecipes.smokable",
|
||||
}
|
||||
};
|
||||
tooltip = Some(vec![(self.translate(key, key), u32::MAX)]);
|
||||
}
|
||||
self.draw_overlay(batch, book_type);
|
||||
if let Some(lines) = tooltip {
|
||||
self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1);
|
||||
}
|
||||
}
|
||||
/// An item without count or bars (`GuiGraphics.fakeItem`).
|
||||
fn draw_item_plain(&mut self, batch: &mut HudBatch, stack: &ItemStack, x: f32, y: f32) {
|
||||
let one = ItemStack {
|
||||
count: 1,
|
||||
damage: 0,
|
||||
..stack.clone()
|
||||
};
|
||||
self.draw_item(batch, &one, x, y);
|
||||
}
|
||||
fn draw_overlay(&mut self, batch: &mut HudBatch, book_type: BookType) {
|
||||
let Some(overlay) = self.recipe_ui.overlay.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let (ox, oy, entries) = (overlay.x, overlay.y, overlay.entries.clone());
|
||||
let maxrow = if entries.len() <= 16 { 4 } else { 5 };
|
||||
let width = entries.len().min(maxrow) as f32 * 25.0 + 8.0;
|
||||
let height = entries.len().div_ceil(maxrow) as f32 * 25.0 + 8.0;
|
||||
horizon_client::ui::nine_slice(
|
||||
batch,
|
||||
&self.res.atlas,
|
||||
&sprite("overlay_recipe"),
|
||||
ox,
|
||||
oy,
|
||||
width,
|
||||
height,
|
||||
u32::MAX,
|
||||
);
|
||||
let cursor = self.cursor;
|
||||
let step = self.swap_index();
|
||||
let (gw, gh) = if book_type == BookType::Crafting {
|
||||
(3, 3)
|
||||
} else {
|
||||
(1, 1)
|
||||
};
|
||||
for (n, (index, craftable)) in entries.into_iter().enumerate() {
|
||||
let x = ox + 4.0 + 25.0 * (n % maxrow) as f32;
|
||||
let y = oy + 5.0 + 25.0 * (n / maxrow) as f32;
|
||||
let hover = inside(cursor, x, y, 24.0, 24.0);
|
||||
let family = if book_type == BookType::Crafting {
|
||||
"crafting"
|
||||
} else {
|
||||
"furnace"
|
||||
};
|
||||
let state = if craftable { "" } else { "_disabled" };
|
||||
let name = format!(
|
||||
"{family}_overlay{state}{}",
|
||||
if hover { "_highlighted" } else { "" }
|
||||
);
|
||||
batch.sprite(&self.res.atlas, &sprite(&name), x, y);
|
||||
let Some(entry) = self
|
||||
.recipe_ui
|
||||
.book
|
||||
.as_ref()
|
||||
.map(|b| b.entries[index].clone())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// The recipe's layout in miniature, ingredients at 3/8 scale.
|
||||
let mut cells: Vec<(f32, f32, ItemStack)> = Vec::new();
|
||||
if let Some(book) = self.recipe_ui.book.as_ref() {
|
||||
let requirements = entry.requirements();
|
||||
match &entry.display {
|
||||
Display::Furnace(ingredient) => {
|
||||
let items = book.items_of(ingredient);
|
||||
if !items.is_empty() {
|
||||
let item = &items[step % items.len()];
|
||||
cells.push((3.0 + 7.0, 3.0 + 7.0, ItemStack::new(item, 1)));
|
||||
}
|
||||
}
|
||||
Display::Shaped { .. } => {
|
||||
for (ingredient, grid_index) in entry.grid_cells(gw, gh) {
|
||||
if let Some(i) = ingredient {
|
||||
let items = book.items_of(requirements[i]);
|
||||
if !items.is_empty() {
|
||||
let item = &items[step % items.len()];
|
||||
cells.push((
|
||||
3.0 + (grid_index % 3) as f32 * 7.0,
|
||||
3.0 + (grid_index / 3) as f32 * 7.0,
|
||||
ItemStack::new(item, 1),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Display::Shapeless(list) => {
|
||||
for (i, ingredient) in list.iter().enumerate() {
|
||||
let items = book.items_of(ingredient);
|
||||
if !items.is_empty() {
|
||||
let item = &items[step % items.len()];
|
||||
cells.push((
|
||||
3.0 + (i % 3) as f32 * 7.0,
|
||||
3.0 + (i / 3) as f32 * 7.0,
|
||||
ItemStack::new(item, 1),
|
||||
));
|
||||
}
|
||||
}
|
||||
/// Paints recipe book calls; returns the first tooltip set (vanilla keeps
|
||||
/// the first one a frame asks for).
|
||||
fn paint_book(&mut self, batch: &mut HudBatch, calls: &[Drawn]) -> Option<Vec<(String, u32)>> {
|
||||
let mut tooltip: Option<Vec<(String, u32)>> = None;
|
||||
for d in calls {
|
||||
let start = batch.vertices.len();
|
||||
let atlas = &self.res.atlas;
|
||||
match &d.call {
|
||||
Call::Blit {
|
||||
x, y, w, h, u, v, ..
|
||||
} => {
|
||||
if let Some(r) = atlas.sprites.get("gui/recipe_book").copied() {
|
||||
let (w, h) = (*w as f32, *h as f32);
|
||||
batch.rect_uv(
|
||||
*x as f32,
|
||||
*y as f32,
|
||||
w,
|
||||
h,
|
||||
sub_rect(r, [*u, *v, w, h]),
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
}
|
||||
Call::Sprite { id, x, y, w, h } => {
|
||||
let name = format!("gui/sprites/{id}");
|
||||
let native = atlas
|
||||
.sprites
|
||||
.get(&name)
|
||||
.is_some_and(|r| r.w as i32 == *w && r.h as i32 == *h);
|
||||
if native {
|
||||
batch.sprite(atlas, &name, *x as f32, *y as f32);
|
||||
} else {
|
||||
horizon_client::ui::nine_slice(
|
||||
batch,
|
||||
atlas,
|
||||
&name,
|
||||
*x as f32,
|
||||
*y as f32,
|
||||
*w as f32,
|
||||
*h as f32,
|
||||
u32::MAX,
|
||||
);
|
||||
}
|
||||
}
|
||||
Call::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
} => batch.fill(
|
||||
atlas,
|
||||
*x0 as f32,
|
||||
*y0 as f32,
|
||||
(x1 - x0) as f32,
|
||||
(y1 - y0) as f32,
|
||||
argb(*color),
|
||||
),
|
||||
Call::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,
|
||||
rgba(0, 0, 255, 128),
|
||||
);
|
||||
}
|
||||
Call::Text {
|
||||
runs,
|
||||
x,
|
||||
y,
|
||||
color,
|
||||
shadow,
|
||||
} => {
|
||||
let mut x = *x as f32;
|
||||
for r in runs {
|
||||
let style = Style {
|
||||
color: (r.color >= 0).then_some(r.color as u32),
|
||||
italic: r.italic.then_some(true),
|
||||
..Style::default()
|
||||
};
|
||||
let t = Text::styled(r.text.clone(), style);
|
||||
batch.text_styled(atlas, &t, x, *y as f32, argb(*color), *shadow);
|
||||
x += atlas.font.width_text(&t);
|
||||
}
|
||||
}
|
||||
Call::Item { call, stack, x, y } => match call {
|
||||
ItemCall::Item | ItemCall::Fake => {
|
||||
self.draw_item_model(batch, stack, *x as f32, *y as f32)
|
||||
}
|
||||
ItemCall::Decorations => {
|
||||
self.draw_item_decorations(batch, stack, *x as f32, *y as f32)
|
||||
}
|
||||
},
|
||||
Call::Tooltip(lines) => {
|
||||
if tooltip.is_none() {
|
||||
tooltip = Some(
|
||||
lines
|
||||
.iter()
|
||||
.map(|l| (l.iter().map(|r| r.text.as_str()).collect(), u32::MAX))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Call::ItemTooltip { stack, more } => {
|
||||
if tooltip.is_none() {
|
||||
let mut lines = self.stack_tooltip(stack);
|
||||
if *more {
|
||||
lines.push((
|
||||
self.translate(
|
||||
"gui.recipebook.moreRecipes",
|
||||
"Right Click for More",
|
||||
),
|
||||
u32::MAX,
|
||||
));
|
||||
}
|
||||
tooltip = Some(lines);
|
||||
}
|
||||
}
|
||||
Call::Stratum => {}
|
||||
}
|
||||
for (cx, cy, stack) in cells {
|
||||
// Draw at the origin, then shrink around the cell centre.
|
||||
let start = batch.vertices.len();
|
||||
self.draw_item_plain(batch, &stack, 0.0, 0.0);
|
||||
let (px, py) = (x + 2.0 + cx, y + 2.0 + cy);
|
||||
if d.pose != screen::IDENTITY {
|
||||
let m = d.pose;
|
||||
for v in &mut batch.vertices[start..] {
|
||||
v.pos = [px + (v.pos[0] - 8.0) * 0.375, py + (v.pos[1] - 8.0) * 0.375];
|
||||
let [x, y] = v.pos;
|
||||
v.pos = [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
|
||||
}
|
||||
}
|
||||
}
|
||||
tooltip
|
||||
}
|
||||
}
|
||||
|
||||
/// An ARGB colour as a HUD vertex colour.
|
||||
fn argb(c: i32) -> u32 {
|
||||
let c = c as u32;
|
||||
rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, (c >> 24) as u8)
|
||||
}
|
||||
|
||||
/// A sub-rectangle of a sprite given in texels.
|
||||
fn sub_rect(r: Rect, [x, y, w, h]: [f32; 4]) -> Rect {
|
||||
let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32);
|
||||
|
||||
@@ -166,6 +166,9 @@ pub struct Items {
|
||||
/// Block tag name (without '#') -> member block names.
|
||||
pub block_tags: HashMap<String, HashSet<String>>,
|
||||
pub item_tags: HashMap<String, HashSet<String>>,
|
||||
/// Item tags in vanilla's order (`TagLoader`: file order, nested tags in
|
||||
/// place, first occurrence kept), the order `TagSlotDisplay` resolves.
|
||||
pub item_tag_order: HashMap<String, Vec<String>>,
|
||||
loot: HashMap<String, Value>,
|
||||
/// The `jukebox_song` registry.
|
||||
pub songs: HashMap<String, Song>,
|
||||
@@ -216,6 +219,13 @@ fn load_songs(root: &Path) -> HashMap<String, Song> {
|
||||
songs
|
||||
}
|
||||
pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashSet<String>>> {
|
||||
Ok(load_tag_lists(root, kind)?
|
||||
.into_iter()
|
||||
.map(|(k, v)| (k, v.into_iter().collect()))
|
||||
.collect())
|
||||
}
|
||||
/// Every tag's contents in `TagLoader.tryBuildTag` order (a `LinkedHashSet`).
|
||||
pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> Result<HashMap<String, Vec<String>>> {
|
||||
let dir = root.join(format!("data/minecraft/tags/{kind}"));
|
||||
let mut raw: HashMap<String, Vec<String>> = HashMap::new();
|
||||
fn walk(dir: &Path, base: &Path, raw: &mut HashMap<String, Vec<String>>) -> Result<()> {
|
||||
@@ -246,29 +256,24 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashS
|
||||
if dir.exists() {
|
||||
walk(&dir, &dir, &mut raw)?;
|
||||
}
|
||||
fn resolve(
|
||||
name: &str,
|
||||
raw: &HashMap<String, Vec<String>>,
|
||||
out: &mut HashSet<String>,
|
||||
depth: u32,
|
||||
) {
|
||||
fn resolve(name: &str, raw: &HashMap<String, Vec<String>>, out: &mut Vec<String>, depth: u32) {
|
||||
if depth > 32 {
|
||||
return;
|
||||
}
|
||||
for v in raw.get(name).into_iter().flatten() {
|
||||
if let Some(tag) = v.strip_prefix('#') {
|
||||
resolve(tag, raw, out, depth + 1);
|
||||
} else {
|
||||
out.insert(v.clone());
|
||||
} else if !out.contains(v) {
|
||||
out.push(v.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(raw
|
||||
.keys()
|
||||
.map(|k| {
|
||||
let mut set = HashSet::new();
|
||||
resolve(k, &raw, &mut set, 0);
|
||||
(k.clone(), set)
|
||||
let mut list = Vec::new();
|
||||
resolve(k, &raw, &mut list, 0);
|
||||
(k.clone(), list)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -456,6 +461,7 @@ impl Items {
|
||||
order,
|
||||
block_tags: load_tags(root, "block")?,
|
||||
item_tags: load_tags(root, "item")?,
|
||||
item_tag_order: load_tag_lists(root, "item")?,
|
||||
loot,
|
||||
songs: load_songs(root),
|
||||
})
|
||||
@@ -470,6 +476,7 @@ impl Items {
|
||||
order: Vec::new(),
|
||||
block_tags: load_tags(root, "block")?,
|
||||
item_tags: load_tags(root, "item")?,
|
||||
item_tag_order: load_tag_lists(root, "item")?,
|
||||
loot: HashMap::new(),
|
||||
songs: HashMap::new(),
|
||||
})
|
||||
@@ -481,6 +488,10 @@ impl Items {
|
||||
items: HashMap::new(),
|
||||
order: Vec::new(),
|
||||
block_tags: HashMap::new(),
|
||||
item_tag_order: item_tags
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), v.iter().cloned().collect()))
|
||||
.collect(),
|
||||
item_tags,
|
||||
loot: HashMap::new(),
|
||||
songs: HashMap::new(),
|
||||
|
||||
@@ -85,6 +85,7 @@ pub mod projectiles;
|
||||
pub mod raid;
|
||||
pub mod random_sequences;
|
||||
pub mod recipe_book;
|
||||
pub mod recipe_book_screen;
|
||||
pub mod save;
|
||||
pub mod scoreboard;
|
||||
pub mod scoreboard_cmd;
|
||||
|
||||
@@ -639,7 +639,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ing(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
fn have(items: &[(&str, i32)]) -> Stacked {
|
||||
let mut s = Stacked::default();
|
||||
|
||||
@@ -405,11 +405,10 @@ impl Book {
|
||||
pub fn entry(&self, id: &str) -> Option<&Entry> {
|
||||
self.entries.iter().find(|e| e.id == id)
|
||||
}
|
||||
/// `ingredient`'s items in registry order (the cycling order of ghost slots).
|
||||
/// `ingredient`'s items as its display resolves them (the cycling order
|
||||
/// of ghost slots and the overlay).
|
||||
pub fn items_of(&self, ingredient: &Ingredient) -> Vec<String> {
|
||||
let mut items: Vec<String> = ingredient.0.iter().cloned().collect();
|
||||
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
|
||||
items
|
||||
ingredient.1.clone()
|
||||
}
|
||||
/// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a
|
||||
/// `FullTextSearchTree`): without a colon the text must occur in a
|
||||
@@ -714,7 +713,7 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ing(items: &[&str]) -> Ingredient {
|
||||
Ingredient(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
|
||||
}
|
||||
#[test]
|
||||
fn small_recipes_are_centred_in_the_grid() {
|
||||
|
||||
@@ -0,0 +1,734 @@
|
||||
//! The recipe book's drawing (`RecipeBookComponent.extractRenderState`,
|
||||
//! `extractTooltip` and `GhostSlots.extractRenderState`) as the list of GUI
|
||||
//! calls vanilla's widgets make: the background, the search `EditBox`, the
|
||||
//! `RecipeBookTabButton`s, the craftable filter `CycleButton`, the
|
||||
//! `RecipeBookPage` with its `RecipeButton`s, page number and arrows, the
|
||||
//! `OverlayRecipeComponent` and the ghost slots, each with the pose it is
|
||||
//! drawn under. The game paints them; the render parity harness compares them.
|
||||
use crate::{
|
||||
items::ItemStack,
|
||||
recipe_book::{Book, BookType, Display, Entry},
|
||||
};
|
||||
|
||||
/// A styled run of text: its characters, colour (`-1` for the call's own) and italics.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Run {
|
||||
pub text: String,
|
||||
pub color: i32,
|
||||
pub italic: bool,
|
||||
}
|
||||
impl Run {
|
||||
pub fn plain(text: impl Into<String>) -> Self {
|
||||
Run {
|
||||
text: text.into(),
|
||||
color: -1,
|
||||
italic: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an item is drawn: `GuiGraphicsExtractor.item`, `fakeItem` or `itemDecorations`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ItemCall {
|
||||
Item,
|
||||
Fake,
|
||||
Decorations,
|
||||
}
|
||||
|
||||
/// One GUI call.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Call {
|
||||
/// `blit` of a texture region (the book's background).
|
||||
Blit {
|
||||
texture: &'static str,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: i32,
|
||||
h: i32,
|
||||
u: f32,
|
||||
v: f32,
|
||||
tw: i32,
|
||||
th: i32,
|
||||
},
|
||||
/// `blitSprite`, the id without its namespace.
|
||||
Sprite {
|
||||
id: String,
|
||||
x: i32,
|
||||
y: i32,
|
||||
w: i32,
|
||||
h: i32,
|
||||
},
|
||||
Fill {
|
||||
x0: i32,
|
||||
y0: i32,
|
||||
x1: i32,
|
||||
y1: i32,
|
||||
color: i32,
|
||||
},
|
||||
/// `textHighlight` (the search box's selection).
|
||||
Highlight { x0: i32, y0: i32, x1: i32, y1: i32 },
|
||||
Text {
|
||||
runs: Vec<Run>,
|
||||
x: i32,
|
||||
y: i32,
|
||||
color: i32,
|
||||
shadow: bool,
|
||||
},
|
||||
Item {
|
||||
call: ItemCall,
|
||||
stack: ItemStack,
|
||||
x: i32,
|
||||
y: i32,
|
||||
},
|
||||
/// A widget's tooltip lines.
|
||||
Tooltip(Vec<Vec<Run>>),
|
||||
/// The hovered recipe button's tooltip: its display stack's own tooltip,
|
||||
/// then "Right Click for More" when it has several recipes.
|
||||
ItemTooltip { stack: ItemStack, more: bool },
|
||||
/// `nextStratum`.
|
||||
Stratum,
|
||||
}
|
||||
|
||||
/// A call and the pose (`Matrix3x2f` m00, m01, m10, m11, m20, m21) it is made under.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drawn {
|
||||
pub call: Call,
|
||||
pub pose: [f32; 6],
|
||||
}
|
||||
|
||||
pub const IDENTITY: [f32; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// JOML `Matrix3x2f.translate`.
|
||||
fn translate(m: [f32; 6], x: f32, y: f32) -> [f32; 6] {
|
||||
[
|
||||
m[0],
|
||||
m[1],
|
||||
m[2],
|
||||
m[3],
|
||||
m[0] * x + m[2] * y + m[4],
|
||||
m[1] * x + m[3] * y + m[5],
|
||||
]
|
||||
}
|
||||
/// JOML `Matrix3x2f.scale`.
|
||||
fn scale(m: [f32; 6], x: f32, y: f32) -> [f32; 6] {
|
||||
[m[0] * x, m[1] * x, m[2] * y, m[3] * y, m[4], m[5]]
|
||||
}
|
||||
|
||||
/// The search box (`EditBox` fields).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Search {
|
||||
pub value: String,
|
||||
/// Cursor, selection end and first shown character, in characters.
|
||||
pub cursor: usize,
|
||||
pub highlight: usize,
|
||||
pub display: usize,
|
||||
pub focused: bool,
|
||||
/// Milliseconds since the box was focused (`TextCursorUtils.isCursorVisible`).
|
||||
pub blink_ms: u64,
|
||||
}
|
||||
|
||||
/// A visible tab, in order: its icons, whether selected, its squeeze time left.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TabView {
|
||||
pub icons: (String, Option<String>),
|
||||
pub selected: bool,
|
||||
pub anim: f32,
|
||||
}
|
||||
|
||||
/// A recipe button: its collection has a craftable recipe; the display
|
||||
/// stacks of each selected recipe; the squeeze time left.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ButtonView {
|
||||
pub has_craftable: bool,
|
||||
pub entries: Vec<Vec<ItemStack>>,
|
||||
pub anim: f32,
|
||||
}
|
||||
|
||||
/// A recipe of the overlay: craftable, and its ingredient cells (grid
|
||||
/// x, y and the stacks the cell cycles through).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OverlayRecipe {
|
||||
pub craftable: bool,
|
||||
pub cells: Vec<(i32, i32, Vec<ItemStack>)>,
|
||||
}
|
||||
|
||||
/// The alternatives overlay of a button, at the corner [`overlay_origin`] gives.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OverlayView {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
/// Craftable recipes first.
|
||||
pub recipes: Vec<OverlayRecipe>,
|
||||
}
|
||||
|
||||
/// A ghost slot: its position in the menu, the stacks it cycles through,
|
||||
/// and whether it is the result slot.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GhostView {
|
||||
pub x: i32,
|
||||
pub y: i32,
|
||||
pub items: Vec<ItemStack>,
|
||||
pub result: bool,
|
||||
}
|
||||
|
||||
/// What the recipe book shows.
|
||||
pub struct Screen<'a> {
|
||||
pub book: BookType,
|
||||
/// GUI size and `widthTooNarrow`.
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub narrow: bool,
|
||||
pub mouse: (i32, i32),
|
||||
/// `slotSelectTime.currentIndex()`.
|
||||
pub index: usize,
|
||||
pub filtering: bool,
|
||||
pub search: &'a Search,
|
||||
pub tabs: &'a [TabView],
|
||||
/// The current page's buttons.
|
||||
pub buttons: &'a [ButtonView],
|
||||
pub page: usize,
|
||||
pub pages: usize,
|
||||
pub overlay: Option<&'a OverlayView>,
|
||||
/// The container's corner, whether its result slot is big, and the ghost slots.
|
||||
pub ghost: Option<(i32, i32, bool, &'a [GhostView])>,
|
||||
/// Translations.
|
||||
pub translate: &'a dyn Fn(&str) -> String,
|
||||
/// `Font.width`.
|
||||
pub text_width: &'a dyn Fn(&str) -> i32,
|
||||
}
|
||||
|
||||
impl Screen<'_> {
|
||||
/// `RecipeBookComponent.getXOrigin` and `getYOrigin`.
|
||||
pub fn origin(&self) -> (i32, i32) {
|
||||
let offset = if self.narrow { 0 } else { 86 };
|
||||
((self.width - 147) / 2 - offset, (self.height - 166) / 2)
|
||||
}
|
||||
fn hovered(&self, x: i32, y: i32, w: i32, h: i32) -> bool {
|
||||
let (mx, my) = self.mouse;
|
||||
mx >= x && my >= y && mx < x + w && my < y + h
|
||||
}
|
||||
/// `Font.plainSubstrByWidth`.
|
||||
fn substr_by_width<'s>(&self, s: &'s str, max: i32) -> &'s str {
|
||||
let mut end = 0;
|
||||
for (i, c) in s.char_indices() {
|
||||
if (self.text_width)(&s[..i + c.len_utf8()]) > max {
|
||||
break;
|
||||
}
|
||||
end = i + c.len_utf8();
|
||||
}
|
||||
&s[..end]
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipe book's calls, in vanilla's order.
|
||||
pub fn draw(s: &Screen) -> Vec<Drawn> {
|
||||
let mut out = Vec::new();
|
||||
let mut put = |call: Call, pose: [f32; 6]| out.push(Drawn { call, pose });
|
||||
let (xo, yo) = s.origin();
|
||||
put(
|
||||
Call::Blit {
|
||||
texture: "textures/gui/recipe_book.png",
|
||||
x: xo,
|
||||
y: yo,
|
||||
w: 147,
|
||||
h: 166,
|
||||
u: 1.0,
|
||||
v: 1.0,
|
||||
tw: 256,
|
||||
th: 256,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
search_box(s, xo + 25, yo + 13, &mut put);
|
||||
// updateTabs.
|
||||
let offset = if s.narrow { 0 } else { 86 };
|
||||
let tab_x = (s.width - 147) / 2 - offset - 30;
|
||||
let tab_y = (s.height - 166) / 2 + 3;
|
||||
for (n, tab) in s.tabs.iter().enumerate() {
|
||||
let (x, y) = (tab_x, tab_y + 27 * n as i32);
|
||||
let mut pose = IDENTITY;
|
||||
if tab.anim > 0.0 {
|
||||
let squeeze = squeeze(tab.anim);
|
||||
let (cx, cy) = ((x + 8) as f32, (y + 12) as f32);
|
||||
pose = translate(scale(translate(pose, cx, cy), 1.0, squeeze), -cx, -cy);
|
||||
}
|
||||
let sprite = if tab.selected {
|
||||
"recipe_book/tab_selected"
|
||||
} else {
|
||||
"recipe_book/tab"
|
||||
};
|
||||
let left = if tab.selected { -2 } else { 0 };
|
||||
put(sprite_call(sprite, x + left, y, 35, 27), pose);
|
||||
let fake = |id: &str, x: i32| Call::Item {
|
||||
call: ItemCall::Fake,
|
||||
stack: ItemStack::new(id, 1),
|
||||
x,
|
||||
y: y + 5,
|
||||
};
|
||||
match &tab.icons.1 {
|
||||
Some(second) => {
|
||||
put(fake(&tab.icons.0, x + 3 + left), pose);
|
||||
put(fake(second, x + 14 + left), pose);
|
||||
}
|
||||
None => put(fake(&tab.icons.0, x + 9 + left), pose),
|
||||
}
|
||||
}
|
||||
// The craftable filter.
|
||||
let (fx, fy) = (xo + 110, yo + 12);
|
||||
let hover = s.hovered(fx, fy, 26, 16);
|
||||
let prefix = if s.book == BookType::Crafting {
|
||||
"recipe_book/"
|
||||
} else {
|
||||
"recipe_book/furnace_"
|
||||
};
|
||||
let state = if s.filtering {
|
||||
"filter_enabled"
|
||||
} else {
|
||||
"filter_disabled"
|
||||
};
|
||||
put(
|
||||
sprite_call(
|
||||
&format!("{prefix}{state}{}", if hover { "_highlighted" } else { "" }),
|
||||
fx,
|
||||
fy,
|
||||
26,
|
||||
16,
|
||||
),
|
||||
IDENTITY,
|
||||
);
|
||||
if hover {
|
||||
let key = if !s.filtering {
|
||||
"gui.recipebook.toggleRecipes.all"
|
||||
} else {
|
||||
match s.book {
|
||||
BookType::Crafting => "gui.recipebook.toggleRecipes.craftable",
|
||||
BookType::Furnace => "gui.recipebook.toggleRecipes.smeltable",
|
||||
BookType::BlastFurnace => "gui.recipebook.toggleRecipes.blastable",
|
||||
BookType::Smoker => "gui.recipebook.toggleRecipes.smokable",
|
||||
}
|
||||
};
|
||||
put(
|
||||
Call::Tooltip(vec![vec![Run::plain((s.translate)(key))]]),
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
// RecipeBookPage.extractRenderState.
|
||||
if s.pages > 1 {
|
||||
let text = (s.translate)("gui.recipebook.page")
|
||||
.replacen("%s", &(s.page + 1).to_string(), 1)
|
||||
.replacen("%s", &s.pages.to_string(), 1);
|
||||
let w = (s.text_width)(&text);
|
||||
put(
|
||||
Call::Text {
|
||||
runs: vec![Run::plain(text)],
|
||||
x: xo - w / 2 + 73,
|
||||
y: yo + 141,
|
||||
color: -1,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
let mut hovered = None;
|
||||
for (i, b) in s.buttons.iter().enumerate().take(20) {
|
||||
let (x, y) = (xo + 11 + 25 * (i as i32 % 5), yo + 31 + 25 * (i as i32 / 5));
|
||||
let many = b.entries.len() > 1;
|
||||
let sprite = match (b.has_craftable, many) {
|
||||
(true, true) => "recipe_book/slot_many_craftable",
|
||||
(true, false) => "recipe_book/slot_craftable",
|
||||
(false, true) => "recipe_book/slot_many_uncraftable",
|
||||
(false, false) => "recipe_book/slot_uncraftable",
|
||||
};
|
||||
let mut pose = IDENTITY;
|
||||
if b.anim > 0.0 {
|
||||
let squeeze = squeeze(b.anim);
|
||||
let (cx, cy) = ((x + 8) as f32, (y + 12) as f32);
|
||||
pose = translate(scale(translate(pose, cx, cy), squeeze, squeeze), -cx, -cy);
|
||||
}
|
||||
put(sprite_call(sprite, x, y, 25, 25), pose);
|
||||
let stack = display_stack(&b.entries, s.index);
|
||||
let mut offset = 4;
|
||||
if many && same_result_display(&b.entries) {
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Item,
|
||||
stack: stack.clone(),
|
||||
x: x + offset + 1,
|
||||
y: y + offset + 1,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
offset -= 1;
|
||||
}
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Fake,
|
||||
stack: stack.clone(),
|
||||
x: x + offset,
|
||||
y: y + offset,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
if s.hovered(x, y, 25, 25) {
|
||||
hovered = Some((stack, many));
|
||||
}
|
||||
}
|
||||
let arrows = [
|
||||
(
|
||||
s.pages > 1 && s.page + 1 < s.pages,
|
||||
xo + 93,
|
||||
"recipe_book/page_forward",
|
||||
"gui.recipebook.next_page",
|
||||
),
|
||||
(
|
||||
s.pages > 1 && s.page > 0,
|
||||
xo + 38,
|
||||
"recipe_book/page_backward",
|
||||
"gui.recipebook.previous_page",
|
||||
),
|
||||
];
|
||||
for (visible, x, sprite, key) in arrows {
|
||||
if !visible {
|
||||
continue;
|
||||
}
|
||||
let hover = s.hovered(x, yo + 137, 12, 17);
|
||||
let id = if hover {
|
||||
format!("{sprite}_highlighted")
|
||||
} else {
|
||||
sprite.to_owned()
|
||||
};
|
||||
put(sprite_call(&id, x, yo + 137, 12, 17), IDENTITY);
|
||||
if hover {
|
||||
put(
|
||||
Call::Tooltip(vec![vec![Run::plain((s.translate)(key))]]),
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
}
|
||||
put(Call::Stratum, IDENTITY);
|
||||
if let Some(o) = s.overlay {
|
||||
overlay(s, o, &mut put);
|
||||
}
|
||||
// RecipeBookPage.extractTooltip.
|
||||
if let Some((stack, more)) = hovered
|
||||
&& s.overlay.is_none()
|
||||
{
|
||||
put(Call::ItemTooltip { stack, more }, IDENTITY);
|
||||
}
|
||||
if let Some((left, top, big, ghosts)) = s.ghost {
|
||||
out.extend(ghost(s.index, left, top, big, ghosts));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `GhostSlots.extractRenderState` for a container whose corner is `(left, top)`.
|
||||
pub fn ghost(index: usize, left: i32, top: i32, big: bool, ghosts: &[GhostView]) -> Vec<Drawn> {
|
||||
let mut out = Vec::new();
|
||||
let mut put = |call: Call, pose: [f32; 6]| out.push(Drawn { call, pose });
|
||||
let pose = translate(IDENTITY, left as f32, top as f32);
|
||||
for g in ghosts.iter().filter(|g| !g.items.is_empty()) {
|
||||
let (x, y) = (g.x, g.y);
|
||||
if g.result && big {
|
||||
put(fill(x - 4, y - 4, x + 20, y + 20, 822_018_048), pose);
|
||||
} else {
|
||||
put(fill(x, y, x + 16, y + 16, 822_018_048), pose);
|
||||
}
|
||||
let stack = g.items[index % g.items.len()].clone();
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Fake,
|
||||
stack: stack.clone(),
|
||||
x,
|
||||
y,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
put(fill(x, y, x + 16, y + 16, 822_083_583), pose);
|
||||
if g.result {
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Decorations,
|
||||
stack,
|
||||
x,
|
||||
y,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `1 + 0.1 sin(t / 15 * PI)`, the squeeze of new recipes' buttons and tabs.
|
||||
fn squeeze(time: f32) -> f32 {
|
||||
1.0 + 0.1 * f64::from(time / 15.0 * std::f32::consts::PI).sin() as f32
|
||||
}
|
||||
|
||||
fn sprite_call(id: &str, x: i32, y: i32, w: i32, h: i32) -> Call {
|
||||
Call::Sprite {
|
||||
id: id.to_owned(),
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
}
|
||||
}
|
||||
fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: i32) -> Call {
|
||||
Call::Fill {
|
||||
x0,
|
||||
y0,
|
||||
x1,
|
||||
y1,
|
||||
color,
|
||||
}
|
||||
}
|
||||
|
||||
/// `RecipeButton.getDisplayStack`.
|
||||
fn display_stack(entries: &[Vec<ItemStack>], index: usize) -> ItemStack {
|
||||
let n = entries.len().max(1);
|
||||
let (offset, entry) = (index / n, index % n);
|
||||
match entries.get(entry) {
|
||||
Some(items) if !items.is_empty() => items[offset % items.len()].clone(),
|
||||
_ => ItemStack::new("minecraft:air", 0),
|
||||
}
|
||||
}
|
||||
/// `RecipeButton.allRecipesHaveSameResultDisplay`.
|
||||
fn same_result_display(entries: &[Vec<ItemStack>]) -> bool {
|
||||
let mut items = entries.iter().flatten();
|
||||
let Some(first) = items.next() else {
|
||||
return true;
|
||||
};
|
||||
items.all(|s| first.same_item_same_components(s))
|
||||
}
|
||||
|
||||
/// `EditBox.extractWidgetRenderState` for the recipe book's search box.
|
||||
fn search_box(s: &Screen, x: i32, y: i32, put: &mut impl FnMut(Call, [f32; 6])) {
|
||||
let b = s.search;
|
||||
let (w, h) = (81, 9 + 5);
|
||||
let sprite = if b.focused {
|
||||
"widget/text_field_highlighted"
|
||||
} else {
|
||||
"widget/text_field"
|
||||
};
|
||||
put(sprite_call(sprite, x, y, w, h), IDENTITY);
|
||||
let (text_x, text_y) = (x + 4, y + (h - 8) / 2);
|
||||
let color = -1;
|
||||
let chars: Vec<char> = b.value.chars().collect();
|
||||
let tail: String = chars[b.display.min(chars.len())..].iter().collect();
|
||||
let displayed = s.substr_by_width(&tail, w - 8).to_owned();
|
||||
let shown = displayed.chars().count();
|
||||
let rel_cursor = b.cursor as i64 - b.display as i64;
|
||||
let on_screen = rel_cursor >= 0 && rel_cursor <= shown as i64;
|
||||
let visible = b.focused && (b.blink_ms / 300).is_multiple_of(2) && on_screen;
|
||||
let mut draw_x = text_x;
|
||||
let rel_highlight = (b.highlight as i64 - b.display as i64).clamp(0, shown as i64) as usize;
|
||||
let prefix = |n: usize| displayed.chars().take(n).collect::<String>();
|
||||
if !displayed.is_empty() {
|
||||
let half = if on_screen {
|
||||
prefix(rel_cursor as usize)
|
||||
} else {
|
||||
displayed.clone()
|
||||
};
|
||||
let width = (s.text_width)(&half);
|
||||
put(
|
||||
Call::Text {
|
||||
runs: runs_of(half),
|
||||
x: draw_x,
|
||||
y: text_y,
|
||||
color,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
draw_x += width + 1;
|
||||
}
|
||||
let insert = b.cursor < chars.len() || chars.len() >= 50;
|
||||
let mut cursor_x = draw_x;
|
||||
if !on_screen {
|
||||
cursor_x = if rel_cursor > 0 { text_x + w } else { text_x };
|
||||
} else if insert {
|
||||
cursor_x -= 1;
|
||||
draw_x -= 1;
|
||||
}
|
||||
if !displayed.is_empty() && on_screen && (rel_cursor as usize) < shown {
|
||||
let rest: String = displayed.chars().skip(rel_cursor as usize).collect();
|
||||
put(
|
||||
Call::Text {
|
||||
runs: runs_of(rest),
|
||||
x: draw_x,
|
||||
y: text_y,
|
||||
color,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
if displayed.is_empty() && !b.focused {
|
||||
// SEARCH_HINT: gray, italic.
|
||||
put(
|
||||
Call::Text {
|
||||
runs: vec![Run {
|
||||
text: (s.translate)("gui.recipebook.search_hint"),
|
||||
color: 0xAAAAAA,
|
||||
italic: true,
|
||||
}],
|
||||
x: draw_x,
|
||||
y: text_y,
|
||||
color,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
if rel_highlight as i64 != rel_cursor {
|
||||
let highlight_x = text_x + (s.text_width)(&prefix(rel_highlight));
|
||||
put(
|
||||
Call::Highlight {
|
||||
x0: cursor_x.min(x + w),
|
||||
y0: text_y - 1,
|
||||
x1: (highlight_x - 1).min(x + w),
|
||||
y1: text_y + 1 + 9,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
if visible {
|
||||
if insert {
|
||||
put(
|
||||
fill(cursor_x, text_y - 1, cursor_x + 1, text_y + 10, color),
|
||||
IDENTITY,
|
||||
);
|
||||
} else {
|
||||
put(
|
||||
Call::Text {
|
||||
runs: vec![Run::plain("_")],
|
||||
x: cursor_x,
|
||||
y: text_y,
|
||||
color,
|
||||
shadow: true,
|
||||
},
|
||||
IDENTITY,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn runs_of(text: String) -> Vec<Run> {
|
||||
if text.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
vec![Run::plain(text)]
|
||||
}
|
||||
}
|
||||
|
||||
/// `OverlayRecipeComponent.init`'s corner for `total` recipes opened from the
|
||||
/// button at `(button_x, button_y)` of the book at `(xo, yo)`.
|
||||
pub fn overlay_origin(button_x: i32, button_y: i32, total: usize, xo: i32, yo: i32) -> (i32, i32) {
|
||||
let total = total as i32;
|
||||
let max_row = if total <= 16 { 4 } else { 5 };
|
||||
let rows = (total as f32 / max_row as f32).ceil() as i32;
|
||||
let (mut x, mut y) = (button_x, button_y);
|
||||
let width = 25.0f32;
|
||||
let (center_x, center_y) = (xo + 147 / 2, yo + 13 + 166 / 2);
|
||||
let right = (x + total.min(max_row) * 25) as f32;
|
||||
let max_left = (center_x + 50) as f32;
|
||||
if right > max_left {
|
||||
x = (x as f32 - width * ((right - max_left) / width) as i32 as f32) as i32;
|
||||
}
|
||||
let bottom = (y + rows * 25) as f32;
|
||||
let max_bottom = (center_y + 50) as f32;
|
||||
if bottom > max_bottom {
|
||||
y = (y as f32 - width * ((bottom - max_bottom) / width).ceil()) as i32;
|
||||
}
|
||||
let top = y as f32;
|
||||
let max_top = (center_y - 100) as f32;
|
||||
if top < max_top {
|
||||
y = (y as f32 - width * ((top - max_top) / width).ceil()) as i32;
|
||||
}
|
||||
(x, y)
|
||||
}
|
||||
|
||||
/// `OverlayRecipeComponent.extractRenderState`.
|
||||
fn overlay(s: &Screen, o: &OverlayView, put: &mut impl FnMut(Call, [f32; 6])) {
|
||||
let total = o.recipes.len() as i32;
|
||||
let max_row = if total <= 16 { 4 } else { 5 };
|
||||
let (x, y) = (o.x, o.y);
|
||||
let columns = total.min(max_row);
|
||||
let height = (total as f32 / max_row as f32).ceil() as i32;
|
||||
put(
|
||||
sprite_call(
|
||||
"recipe_book/overlay_recipe",
|
||||
x,
|
||||
y,
|
||||
columns * 25 + 8,
|
||||
height * 25 + 8,
|
||||
),
|
||||
IDENTITY,
|
||||
);
|
||||
let family = if s.book == BookType::Crafting {
|
||||
"crafting"
|
||||
} else {
|
||||
"furnace"
|
||||
};
|
||||
for (i, r) in o.recipes.iter().enumerate() {
|
||||
let i = i as i32;
|
||||
let (bx, by) = (x + 4 + 25 * (i % max_row), y + 5 + 25 * (i / max_row));
|
||||
let hover = s.hovered(bx, by, 24, 24);
|
||||
let id = format!(
|
||||
"recipe_book/{family}_overlay{}{}",
|
||||
if r.craftable { "" } else { "_disabled" },
|
||||
if hover { "_highlighted" } else { "" }
|
||||
);
|
||||
put(sprite_call(&id, bx, by, 24, 24), IDENTITY);
|
||||
let (gx, gy) = ((bx + 2) as f32, (by + 2) as f32);
|
||||
for (cx, cy, items) in &r.cells {
|
||||
let pose = translate(
|
||||
scale(
|
||||
translate(IDENTITY, gx + (3 + cx * 7) as f32, gy + (3 + cy * 7) as f32),
|
||||
0.375,
|
||||
0.375,
|
||||
),
|
||||
-8.0,
|
||||
-8.0,
|
||||
);
|
||||
put(
|
||||
Call::Item {
|
||||
call: ItemCall::Item,
|
||||
stack: items[s.index % items.len()].clone(),
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
pose,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The ingredient cells a recipe shows in the overlay
|
||||
/// (`OverlayCraftingRecipeButton` / `OverlaySmeltingRecipeButton.calculateIngredientsPositions`).
|
||||
pub fn overlay_cells(book: &Book, entry: &Entry) -> Vec<(i32, i32, Vec<ItemStack>)> {
|
||||
let stacks = |ingredient| -> Vec<ItemStack> {
|
||||
book.items_of(ingredient)
|
||||
.iter()
|
||||
.map(|i| ItemStack::new(i, 1))
|
||||
.collect()
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
match &entry.display {
|
||||
Display::Furnace(i) => out.push((1, 1, stacks(i))),
|
||||
Display::Shaped { .. } => {
|
||||
let requirements = entry.requirements();
|
||||
for (ingredient, grid) in entry.grid_cells(3, 3) {
|
||||
if let Some(i) = ingredient {
|
||||
out.push((grid as i32 % 3, grid as i32 / 3, stacks(requirements[i])));
|
||||
}
|
||||
}
|
||||
}
|
||||
Display::Shapeless(list) => {
|
||||
for (i, ingredient) in list.iter().enumerate() {
|
||||
out.push((i as i32 % 3, i as i32 / 3, stacks(ingredient)));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.retain(|c| !c.2.is_empty());
|
||||
out
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use serde_json::Value;
|
||||
use std::{collections::HashSet, fs, path::Path, sync::Arc};
|
||||
use std::{fs, path::Path, sync::Arc};
|
||||
|
||||
/// Everything the workstation menus read, loaded once with the resources.
|
||||
pub struct StationData {
|
||||
@@ -457,7 +457,7 @@ pub struct StationRecipes {
|
||||
pub trim_materials: Vec<(String, String)>,
|
||||
}
|
||||
fn ingredient(v: &Value, items: &Items) -> Ingredient {
|
||||
let mut set = HashSet::new();
|
||||
let mut list: Vec<String> = Vec::new();
|
||||
for s in match v {
|
||||
Value::String(s) => vec![s.clone()],
|
||||
Value::Array(a) => a
|
||||
@@ -466,14 +466,17 @@ fn ingredient(v: &Value, items: &Items) -> Ingredient {
|
||||
.collect(),
|
||||
_ => vec![],
|
||||
} {
|
||||
match s.strip_prefix('#') {
|
||||
Some(tag) => set.extend(items.item_tags.get(tag).into_iter().flatten().cloned()),
|
||||
None => {
|
||||
set.insert(s);
|
||||
let more = match s.strip_prefix('#') {
|
||||
Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(),
|
||||
None => vec![s],
|
||||
};
|
||||
for i in more {
|
||||
if !list.contains(&i) {
|
||||
list.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ingredient(set)
|
||||
Ingredient::of(list)
|
||||
}
|
||||
impl StationRecipes {
|
||||
pub fn load(root: &Path, items: &Items) -> Self {
|
||||
|
||||
@@ -701,6 +701,12 @@ impl EditBox {
|
||||
}
|
||||
true
|
||||
}
|
||||
/// The first shown character after scrolling to the cursor, and the
|
||||
/// milliseconds since the field was focused (the cursor's blink).
|
||||
pub fn view_state(&mut self, atlas: &HudAtlas) -> (usize, u64) {
|
||||
self.layout(atlas);
|
||||
(self.display, self.focused_at.elapsed().as_millis() as u64)
|
||||
}
|
||||
/// Draw the field; `format` styles the visible text (command colouring).
|
||||
pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, format: Option<&Text>) {
|
||||
self.layout(atlas);
|
||||
|
||||
@@ -0,0 +1,366 @@
|
||||
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.ClientRecipeBook;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.Font;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.CycleButton;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.components.WidgetSprites;
|
||||
import net.minecraft.client.gui.components.WidgetTooltipHolder;
|
||||
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner;
|
||||
import net.minecraft.client.gui.screens.recipebook.*;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.client.player.LocalPlayer;
|
||||
import net.minecraft.client.renderer.RenderPipelines;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.network.chat.CommonComponents;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.util.FormattedCharSequence;
|
||||
import net.minecraft.util.Util;
|
||||
import net.minecraft.util.context.ContextMap;
|
||||
import net.minecraft.world.SimpleContainer;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.inventory.Slot;
|
||||
import net.minecraft.world.inventory.tooltip.TooltipComponent;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
import net.minecraft.world.item.crafting.display.RecipeDisplayEntry;
|
||||
import net.minecraft.world.item.crafting.display.RecipeDisplayId;
|
||||
import net.minecraft.world.item.crafting.display.SlotDisplay;
|
||||
import net.minecraft.world.item.crafting.display.SlotDisplayContext;
|
||||
import net.minecraft.world.level.Level;
|
||||
import org.joml.Matrix3x2fStack;
|
||||
|
||||
/**
|
||||
* Original oracle for the recipe book's drawing (RecipeBookComponent.extractRenderState,
|
||||
* its tooltips and GhostSlots.extractRenderState): the background, the real
|
||||
* search EditBox, RecipeBookTabButtons, the craftable filter CycleButton, a
|
||||
* RecipeBookPage of RecipeButtons over real RecipeCollections with its page
|
||||
* arrows and number, the OverlayRecipeComponent of a button and ghost slots,
|
||||
* each built as RecipeBookComponent.initVisuals and RecipeBookPage.init build
|
||||
* them, with the state the case gives (tab and button animations, the cycling
|
||||
* index, the search box, the mouse). Every GuiGraphicsExtractor call is recorded
|
||||
* with its pose. The hovered button's tooltip is recorded as its display stack
|
||||
* (RecipeButton.getTooltipText adds the item's own tooltip, compared elsewhere).
|
||||
*/
|
||||
public final class VanillaRecipeBookScreenOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
@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 float round(float v) { return Math.round(v * 1e4f) / 1e4f; }
|
||||
|
||||
/** A text's styled runs: [text, rgb or -1, italic]. */
|
||||
static JsonArray runs(FormattedCharSequence s) {
|
||||
var out = new JsonArray();
|
||||
StringBuilder text = new StringBuilder();
|
||||
int[] style = {Integer.MIN_VALUE, 0};
|
||||
s.accept((i, st, cp) -> {
|
||||
int color = st.getColor() == null ? -1 : st.getColor().getValue();
|
||||
int italic = st.isItalic() ? 1 : 0;
|
||||
if (text.length() > 0 && (color != style[0] || italic != style[1])) {
|
||||
var r = new JsonArray(); r.add(text.toString()); r.add(style[0]); r.add(style[1] == 1); out.add(r);
|
||||
text.setLength(0);
|
||||
}
|
||||
style[0] = color; style[1] = italic;
|
||||
text.appendCodePoint(cp);
|
||||
return true;
|
||||
});
|
||||
if (text.length() > 0) {
|
||||
var r = new JsonArray(); r.add(text.toString()); r.add(style[0]); r.add(style[1] == 1); out.add(r);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static String id(ItemStack s) { return s.isEmpty() ? "minecraft:air" : s.getItem().builtInRegistryHolder().key().identifier().toString(); }
|
||||
|
||||
/** Records every GuiGraphicsExtractor call with the pose it was made under. */
|
||||
public static final class Capture extends GuiGraphicsExtractor {
|
||||
JsonArray draws = new JsonArray();
|
||||
Matrix3x2fStack stack = new Matrix3x2fStack(16);
|
||||
private Capture() { super(null, null, 0, 0); }
|
||||
@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("t", type);
|
||||
var m = new JsonArray();
|
||||
for (float v : new float[] {stack.m00(), stack.m01(), stack.m10(), stack.m11(), stack.m20(), stack.m21()}) m.add(round(v));
|
||||
o.add("m", m);
|
||||
draws.add(o);
|
||||
return o;
|
||||
}
|
||||
@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("id", id.getPath());
|
||||
o.addProperty("x", x); o.addProperty("y", 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", x); o.addProperty("y", 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 text(Font font, 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, String str, int x, int y, int color, boolean shadow) {
|
||||
if (str != null) text(font, FormattedCharSequence.forward(str, net.minecraft.network.chat.Style.EMPTY), x, y, color, shadow);
|
||||
}
|
||||
void item(String kind, ItemStack s, int x, int y) {
|
||||
if (s.isEmpty()) return;
|
||||
var o = add(kind);
|
||||
o.addProperty("id", id(s)); o.addProperty("count", s.getCount());
|
||||
o.addProperty("x", x); o.addProperty("y", y);
|
||||
}
|
||||
@Override public void item(ItemStack s, int x, int y) { item("item", s, x, y); }
|
||||
@Override public void item(ItemStack s, int x, int y, int seed) { item("item", s, x, y); }
|
||||
@Override public void fakeItem(ItemStack s, int x, int y) { item("fake", s, x, y); }
|
||||
@Override public void fakeItem(ItemStack s, int x, int y, int seed) { item("fake", s, x, y); }
|
||||
@Override public void itemDecorations(Font font, ItemStack s, int x, int y, String count) { item("decorations", s, x, y); }
|
||||
@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);
|
||||
}
|
||||
}
|
||||
|
||||
/** The window's text input area, which a focused EditBox moves: not tracked here. */
|
||||
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) { }
|
||||
}
|
||||
|
||||
static List<RecipeDisplayEntry> displays(RecipeManager recipes, String id) {
|
||||
List<RecipeDisplayEntry> out = new ArrayList<>();
|
||||
recipes.listDisplaysForRecipe(ResourceKey.create(Registries.RECIPE, Identifier.parse(id)), out::add);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A collection of the given recipes' displays; `craftable` lists the recipes the inventory can craft. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static RecipeCollection collection(RecipeManager recipes, JsonObject b) throws Exception {
|
||||
List<RecipeDisplayEntry> entries = new ArrayList<>();
|
||||
Set<RecipeDisplayId> craftable = (Set<RecipeDisplayId>) new HashSet<RecipeDisplayId>();
|
||||
for (var r : b.getAsJsonArray("recipes")) {
|
||||
var a = r.getAsJsonArray();
|
||||
for (var e : displays(recipes, a.get(0).getAsString())) {
|
||||
entries.add(e);
|
||||
if (a.get(1).getAsBoolean()) craftable.add(e.id());
|
||||
}
|
||||
}
|
||||
var c = new RecipeCollection(entries);
|
||||
((Set<RecipeDisplayId>) field(RecipeCollection.class, "selected").get(c)).addAll(entries.stream().map(RecipeDisplayEntry::id).toList());
|
||||
((Set<RecipeDisplayId>) field(RecipeCollection.class, "craftable").get(c)).addAll(craftable);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** The widget's tooltip shows on this frame when hovered (its delay has passed). */
|
||||
static void settled(Object widget) throws Exception {
|
||||
var holder = (WidgetTooltipHolder) field(net.minecraft.client.gui.components.AbstractWidget.class, "tooltip").get(widget);
|
||||
put(holder, WidgetTooltipHolder.class, "wasDisplayed", true);
|
||||
put(holder, WidgetTooltipHolder.class, "displayStartTime", Util.getMillis() - 1000L);
|
||||
}
|
||||
|
||||
static JsonArray run(JsonObject c, Minecraft mc, RecipeManager recipes) throws Exception {
|
||||
var g = alloc(Capture.class);
|
||||
g.draws = new JsonArray();
|
||||
g.stack = new Matrix3x2fStack(16);
|
||||
String type = c.get("type").getAsString();
|
||||
boolean furnace = !type.equals("crafting");
|
||||
int width = c.get("width").getAsInt(), height = c.get("height").getAsInt();
|
||||
int xOffset = c.get("narrow").getAsBoolean() ? 0 : 86;
|
||||
int xo = (width - 147) / 2 - xOffset, yo = (height - 166) / 2;
|
||||
int mx = c.getAsJsonArray("mouse").get(0).getAsInt(), my = c.getAsJsonArray("mouse").get(1).getAsInt();
|
||||
int index = c.get("index").getAsInt();
|
||||
SlotSelectTime time = () -> index;
|
||||
boolean filtering = c.get("filtering").getAsBoolean();
|
||||
// RecipeBookComponent.extractRenderState.
|
||||
g.blit(RenderPipelines.GUI_TEXTURED, (Identifier) field(RecipeBookComponent.class, "RECIPE_BOOK_LOCATION").get(null), xo, yo, 1.0F, 1.0F, 147, 166, 256, 256);
|
||||
var s = c.getAsJsonObject("search");
|
||||
var search = new EditBox(mc.font, xo + 25, yo + 13, 81, 9 + 5, Component.translatable("itemGroup.search"));
|
||||
search.setMaxLength(50);
|
||||
search.setVisible(true);
|
||||
search.setTextColor(-1);
|
||||
search.setValue(s.get("value").getAsString());
|
||||
search.setHint((Component) field(RecipeBookComponent.class, "SEARCH_HINT").get(null));
|
||||
put(search, net.minecraft.client.gui.components.AbstractWidget.class, "focused", s.get("focused").getAsBoolean());
|
||||
put(search, EditBox.class, "displayPos", s.get("display").getAsInt());
|
||||
put(search, EditBox.class, "cursorPos", s.get("cursor").getAsInt());
|
||||
put(search, EditBox.class, "highlightPos", s.get("highlight").getAsInt());
|
||||
put(search, EditBox.class, "focusedTime", Util.getMillis() - s.get("blink").getAsLong());
|
||||
search.extractRenderState(g, mx, my, 1.0F);
|
||||
Class<?> tabOwner = switch (type) {
|
||||
case "crafting" -> CraftingRecipeBookComponent.class;
|
||||
case "furnace" -> net.minecraft.client.gui.screens.inventory.FurnaceScreen.class;
|
||||
case "blast_furnace" -> net.minecraft.client.gui.screens.inventory.BlastFurnaceScreen.class;
|
||||
default -> net.minecraft.client.gui.screens.inventory.SmokerScreen.class;
|
||||
};
|
||||
@SuppressWarnings("unchecked")
|
||||
var infos = (List<RecipeBookComponent.TabInfo>) field(tabOwner, "TABS").get(null);
|
||||
// updateTabs: the visible tabs in order.
|
||||
int n = 0;
|
||||
for (var t : c.getAsJsonArray("tabs")) {
|
||||
var tab = t.getAsJsonObject();
|
||||
var button = new RecipeBookTabButton(0, 0, infos.get(tab.get("tab").getAsInt()), b -> {});
|
||||
button.setPosition((width - 147) / 2 - xOffset - 30, (height - 166) / 2 + 3 + 27 * n++);
|
||||
if (tab.get("selected").getAsBoolean()) button.select();
|
||||
put(button, RecipeBookTabButton.class, "animationTime", tab.get("anim").getAsFloat());
|
||||
button.extractRenderState(g, mx, my, 1.0F);
|
||||
}
|
||||
RecipeBookComponent<?> component = furnace ? alloc(FurnaceRecipeBookComponent.class) : alloc(CraftingRecipeBookComponent.class);
|
||||
Method name = RecipeBookComponent.class.getDeclaredMethod("getRecipeFilterName");
|
||||
name.setAccessible(true);
|
||||
Method sprites = RecipeBookComponent.class.getDeclaredMethod("getFilterButtonTextures");
|
||||
sprites.setAccessible(true);
|
||||
if (furnace) put(component, FurnaceRecipeBookComponent.class, "recipeFilterName", Component.translatable(switch (type) {
|
||||
case "furnace" -> "gui.recipebook.toggleRecipes.smeltable";
|
||||
case "blast_furnace" -> "gui.recipebook.toggleRecipes.blastable";
|
||||
default -> "gui.recipebook.toggleRecipes.smokable";
|
||||
}));
|
||||
Component filterName = (Component) name.invoke(component);
|
||||
WidgetSprites filterSprites = (WidgetSprites) sprites.invoke(component);
|
||||
Component all = (Component) field(RecipeBookComponent.class, "ALL_RECIPES_TOOLTIP").get(null);
|
||||
var filter = CycleButton.booleanBuilder(filterName, all, filtering)
|
||||
.withTooltip(f -> f ? Tooltip.create(filterName) : Tooltip.create(all))
|
||||
.withSprite((b, f) -> filterSprites.get(f, b.isHoveredOrFocused()))
|
||||
.displayState(CycleButton.DisplayState.HIDE)
|
||||
.create(xo + 110, yo + 12, 26, 16, CommonComponents.EMPTY, (b, v) -> {});
|
||||
settled(filter);
|
||||
filter.extractRenderState(g, mx, my, 1.0F);
|
||||
// RecipeBookPage.init and updateCollections.
|
||||
var page = new RecipeBookPage(null, time, furnace);
|
||||
page.init(mc, xo, yo);
|
||||
List<RecipeCollection> collections = new ArrayList<>();
|
||||
for (var b : c.getAsJsonArray("collections")) collections.add(collection(recipes, b.getAsJsonObject()));
|
||||
put(page, RecipeBookPage.class, "currentPage", c.get("page").getAsInt());
|
||||
page.updateCollections(collections, false, filtering);
|
||||
@SuppressWarnings("unchecked")
|
||||
var buttons = (List<RecipeButton>) field(RecipeBookPage.class, "buttons").get(page);
|
||||
var anims = c.getAsJsonArray("buttonAnims");
|
||||
for (int i = 0; i < anims.size(); i++) put(buttons.get(i), RecipeButton.class, "animationTime", anims.get(i).getAsFloat());
|
||||
for (String arrow : new String[] {"forwardButton", "backButton"}) settled(field(RecipeBookPage.class, arrow).get(page));
|
||||
var overlay = (OverlayRecipeComponent) field(RecipeBookPage.class, "overlay").get(page);
|
||||
if (c.has("overlay")) {
|
||||
// RecipeBookPage.mouseClicked: right click on a button.
|
||||
var button = buttons.get(c.get("overlay").getAsInt());
|
||||
ContextMap context = SlotDisplayContext.fromLevel(mc.level);
|
||||
overlay.init(button.getCollection(), context, filtering, button.getX(), button.getY(), xo + 147 / 2, yo + 13 + 166 / 2, button.getWidth());
|
||||
}
|
||||
page.extractRenderState(g, xo, yo, mx, my, 1.0F);
|
||||
// RecipeBookPage.extractTooltip.
|
||||
var hovered = (RecipeButton) field(RecipeBookPage.class, "hoveredButton").get(page);
|
||||
if (hovered != null && !overlay.isVisible()) {
|
||||
var o = g.add("item_tooltip");
|
||||
o.addProperty("id", id(hovered.getDisplayStack()));
|
||||
o.addProperty("more", !hovered.isOnlyOption());
|
||||
}
|
||||
// GhostSlots.extractRenderState.
|
||||
if (c.has("ghost")) {
|
||||
var ghost = new GhostSlots(time);
|
||||
ContextMap context = SlotDisplayContext.fromLevel(mc.level);
|
||||
var container = new SimpleContainer(16);
|
||||
int i = 0;
|
||||
for (var e : c.getAsJsonArray("ghost")) {
|
||||
var gs = e.getAsJsonObject();
|
||||
var slot = new Slot(container, i++, gs.get("x").getAsInt(), gs.get("y").getAsInt());
|
||||
List<SlotDisplay> items = new ArrayList<>();
|
||||
for (var it : gs.getAsJsonArray("items")) items.add(new SlotDisplay.ItemStackSlotDisplay(new net.minecraft.world.item.ItemStackTemplate(net.minecraft.core.registries.BuiltInRegistries.ITEM.getValue(Identifier.parse(it.getAsString())))));
|
||||
SlotDisplay display = new SlotDisplay.Composite(items);
|
||||
Method set = GhostSlots.class.getDeclaredMethod(gs.get("result").getAsBoolean() ? "setResult" : "setInput", Slot.class, ContextMap.class, SlotDisplay.class);
|
||||
set.setAccessible(true);
|
||||
set.invoke(ghost, slot, context, display);
|
||||
}
|
||||
g.pose().pushMatrix();
|
||||
g.pose().translate(c.get("left").getAsInt(), c.get("top").getAsInt());
|
||||
ghost.extractRenderState(g, mc, c.get("big").getAsBoolean());
|
||||
g.pose().popMatrix();
|
||||
}
|
||||
return g.draws;
|
||||
}
|
||||
|
||||
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);
|
||||
RecipeManager recipes = new RecipeManager(ParityData.lookup);
|
||||
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
|
||||
// A stand-in client: its font, a level for the slot display context, a player's book.
|
||||
Minecraft mc = alloc(Minecraft.class);
|
||||
put(mc, Minecraft.class, "font", ParityFont.create(ParityFont.resources()));
|
||||
var level = alloc(ClientLevel.class);
|
||||
put(level, Level.class, "registryAccess", ParityData.access);
|
||||
put(mc, Minecraft.class, "level", level);
|
||||
var player = alloc(LocalPlayer.class);
|
||||
put(player, LocalPlayer.class, "recipeBook", new ClientRecipeBook());
|
||||
put(mc, Minecraft.class, "player", player);
|
||||
put(mc, Minecraft.class, "lastInputType", net.minecraft.client.InputType.MOUSE);
|
||||
put(mc, Minecraft.class, "textInputManager", new NoTextInput());
|
||||
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();
|
||||
var result = new JsonObject();
|
||||
try {
|
||||
result.add("draws", run(c, mc, recipes));
|
||||
} catch (Throwable error) {
|
||||
var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error;
|
||||
var sw = new java.io.StringWriter();
|
||||
cause.printStackTrace(new java.io.PrintWriter(sw));
|
||||
result.addProperty("error", sw.toString().lines().limit(8).reduce("", (a, b) -> a + b + " | "));
|
||||
}
|
||||
out.append(gson.toJson(result)).append('\n');
|
||||
}
|
||||
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the recipe book's drawing with the vanilla client's.
|
||||
|
||||
Each case opens a book type (the inventory's or a crafting table's crafting
|
||||
book, the furnace, blast furnace or smoker) at a GUI size, with its visible
|
||||
tabs (one selected, some in their new-recipe squeeze), the search box (text,
|
||||
cursor, selection, focus and cursor blink), the craftable filter, a page of
|
||||
recipe collections (real recipes, some craftable, some buttons squeezing),
|
||||
the alternatives overlay of one button, ghost slots, the cycling index and
|
||||
the mouse. The Java oracle (VanillaRecipeBookScreenOracle) builds vanilla's
|
||||
widgets for that state as RecipeBookComponent.initVisuals and
|
||||
RecipeBookPage.init do and records every GuiGraphicsExtractor call of their
|
||||
extractRenderState, the tooltips and GhostSlots.extractRenderState, with its
|
||||
pose; examples/recipe_book_render_fixture lays out the same state with
|
||||
horizon_client::recipe_book_screen, which the game paints. The 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
|
||||
|
||||
TABS = {'crafting': 5, 'furnace': 4, 'blast_furnace': 3, 'smoker': 2}
|
||||
TYPES = {'crafting': ('minecraft:crafting_shaped', 'minecraft:crafting_shapeless'), 'furnace': ('minecraft:smelting',),
|
||||
'blast_furnace': ('minecraft:blasting',), 'smoker': ('minecraft:smoking',)}
|
||||
WORDS = ['', '', 'a', 'stone', 'iron ingot', 'oak', 'zzz', 'red', 'a very long search text that overflows']
|
||||
|
||||
|
||||
def recipes_by_type():
|
||||
out = {k: [] for k in TYPES}
|
||||
for path in sorted((lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')):
|
||||
kind = json.loads(path.read_text()).get('type')
|
||||
for k, types in TYPES.items():
|
||||
if kind in types:
|
||||
out[k].append('minecraft:' + path.stem)
|
||||
return out
|
||||
|
||||
|
||||
def cases(count, seed):
|
||||
rng = random.Random(seed)
|
||||
by_type = recipes_by_type()
|
||||
items = sorted(i for i in json.loads((lib.RESOURCES / 'items.json').read_text()) if i != 'minecraft:air')
|
||||
out = []
|
||||
for n in range(count):
|
||||
kind = ['crafting', 'crafting', 'furnace', 'blast_furnace', 'smoker'][n % 5]
|
||||
width, height = rng.choice([(427, 240), (480, 270), (640, 360), (320, 240), (378, 260), (854, 480)])
|
||||
narrow = width < 379
|
||||
xo = (width - 147) // 2 - (0 if narrow else 86)
|
||||
yo = (height - 166) // 2
|
||||
tabs = [0] + sorted(rng.sample(range(1, TABS[kind]), rng.randint(0, TABS[kind] - 1)))
|
||||
selected = rng.choice(tabs)
|
||||
tab_list = [{'tab': t, 'selected': t == selected, 'anim': rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)])}
|
||||
for t in tabs]
|
||||
total = rng.choice([0, 1, 5, 19, 20, 21, 47, 80])
|
||||
pages = (total + 19) // 20
|
||||
page = rng.randrange(pages) if pages else 0
|
||||
filtering = rng.random() < 0.4
|
||||
collections = []
|
||||
for _ in range(total):
|
||||
group = rng.sample(by_type[kind], rng.choice([1, 1, 1, 2, 3, 6]))
|
||||
recipes = [[r, rng.random() < 0.4] for r in group]
|
||||
if filtering and not any(c for _, c in recipes):
|
||||
recipes[0][1] = True
|
||||
collections.append({'recipes': recipes})
|
||||
on_page = max(0, min(20, total - 20 * page))
|
||||
value = rng.choice(WORDS)
|
||||
cursor = rng.randint(0, len(value))
|
||||
highlight = rng.choice([cursor, rng.randint(0, len(value))])
|
||||
search = {'value': value, 'cursor': cursor, 'highlight': highlight,
|
||||
'display': rng.choice([0, 0, min(cursor, rng.randint(0, len(value)))]), 'focused': rng.random() < 0.5,
|
||||
'blink': rng.choice([0, 150, 450, 700])}
|
||||
targets = [(xo + 11 + 25 * (i % 5) + rng.randint(0, 24), yo + 31 + 25 * (i // 5) + rng.randint(0, 24)) for i in range(on_page)]
|
||||
targets += [(xo + 115, yo + 20), (xo + 95, yo + 140), (xo + 40, yo + 140), (xo + 30, yo + 18), (xo - 20, yo + 40),
|
||||
(rng.randint(0, width), rng.randint(0, height))]
|
||||
case = {'type': kind, 'grid': 2 if rng.random() < 0.5 else 3, 'width': width, 'height': height, 'narrow': narrow,
|
||||
'mouse': list(rng.choice(targets)), 'index': rng.choice([0, 0, 1, 2, 5, 13, 60]), 'filtering': filtering,
|
||||
'tabs': tab_list, 'search': search, 'collections': collections, 'page': page,
|
||||
'buttonAnims': [rng.choice([0.0, 0.0, 0.0, round(rng.uniform(0.1, 15), 3)]) for _ in range(on_page)]}
|
||||
multi = [i for i in range(on_page) if sum(1 for _, c in collections[20 * page + i]['recipes'] if c or not filtering) > 1]
|
||||
if multi and rng.random() < 0.4:
|
||||
case['overlay'] = rng.choice(multi)
|
||||
if rng.random() < 0.4:
|
||||
left, top = (width - 176) // 2, (height - 166) // 2
|
||||
slots = [(124, 35, True)] + [(30 + 18 * (i % 3), 17 + 18 * (i // 3), False) for i in range(9)]
|
||||
if kind != 'crafting':
|
||||
slots = [(116, 35, True), (56, 17, False)]
|
||||
case.update({'left': left, 'top': top, 'big': rng.random() < 0.7,
|
||||
'ghost': [{'x': x, 'y': y, 'result': r, 'items': rng.sample(items, rng.choice([1, 1, 2, 4]))}
|
||||
for x, y, r in rng.sample(slots, rng.randint(1, len(slots)))]})
|
||||
out.append(case)
|
||||
return out
|
||||
|
||||
|
||||
def same(a, b):
|
||||
"""Calls agree: every field exactly, poses within float printing."""
|
||||
if a is None or b is None or set(a) != set(b):
|
||||
return False
|
||||
return all(all(abs(x - y) <= 1e-3 for x, y in zip(a[k], b[k])) if k == 'm' else a[k] == b[k] for k in a)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--seed', type=int, default=29)
|
||||
parser.add_argument('--cases', type=int, default=600)
|
||||
parser.add_argument('--limit', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
work = lib.work_dir('recipe-book-render-parity')
|
||||
classes = work / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()]))
|
||||
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', 'ParityFont', 'VanillaRecipeBookScreenOracle'))],
|
||||
capture_output=True, text=True)
|
||||
if done.returncode:
|
||||
print(done.stderr[-4000:])
|
||||
sys.exit('javac failed')
|
||||
chosen = cases(args.cases, args.seed)
|
||||
inputs = work / 'cases.jsonl'
|
||||
inputs.write_text(''.join(json.dumps(c) + '\n' for c in chosen))
|
||||
run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaRecipeBookScreenOracle',
|
||||
str(inputs), str(work / 'vanilla.jsonl')], capture_output=True, text=True)
|
||||
if run.returncode:
|
||||
print(run.stderr[-4000:])
|
||||
sys.exit('oracle failed')
|
||||
lib.cargo_example('horizon-client', 'recipe_book_render_fixture', lib.RESOURCES, inputs, work / 'rust.jsonl')
|
||||
vanilla = [json.loads(l) for l in (work / 'vanilla.jsonl').read_text().splitlines()]
|
||||
rust = [json.loads(l) for l in (work / 'rust.jsonl').read_text().splitlines()]
|
||||
assert len(vanilla) == len(rust) == len(chosen), (len(vanilla), len(rust), len(chosen))
|
||||
errors, failures, passed = {}, {}, 0
|
||||
for case, v, r in zip(chosen, vanilla, rust):
|
||||
if 'error' in v:
|
||||
errors.setdefault(case['type'], v['error'])
|
||||
continue
|
||||
a, b = v['draws'], r['draws']
|
||||
bad = next((i for i in range(max(len(a), len(b))) if i >= len(a) or i >= len(b) or not same(a[i], b[i])), None)
|
||||
if bad is None:
|
||||
passed += 1
|
||||
else:
|
||||
failures.setdefault(case['type'], []).append((case, bad, a[bad] if bad < len(a) else None, b[bad] if bad < len(b) else None))
|
||||
for kind, error in sorted(errors.items()):
|
||||
print(f'ORACLE ERROR {kind}: {error[:1500]}')
|
||||
for kind, items in sorted(failures.items()):
|
||||
print(f'MISMATCH {kind}: {len(items)} cases')
|
||||
for case, i, x, y in items[:args.limit]:
|
||||
brief = {k: v for k, v in case.items() if k not in ('collections',)}
|
||||
print(f' {json.dumps(brief)[:700]}')
|
||||
print(f' call {i}: vanilla {json.dumps(x)}')
|
||||
print(f' call {i}: horizon {json.dumps(y)}')
|
||||
print(f'{passed}/{len(chosen)} cases match')
|
||||
if errors or failures:
|
||||
sys.exit(1)
|
||||
print('recipe book render parity ok')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user