Compare item decorations with GuiGraphicsExtractor.itemDecorations

The decor cases run vanilla's itemDecorations on stacks with counts,
durability (Item.getBarWidth/getBarColor), unbreakable stacks and item
cooldowns ticked through ItemCooldowns. Horizon's item drawing now uses
the same layout: the bar rounds and colours like vanilla's and the count
sits at vanilla's offsets.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-12 13:13:12 +02:00
parent f55b4281e5
commit 5b53d37e30
5 changed files with 166 additions and 23 deletions
@@ -3,7 +3,7 @@ use horizon_client::{
brewing, component,
hud::HudAtlas,
hud_layout::{self, GuiDraw},
hud_overlays::{self, BossBar, EffectIcon, HeldName, Titles, ToolHighlight},
hud_overlays::{self, BossBar, EffectIcon, HeldName, ItemDecorations, Titles, ToolHighlight},
scoreboard::{NumberFormat, RenderType, Scoreboard},
text::{self, Text},
};
@@ -37,6 +37,7 @@ pub fn run(kind: &str, c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
"boss" => boss(c, w, h, atlas),
"jump" => hud_overlays::jump_bar(w, h, int(c, "cooldown", 0), float(c, "jumpScale", 0.0)),
"sidebar" => sidebar(c, w, h, atlas),
"decor" => decor(c, atlas),
_ => Vec::new(),
}
}
@@ -187,3 +188,36 @@ fn sidebar(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
hud_layout::background_color(chat_only, opacity, 0.4),
)
}
/// `itemDecorations` for a stack with a count, damage and an item cooldown
/// `elapsed` ticks into `duration` (ItemCooldowns.getCooldownPercent).
fn decor(c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
let count = int(c, "count", 1);
if count <= 0 {
return Vec::new();
}
let cd = &c["cooldown"];
let cooldown = if cd.is_null() {
0.0
} else {
let (duration, elapsed) = (int(cd, "duration", 0), int(cd, "elapsed", 0));
if duration <= elapsed {
0.0 // ItemCooldowns.tick dropped it
} else {
let remaining = duration as f32 - (elapsed as f32 + float(c, "partial", 0.0));
(remaining / duration as f32).clamp(0.0, 1.0)
}
};
let max_damage = if c["unbreakable"].as_bool().unwrap_or(false) {
0
} else {
int(c, "maxDamage", 0)
};
let d = ItemDecorations {
count: count as u32,
count_text: c["countText"].as_str().map(str::to_owned),
bar: hud_overlays::damage_bar(int(c, "damage", 0), max_damage),
cooldown,
};
hud_overlays::item_decorations(int(c, "x", 0), int(c, "y", 0), &d, &atlas.font)
}
+25 -21
View File
@@ -108,7 +108,7 @@ use horizon_client::{
environment::Environment,
gfx::{Frame, Renderer},
hud::{HudAtlas, HudBatch, rgba},
hud_layout,
hud_layout, hud_overlays,
items::{ItemStack, Items},
keymapping::KeyAction,
light::LightTables,
@@ -2844,26 +2844,30 @@ 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);
let atlas = &self.res.atlas;
if stack.count > 1 {
let text = stack.count.to_string();
let w = HudBatch::text_width(atlas, &text);
batch.text(atlas, &text, x + 17.0 - w, y + 9.0, u32::MAX, true);
}
if let Some(info) = self.res.items.get(&stack.item)
&& info.max_damage > 0
&& stack.damage > 0
{
let f = 1.0 - stack.damage as f32 / info.max_damage as f32;
let width = (13.0 * f).round();
let hue = f / 3.0;
let (r, g) = (
(255.0 * (1.0 - hue * 3.0).clamp(0.0, 1.0)) as u8,
(255.0 * (hue * 3.0).clamp(0.0, 1.0)) as u8,
);
batch.fill(atlas, x + 2.0, y + 13.0, 13.0, 2.0, rgba(0, 0, 0, 255));
batch.fill(atlas, x + 2.0, y + 13.0, width, 1.0, rgba(r, g, 0, 255));
}
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
// moved to (x, y). Horizon tracks no item cooldowns to shade yet.
let max_damage = self
.res
.items
.get(&stack.item)
.map_or(0, |info| info.max_damage as i32);
let decorations = hud_overlays::ItemDecorations {
count: stack.count,
count_text: None,
bar: hud_overlays::damage_bar(stack.damage as i32, max_damage),
cooldown: 0.0,
};
let mut draws = vec![hud_layout::GuiDraw::Push(vec![
hud_layout::PoseOp::Translate(x, y),
])];
draws.extend(hud_overlays::item_decorations(
0,
0,
&decorations,
&self.res.atlas.font,
));
draws.push(hud_layout::GuiDraw::Pop);
hud_layout::paint(batch, &self.res.atlas, &draws);
}
fn hud(&mut self, size: [u32; 2]) -> HudBatch {
let mut batch = HudBatch::new(size);
+60
View File
@@ -632,3 +632,63 @@ pub fn sidebar(
}
out
}
/// `Mth.ceil`.
fn ceil(x: f32) -> i32 {
let i = x as i32;
if x > i as f32 { i + 1 } else { i }
}
/// What `GuiGraphicsExtractor.itemDecorations` draws over a stack.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ItemDecorations {
pub count: u32,
/// The text shown instead of the count, if any.
pub count_text: Option<String>,
/// `isBarVisible`: `getBarWidth` and `getBarColor` (RGB).
pub bar: Option<(i32, u32)>,
/// `ItemCooldowns.getCooldownPercent` of the stack.
pub cooldown: f32,
}
/// `Item.getBarWidth` and `getBarColor` for a damaged stack (`isDamaged`).
pub fn damage_bar(damage: i32, max_damage: i32) -> Option<(i32, u32)> {
if max_damage <= 0 || damage <= 0 {
return None;
}
let width = (13.0 - damage as f32 * 13.0 / max_damage as f32)
.round()
.clamp(0.0, 13.0) as i32;
let health = ((max_damage as f32 - damage as f32) / max_damage as f32).max(0.0);
Some((width, hsv_to_argb(health / 3.0, 1.0, 1.0, 0)))
}
/// `GuiGraphicsExtractor.itemDecorations` for a non-empty stack at (x, y):
/// the durability bar, the cooldown shade and the count.
pub fn item_decorations(x: i32, y: i32, d: &ItemDecorations, font: &Font) -> Vec<GuiDraw> {
let mut out = vec![GuiDraw::Push(Vec::new())];
if let Some((width, color)) = d.bar {
let (left, top) = (x + 2, y + 13);
out.push(fill(left, top, left + 13, top + 2, 0xFF00_0000));
out.push(fill(left, top, left + width, top + 1, color | 0xFF00_0000));
}
if d.cooldown > 0.0 {
let top = y + crate::hud_layout::floor(16.0 * (1.0 - d.cooldown));
let bottom = top + ceil(16.0 * d.cooldown);
out.push(fill(x, top, x + 16, bottom, 0x7FFF_FFFF));
}
if d.count != 1 || d.count_text.is_some() {
let amount = d.count_text.clone().unwrap_or_else(|| d.count.to_string());
let w = font.width(&amount) as i32;
text(
&mut out,
Text::literal(amount),
x + 19 - 2 - w,
y + 6 + 3,
crate::hud_layout::WHITE,
true,
);
}
out.push(GuiDraw::Pop);
out
}
@@ -281,7 +281,11 @@ public final class VanillaHudOracle {
o.add("matrix", a);
draws.add(o);
}
@Override public void itemDecorations(Font font, ItemStack stack, int x, int y, String count) { }
/** Off for the hotbar cases (Horizon draws the decorations with the item). */
boolean realDecorations;
@Override public void itemDecorations(Font font, ItemStack stack, int x, int y, String count) {
if (realDecorations) super.itemDecorations(font, stack, x, y, count);
}
}
public static void main(String[] args) throws Exception {
@@ -388,6 +392,7 @@ public final class VanillaHudOracle {
capture.draws = new JsonArray();
capture.stack = new Matrix3x2fStack(16);
put(capture, GuiGraphicsExtractor.class, "minecraft", mc);
put(capture, GuiGraphicsExtractor.class, "pose", capture.stack);
float partial = f("partial", 0);
DeltaTracker delta = (DeltaTracker) Proxy.newProxyInstance(DeltaTracker.class.getClassLoader(), new Class<?>[] {DeltaTracker.class},
(proxy, method, a) -> method.getReturnType() == float.class ? partial : null);
@@ -487,6 +492,24 @@ public final class VanillaHudOracle {
}
sidebar.invoke(hud, capture, objective);
}
case "decor" -> {
var stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(c.get("item").getAsString())));
stack.setCount(i("count", 1));
stack.setDamageValue(i("damage", 0));
if (b("unbreakable")) stack.set(net.minecraft.core.component.DataComponents.UNBREAKABLE, net.minecraft.util.Unit.INSTANCE);
var cooldowns = new net.minecraft.world.item.ItemCooldowns();
put(actor, net.minecraft.world.entity.player.Player.class, "cooldowns", cooldowns);
if (c.has("cooldown") && !c.get("cooldown").isJsonNull()) {
var cd = c.getAsJsonObject("cooldown");
cooldowns.addCooldown(stack, cd.get("duration").getAsInt());
for (int n = cd.get("elapsed").getAsInt(); n > 0; n--) cooldowns.tick();
}
var timer = alloc(DeltaTracker.Timer.class);
put(timer, DeltaTracker.Timer.class, "deltaTickResidual", partial);
put(mc, Minecraft.class, "deltaTracker", timer);
capture.realDecorations = true;
capture.itemDecorations(font, stack, i("x", 0), i("y", 0), c.has("countText") ? c.get("countText").getAsString() : null);
}
default -> throw new IllegalArgumentException(c.get("kind").getAsString());
}
result.add("draws", capture.draws);
+22
View File
@@ -153,6 +153,27 @@ def sidebar(rng, n):
'scores': scores, 'teams': teams}
# Items for the decorations: id and max damage (0 = not damageable), checked by the oracle's own stacks.
DECOR_ITEMS = [('diamond_sword', 1561), ('bow', 384), ('shield', 336), ('flint_and_steel', 64), ('elytra', 432),
('stone', 0), ('ender_pearl', 0), ('apple', 0)]
def decor(rng, n):
"""GuiGraphicsExtractor.itemDecorations: count, durability bar and cooldown shade."""
item, max_damage = rng.choice(DECOR_ITEMS)
case = {'x': rng.randint(-20, 400), 'y': rng.randint(-20, 300), 'item': item, 'maxDamage': max_damage,
'count': rng.choice([1, 1, 2, 16, 64, 99, 0, 10, 127]),
'damage': rng.choice([0, 0, 1, max_damage // 2, max_damage - 1, max_damage, rng.randint(0, max(max_damage, 1))]) if max_damage else 0,
'unbreakable': rng.random() < 0.1, 'partial': round(rng.random(), 3)}
if rng.random() < 0.4:
duration = rng.choice([1, 2, 7, 20, 100, 200])
case['cooldown'] = {'duration': duration, 'elapsed': rng.choice([0, 1, duration - 1, duration, rng.randint(0, duration)])}
if rng.random() < 0.1:
case['countText'] = rng.choice(['', '+', '1/2', 'x9'])
return case
# Generators by kind: (rng, index) -> case. Cases are drawn round-robin.
KINDS = {
'decorations': decorations,
@@ -162,4 +183,5 @@ KINDS = {
'boss': boss,
'jump': jump,
'sidebar': sidebar,
'decor': decor,
}