Files
bworld/client/gui/gui_container.ts
T

105 lines
2.9 KiB
TypeScript

import { add_player_hotbar, add_player_inventory, GuiInventoryScreen, Slot } from "./gui_screen.ts";
import { canvas, draw_rect, draw_texture_region, Texture } from "$/client/renderer/mod.ts";
import { AssetManager } from "../assets.ts";
import { SLOT_SIZE } from "$/common/constants.ts";
import { ClientMessage, ScreenLayout } from "$/common/protocol.ts";
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
import { get_sprite_region } from "$/client/sprites.ts";
import { ClientInventories } from "../inventory.ts";
// around the slots, and between the hotbar, the rest of the inventory and what's below, like minecraft's
const MARGIN = 7 * GUI_SCALE;
const GAP = 4 * GUI_SCALE;
// where the screen's own slots start, below the player's
const AREA_Y = MARGIN + GAP * 2 + SLOT_SIZE * 4;
// a screen opened by the server (chest, furnace, ...), drawn from the layout it sent
export class GuiContainer extends GuiInventoryScreen {
layout: ScreenLayout;
properties: Record<string, number>;
constructor(
inventories: ClientInventories,
send: (message: ClientMessage) => void,
layout: ScreenLayout,
properties: Record<string, number>,
) {
super(inventories, send);
this.layout = layout;
this.properties = properties;
this.inventory_width = MARGIN * 2 + SLOT_SIZE * 9;
this.inventory_height = MARGIN * 2 + GAP * 2 + SLOT_SIZE * (4 + layout.rows);
add_player_hotbar(this, MARGIN, MARGIN);
add_player_inventory(this, MARGIN, MARGIN + GAP + SLOT_SIZE);
for (const slot of layout.slots) {
this.slots.push(
new Slot("screen", slot.index, MARGIN + slot.x * SLOT_SIZE, AREA_Y + slot.y * SLOT_SIZE, slot.output),
);
}
}
override on_render(): void {
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
draw_gui_sprite("panel", this.x, this.y, this.inventory_width, this.inventory_height);
this.draw_bars();
super.on_render();
}
draw_bars() {
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
for (const bar of this.layout.bars) {
const x = this.x + MARGIN + bar.x * SLOT_SIZE;
const y = this.y + AREA_Y + bar.y * SLOT_SIZE;
const max = this.properties[bar.max] ?? 0;
const pct = max > 0 ? Math.max(0, Math.min(1, (this.properties[bar.value] ?? 0) / max)) : 0;
const empty = get_sprite_region(bar.empty_texture);
draw_texture_region(
atlas,
empty.x,
empty.y,
empty.width,
empty.height,
x,
y,
SLOT_SIZE,
SLOT_SIZE,
);
const full = get_sprite_region(bar.full_texture);
if (bar.direction === "right") {
draw_texture_region(
atlas,
full.x,
full.y,
full.width * pct,
full.height,
x,
y,
SLOT_SIZE * pct,
SLOT_SIZE,
);
} else {
// fills from the bottom up
draw_texture_region(
atlas,
full.x,
full.y + full.height * (1 - pct),
full.width,
full.height * pct,
x,
y + SLOT_SIZE * (1 - pct),
SLOT_SIZE,
SLOT_SIZE * pct,
);
}
}
}
}