Hud api
This commit is contained in:
@@ -74,6 +74,7 @@ deno task build && deno task server # packs the mods and starts a se
|
||||
- [World Generation](docs/modding/worldgen/index.md): ores and features
|
||||
- [Biomes](docs/modding/worldgen/biomes.md): surfaces, colors and seasons
|
||||
- [Screens](docs/modding/gui/index.md): plain screens, inventory overlays and drawing with `Graphics`
|
||||
- [HUD](docs/modding/gui/hud.md): layers drawn over the world, like the base game's hotbar and hearts
|
||||
- [Networking](docs/modding/networking/index.md): how players get mods and the world
|
||||
- [Saving Data](docs/modding/datastorage/index.md): where a mod keeps what should last
|
||||
- [Config](docs/modding/misc/config.md): settings a server can change, like how fast a machine works
|
||||
@@ -87,5 +88,5 @@ deno task build && deno task server # packs the mods and starts a se
|
||||
The API types are the reference for everything scripts can call. Scripts import them as `cubi/server`, `cubi/client`,
|
||||
`cubi/shared`, `cubi/worldgen` and `cubi/content`, and they live in [`common/mod_api/`](common/mod_api/).
|
||||
|
||||
A few parts of those types aren't built yet and throw when used: forms, custom screens, HUD elements and keybinds.
|
||||
A few parts of those types aren't built yet and throw when used: forms, custom screens and keybinds.
|
||||
[`docs/modding_plan.md`](docs/modding_plan.md) covers those, what else is planned, and the design behind the mod API.
|
||||
|
||||
+15
-252
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
@@ -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),
|
||||
|
||||
@@ -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":
|
||||
|
||||
@@ -48,6 +48,20 @@ export interface ClientContext {
|
||||
readonly season: Season | undefined;
|
||||
is_swimming(): boolean;
|
||||
is_sneaking(): boolean;
|
||||
// health and hunger as the server last sent them, like the server's Player. air is out of 20 like food, 2 a
|
||||
// bubble
|
||||
readonly health: number;
|
||||
readonly max_health: number;
|
||||
readonly food: number;
|
||||
readonly saturation: number;
|
||||
readonly air: number;
|
||||
// their eyes are in water, like minecraft's isUnderWater
|
||||
is_underwater(): boolean;
|
||||
// how far the attack cooldown is, 0 right after attacking and 1 when it's done, like getAttackStrengthScale
|
||||
attack_strength(): number;
|
||||
// their 36 slots, hotbar is 0-8, as the server last synced them. copies
|
||||
readonly inventory: { readonly size: number; get(slot: number): ItemStack | undefined };
|
||||
readonly selected_slot: number;
|
||||
};
|
||||
// read only, what this client sees
|
||||
world: {
|
||||
@@ -61,8 +75,10 @@ export interface ClientContext {
|
||||
// the dimension's blocks go from min_y up to max_y - 1
|
||||
readonly min_y: number;
|
||||
readonly max_y: number;
|
||||
// ticks since 06:00 of day 1, see ServerWorld.time
|
||||
// ticks since 06:00 of day 1, see ServerWorld.time. day and hour are like ServerWorld's
|
||||
readonly time: number;
|
||||
readonly day: number;
|
||||
readonly hour: number;
|
||||
};
|
||||
// every item any mod registered, in load order
|
||||
items: {
|
||||
@@ -281,7 +297,8 @@ export interface Graphics {
|
||||
panel(x: number, y: number, w: number, h: number): void;
|
||||
// how tall a line of text is at scale 1, the game's text size
|
||||
readonly text_height: number;
|
||||
text(text: string, x: number, y: number, options?: { scale?: number; color?: Color }): void;
|
||||
// shadow draws it again under, a bit down and right in dark grey, so it reads over the world, like drawString's
|
||||
text(text: string, x: number, y: number, options?: { scale?: number; color?: Color; shadow?: boolean }): void;
|
||||
measure_text(text: string, scale?: number): number;
|
||||
// part is the part of the texture to draw, [u, v, width, height] from 0 to 1, like a progress bar's filled part
|
||||
texture(id: Id, x: number, y: number, w: number, h: number, part?: [number, number, number, number]): void;
|
||||
@@ -296,7 +313,12 @@ export interface Graphics {
|
||||
filled: number,
|
||||
direction?: "right" | "up",
|
||||
): void;
|
||||
item(id: Id, x: number, y: number, count?: number): void;
|
||||
// one of the engine's gui sprites (assets/sprites/gui.png), like "cubi:heart_full", at its size unless given one.
|
||||
// like neoforge's blitSprite. color multiplies it, like a shadow drawn in see through black
|
||||
sprite(id: Id, x: number, y: number, options?: { width?: number; height?: number; color?: Color }): void;
|
||||
// an item at a slot's top left. a stack draws like a slot does, with its count and its data, like a worn tool's
|
||||
// durability bar
|
||||
item(item: Id | ItemStack, x: number, y: number, count?: number): void;
|
||||
// a fluid as a slot shows it, its texture in its color, at a slot's top left like item. filled (0 to 1, 1 when not
|
||||
// set) is how much of the slot it fills from the bottom up, like amount / capacity for a machine's tank
|
||||
fluid(fluid: FluidVariant, x: number, y: number, filled?: number): void;
|
||||
@@ -349,8 +371,25 @@ export interface ClientUi {
|
||||
add_item_tooltip(fn: (item: ItemStack, lines: TooltipLine[]) => void): void;
|
||||
}
|
||||
|
||||
// what's drawn over the world while playing, under screens, like neoforge's gui layers. see docs/modding/gui/hud.md
|
||||
export interface HudRegistry {
|
||||
register(id: Id, element: { on_render(g: Graphics): void }): void;
|
||||
// a layer, drawn every frame in the order they're registered, mods in load order, like RegisterGuiLayersEvent's
|
||||
// registerAboveAll. only during setup. one that throws is removed, with the error in the console
|
||||
register(id: Id, layer: HudLayer): void;
|
||||
// a server script sent an overlay message (MessageOptions.overlay), for a layer to show
|
||||
on_overlay_message(fn: (text: string) => void): void;
|
||||
}
|
||||
|
||||
export interface HudLayer {
|
||||
on_render(g: Graphics, hud: HudSpace): void;
|
||||
}
|
||||
|
||||
// how far up from the bottom of the window the hud reaches on the left and right, in gui pixels, like neoforge's
|
||||
// leftHeight and rightHeight. both start at 0 each frame. a layer drawing along the bottom, like a row of hearts, draws
|
||||
// above them and raises them, so the next one goes on top. chat goes above the higher one
|
||||
export interface HudSpace {
|
||||
left_height: number;
|
||||
right_height: number;
|
||||
}
|
||||
|
||||
export interface ClientNet {
|
||||
|
||||
@@ -36,7 +36,7 @@ clicking them does something else.
|
||||
| Script | Runs on | Sent to players | For |
|
||||
| ---------- | -------------------------------- | ---------------------- | ------------------------------------------------------------------- |
|
||||
| `server` | the server, in the game worker | **never** | game logic: block and item components, events, commands, containers |
|
||||
| `client` | every player's browser | yes | presentation: inventory overlays, and later custom screens and HUD |
|
||||
| `client` | every player's browser | yes | presentation: screens, inventory overlays and the HUD |
|
||||
| `shared` | the server and every browser | yes | block rules: the states blocks are placed with, joining neighbors |
|
||||
| `worldgen` | the server, when it makes chunks | no | features that decorate terrain, deterministic |
|
||||
| `content` | the server, while it loads mods | no, only what it makes | blocks made in code, like one for every kind of rock |
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# HUD
|
||||
|
||||
The HUD is what's drawn over the world while playing, under any open screen. Mods add to it with layers, like NeoForge's
|
||||
GUI layers. The base game's whole HUD is layers in `mods/bworld/scripts/hud.ts`: the hotbar, hearts, hunger, air, the
|
||||
held item's name, overlay messages, the crosshair, and the day, time, biome and season. The engine only draws chat,
|
||||
above them.
|
||||
|
||||
## Layers
|
||||
|
||||
A client script registers layers during `setup`, with ids in its namespace:
|
||||
|
||||
```ts
|
||||
import type { ClientContext } from "cubi/client";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
ctx.hud.register("thirst:water", {
|
||||
on_render(g, hud) {
|
||||
// a row of drops above the hunger, on the right
|
||||
const y = g.height - hud.right_height - 10;
|
||||
const right = Math.floor((g.width - 182) / 2) + 182;
|
||||
for (let i = 0; i < 10; i++) g.texture("thirst:drop", right - i * 8 - 9, y, 9, 9);
|
||||
hud.right_height += 10;
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
`on_render` runs every frame with a [`Graphics`](index.md#graphics) for the whole window, in GUI pixels. Layers draw in
|
||||
the order they're registered, mods in load order, so a mod's layers go over the base game's, like NeoForge's
|
||||
`registerAboveAll`. A layer that throws is removed, with the error in the console.
|
||||
|
||||
## Stacking Along the Bottom
|
||||
|
||||
`hud` says how far up from the bottom of the window the HUD reaches on each side, in GUI pixels, like NeoForge's
|
||||
`leftHeight` and `rightHeight`:
|
||||
|
||||
```ts
|
||||
interface HudSpace {
|
||||
left_height: number;
|
||||
right_height: number;
|
||||
}
|
||||
```
|
||||
|
||||
Both start at 0 each frame. A layer that draws along the bottom draws above them and raises them, so the next one goes
|
||||
on top. The base game's hotbar raises both by 29: its 22, and the room above it Minecraft's experience bar takes. Hearts
|
||||
then go up the left 10 a row, hunger and air up the right. The held item's name and overlay messages go above the higher
|
||||
side without raising it, and chat goes above that.
|
||||
|
||||
## Overlay Messages
|
||||
|
||||
A server script's message with `{ overlay: true }` (see `Player.send_message`) isn't chat: it goes to the client scripts
|
||||
that listen for it, and the base game shows it above the hotbar for a few seconds:
|
||||
|
||||
```ts
|
||||
let message = "";
|
||||
ctx.hud.on_overlay_message((text) => (message = text));
|
||||
```
|
||||
|
||||
## What Layers Can Read
|
||||
|
||||
Besides [the rest of the client's state](index.md#reading-game-state), the player's vitals and hotbar are there for the
|
||||
HUD:
|
||||
|
||||
```ts
|
||||
ctx.player.health; // and max_health, as the server last sent them
|
||||
ctx.player.food; // and saturation, out of 20
|
||||
ctx.player.air; // out of 20 like food, 2 a bubble. it goes down while their eyes are under water
|
||||
ctx.player.is_underwater(); // their eyes are in water, like Minecraft's isUnderWater
|
||||
ctx.player.attack_strength(); // 0 right after attacking, 1 once the cooldown is done
|
||||
ctx.player.inventory.get(slot); // a copy of what's in a slot, hotbar is 0-8
|
||||
ctx.player.selected_slot; // the hotbar slot they hold
|
||||
ctx.world.day; // days since the world started, 0 on the first, and hour, 14.5 for 14:30
|
||||
```
|
||||
|
||||
`g.sprite("cubi:heart_full", x, y)` draws one of the engine's GUI sprites at its size, like NeoForge's `blitSprite`, and
|
||||
`g.item(stack, x, y)` draws a stack the way a slot does, with its count and durability bar.
|
||||
@@ -7,7 +7,8 @@ There are a few ways for a mod to show players a GUI. Pick the first one that's
|
||||
| [Menus](../inventories/menus.md) | server, and client | Inventories and machines: slots, filters, progress bars |
|
||||
| [Plain screens](#plain-screens) | client only | Screens with nothing the server checks: maps, guide books |
|
||||
| [Inventory overlays](#inventory-overlays) | client only | Drawing next to every menu's screen, like a recipe list |
|
||||
| Forms and HUD elements | not built yet | See [below](#not-built-yet) |
|
||||
| [HUD layers](hud.md) | client only | Drawing over the world while playing, like health bars |
|
||||
| Forms | not built yet | See [below](#not-built-yet) |
|
||||
|
||||
Everything is in **GUI pixels**, like NeoForge's: 18 of them are a slot, and the game draws each one 3 screen pixels
|
||||
wide.
|
||||
@@ -111,7 +112,13 @@ interface Graphics {
|
||||
|
||||
rect(x: number, y: number, w: number, h: number, color?: [r, g, b, a]): void;
|
||||
panel(x: number, y: number, w: number, h: number): void; // the game's panel background
|
||||
text(text: string, x: number, y: number, options?: { scale?: number; color?: [r, g, b, a] }): void; // scale 1 is normal
|
||||
// scale 1 is normal. shadow draws it again under, in dark grey, so it reads over the world
|
||||
text(
|
||||
text: string,
|
||||
x: number,
|
||||
y: number,
|
||||
options?: { scale?: number; color?: [r, g, b, a]; shadow?: boolean },
|
||||
): void;
|
||||
measure_text(text: string, scale?: number): number;
|
||||
// any texture. part is [u, v, width, height] from 0 to 1, the part of it to draw, like a progress bar's filled part
|
||||
texture(id: string, x: number, y: number, w: number, h: number, part?: [u, v, w, h]): void;
|
||||
@@ -126,7 +133,10 @@ interface Graphics {
|
||||
filled: number,
|
||||
direction?: "right" | "up",
|
||||
): void;
|
||||
item(id: string, x: number, y: number, count?: number): void; // an item as a slot shows it
|
||||
// one of the engine's gui sprites, like "cubi:heart_full", at its size unless given one. color multiplies it
|
||||
sprite(id: string, x: number, y: number, options?: { width?: number; height?: number; color?: [r, g, b, a] }): void;
|
||||
// an item as a slot shows it. a stack draws with its count and data, like a worn tool's durability bar
|
||||
item(item: string | ItemStack, x: number, y: number, count?: number): void;
|
||||
// a fluid as a slot shows it, like { id: "bworld:juice", data: { item: "bworld:apple" } }. filled is how much of
|
||||
// the slot it fills from the bottom up, 0 to 1, like a tank's amount / capacity
|
||||
fluid(fluid: FluidVariant, x: number, y: number, filled?: number): void;
|
||||
@@ -203,7 +213,8 @@ ctx.player.biome; // and ctx.player.season, see ../worldgen/biomes.md#seasons
|
||||
ctx.world.get_block(x, y, z); // a block id, what this client sees
|
||||
ctx.world.get_client_data<number>(x, y, z, "speed"); // see ../blocks/tiledata.md#client-data, a copy
|
||||
ctx.world.biome_at(x, y, z); // and ctx.world.season_at(x, y, z), undefined where nothing's loaded
|
||||
ctx.world.time; // see Time
|
||||
ctx.world.time; // see Time, and ctx.world.day and ctx.world.hour like the server's
|
||||
ctx.player.health; // and the rest of the vitals, the hotbar and the attack cooldown, see hud.md
|
||||
ctx.world.min_y; // and ctx.world.max_y, see ../worldgen/terrain.md#height
|
||||
ctx.items.ids(); // every item, in load order
|
||||
ctx.items.exists(id);
|
||||
@@ -235,7 +246,6 @@ The client and server APIs have types for these, but calling them throws for now
|
||||
|
||||
- **Forms** (`ctx.ui.message_form`, `action_form` and `modal_form` on the server): simple dialogs defined entirely by
|
||||
the server script, like Bedrock's server forms. They'll be menus whose screens the engine draws.
|
||||
- **HUD elements** (`ctx.hud.register`): drawing over the world every frame.
|
||||
- **Keybinds** (`ctx.input.bind`). Until then, an inventory overlay can check `g.key_pressed` while an inventory is
|
||||
open.
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.t
|
||||
`common/worldgen_loader.ts`, and for worn items `client/rendering/worn_renderer.ts`, `player_model.ts` and
|
||||
`model_math.ts`.
|
||||
|
||||
**In the API types but throwing:** forms, HUD elements, keybinds, `g.slider`, `register_terrain`.
|
||||
**In the API types but throwing:** forms, keybinds, `g.slider`, `register_terrain`.
|
||||
|
||||
**Content scripts** are built, the first part of common scripts: `scripts.content` with `ctx.blocks.register`, see
|
||||
[Content Scripts](#content-scripts-as-built). The code is in `common/content_scripts.ts`, `common/mod_api/content.ts`,
|
||||
@@ -276,7 +276,8 @@ Worn items are drawn by `render_worn`, which puts an item's `worn` model on a pl
|
||||
|
||||
### HUD, Keybinds and Mod Channels
|
||||
|
||||
- `ctx.hud.register(id, { on_render(g) })` draws every frame after the world, under open screens.
|
||||
- `ctx.hud.register(id, { on_render(g, hud) })` draws every frame after the world, under open screens. Built, see
|
||||
[HUD](modding/gui/hud.md).
|
||||
- `ctx.input.bind(id, default_key, on_press)` with ids like `copper_tools:open_smelter`, so a controls menu can rebind
|
||||
them. They only fire while no screen is open.
|
||||
- `ctx.net` on both sides: `on(channel, handler)`, `send`, and `broadcast` on the server. Channel ids are in the mod's
|
||||
@@ -302,7 +303,7 @@ engine assets in `assets/`.
|
||||
| Hoeing, chest, furnace, smithing table, farming, watering can, fishing | `mods/bworld/scripts/server.ts` | Done |
|
||||
| Recipe type `shaped` | engine (`common/mod_loader.ts`, `server/game/crafting.ts`) | Phase 5 |
|
||||
| The player's inventory screen and crafting grid | engine (`client/gui/gui_player_inventory.ts`, `server/game/crafting.ts`) | Phase 5 |
|
||||
| The hotbar and crosshair | engine (`client/gui/hud.ts`) | Phase 5 |
|
||||
| The hotbar, hearts, hunger, crosshair and the rest of the HUD | `mods/bworld/scripts/hud.ts` | Done |
|
||||
| `/give`, `/time` and `/summon` | engine (`server/game/game_server.ts`) | Phase 5 |
|
||||
| Mining: tool speed, `requires_tool`, drops | engine (`client/game_mode.ts`, `server/game/game_server.ts`) | Phase 5 |
|
||||
| Day and night lengths, sky colors | engine (`common/time.ts`, `client/rendering/game_renderer.ts`) | Phase 5 |
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the screens of the base game's menus, see scripts/server.ts for their slots. in gui pixels, like minecraft's. and the
|
||||
// juicer's visual
|
||||
// juicer's visual and the hud, see hud.ts
|
||||
import { mat4 } from "gl-matrix";
|
||||
import type {
|
||||
ClientContext,
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
VisualBlock,
|
||||
} from "cubi/client";
|
||||
import { TOOLTIP_PRIORITY } from "cubi/client";
|
||||
import { register_hud } from "./hud.ts";
|
||||
import { MINIGAMES } from "./minigames/mod.ts";
|
||||
import { JUICER_CAPACITY, JUICER_PRESSES } from "./shared.ts";
|
||||
import { STONECUTTING, stonecutting_options, type StonecuttingRecipe } from "./stonecutting.ts";
|
||||
@@ -38,6 +39,7 @@ export function setup(ctx: ClientContext) {
|
||||
ctx.ui.register_menu_screen("bworld:stonecutter", (menu) => stonecutter_screen(ctx, menu));
|
||||
ctx.ui.register_menu_screen("bworld:fishing_minigame", fishing_minigame_screen);
|
||||
ctx.render.register_visual("bworld:juicer", juicer_visual);
|
||||
register_hud(ctx);
|
||||
|
||||
ctx.ui.add_item_tooltip((item, lines) => {
|
||||
const value = ctx.items.sell_value(item.id, item.data);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// bworld:curio_modifiers component change the wearer's attributes, like curios' attribute modifiers, and ones with
|
||||
// bworld:curio_unhurt_effect give them an effect once they've gone a while without being hurt
|
||||
import type { AttributeModifier, Container, ItemStack, Player, ServerContext, TagApi } from "cubi/server";
|
||||
import { title } from "./shared.ts";
|
||||
|
||||
// where the left column of slots goes, from the inventory screen's left edge. the panel around them ends just left of it
|
||||
const COLUMNS_X = -45;
|
||||
@@ -169,11 +170,6 @@ function describe({ attribute, amount, operation }: WornModifier): string {
|
||||
return `${sign}${value} ${name}`;
|
||||
}
|
||||
|
||||
// "bworld:regeneration" is "Regeneration", like minecraft's effect names
|
||||
function title(id: string): string {
|
||||
return id.split(":").at(-1)!.split("_").map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
|
||||
}
|
||||
|
||||
function roman(level: number): string {
|
||||
return ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"][level - 1] ?? `${level}`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// what's drawn over the world while playing, like minecraft's gui: the hotbar, hearts, hunger and air, the held item's
|
||||
// name, overlay messages, the crosshair, and the day, time, biome and season. in gui pixels
|
||||
import type { ClientContext, Color, Graphics, HudSpace } from "cubi/client";
|
||||
import { title } from "./shared.ts";
|
||||
|
||||
const HOTBAR_WIDTH = 182;
|
||||
const HOTBAR_HEIGHT = 22;
|
||||
// each slot is 20 across, the item's slot corner 2 in from the cell's and the selection 1 out
|
||||
const HOTBAR_CELL = 20;
|
||||
const HOTBAR_ITEM_INSET = 2;
|
||||
// above the hotbar, the room minecraft's experience bar takes
|
||||
const HOTBAR_ROOM = 7;
|
||||
// hearts, hunger and air are rows of 10 icons, 8 apart. each row takes 10 up, the icon and a gap under it. more max
|
||||
// health stacks more rows of hearts, closer together when there are many, like minecraft
|
||||
const ICON_SIZE = 9;
|
||||
const ICON_SPACING = 8;
|
||||
const ICONS_PER_ROW = 10;
|
||||
const ROW_HEIGHT = 10;
|
||||
const MIN_HEART_ROW_SPACING = 3;
|
||||
// air goes from 20 down while the head is under water, 2 a bubble like hunger
|
||||
const MAX_AIR = 20;
|
||||
// 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 = 4;
|
||||
// a server's overlay message, 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: Color = [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: Color = [0, 0, 0, 0.4];
|
||||
const ATTACK_BAR_FILL: Color = [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: Color = [0, 0, 0, 0.4];
|
||||
|
||||
export function register_hud(ctx: ClientContext) {
|
||||
ctx.hud.register("bworld:hotbar", { on_render: (g, hud) => render_hotbar(ctx, g, hud) });
|
||||
ctx.hud.register("bworld:health", { on_render: (g, hud) => render_health(ctx, g, hud) });
|
||||
ctx.hud.register("bworld:food", { on_render: (g, hud) => render_food(ctx, g, hud) });
|
||||
ctx.hud.register("bworld:air", { on_render: (g, hud) => render_air(ctx, g, hud) });
|
||||
|
||||
// like minecraft: switching slots, or a different item ending up in the selected one, shows its name for a bit
|
||||
let held = "";
|
||||
let held_since = -Infinity;
|
||||
ctx.hud.register("bworld:held_item_name", {
|
||||
on_render(g, hud) {
|
||||
const slot = ctx.player.selected_slot;
|
||||
const item = ctx.player.inventory.get(slot);
|
||||
const now = performance.now();
|
||||
if ((item ? `${slot} ${item.id}` : "") !== held) {
|
||||
held = item ? `${slot} ${item.id}` : "";
|
||||
held_since = item ? now : -Infinity;
|
||||
}
|
||||
const shown_for = now - held_since;
|
||||
if (!item || shown_for > HELD_NAME_MS) return;
|
||||
const alpha = Math.min(1, (HELD_NAME_MS - shown_for) / HELD_NAME_FADE_MS);
|
||||
const y = g.height - hud_top(hud) - HELD_NAME_GAP - g.text_height;
|
||||
text_centered(g, ctx.items.name(item.id), y, alpha);
|
||||
},
|
||||
});
|
||||
|
||||
let overlay = "";
|
||||
let overlay_since = -Infinity;
|
||||
ctx.hud.on_overlay_message((text) => {
|
||||
overlay = text;
|
||||
overlay_since = performance.now();
|
||||
});
|
||||
ctx.hud.register("bworld:overlay_message", {
|
||||
on_render(g, hud) {
|
||||
const shown_for = performance.now() - overlay_since;
|
||||
if (shown_for > OVERLAY_MS) return;
|
||||
const alpha = Math.min(1, (OVERLAY_MS - shown_for) / OVERLAY_FADE_MS);
|
||||
// above where the held item's name goes
|
||||
const y = g.height - hud_top(hud) - HELD_NAME_GAP - OVERLAY_GAP - g.text_height * 2;
|
||||
text_centered(g, overlay, y, alpha);
|
||||
},
|
||||
});
|
||||
|
||||
ctx.hud.register("bworld:crosshair", { on_render: (g) => render_crosshair(ctx, g) });
|
||||
ctx.hud.register("bworld:info", { on_render: (g) => render_info(ctx, g) });
|
||||
}
|
||||
|
||||
function render_hotbar(ctx: ClientContext, g: Graphics, hud: HudSpace) {
|
||||
const x = hotbar_x(g);
|
||||
const y = g.height - HOTBAR_HEIGHT;
|
||||
g.sprite("cubi:hotbar", x, y);
|
||||
g.sprite("cubi:hotbar_selection", x + ctx.player.selected_slot * HOTBAR_CELL - 1, y - 1);
|
||||
for (let slot = 0; slot < 9; slot++) {
|
||||
const item = ctx.player.inventory.get(slot);
|
||||
if (item) g.item(item, x + slot * HOTBAR_CELL + HOTBAR_ITEM_INSET, y + HOTBAR_ITEM_INSET);
|
||||
}
|
||||
hud.left_height += HOTBAR_HEIGHT + HOTBAR_ROOM;
|
||||
hud.right_height += HOTBAR_HEIGHT + HOTBAR_ROOM;
|
||||
}
|
||||
|
||||
// on the left, each heart 2 points, rows going up
|
||||
function render_health(ctx: ClientContext, g: Graphics, hud: HudSpace) {
|
||||
const { max_health } = ctx.player;
|
||||
const health = Math.ceil(ctx.player.health);
|
||||
const hearts = Math.ceil(max_health / 2);
|
||||
const rows = Math.ceil(hearts / ICONS_PER_ROW);
|
||||
const row_spacing = Math.max(ROW_HEIGHT - (rows - 2), MIN_HEART_ROW_SPACING);
|
||||
const y = g.height - hud.left_height - ROW_HEIGHT;
|
||||
for (let i = 0; i < hearts; i++) {
|
||||
const heart_x = hotbar_x(g) + (i % ICONS_PER_ROW) * ICON_SPACING;
|
||||
const heart_y = y - Math.floor(i / ICONS_PER_ROW) * row_spacing;
|
||||
g.sprite("cubi:heart_container", heart_x, heart_y);
|
||||
const fill = icon_fill(health, i);
|
||||
if (fill) g.sprite(fill === "full" ? "cubi:heart_full" : "cubi:heart_half", heart_x, heart_y);
|
||||
}
|
||||
hud.left_height += ROW_HEIGHT + Math.max(0, rows - 1) * row_spacing;
|
||||
}
|
||||
|
||||
// on the right, going right to left. saturation is appleskin's outline over the hunger icons, never more than hunger
|
||||
function render_food(ctx: ClientContext, g: Graphics, hud: HudSpace) {
|
||||
const food = Math.ceil(ctx.player.food);
|
||||
const saturation = Math.min(ctx.player.saturation, ctx.player.food);
|
||||
const y = g.height - hud.right_height - ROW_HEIGHT;
|
||||
for (let i = 0; i < ICONS_PER_ROW; i++) {
|
||||
const x = right_icon_x(g, i);
|
||||
g.sprite("cubi:food_empty", x, y);
|
||||
const fill = icon_fill(food, i);
|
||||
if (fill) g.sprite(fill === "full" ? "cubi:food_full" : "cubi:food_half", 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;
|
||||
g.sprite(`cubi:saturation_${quarters}`, x, y);
|
||||
}
|
||||
}
|
||||
hud.right_height += ROW_HEIGHT;
|
||||
}
|
||||
|
||||
// bubbles above the hunger, as soon as the head is under, so it shows full before it starts going down, and while it
|
||||
// fills back up after
|
||||
function render_air(ctx: ClientContext, g: Graphics, hud: HudSpace) {
|
||||
const air = ctx.player.air;
|
||||
if (!ctx.player.is_underwater() && air >= MAX_AIR) return;
|
||||
const y = g.height - hud.right_height - ROW_HEIGHT;
|
||||
for (let i = 0; i < ICONS_PER_ROW; i++) {
|
||||
const x = right_icon_x(g, i);
|
||||
g.sprite("cubi:air_empty", x, y);
|
||||
const fill = icon_fill(air, i);
|
||||
if (fill) g.sprite(fill === "full" ? "cubi:air_full" : "cubi:air_half", x, y);
|
||||
}
|
||||
hud.right_height += ROW_HEIGHT;
|
||||
}
|
||||
|
||||
function render_crosshair(ctx: ClientContext, g: Graphics) {
|
||||
const x = Math.floor((g.width - CROSSHAIR_SIZE) / 2);
|
||||
const y = Math.floor((g.height - CROSSHAIR_SIZE) / 2);
|
||||
g.sprite("cubi:crosshair", x + 1, y + 1, { color: CROSSHAIR_SHADOW });
|
||||
g.sprite("cubi:crosshair", x, y);
|
||||
|
||||
// only while it's charging, like minecraft
|
||||
const strength = ctx.player.attack_strength();
|
||||
if (strength >= 1) return;
|
||||
const bar_x = Math.floor((g.width - ATTACK_BAR_WIDTH) / 2);
|
||||
const bar_y = y + CROSSHAIR_SIZE + ATTACK_BAR_GAP;
|
||||
g.rect(bar_x, bar_y, ATTACK_BAR_WIDTH, ATTACK_BAR_HEIGHT, ATTACK_BAR_BACK);
|
||||
g.rect(bar_x, bar_y, ATTACK_BAR_WIDTH * strength, ATTACK_BAR_HEIGHT, ATTACK_BAR_FILL);
|
||||
}
|
||||
|
||||
function render_info(ctx: ClientContext, g: Graphics) {
|
||||
const { day, hour } = ctx.world;
|
||||
const minute = Math.round((hour % 1) * 60);
|
||||
const { biome, season } = ctx.player;
|
||||
const lines = [
|
||||
`Day ${day + 1}`,
|
||||
`${String(Math.floor(hour)).padStart(2, "0")}:${String(minute).padStart(2, "0")}`,
|
||||
biome === undefined ? "Unknown" : title(biome),
|
||||
season === undefined ? "Unknown" : title(season),
|
||||
];
|
||||
const line_height = g.text_height + INFO_LINE_GAP;
|
||||
const width = Math.max(...lines.map((line) => g.measure_text(line))) + INFO_PADDING * 2;
|
||||
const height = lines.length * line_height - INFO_LINE_GAP + INFO_PADDING * 2;
|
||||
g.rect(INFO_MARGIN, INFO_MARGIN, width, height, INFO_BACK);
|
||||
lines.forEach((line, i) => {
|
||||
g.text(line, INFO_MARGIN + INFO_PADDING, INFO_MARGIN + INFO_PADDING + i * line_height, { shadow: true });
|
||||
});
|
||||
}
|
||||
|
||||
function hotbar_x(g: Graphics) {
|
||||
return Math.floor((g.width - HOTBAR_WIDTH) / 2);
|
||||
}
|
||||
|
||||
// icon i of a row on the right, counting from the right end of the hotbar
|
||||
function right_icon_x(g: Graphics, i: number) {
|
||||
return hotbar_x(g) + HOTBAR_WIDTH - i * ICON_SPACING - ICON_SIZE;
|
||||
}
|
||||
|
||||
// the top of the rows of icons above the hotbar, from the bottom of the window
|
||||
function hud_top(hud: HudSpace) {
|
||||
return Math.max(hud.left_height, hud.right_height);
|
||||
}
|
||||
|
||||
// text across the middle of the window at y, with a shadow so it reads over bright sky and snow
|
||||
function text_centered(g: Graphics, text: string, y: number, alpha: number) {
|
||||
g.text(text, (g.width - g.measure_text(text)) / 2, y, { color: [1, 1, 1, alpha], shadow: true });
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
@@ -205,3 +205,8 @@ function register_juice_and_wine(ctx: SharedContext) {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// "bworld:regeneration" is "Regeneration", like minecraft's effect names, biomes' and seasons' too
|
||||
export function title(id: string): string {
|
||||
return id.split(":").at(-1)!.split("_").map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// mods' hud layers, see ctx.hud and client/gui/hud.ts
|
||||
import { assertEquals, assertRejects } from "@std/assert";
|
||||
import { EverythingRegistry } from "@/common/everything_registry.ts";
|
||||
import type { ModListing } from "@/common/mod_loader.ts";
|
||||
import { read_mod } from "@/common/mod.ts";
|
||||
import type { Graphics, HudSpace } from "@/common/mod_api/client.ts";
|
||||
import { hud_layers, load_client_mods, receive_overlay_message, render_hud_layers } from "@/client/mods.ts";
|
||||
import { load_and_check } from "@/tools/check_mods.ts";
|
||||
import { pack_mod } from "@/tools/pack_mod.ts";
|
||||
|
||||
async function load(script: string) {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_hud_" });
|
||||
try {
|
||||
Deno.mkdirSync(`${dir}/testmod/scripts`, { recursive: true });
|
||||
Deno.writeTextFileSync(
|
||||
`${dir}/testmod/manifest.json`,
|
||||
JSON.stringify({
|
||||
format_version: 1,
|
||||
id: "testmod",
|
||||
name: "Test",
|
||||
version: "1.0.0",
|
||||
scripts: { client: "scripts/client.ts" },
|
||||
}),
|
||||
);
|
||||
Deno.writeTextFileSync(`${dir}/testmod/scripts/client.ts`, script);
|
||||
const mod = (await load_and_check(dir))[0];
|
||||
const packed = read_mod(await pack_mod(mod), "testmod.cubi");
|
||||
const listing: ModListing = { id: "testmod", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };
|
||||
EverythingRegistry.clear();
|
||||
await load_client_mods([listing], [packed]);
|
||||
} finally {
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
Deno.test("hud layers draw in order on the same space, and one that throws is removed", async () => {
|
||||
await load(`
|
||||
import type { ClientContext } from "cubi/client";
|
||||
export function setup(ctx: ClientContext) {
|
||||
ctx.hud.register("testmod:bar", { on_render(_g, hud) { hud.left_height += 10; } });
|
||||
ctx.hud.register("testmod:broken", { on_render() { throw new Error("broken"); } });
|
||||
const above = {
|
||||
seen: [] as number[],
|
||||
overlay: "",
|
||||
on_render(_g, hud) { this.seen.push(hud.left_height); },
|
||||
};
|
||||
ctx.hud.register("testmod:above", above);
|
||||
ctx.hud.on_overlay_message((text) => above.overlay = text);
|
||||
}
|
||||
`);
|
||||
assertEquals(hud_layers.map((entry) => entry.id), ["testmod:bar", "testmod:broken", "testmod:above"]);
|
||||
const above = hud_layers[2].layer as unknown as { seen: number[]; overlay: string };
|
||||
|
||||
const error = console.error;
|
||||
console.error = () => {};
|
||||
try {
|
||||
for (let frame = 0; frame < 2; frame++) {
|
||||
const space: HudSpace = { left_height: 0, right_height: 0 };
|
||||
render_hud_layers({} as Graphics, space);
|
||||
assertEquals(space, { left_height: 10, right_height: 0 });
|
||||
}
|
||||
} finally {
|
||||
console.error = error;
|
||||
}
|
||||
assertEquals(above.seen, [10, 10]);
|
||||
assertEquals(hud_layers.map((entry) => entry.id), ["testmod:bar", "testmod:above"]);
|
||||
|
||||
receive_overlay_message("Too dark to sleep");
|
||||
assertEquals(above.overlay, "Too dark to sleep");
|
||||
});
|
||||
|
||||
Deno.test("hud layers are in the mod's namespace, one to an id", async () => {
|
||||
const layer = `{ on_render() {} }`;
|
||||
await assertRejects(
|
||||
() => load(`export function setup(ctx) { ctx.hud.register("bworld:hotbar", ${layer}); }`),
|
||||
Error,
|
||||
`must be in the namespace "testmod"`,
|
||||
);
|
||||
await assertRejects(
|
||||
() =>
|
||||
load(`export function setup(ctx) {
|
||||
ctx.hud.register("testmod:bar", ${layer});
|
||||
ctx.hud.register("testmod:bar", ${layer});
|
||||
}`),
|
||||
Error,
|
||||
"hud layer testmod:bar already exists",
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user