Merge remote-tracking branch 'origin/main' into refactor/horizon-items
This commit is contained in:
@@ -9956,8 +9956,7 @@ impl Game<'_> {
|
||||
} else if self.carried.is_none()
|
||||
&& let Some(item) = hovered
|
||||
{
|
||||
let lines = self.stack_tooltip(&item);
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
self.draw_stack_tooltip(batch, &item, self.cursor.0, self.cursor.1);
|
||||
}
|
||||
self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32);
|
||||
}
|
||||
|
||||
@@ -515,8 +515,7 @@ impl Game<'_> {
|
||||
if self.carried.is_some() {
|
||||
self.draw_carried(batch);
|
||||
} else if let Some(stack) = stack_tip {
|
||||
let lines = self.stack_tooltip(&stack);
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
|
||||
} else if let Some(key) = tooltip {
|
||||
let text = self.translate(&key, &key);
|
||||
self.draw_tooltip_lines(
|
||||
|
||||
@@ -1094,6 +1094,9 @@ impl Game<'_> {
|
||||
let (ox, oy) = self.inventory_origin(batch);
|
||||
let local = (self.cursor.0 - ox, self.cursor.1 - oy);
|
||||
let mut tooltip: Option<Vec<(horizon_client::text::Text, u32)>> = None;
|
||||
// Keep item tooltips as stacks until drawing: text alone loses the
|
||||
// bundle contents component (including in the player's inventory).
|
||||
let mut tooltip_stack: Option<ItemStack> = None;
|
||||
{
|
||||
let atlas = &self.gui.atlas;
|
||||
batch.fill(
|
||||
@@ -1579,7 +1582,7 @@ impl Game<'_> {
|
||||
);
|
||||
self.draw_item(batch, &result, ox + x, oy + y);
|
||||
if hover {
|
||||
tooltip = Some(self.stack_tooltip(&result));
|
||||
tooltip_stack = Some(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1606,13 +1609,16 @@ impl Game<'_> {
|
||||
);
|
||||
if self.carried.is_none()
|
||||
&& tooltip.is_none()
|
||||
&& tooltip_stack.is_none()
|
||||
&& let Some(stack) = self.slot_mut(slot).clone()
|
||||
{
|
||||
tooltip = Some(self.stack_tooltip(&stack));
|
||||
tooltip_stack = Some(stack);
|
||||
}
|
||||
}
|
||||
if self.carried.is_some() {
|
||||
self.draw_carried(batch);
|
||||
} else if let Some(stack) = tooltip_stack {
|
||||
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
|
||||
} else if let Some(lines) = tooltip {
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
}
|
||||
@@ -1907,32 +1913,65 @@ impl Game<'_> {
|
||||
if lines.is_empty() {
|
||||
return;
|
||||
}
|
||||
let lines: Vec<_> = lines
|
||||
let lines = Self::resolved(lines);
|
||||
let atlas = &self.gui.atlas;
|
||||
let (x, y, w, h) =
|
||||
Self::tooltip_geometry(atlas, &lines, (x, y), (batch.width, batch.height), 0.0);
|
||||
Self::tooltip_box(batch, atlas, x, y, w, h);
|
||||
Self::tooltip_text(batch, atlas, &lines, x, y);
|
||||
}
|
||||
/// A tooltip's lines with their legacy codes resolved and their colours.
|
||||
fn resolved<T: Clone + Into<horizon_client::text::Text>>(
|
||||
lines: &[(T, u32)],
|
||||
) -> Vec<(horizon_client::text::Text, u32)> {
|
||||
lines
|
||||
.iter()
|
||||
.map(|(text, color)| {
|
||||
let text: horizon_client::text::Text = text.clone().into();
|
||||
(text.resolve_legacy(), *color)
|
||||
})
|
||||
.collect();
|
||||
let atlas = &self.gui.atlas;
|
||||
.collect()
|
||||
}
|
||||
/// The tooltip's text's top-left corner and the box's size: beside the
|
||||
/// cursor, kept on screen, `extra` pixels taller than the text.
|
||||
fn tooltip_geometry(
|
||||
atlas: &horizon_client::hud::HudAtlas,
|
||||
lines: &[(horizon_client::text::Text, u32)],
|
||||
(x, y): (f32, f32),
|
||||
(width, height): (f32, f32),
|
||||
extra: f32,
|
||||
) -> (f32, f32, f32, f32) {
|
||||
let w = lines
|
||||
.iter()
|
||||
.map(|(t, _)| atlas.font.width_text(t))
|
||||
.fold(0.0, f32::max);
|
||||
let h = if lines.len() == 1 {
|
||||
.fold(0.0, f32::max)
|
||||
.max(if extra > 0.0 { 96.0 } else { 0.0 });
|
||||
let text_h = if lines.len() == 1 {
|
||||
8.0
|
||||
} else {
|
||||
8.0 + 2.0 + (lines.len() - 1) as f32 * 10.0
|
||||
};
|
||||
let h = text_h + extra;
|
||||
let mut x = x + 12.0;
|
||||
let mut y = y - 12.0;
|
||||
if x + w > batch.width - 4.0 {
|
||||
if x + w > width - 4.0 {
|
||||
x = (x - 28.0 - w).max(4.0);
|
||||
}
|
||||
if y + h + 3.0 > batch.height {
|
||||
y = batch.height - h - 3.0;
|
||||
if y + h + 3.0 > height {
|
||||
y = height - h - 3.0;
|
||||
}
|
||||
y = y.max(4.0);
|
||||
(x, y, w, h)
|
||||
}
|
||||
/// The box and its frame sprites.
|
||||
fn tooltip_box(
|
||||
batch: &mut HudBatch,
|
||||
atlas: &horizon_client::hud::HudAtlas,
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
h: f32,
|
||||
) {
|
||||
batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 1.0, rgba(16, 0, 16, 240));
|
||||
batch.fill(
|
||||
atlas,
|
||||
@@ -1968,12 +2007,137 @@ impl Game<'_> {
|
||||
h + 4.0,
|
||||
rgba(60, 0, 190, 80),
|
||||
);
|
||||
}
|
||||
fn tooltip_text(
|
||||
batch: &mut HudBatch,
|
||||
atlas: &horizon_client::hud::HudAtlas,
|
||||
lines: &[(horizon_client::text::Text, u32)],
|
||||
x: f32,
|
||||
y: f32,
|
||||
) {
|
||||
let mut ty = y;
|
||||
for (i, (text, color)) in lines.iter().enumerate() {
|
||||
batch.text_styled(atlas, text, x, ty, *color, true);
|
||||
ty += if i == 0 { 12.0 } else { 10.0 };
|
||||
}
|
||||
}
|
||||
/// A stack's tooltip: its lines, and under them a bundle's contents
|
||||
/// (`ClientBundleTooltip`: the 4 wide grid, the `+N` of what it leaves
|
||||
/// out, and the weight bar).
|
||||
pub(super) fn draw_stack_tooltip(
|
||||
&mut self,
|
||||
batch: &mut HudBatch,
|
||||
stack: &ItemStack,
|
||||
x: f32,
|
||||
y: f32,
|
||||
) {
|
||||
let lines = Self::resolved(&self.stack_tooltip(stack));
|
||||
if lines.is_empty() {
|
||||
return;
|
||||
}
|
||||
// The component's height does not depend on where it is drawn, so a
|
||||
// probe at the origin gives the box its extra height.
|
||||
let probe = horizon_client::bundle::tooltip_layout(self.res.items(), stack, 0.0, 0.0, 96.0);
|
||||
let extra = probe.as_ref().map_or(0.0, |l| l.height + 2.0);
|
||||
let atlas = &self.gui.atlas;
|
||||
let (x, y, w, h) =
|
||||
Self::tooltip_geometry(atlas, &lines, (x, y), (batch.width, batch.height), extra);
|
||||
Self::tooltip_box(batch, atlas, x, y, w, h);
|
||||
let text_h = h - extra;
|
||||
Self::tooltip_text(batch, atlas, &lines, x, y);
|
||||
let Some(layout) =
|
||||
horizon_client::bundle::tooltip_layout(self.res.items(), stack, x, y + text_h + 2.0, w)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.draw_bundle_tooltip(batch, &layout);
|
||||
}
|
||||
/// `ClientBundleTooltip.extractImage`: the slots, the count past them and
|
||||
/// the progress bar.
|
||||
fn draw_bundle_tooltip(
|
||||
&mut self,
|
||||
batch: &mut HudBatch,
|
||||
layout: &horizon_client::bundle::TooltipLayout,
|
||||
) {
|
||||
for (at, stack) in &layout.slots {
|
||||
// Each draw takes the atlas on its own: the item's needs `&mut self`.
|
||||
horizon_client::ui::nine_slice(
|
||||
batch,
|
||||
&self.gui.atlas,
|
||||
"gui/sprites/container/bundle/slot_background",
|
||||
at[0],
|
||||
at[1],
|
||||
24.0,
|
||||
24.0,
|
||||
u32::MAX,
|
||||
);
|
||||
let stack = stack.clone();
|
||||
let [x, y] = *at;
|
||||
self.draw_item(batch, &stack, x + 4.0, y + 4.0);
|
||||
}
|
||||
let atlas = &self.gui.atlas;
|
||||
if let Some((at, hidden)) = layout.overflow {
|
||||
let label = horizon_client::text::Text::literal(format!("+{hidden}"));
|
||||
let w = atlas.font.width_text(&label);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&label,
|
||||
at[0] + 12.0 - (w / 2.0).floor(),
|
||||
at[1] + 10.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
}
|
||||
if let Some((at, description)) = layout
|
||||
.empty_description
|
||||
.zip(Some("item.minecraft.bundle.empty.description"))
|
||||
{
|
||||
let text = horizon_client::text::Text::translate(description, &[]);
|
||||
let mut ty = at[1];
|
||||
for line in atlas.font.split_lines(&text, layout.width) {
|
||||
batch.text_styled(atlas, &line.0, at[0], ty, 0xFFAA_AAAA, false);
|
||||
ty += 9.0;
|
||||
}
|
||||
}
|
||||
let [bx, by] = layout.bar;
|
||||
let fill_sprite = if layout.full {
|
||||
"gui/sprites/container/bundle/bundle_progressbar_full"
|
||||
} else {
|
||||
"gui/sprites/container/bundle/bundle_progressbar_fill"
|
||||
};
|
||||
horizon_client::ui::nine_slice(
|
||||
batch,
|
||||
atlas,
|
||||
fill_sprite,
|
||||
bx + 1.0,
|
||||
by,
|
||||
layout.fill,
|
||||
13.0,
|
||||
u32::MAX,
|
||||
);
|
||||
horizon_client::ui::nine_slice(
|
||||
batch,
|
||||
atlas,
|
||||
"gui/sprites/container/bundle/bundle_progressbar_border",
|
||||
bx,
|
||||
by,
|
||||
96.0,
|
||||
13.0,
|
||||
u32::MAX,
|
||||
);
|
||||
if let Some(key) = layout.label {
|
||||
let label = horizon_client::text::Text::translate(key, &[]);
|
||||
let w = atlas.font.width_text(&label);
|
||||
batch.text_styled(
|
||||
atlas,
|
||||
&label,
|
||||
bx + 48.0 - (w / 2.0).floor(),
|
||||
by + 3.0,
|
||||
u32::MAX,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// Hovered-slot tooltip on the plain inventory, crafting and container screens.
|
||||
pub(super) fn draw_slot_tooltip(&mut self, batch: &mut HudBatch) {
|
||||
if self.carried.is_some() {
|
||||
@@ -1984,8 +2148,7 @@ impl Game<'_> {
|
||||
};
|
||||
let stack = self.slot_view(slot);
|
||||
if let Some(stack) = stack {
|
||||
let lines = self.stack_tooltip(&stack);
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
|
||||
} else if let Some(text) = self.crafter_tooltip(slot) {
|
||||
self.draw_tooltip_lines(
|
||||
batch,
|
||||
|
||||
@@ -803,8 +803,7 @@ impl Game<'_> {
|
||||
text.split('\n').map(|l| (l.to_owned(), u32::MAX)).collect();
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
} else if let Some(stack) = tooltip {
|
||||
let lines = self.stack_tooltip(&stack);
|
||||
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
|
||||
self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
@@ -238,6 +238,46 @@ mod tests {
|
||||
use super::*;
|
||||
use horizon_protocol::registry::Ids;
|
||||
|
||||
/// A bundle's contents cross the wire, so a server's client can draw
|
||||
/// its tooltip (BundleContents' stream codec: a list of templates).
|
||||
#[test]
|
||||
fn a_bundle_keeps_its_contents_across_the_wire() {
|
||||
let mut components = vec![String::new(); 60];
|
||||
components[component::BUNDLE_CONTENTS as usize] = "minecraft:bundle_contents".into();
|
||||
let items = ["minecraft:air", "minecraft:bundle", "minecraft:stone"];
|
||||
let builtin = Builtin {
|
||||
registries: [
|
||||
(
|
||||
"minecraft:item".to_owned(),
|
||||
Ids::from_names(items.iter().map(|s| s.to_string()).collect()),
|
||||
),
|
||||
(
|
||||
"minecraft:data_component_type".to_owned(),
|
||||
Ids::from_names(components),
|
||||
),
|
||||
]
|
||||
.into(),
|
||||
};
|
||||
let dynamic = Dynamic {
|
||||
registries: Default::default(),
|
||||
};
|
||||
let mut bundle = ItemStack::new("minecraft:bundle", 1);
|
||||
bundle.data_mut().bundle_contents = vec![ItemStack::new("minecraft:stone", 32)];
|
||||
let wire = crate::lan::guest::stack_to_network(
|
||||
|name| items.iter().position(|i| *i == name).unwrap_or(0) as i32,
|
||||
|_, _| None,
|
||||
&Some(bundle),
|
||||
)
|
||||
.unwrap();
|
||||
let back = from_network(&wire, &builtin, &dynamic);
|
||||
let contents = &back.data().expect("components").bundle_contents;
|
||||
assert_eq!(contents.len(), 1);
|
||||
assert_eq!(
|
||||
(&*contents[0].item, contents[0].count),
|
||||
("minecraft:stone", 32)
|
||||
);
|
||||
}
|
||||
|
||||
/// What a creative client sends (`stack_to_network`) comes back whole on
|
||||
/// the server: damage, both enchantment lists, repair cost, name, trim.
|
||||
#[test]
|
||||
|
||||
@@ -601,6 +601,18 @@ fn network_stack(
|
||||
horizon_protocol::item::Component::Stacks(charged),
|
||||
));
|
||||
}
|
||||
// What a bundle holds, for its tooltip (ClientBundleTooltip).
|
||||
if !d.bundle_contents.is_empty() {
|
||||
let contents = d
|
||||
.bundle_contents
|
||||
.iter()
|
||||
.filter_map(|c| network_stack(item_id, synced_id, &Some(c.clone())))
|
||||
.collect();
|
||||
stack.added.push((
|
||||
horizon_protocol::item::component::BUNDLE_CONTENTS,
|
||||
horizon_protocol::item::Component::Stacks(contents),
|
||||
));
|
||||
}
|
||||
// The books a lectern shows and a guest reads.
|
||||
if !d.writable_pages.is_empty() {
|
||||
stack.added.push((
|
||||
|
||||
@@ -376,9 +376,21 @@ impl Hub {
|
||||
id
|
||||
}
|
||||
pub fn stack(&mut self, s: &Option<ItemStack>) -> Option<horizon_protocol::item::Stack> {
|
||||
let id = s.as_ref().map(|s| self.item_id(&s.item))?;
|
||||
let item = s.as_ref()?.item.clone();
|
||||
let id = self.item_id(&item);
|
||||
let sync = self.sync.clone();
|
||||
stack_to_network(|_| id, |registry, name| sync.id(registry, name), s)
|
||||
// The stacks inside it (a bundle's contents, a crossbow's projectiles)
|
||||
// have ids of their own.
|
||||
let item_id = |name: &str| {
|
||||
if name == &*item {
|
||||
return id;
|
||||
}
|
||||
sync.builtin
|
||||
.get("minecraft:item")
|
||||
.and_then(|i| i.id(name))
|
||||
.unwrap_or(0)
|
||||
};
|
||||
stack_to_network(item_id, |registry, name| sync.id(registry, name), s)
|
||||
}
|
||||
|
||||
pub fn broadcast(&self, packet: &C) {
|
||||
|
||||
@@ -166,6 +166,38 @@ impl Contents {
|
||||
Some(stack)
|
||||
}
|
||||
|
||||
/// The stacks inside, in display order (the first is the next out).
|
||||
pub fn items(&self) -> &[ItemStack] {
|
||||
&self.items
|
||||
}
|
||||
|
||||
/// `getNumberOfItemsToShow`: a full grid shows 11 and a `+N`, so the last
|
||||
/// row keeps its fourth cell for the count.
|
||||
pub fn shown_count(&self) -> usize {
|
||||
let count = self.items.len();
|
||||
let available: usize = if count > 12 { 11 } else { 12 };
|
||||
let on_last_row = count % 4;
|
||||
let empty = if on_last_row == 0 { 0 } else { 4 - on_last_row };
|
||||
count.min(available.saturating_sub(empty))
|
||||
}
|
||||
|
||||
/// The items the tooltip shows, and how many sit beyond them.
|
||||
pub fn shown(&self) -> (&[ItemStack], u32) {
|
||||
let n = self.shown_count();
|
||||
let hidden = self.items[n..].iter().map(|s| s.count).sum();
|
||||
(&self.items[..n], hidden)
|
||||
}
|
||||
|
||||
/// The `Fraction` weight as the float the progress bar reads.
|
||||
pub fn weight_fraction(&self) -> f32 {
|
||||
self.weight.n as f32 / self.weight.d as f32
|
||||
}
|
||||
|
||||
/// `Fraction.ONE`: a full bundle draws the full bar and says so.
|
||||
pub fn is_full(&self) -> bool {
|
||||
self.weight.n >= self.weight.d
|
||||
}
|
||||
|
||||
/// `toImmutable`, written back into the bundle's component.
|
||||
pub fn store(self, bundle: &mut ItemStack) {
|
||||
bundle.data_mut().bundle_contents = self.items;
|
||||
@@ -190,3 +222,174 @@ mod tests {
|
||||
assert_eq!(over.how_many(Weight::new(1, 64)), 0);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------- the tooltip
|
||||
|
||||
/// `ClientBundleTooltip`'s geometry, relative to the tooltip box's top-left:
|
||||
/// the 96 pixel column of a 4 wide slot grid and the progress bar under it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TooltipLayout {
|
||||
/// The component's own width (96) and height, the text's excluded.
|
||||
pub width: f32,
|
||||
pub height: f32,
|
||||
/// Each slot's top-left and the stack in it, in reading order.
|
||||
pub slots: Vec<([f32; 2], ItemStack)>,
|
||||
/// The `+N` of the items past the grid: its top-left and the count.
|
||||
pub overflow: Option<([f32; 2], u32)>,
|
||||
/// The progress bar's top-left, its fill's width out of 94, and whether
|
||||
/// the weight fills it (the full sprite).
|
||||
pub bar: [f32; 2],
|
||||
pub fill: f32,
|
||||
pub full: bool,
|
||||
/// `item.minecraft.bundle.empty` / `.full`, centred over the bar.
|
||||
pub label: Option<&'static str>,
|
||||
/// An empty bundle's description, wrapped at `width` from here.
|
||||
pub empty_description: Option<[f32; 2]>,
|
||||
}
|
||||
|
||||
/// The tooltip of a bundle's contents (`ClientBundleTooltip`), or None when
|
||||
/// the stack is not a bundle. `x`/`y` are the box's top-left, `box_width` the
|
||||
/// tooltip's width, which the component is centred in.
|
||||
pub fn tooltip_layout(
|
||||
items: &Items,
|
||||
stack: &ItemStack,
|
||||
x: f32,
|
||||
y: f32,
|
||||
box_width: f32,
|
||||
) -> Option<TooltipLayout> {
|
||||
let contents = Contents::of(items, stack)?;
|
||||
let offset = ((box_width - 96.0) / 2.0).floor();
|
||||
if contents.items().is_empty() {
|
||||
// The description takes the top; the bar follows it.
|
||||
let description_height = 9.0 * 2.0;
|
||||
return Some(TooltipLayout {
|
||||
width: 96.0,
|
||||
height: description_height + 13.0 + 8.0,
|
||||
slots: Vec::new(),
|
||||
overflow: None,
|
||||
bar: [x + offset, y + description_height + 4.0],
|
||||
fill: 0.0,
|
||||
full: false,
|
||||
label: Some("item.minecraft.bundle.empty"),
|
||||
empty_description: Some([x + offset, y]),
|
||||
});
|
||||
}
|
||||
let (shown, hidden) = contents.shown();
|
||||
// `gridSizeY` counts `slotCount()` (at most twelve), not the slots the
|
||||
// overflow count leaves room for.
|
||||
let rows = contents.items().len().min(12).div_ceil(4).max(1);
|
||||
let grid_height = rows as f32 * 24.0;
|
||||
let x_start = x + offset + 96.0;
|
||||
let y_start = y + grid_height;
|
||||
let mut slots = Vec::with_capacity(shown.len());
|
||||
let mut overflow = None;
|
||||
// Rows fill bottom-up and columns right-to-left, as vanilla draws them.
|
||||
let mut slot = 0;
|
||||
for row in 1..=rows {
|
||||
for column in 1..=4 {
|
||||
let at = [x_start - column as f32 * 24.0, y_start - row as f32 * 24.0];
|
||||
if hidden > 0 && row == 1 && column == 1 {
|
||||
overflow = Some((at, hidden));
|
||||
} else if let Some(stack) = shown.get(slot) {
|
||||
slots.push((at, stack.clone()));
|
||||
slot += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let weight = contents.weight_fraction();
|
||||
Some(TooltipLayout {
|
||||
width: 96.0,
|
||||
height: grid_height + 13.0 + 8.0,
|
||||
slots,
|
||||
overflow,
|
||||
bar: [x + offset, y + grid_height + 4.0],
|
||||
// `Mth.mulAndTruncate(weight, 94)`, kept within the bar.
|
||||
fill: (weight * 94.0).trunc().clamp(0.0, 94.0),
|
||||
full: contents.is_full(),
|
||||
label: if contents.is_full() {
|
||||
Some("item.minecraft.bundle.full")
|
||||
} else {
|
||||
None
|
||||
},
|
||||
empty_description: None,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tooltip_tests {
|
||||
use super::*;
|
||||
|
||||
/// The prepared resources, when they are on this machine: the tooltip
|
||||
/// asks the item registry whether a stack is a bundle.
|
||||
fn items() -> Option<Items> {
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../.local/horizon-client/26.3");
|
||||
if !root.join("items.json").exists() {
|
||||
return None;
|
||||
}
|
||||
let assets = crate::assets::Assets::load(&root).ok()?;
|
||||
let facts = crate::blocks::BlockFacts::load(&root, assets.registry).ok()?;
|
||||
Items::load(&root, assets.registry, &facts).ok()
|
||||
}
|
||||
|
||||
fn bundle_with(counts: &[(&str, u32)]) -> ItemStack {
|
||||
let mut bundle = ItemStack::new("minecraft:bundle", 1);
|
||||
bundle.data_mut().bundle_contents = counts
|
||||
.iter()
|
||||
.map(|(item, n)| ItemStack::new(item, *n))
|
||||
.collect();
|
||||
bundle
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_grid_shows_twelve_stacks_and_counts_the_rest() {
|
||||
let Some(items) = items() else { return };
|
||||
let twelve: Vec<(&str, u32)> = (0..12).map(|_| ("minecraft:stone", 1)).collect();
|
||||
let layout = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 96.0).unwrap();
|
||||
assert_eq!(layout.slots.len(), 12);
|
||||
assert_eq!(layout.overflow, None);
|
||||
assert_eq!(layout.height, 3.0 * 24.0 + 13.0 + 8.0);
|
||||
// Rows fill bottom-up and columns right-to-left: the first item is in
|
||||
// the bottom-right cell, the twelfth in the top-left.
|
||||
assert_eq!(layout.slots[0].0, [96.0 - 24.0, 3.0 * 24.0 - 24.0]);
|
||||
assert_eq!(&*layout.slots[0].1.item, "minecraft:stone");
|
||||
assert_eq!(layout.slots[11].0, [0.0, 0.0]);
|
||||
// A wider tooltip centres the 96 pixel column in it.
|
||||
let centred = tooltip_layout(&items, &bundle_with(&twelve), 0.0, 0.0, 120.0).unwrap();
|
||||
assert_eq!(centred.slots[0].0[0], 12.0 + 96.0 - 24.0);
|
||||
// Thirteen stacks: `getNumberOfItemsToShow` leaves the last row room
|
||||
// for the count, so 8 slots show and `+6` (four stones and two dirt)
|
||||
// takes the first cell.
|
||||
let mut counts = twelve;
|
||||
counts.push(("minecraft:dirt", 2));
|
||||
let layout = tooltip_layout(&items, &bundle_with(&counts), 0.0, 0.0, 96.0).unwrap();
|
||||
assert_eq!(layout.slots.len(), 8);
|
||||
assert_eq!(layout.overflow, Some(([96.0 - 24.0, 48.0], 6)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_fills_with_the_weight_and_an_empty_bundle_explains_itself() {
|
||||
let Some(items) = items() else { return };
|
||||
let layout = tooltip_layout(&items, &bundle_with(&[]), 4.0, 8.0, 96.0).unwrap();
|
||||
assert!(layout.slots.is_empty());
|
||||
assert_eq!(layout.fill, 0.0);
|
||||
assert_eq!(layout.label, Some("item.minecraft.bundle.empty"));
|
||||
assert_eq!(layout.empty_description, Some([4.0, 8.0]));
|
||||
assert_eq!(layout.bar, [4.0, 8.0 + 18.0 + 4.0]);
|
||||
// A bundle holding one 64 stack is full: the whole bar, the full label.
|
||||
let layout = tooltip_layout(
|
||||
&items,
|
||||
&bundle_with(&[("minecraft:stone", 64)]),
|
||||
0.0,
|
||||
0.0,
|
||||
96.0,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(layout.full);
|
||||
assert_eq!(layout.fill, 94.0);
|
||||
assert_eq!(layout.label, Some("item.minecraft.bundle.full"));
|
||||
// Something that is not a bundle has no component.
|
||||
let dirt = ItemStack::new("minecraft:dirt", 1);
|
||||
assert!(tooltip_layout(&items, &dirt, 0.0, 0.0, 96.0).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ pub mod component {
|
||||
pub const MAP_ID: i32 = 48;
|
||||
pub const MAP_POST_PROCESSING: i32 = 50;
|
||||
pub const CHARGED_PROJECTILES: i32 = 51;
|
||||
pub const BUNDLE_CONTENTS: i32 = 52;
|
||||
pub const POTION_CONTENTS: i32 = 53;
|
||||
pub const WRITABLE_BOOK_CONTENT: i32 = 56;
|
||||
pub const WRITTEN_BOOK_CONTENT: i32 = 57;
|
||||
@@ -192,7 +193,7 @@ impl Component {
|
||||
resolved: r.bool()?,
|
||||
})
|
||||
}
|
||||
CHARGED_PROJECTILES => {
|
||||
CHARGED_PROJECTILES | BUNDLE_CONTENTS => {
|
||||
let n = r.count(1024)?;
|
||||
Self::Stacks((0..n).map(|_| Template::read(r)).collect::<Result<_>>()?)
|
||||
}
|
||||
@@ -784,6 +785,21 @@ mod tests {
|
||||
assert_eq!(w.data, bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundle_contents_are_item_stack_templates() {
|
||||
// A bundle (id 7) holding 32 of item 9: BundleContents is a list of
|
||||
// ItemStackTemplate, as ChargedProjectiles is.
|
||||
let bytes = [1, 7, 1, 0, 52, 1, 9, 32, 0, 0];
|
||||
let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
stack.component(component::BUNDLE_CONTENTS),
|
||||
Some(&Component::Stacks(vec![Stack::new(9, 32)]))
|
||||
);
|
||||
let mut w = Writer::new();
|
||||
Slot::write(&Some(stack), &mut w);
|
||||
assert_eq!(w.data, bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filtered_book_pages_are_read_and_dropped() {
|
||||
// A writable book with one page "hi" and its filtered "**".
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render regression: bundle component tooltips in anvil and brewing screens.
|
||||
|
||||
Requires prepared 26.3 resources, a built horizon-client/horizon-ctl and Pillow.
|
||||
Runs an isolated offscreen game; never opens existing player data. A name-only
|
||||
bundle tooltip is narrower than the component's 96 GUI-pixel minimum, so its
|
||||
purple frame cannot pass the image assertion. Screenshots are kept as evidence.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from PIL import Image
|
||||
import lab
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def longest_tooltip_border(image):
|
||||
"""Longest horizontal purple tooltip-frame run (physical pixels)."""
|
||||
rgb = image.convert("RGB")
|
||||
longest = 0
|
||||
pixels = rgb.load()
|
||||
for y in range(rgb.height):
|
||||
run = 0
|
||||
for x in range(rgb.width):
|
||||
r, g, b = pixels[x, y]
|
||||
if g < 25 and r < 100 and b >= r + 15:
|
||||
run += 1
|
||||
longest = max(longest, run)
|
||||
else:
|
||||
run = 0
|
||||
return longest
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--game", type=Path, default=ROOT / "target/fast/horizon-client")
|
||||
parser.add_argument("--ctl", type=Path, default=ROOT / "target/fast/horizon-ctl")
|
||||
parser.add_argument("--resources", type=Path, default=ROOT / ".local/horizon-client/26.3")
|
||||
parser.add_argument("--output", type=Path)
|
||||
parser.add_argument("--in-frame", action="store_true")
|
||||
args = parser.parse_args()
|
||||
output = args.output or Path(tempfile.mkdtemp(prefix="bundle-tooltip-"))
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
output = output.resolve()
|
||||
homes = {}
|
||||
for key in ("HORIZON_HOME", "HORIZON_LAUNCHER_HOME", "XDG_DATA_HOME", "XDG_CONFIG_HOME"):
|
||||
directory = output / key
|
||||
directory.mkdir(exist_ok=True)
|
||||
homes[key] = directory
|
||||
env = lab.game_env(**homes)
|
||||
socket = output / "ctl.sock"
|
||||
|
||||
def ctl(*commands, timeout=45):
|
||||
result = subprocess.run(
|
||||
[str(args.ctl.resolve()), "--socket", str(socket), *map(str, commands)],
|
||||
env=env, cwd=output, capture_output=True, text=True, timeout=timeout,
|
||||
)
|
||||
data = json.loads(result.stdout)
|
||||
if result.returncode or data.get("error"):
|
||||
raise RuntimeError(f"{commands}: {data}; {result.stderr}")
|
||||
return data
|
||||
|
||||
results = []
|
||||
try:
|
||||
ctl("launch", "--game", args.game.resolve(), "--world", output / "world",
|
||||
"--creative", "--offscreen", "--wait", "--resources", args.resources.resolve(),
|
||||
*(["--in-frame"] if args.in_frame else []), timeout=120)
|
||||
state = ctl("state")
|
||||
px, _, pz = state["player"]["block_pos"]
|
||||
x, z = (px // 16) * 16 + 8, (pz // 16) * 16 + 8
|
||||
ctl("command", f"fill {x-3} 99 {z-3} {x+3} 99 {z+3} minecraft:stone")
|
||||
ctl("command", f"fill {x-3} 100 {z-3} {x+3} 105 {z+3} minecraft:air")
|
||||
ctl("tp", x + 0.5, 100, z + 0.5)
|
||||
ctl("command", 'item replace entity @s hotbar.0 with minecraft:bundle['
|
||||
'minecraft:bundle_contents=[{id:"minecraft:stone",count:32}]]')
|
||||
for station in ("anvil", "brewing_stand"):
|
||||
ctl("command", f"setblock {x} 100 {z+2} minecraft:{station}")
|
||||
ctl("wait", 5)
|
||||
ctl("look-at-block", x, 100, z+2, "north")
|
||||
ctl("interact", x, 100, z+2, "north")
|
||||
time.sleep(0.3)
|
||||
ui = ctl("ui")
|
||||
slot = next(w for w in ui["widgets"] if w["id"] == "slot-0")
|
||||
assert slot["stack"]["item"] == "minecraft:bundle", slot
|
||||
sx, sy, sw, sh = slot["bounds"]
|
||||
ctl("scroll-at", sx + sw / 2, sy + sh / 2, 0)
|
||||
screenshot = output / f"{station}.png"
|
||||
ctl("screenshot", screenshot)
|
||||
with Image.open(screenshot) as image:
|
||||
scale = image.width / ui["gui_size"][0]
|
||||
longest = longest_tooltip_border(image)
|
||||
# The component reserves 96 GUI pixels; allow its border/integer rounding.
|
||||
required = int(90 * scale)
|
||||
results.append({"station": station, "border_pixels": longest,
|
||||
"required_pixels": required, "pass": longest >= required,
|
||||
"screenshot": str(screenshot)})
|
||||
ctl("close")
|
||||
finally:
|
||||
try:
|
||||
ctl("quit")
|
||||
except (RuntimeError, subprocess.TimeoutExpired, json.JSONDecodeError):
|
||||
pass
|
||||
report = {"mode": "in-frame" if args.in_frame else "server-thread", "results": results}
|
||||
(output / "results.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report, indent=2))
|
||||
assert len(results) == 2 and all(r["pass"] for r in results), "Missing bundle component tooltip"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user