This commit is contained in:
2026-11-14 00:29:34 -03:00
parent 6c6be61dd0
commit 297d87164c
15 changed files with 593 additions and 281 deletions
+15 -252
View File
@@ -2,262 +2,25 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { Client } from "@/client/client.ts";
import type { LocalPlayer } from "@/client/entity/local_player.ts";
import type { ClientInventories } from "@/client/inventory.ts";
import { draw_item } from "@/client/rendering/render_utils.ts";
import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts";
import { display_name } from "@/common/utils.ts";
import { clock } from "@/common/time.ts";
import { biome_season } from "@/common/worldgen/biomes.ts";
import { TEXT_HEIGHT, TEXT_SCALE } from "./widgets.ts";
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
import { render_hud_layers } from "@/client/mods.ts";
import { canvas } from "@/client/renderer/mod.ts";
import type { HudSpace } from "@/common/mod_api/client.ts";
import { ModGraphics } from "./mod_graphics.ts";
import { GUI_SCALE } from "./gui_sprites.ts";
// sizes and gaps in minecraft's gui pixels, drawn GUI_SCALE times bigger
const HOTBAR_WIDTH = 182;
const HOTBAR_HEIGHT = 22;
// each slot is 20 across, the item sits 3 in from its corner and the selection 1 out
const HOTBAR_CELL = 20;
const HOTBAR_ITEM_INSET = 3;
// hearts and hunger: 10 icons each, 8 apart, above the hotbar's top. more max health stacks more rows of hearts above,
// 10 apart, closer together when there are many, like minecraft
const ICON_SIZE = 9;
const ICON_SPACING = 8;
const ICONS_ABOVE_HOTBAR = 17;
const ICONS_PER_ROW = 10;
const HEART_ROW_SPACING = 10;
const MIN_HEART_ROW_SPACING = 3;
// air: 10 bubbles above the hunger, like minecraft, from when the head goes under water until it's full again
const MAX_AIR = 20;
const AIR_ROW_SPACING = 10;
// how long the held item's name shows above the hotbar after it changes, and the last part of that it fades out in
const HELD_NAME_MS = 2000;
const HELD_NAME_FADE_MS = 500;
const HELD_NAME_GAP = 12;
// a server's overlay message, see MessageOptions.overlay: above the held item's name, for as long as minecraft's
const OVERLAY_MS = 3000;
const OVERLAY_FADE_MS = 500;
const OVERLAY_GAP = 4;
const CROSSHAIR_SIZE = 15;
// under the crosshair so it shows on bright sky and snow, minecraft inverts the colors behind it instead
const CROSSHAIR_SHADOW: [number, number, number, number] = [0, 0, 0, 0.4];
// the attack indicator, like minecraft's: a bar under the crosshair filling up while the attack cooldown runs
const ATTACK_BAR_WIDTH = 16;
const ATTACK_BAR_HEIGHT = 2;
const ATTACK_BAR_GAP = 2;
const ATTACK_BAR_BACK: [number, number, number, number] = [0, 0, 0, 0.4];
const ATTACK_BAR_FILL: [number, number, number, number] = [1, 1, 1, 0.9];
// the day, time, biome and season in the top left, on a dark box so it reads over the sky
const INFO_MARGIN = 4;
const INFO_PADDING = 3;
const INFO_LINE_GAP = 1;
const INFO_BACK: [number, number, number, number] = [0, 0, 0, 0.4];
// between the top of the hud and the bottom of chat, in gui pixels
const CHAT_GAP = 4;
// what's drawn over the world while playing, like minecraft's Gui: hotbar, crosshair and chat
// what's drawn over the world while playing, like minecraft's Gui: mods' layers (ctx.hud), then chat above them
export class Hud {
// what was held last frame, as slot and item id, and when the held item last changed
#held = "";
#held_since = -Infinity;
#overlay = "";
#overlay_since = -Infinity;
// shows text above the hotbar for a moment, see MessageOptions.overlay
show_overlay(text: string) {
this.#overlay = text;
this.#overlay_since = performance.now();
}
#graphics = new ModGraphics();
render(client: Client) {
this.#render_hotbar(client.player.inventories);
this.#render_vitals(client);
const top = Math.min(icons_y() - heart_rows_height(client.player.max_health), air_y(client.player));
this.#render_held_name(client.player.inventories, top);
this.#render_overlay(top);
this.#render_crosshair(client);
this.#render_info(client);
client.chat.render(false, top - HELD_NAME_GAP);
}
#render_hotbar(inventories: ClientInventories) {
const { x, y } = hotbar_position();
draw_gui_sprite("hotbar", x, y);
const selected_x = x + (inventories.hotbar_selected * HOTBAR_CELL - 1) * GUI_SCALE;
draw_gui_sprite("hotbar_selection", selected_x, y - GUI_SCALE);
for (let index = 0; index < 9; index += 1) {
const item = inventories.inventory.get_item(index);
if (item) {
// draw_item takes a slot's corner, which is a pixel out from the item
const item_x = x + (index * HOTBAR_CELL + HOTBAR_ITEM_INSET - 1) * GUI_SCALE;
draw_item(item, item_x, y + (HOTBAR_ITEM_INSET - 1) * GUI_SCALE);
}
}
}
// like minecraft: switching slots, or a different item ending up in the selected one, shows its name for a bit
// top is the top of the hearts
#render_held_name(inventories: ClientInventories, top: number) {
const item = inventories.inventory.get_item(inventories.hotbar_selected);
const held = item ? `${inventories.hotbar_selected} ${item.type_id}` : "";
const now = performance.now();
if (held !== this.#held) {
this.#held = held;
this.#held_since = item ? now : -Infinity;
}
const shown_for = now - this.#held_since;
if (!item || shown_for > HELD_NAME_MS) {
return;
}
const alpha = Math.min(1, (HELD_NAME_MS - shown_for) / HELD_NAME_FADE_MS);
draw_centered(display_name(item.type_id), top - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE, alpha);
}
// top is the top of the hearts, like for the held item's name, which it goes above
#render_overlay(top: number) {
const shown_for = performance.now() - this.#overlay_since;
if (shown_for > OVERLAY_MS) return;
const alpha = Math.min(1, (OVERLAY_MS - shown_for) / OVERLAY_FADE_MS);
const y = top - HELD_NAME_GAP - OVERLAY_GAP * GUI_SCALE - TEXT_HEIGHT * TEXT_SCALE * 2;
draw_centered(this.#overlay, y, alpha);
}
// hearts on the left and hunger on the right like minecraft, each icon 2 points. saturation is appleskin's outline
// over the hunger icons, it's never more than the hunger. air's bubbles go above the hunger, see shows_air
#render_vitals(client: Client) {
const player = client.player;
const { x: left } = hotbar_position();
const right = left + HOTBAR_WIDTH * GUI_SCALE;
const y = icons_y();
const health = Math.ceil(player.health);
const food = Math.ceil(player.food);
const saturation = Math.min(player.saturation, player.food);
const hearts = Math.ceil(player.max_health / 2);
const row_spacing = heart_row_spacing(player.max_health) * GUI_SCALE;
for (let i = 0; i < hearts; i++) {
const heart_x = left + (i % ICONS_PER_ROW) * ICON_SPACING * GUI_SCALE;
const heart_y = y - Math.floor(i / ICONS_PER_ROW) * row_spacing;
draw_gui_sprite("heart_container", heart_x, heart_y);
const heart = icon_fill(health, i);
if (heart) {
draw_gui_sprite(heart === "full" ? "heart_full" : "heart_half", heart_x, heart_y);
}
}
for (let i = 0; i < ICONS_PER_ROW; i++) {
// hunger goes right to left
const food_x = right - (i * ICON_SPACING + ICON_SIZE) * GUI_SCALE;
draw_gui_sprite("food_empty", food_x, y);
const fill = icon_fill(food, i);
if (fill) {
draw_gui_sprite(fill === "full" ? "food_full" : "food_half", food_x, y);
}
const saturated = Math.max(0, Math.min(1, (saturation - i * 2) / 2));
if (saturated > 0) {
const quarters = saturated >= 1 ? 4 : saturated > 0.5 ? 3 : saturated > 0.25 ? 2 : 1;
draw_gui_sprite(`saturation_${quarters}`, food_x, y);
}
if (shows_air(player)) {
const air_y = y - AIR_ROW_SPACING * GUI_SCALE;
draw_gui_sprite("air_empty", food_x, air_y);
const bubble = icon_fill(player.air, i);
if (bubble) draw_gui_sprite(bubble === "full" ? "air_full" : "air_half", food_x, air_y);
}
}
}
#render_info(client: Client) {
const { day, hour, minute } = clock(client.level.time);
const { x, y, z } = client.player;
const biome = client.level.biome_at(Math.floor(x), Math.floor(y), Math.floor(z));
const lines = [
`Day ${day}`,
`${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`,
biome === undefined ? "Unknown" : display_name(biome),
biome === undefined ? "Unknown" : capitalize(biome_season(biome, client.level.time)),
];
const padding = INFO_PADDING * GUI_SCALE;
const line_height = (TEXT_HEIGHT + INFO_LINE_GAP) * TEXT_SCALE;
const width = Math.max(...lines.map((line) => measure_text(line, TEXT_SCALE))) + padding * 2;
const height = lines.length * line_height - INFO_LINE_GAP * TEXT_SCALE + padding * 2;
const left = INFO_MARGIN * GUI_SCALE;
const top = INFO_MARGIN * GUI_SCALE;
draw_rect(left, top, width, height, INFO_BACK);
lines.forEach((line, i) => {
const text_y = top + padding + i * line_height;
draw_text(line, left + padding + TEXT_SCALE, text_y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, 1]);
draw_text(line, left + padding, text_y, TEXT_SCALE, [1, 1, 1, 1]);
});
}
#render_crosshair(client: Client) {
const size = CROSSHAIR_SIZE * GUI_SCALE;
const x = Math.round((canvas.width - size) / 2);
const y = Math.round((canvas.height - size) / 2);
draw_gui_sprite("crosshair", x + GUI_SCALE, y + GUI_SCALE, undefined, undefined, CROSSHAIR_SHADOW);
draw_gui_sprite("crosshair", x, y);
// only while it's charging, like minecraft
const strength = client.player.attack_strength();
if (strength >= 1) return;
const width = ATTACK_BAR_WIDTH * GUI_SCALE;
const bar_x = Math.round((canvas.width - width) / 2);
const bar_y = y + size + ATTACK_BAR_GAP * GUI_SCALE;
draw_rect(bar_x, bar_y, width, ATTACK_BAR_HEIGHT * GUI_SCALE, ATTACK_BAR_BACK);
draw_rect(bar_x, bar_y, Math.round(width * strength), ATTACK_BAR_HEIGHT * GUI_SCALE, ATTACK_BAR_FILL);
const space: HudSpace = { left_height: 0, right_height: 0 };
this.#graphics.begin();
render_hud_layers(this.#graphics, space);
this.#graphics.end();
const top = Math.max(space.left_height, space.right_height) + CHAT_GAP;
client.chat.render(false, canvas.height - top * GUI_SCALE);
}
}
// text across the middle of the screen at y, with a shadow so it reads over bright sky and snow
function draw_centered(text: string, y: number, alpha: number) {
const x = (canvas.width - measure_text(text, TEXT_SCALE)) / 2;
draw_text(text, x + TEXT_SCALE, y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, alpha]);
draw_text(text, x, y, TEXT_SCALE, [1, 1, 1, alpha]);
}
function hotbar_position() {
return {
x: Math.round((canvas.width - HOTBAR_WIDTH * GUI_SCALE) / 2),
y: canvas.height - HOTBAR_HEIGHT * GUI_SCALE,
};
}
// the top of the hearts and hunger
function icons_y() {
return hotbar_position().y - ICONS_ABOVE_HOTBAR * GUI_SCALE;
}
// as soon as the head is under, so it shows full before it starts going down, and while it fills back up after
function shows_air(player: LocalPlayer) {
return player.eyes_in_water || player.air < MAX_AIR;
}
// the top of the bubbles while they show, the hearts' otherwise
function air_y(player: LocalPlayer) {
return icons_y() - (shows_air(player) ? AIR_ROW_SPACING * GUI_SCALE : 0);
}
// how far apart rows of hearts are, in gui pixels
function heart_row_spacing(max_health: number) {
const rows = Math.ceil(max_health / 2 / ICONS_PER_ROW);
return Math.max(HEART_ROW_SPACING - (rows - 2), MIN_HEART_ROW_SPACING);
}
// how much higher the rows of hearts past the first go, on the canvas
function heart_rows_height(max_health: number) {
const rows = Math.ceil(max_health / 2 / ICONS_PER_ROW);
return Math.max(0, rows - 1) * heart_row_spacing(max_health) * GUI_SCALE;
}
function capitalize(word: string) {
return word[0].toUpperCase() + word.slice(1);
}
// whether icon i of a value, 2 points an icon, is full, half or empty
function icon_fill(value: number, i: number): "full" | "half" | undefined {
if (value >= i * 2 + 2) return "full";
if (value === i * 2 + 1) return "half";
return undefined;
}
+32 -5
View File
@@ -7,7 +7,7 @@
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
import { ItemStack } from "@/common/inventory.ts";
import type { Color, Graphics, TooltipLine } from "@/common/mod_api/client.ts";
import type { FluidVariant, KeyCode } from "@/common/mod_api/shared.ts";
import type { FluidVariant, ItemStack as ApiItemStack, KeyCode } from "@/common/mod_api/shared.ts";
import { point_inside_rec } from "@/common/utils.ts";
import { AssetManager } from "@/client/assets.ts";
import { InputManager, type KeyCode as InputKey } from "@/client/input_manager.ts";
@@ -25,11 +25,13 @@ import { draw_fluid, draw_item } from "@/client/rendering/render_utils.ts";
import { get_sprite_region } from "@/client/sprites.ts";
import { draw_tooltip, item_tooltip } from "./tooltip.ts";
import { TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
import { GUI_ATLAS } from "./gui_atlas.ts";
import { GUI_ATLAS, type GuiSprite } from "./gui_atlas.ts";
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
const WHITE: Color = [1, 1, 1, 1];
const GREY: Color = [0.66, 0.66, 0.66, 1];
// text's shadow, see Graphics.text
const SHADOW = [0.15, 0.15, 0.15];
// a script's tooltip line, copied so it can't change after, in color when it doesn't say
function tooltip_line(line: string | TooltipLine, color: Color): TooltipLine {
@@ -118,8 +120,13 @@ export class ModGraphics implements Graphics {
draw_gui_sprite("panel", this.#x(x), this.#y(y), w * S, h * S);
}
text(text: string, x: number, y: number, options: { scale?: number; color?: Color } = {}) {
draw_text(text, this.#x(x), this.#y(y), TEXT_SCALE * (options.scale ?? 1), options.color ?? WHITE);
text(text: string, x: number, y: number, options: { scale?: number; color?: Color; shadow?: boolean } = {}) {
const scale = TEXT_SCALE * (options.scale ?? 1);
const color = options.color ?? WHITE;
if (options.shadow) {
draw_text(text, this.#x(x) + scale, this.#y(y) + scale, scale, [...SHADOW, color[3]]);
}
draw_text(text, this.#x(x), this.#y(y), scale, color);
}
measure_text(text: string, scale = 1) {
@@ -163,8 +170,28 @@ export class ModGraphics implements Graphics {
}
}
item(id: string, x: number, y: number, count = 1) {
sprite(id: string, x: number, y: number, options: { width?: number; height?: number; color?: Color } = {}) {
const name = id.startsWith("cubi:") ? id.slice("cubi:".length) : undefined;
if (!name || !Object.hasOwn(GUI_ATLAS, name)) throw new Error(`unknown gui sprite ${id}`);
const { width, height, color } = options;
draw_gui_sprite(
name as GuiSprite,
this.#x(x),
this.#y(y),
width === undefined ? undefined : width * S,
height === undefined ? undefined : height * S,
color,
);
}
item(item: string | ApiItemStack, x: number, y: number, count = 1) {
const id = typeof item === "string" ? item : item.id;
if (!EverythingRegistry.get<ItemRegistry>("items", id)) throw new Error(`unknown item ${id}`);
if (typeof item !== "string") {
// like a slot
draw_item(ItemStack.from_data(structuredClone(item)), this.#x(x), this.#y(y));
return;
}
const stack = new ItemStack(id, count);
// the count only shows when it's more than one
draw_item(stack, this.#x(x), this.#y(y), count !== 1 && stack.max_amount !== 1);
+85 -2
View File
@@ -5,7 +5,16 @@
// see docs/modding/networking/index.md
import { AIR } from "@/common/constants.ts";
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
import type { ClientContext, ClientMenu, InventoryOverlay, KeyMappings, MenuScreen } from "@/common/mod_api/client.ts";
import type {
ClientContext,
ClientMenu,
Graphics,
HudLayer,
HudSpace,
InventoryOverlay,
KeyMappings,
MenuScreen,
} from "@/common/mod_api/client.ts";
import {
check_recipe_types,
ModListing,
@@ -33,6 +42,7 @@ import { common_engine } from "@/common/engine_modules.ts";
import { client_engine } from "./engine_modules.ts";
import { block_visuals } from "./rendering/visuals.ts";
import { biome_season } from "@/common/worldgen/biomes.ts";
import { clock, farming_day } from "@/common/time.ts";
import type { LootTableJson } from "@/common/loot.ts";
// each loaded mod's credits file, for the credits screen
@@ -47,6 +57,27 @@ export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] =
// each menu type's screen, see ctx.ui.register_menu_screen
export const menu_screens = new Map<string, { mod: string; create: (menu: ClientMenu) => MenuScreen }>();
// what mods draw over the world, in order, see ctx.hud and client/gui/hud.ts
export const hud_layers: { mod: string; id: string; layer: HudLayer }[] = [];
// draws every hud layer in order, all raising the same space. one that throws is removed so it doesn't throw every frame
export function render_hud_layers(g: Graphics, space: HudSpace) {
for (const entry of [...hud_layers]) {
try {
entry.layer.on_render(g, space);
} catch (e) {
console.error(`[${entry.mod}] hud layer ${entry.id} threw, so it's removed:`, e);
hud_layers.splice(hud_layers.indexOf(entry), 1);
}
}
}
const overlay_listeners: { mod: string; fn: (text: string) => void }[] = [];
// the server sent an overlay message, see MessageOptions.overlay
export function receive_overlay_message(text: string) {
for (const { mod, fn } of overlay_listeners) run_mod(mod, "an overlay message listener", () => fn(text));
}
// mod channels, see ctx.net: who listens on each channel
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => void }[]>();
@@ -166,6 +197,8 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
const recipes = register_mod_data(mods.map((mod) => ({ id: mod.manifest.id, data: mod.data })));
recipe_book = recipes;
inventory_overlays.length = 0;
hud_layers.length = 0;
overlay_listeners.length = 0;
item_tooltips.length = 0;
menu_screens.clear();
net_handlers.clear();
@@ -316,7 +349,21 @@ function client_context(listing: ModListing): ClientContext {
item_tooltips.push((item, lines) => run_mod(mod, "an item tooltip", () => fn(item, lines)));
},
},
hud: not_yet("hud", "HUD elements") as ClientContext["hud"],
hud: {
register(id, layer) {
if (!client_setup) throw new Error(`[${mod}] hud layers can only be registered during setup`);
own(id, "hud layer");
if (typeof layer?.on_render !== "function") throw new Error(`[${mod}] a hud layer needs an on_render`);
if (hud_layers.some((other) => other.id === id)) {
throw new Error(`[${mod}] hud layer ${id} already exists`);
}
hud_layers.push({ mod, id, layer });
},
on_overlay_message(fn) {
if (typeof fn !== "function") throw new Error(`[${mod}] on_overlay_message takes a function`);
overlay_listeners.push({ mod, fn });
},
},
input: not_yet("input", "keybinds") as ClientContext["input"],
options: key_mappings(need_client),
net: {
@@ -349,6 +396,35 @@ function client_context(listing: ModListing): ClientContext {
},
is_swimming: () => need_client().player.swimming,
is_sneaking: () => need_client().player.holding_sneak,
get health() {
return need_client().player.health;
},
get max_health() {
return need_client().player.max_health;
},
get food() {
return need_client().player.food;
},
get saturation() {
return need_client().player.saturation;
},
get air() {
return need_client().player.air;
},
is_underwater: () => need_client().player.eyes_in_water,
attack_strength: () => need_client().player.attack_strength(),
inventory: {
get size() {
return need_client().player.inventories.inventory.size;
},
get(slot) {
const item = need_client().player.inventories.inventory.get_item(slot);
return item && structuredClone(item.to_data());
},
},
get selected_slot() {
return need_client().player.inventories.hotbar_selected;
},
},
world: {
get_block(x, y, z) {
@@ -369,6 +445,13 @@ function client_context(listing: ModListing): ClientContext {
get time() {
return need_client().level.time;
},
get day() {
return farming_day(need_client().level.time);
},
get hour() {
const { hour, minute } = clock(need_client().level.time);
return hour + minute / 60;
},
},
items: {
...shared_items_api(mod, fluid_rules),
+2 -2
View File
@@ -11,7 +11,7 @@ import { RemotePlayer } from "./entity/remote_player.ts";
import { ItemEntity } from "./entity/item_entity.ts";
import { RemoteEntity } from "./entity/remote_entity.ts";
import { Player } from "./entity/player.ts";
import { menu_screens, receive_mod_message } from "./mods.ts";
import { menu_screens, receive_mod_message, receive_overlay_message } from "./mods.ts";
// minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as
// fit in CHUNK_BUDGET_MS
@@ -223,7 +223,7 @@ export class ClientPacketListener {
level.set_center(message.x, message.z);
break;
case "chat":
if (message.overlay) client.game_renderer.hud.show_overlay(message.text);
if (message.overlay) receive_overlay_message(message.text);
else client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
break;
case "suggestions":