Change whole gui system
This commit is contained in:
@@ -53,7 +53,7 @@ deno task build && deno task server # packs the mods and starts a se
|
|||||||
**Inventories**
|
**Inventories**
|
||||||
|
|
||||||
- [Containers](docs/modding/inventories/containers.md): slots the server owns and saves
|
- [Containers](docs/modding/inventories/containers.md): slots the server owns and saves
|
||||||
- [Container Screens](docs/modding/inventories/menus.md): showing containers to players
|
- [Menus](docs/modding/inventories/menus.md): slots, data and buttons on the server, and their screens
|
||||||
|
|
||||||
**Resources**
|
**Resources**
|
||||||
|
|
||||||
@@ -65,7 +65,7 @@ deno task build && deno task server # packs the mods and starts a se
|
|||||||
**Everything else**
|
**Everything else**
|
||||||
|
|
||||||
- [World Generation](docs/modding/worldgen/index.md): ores and features
|
- [World Generation](docs/modding/worldgen/index.md): ores and features
|
||||||
- [Screens](docs/modding/gui/index.md): inventory overlays and drawing with `Graphics`
|
- [Screens](docs/modding/gui/index.md): plain screens, inventory overlays and drawing with `Graphics`
|
||||||
- [Networking](docs/modding/networking/index.md): how players get mods and the world
|
- [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
|
- [Saving Data](docs/modding/datastorage/index.md): where a mod keeps what should last
|
||||||
- [Commands](docs/modding/misc/commands.md)
|
- [Commands](docs/modding/misc/commands.md)
|
||||||
|
|||||||
+30
-11
@@ -11,7 +11,7 @@ import { MultiPlayerGameMode } from "./game_mode.ts";
|
|||||||
import { ClientPacketListener } from "./packet_listener.ts";
|
import { ClientPacketListener } from "./packet_listener.ts";
|
||||||
import { GameRenderer } from "./rendering/game_renderer.ts";
|
import { GameRenderer } from "./rendering/game_renderer.ts";
|
||||||
import { ChatComponent } from "./gui/chat_component.ts";
|
import { ChatComponent } from "./gui/chat_component.ts";
|
||||||
import { GuiInventoryScreen, GuiScreen } from "./gui/gui_screen.ts";
|
import { GuiMenuScreen, GuiScreen } from "./gui/gui_screen.ts";
|
||||||
import { GuiPlayerInventory } from "./gui/gui_player_inventory.ts";
|
import { GuiPlayerInventory } from "./gui/gui_player_inventory.ts";
|
||||||
import { GuiChat } from "./gui/gui_chat.ts";
|
import { GuiChat } from "./gui/gui_chat.ts";
|
||||||
import { InputManager } from "./input_manager.ts";
|
import { InputManager } from "./input_manager.ts";
|
||||||
@@ -19,6 +19,7 @@ import { Connection } from "./network.ts";
|
|||||||
import { PauseScreen } from "./gui/pause_screen.ts";
|
import { PauseScreen } from "./gui/pause_screen.ts";
|
||||||
import { back_to_title } from "./gui/title_screen.ts";
|
import { back_to_title } from "./gui/title_screen.ts";
|
||||||
import { TICK_DELTA } from "$/common/constants.ts";
|
import { TICK_DELTA } from "$/common/constants.ts";
|
||||||
|
import { PLAYER_MENU } from "$/common/protocol.ts";
|
||||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
||||||
import type { EntityJson } from "$/common/mod_data.ts";
|
import type { EntityJson } from "$/common/mod_data.ts";
|
||||||
|
|
||||||
@@ -97,8 +98,26 @@ export class Client {
|
|||||||
this.screens.push(screen);
|
this.screens.push(screen);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the player closed the one on top
|
||||||
pop_screen() {
|
pop_screen() {
|
||||||
this.screens.pop()?.on_close();
|
const screen = this.screens.pop();
|
||||||
|
screen?.on_close();
|
||||||
|
screen?.on_removed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// the player closed this one, wherever it is
|
||||||
|
close_screen(screen: GuiScreen) {
|
||||||
|
if (!this.screens.includes(screen)) return;
|
||||||
|
this.screens = this.screens.filter((s) => s !== screen);
|
||||||
|
screen.on_close();
|
||||||
|
screen.on_removed();
|
||||||
|
}
|
||||||
|
|
||||||
|
// takes these off without closing them, like when the server opens a menu or closes it
|
||||||
|
remove_screens(which: (screen: GuiScreen) => boolean) {
|
||||||
|
const removed = this.screens.filter(which);
|
||||||
|
this.screens = this.screens.filter((s) => !which(s));
|
||||||
|
for (const screen of removed) screen.on_removed();
|
||||||
}
|
}
|
||||||
|
|
||||||
// leaving on purpose, from the pause screen
|
// leaving on purpose, from the pause screen
|
||||||
@@ -194,7 +213,7 @@ export class Client {
|
|||||||
if (InputManager.is_key_pressed(options.key_inventory)) {
|
if (InputManager.is_key_pressed(options.key_inventory)) {
|
||||||
if (!this.screen) {
|
if (!this.screen) {
|
||||||
this.push_screen(new GuiPlayerInventory(player.inventories, (m) => this.connection.send(m)));
|
this.push_screen(new GuiPlayerInventory(player.inventories, (m) => this.connection.send(m)));
|
||||||
} else if (this.screen instanceof GuiInventoryScreen) {
|
} else if (this.screen instanceof GuiMenuScreen) {
|
||||||
this.pop_screen();
|
this.pop_screen();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -212,7 +231,7 @@ export class Client {
|
|||||||
const lost_mouse = InputManager.take_lost_pointer_lock();
|
const lost_mouse = InputManager.take_lost_pointer_lock();
|
||||||
if (InputManager.is_key_pressed("Escape")) {
|
if (InputManager.is_key_pressed("Escape")) {
|
||||||
if (this.screen) {
|
if (this.screen) {
|
||||||
this.pop_screen();
|
if (this.screen.close_on_escape()) this.pop_screen();
|
||||||
} else {
|
} else {
|
||||||
this.push_screen(new PauseScreen(this));
|
this.push_screen(new PauseScreen(this));
|
||||||
}
|
}
|
||||||
@@ -233,15 +252,15 @@ export class Client {
|
|||||||
const inventories = this.player.inventories;
|
const inventories = this.player.inventories;
|
||||||
const screen = this.screen;
|
const screen = this.screen;
|
||||||
if (!screen) {
|
if (!screen) {
|
||||||
this.game_mode.drop_item(inventories.inventory, "inventory", inventories.hotbar_selected, all);
|
// the hotbar slot of menu 0, they're the same numbers
|
||||||
|
const slot = inventories.hotbar_selected;
|
||||||
|
this.game_mode.drop_item(inventories.inventory, slot, PLAYER_MENU, slot, all);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const slot = screen instanceof GuiInventoryScreen ? screen.hovering : undefined;
|
const slot = screen instanceof GuiMenuScreen ? screen.hovering : undefined;
|
||||||
const container = slot && screen instanceof GuiInventoryScreen
|
if (screen instanceof GuiMenuScreen && slot && !slot.output && !inventories.cursor.item) {
|
||||||
? screen.get_container(slot.container)
|
const index = screen.menu.slots.indexOf(slot);
|
||||||
: undefined;
|
this.game_mode.drop_item(slot.container, slot.index, screen.menu.id, index, all);
|
||||||
if (slot && container && !slot.output && !inventories.cursor.item) {
|
|
||||||
this.game_mode.drop_item(container, slot.container, slot.index, all);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+4
-3
@@ -3,7 +3,7 @@ import { AIR, FACE_OFFSETS, TICK_DELTA } from "$/common/constants.ts";
|
|||||||
import type { Client } from "./client.ts";
|
import type { Client } from "./client.ts";
|
||||||
import type { BlockHitResult } from "./level/client_level.ts";
|
import type { BlockHitResult } from "./level/client_level.ts";
|
||||||
import type { Container } from "$/common/inventory.ts";
|
import type { Container } from "$/common/inventory.ts";
|
||||||
import { AIR_ID, type ContainerKey } from "$/common/protocol.ts";
|
import { AIR_ID } from "$/common/protocol.ts";
|
||||||
import { box_overlaps_block, can_place, placement_target } from "$/common/utils.ts";
|
import { box_overlaps_block, can_place, placement_target } from "$/common/utils.ts";
|
||||||
import type { EntityJson } from "$/common/mod_data.ts";
|
import type { EntityJson } from "$/common/mod_data.ts";
|
||||||
import { RemoteEntity } from "./entity/remote_entity.ts";
|
import { RemoteEntity } from "./entity/remote_entity.ts";
|
||||||
@@ -86,12 +86,13 @@ export class MultiPlayerGameMode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// q on a slot: throws one, or the whole stack. the server spawns the item, this only takes it out right away
|
// q on a slot: throws one, or the whole stack. the server spawns the item, this only takes it out right away
|
||||||
drop_item(container: Container, key: ContainerKey, index: number, all: boolean) {
|
// q on a menu's slot, whose item is in container at index on this client
|
||||||
|
drop_item(container: Container, index: number, menu: number, slot: number, all: boolean) {
|
||||||
const item = container.get_item(index);
|
const item = container.get_item(index);
|
||||||
if (!item) {
|
if (!item) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.client.connection.send({ type: "drop_item", container: key, index, all });
|
this.client.connection.send({ type: "drop_item", menu, slot, all });
|
||||||
item.amount = all ? 0 : item.amount - 1;
|
item.amount = all ? 0 : item.amount - 1;
|
||||||
container.set_item(index, item.amount > 0 ? item : undefined);
|
container.set_item(index, item.amount > 0 ? item : undefined);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
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,
|
|
||||||
slot.icon,
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
// screens mods' client scripts make, see docs/modding/gui/index.md: the screens of their menus, and screens with no
|
||||||
|
// menu. a mod's screen that throws is closed, with the error in the console
|
||||||
|
import { TICK_DELTA } from "$/common/constants.ts";
|
||||||
|
import type { ClientMenu as ModClientMenu, MenuScreen, Screen } from "$/common/mod_api/client.ts";
|
||||||
|
import { canvas } from "../renderer/mod.ts";
|
||||||
|
import type { Client } from "../client.ts";
|
||||||
|
import type { ClientMenu } from "../menu.ts";
|
||||||
|
import { GuiMenuScreen, GuiScreen } from "./gui_screen.ts";
|
||||||
|
import { ModGraphics } from "./mod_graphics.ts";
|
||||||
|
import { GUI_SCALE } from "./gui_sprites.ts";
|
||||||
|
|
||||||
|
// runs on_tick 20 times a second from the frames' deltas, like the game's own ticks
|
||||||
|
class Ticker {
|
||||||
|
#pending = 0;
|
||||||
|
|
||||||
|
run(delta: number, tick: () => void) {
|
||||||
|
this.#pending += delta;
|
||||||
|
for (let i = 0; this.#pending >= TICK_DELTA && i < 10; i++) {
|
||||||
|
this.#pending -= TICK_DELTA;
|
||||||
|
tick();
|
||||||
|
}
|
||||||
|
this.#pending = Math.min(this.#pending, TICK_DELTA);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a menu the server opened, drawn by the screen its mod registered for the menu type
|
||||||
|
export class GuiModMenuScreen extends GuiMenuScreen {
|
||||||
|
#client: Client;
|
||||||
|
#mod: string;
|
||||||
|
#screen: MenuScreen;
|
||||||
|
#ticker = new Ticker();
|
||||||
|
|
||||||
|
constructor(client: Client, mod: string, menu: ClientMenu, create: (menu: ModClientMenu) => MenuScreen) {
|
||||||
|
const send = client.connection.send.bind(client.connection);
|
||||||
|
// this, once super has run
|
||||||
|
const self: { screen?: GuiModMenuScreen } = {};
|
||||||
|
const api: ModClientMenu = {
|
||||||
|
type: menu.type,
|
||||||
|
title: menu.title,
|
||||||
|
open_data: menu.open_data,
|
||||||
|
get data() {
|
||||||
|
return menu.data;
|
||||||
|
},
|
||||||
|
click_button: (id) => {
|
||||||
|
if (!Number.isInteger(id)) throw new Error(`a menu button is a whole number, not ${id}`);
|
||||||
|
if (self.screen && client.screens.includes(self.screen)) {
|
||||||
|
send({ type: "menu_button", menu: menu.id, button: id });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
close: () => {
|
||||||
|
if (self.screen) client.close_screen(self.screen);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const screen = create(api);
|
||||||
|
if (!(screen.width > 0 && screen.height > 0)) throw new Error(`the screen for ${menu.type} has no size`);
|
||||||
|
super(client.player.inventories, send, menu, screen.width, screen.height);
|
||||||
|
this.#client = client;
|
||||||
|
this.#mod = mod;
|
||||||
|
this.#screen = screen;
|
||||||
|
self.screen = this;
|
||||||
|
}
|
||||||
|
|
||||||
|
#guarded(what: string, fn: () => void) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${this.#mod}] the ${this.menu.type} screen's ${what} threw, closing it:`, e);
|
||||||
|
this.#client.close_screen(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override on_tick(delta: number): void {
|
||||||
|
super.on_tick(delta);
|
||||||
|
const tick = this.#screen.on_tick;
|
||||||
|
if (tick) this.#ticker.run(delta, () => this.#guarded("on_tick", () => tick.call(this.#screen)));
|
||||||
|
}
|
||||||
|
|
||||||
|
render_background(g: ModGraphics): void {
|
||||||
|
const render = this.#screen.on_render_background;
|
||||||
|
if (render) this.#guarded("on_render_background", () => render.call(this.#screen, g));
|
||||||
|
}
|
||||||
|
|
||||||
|
render_labels(g: ModGraphics): void {
|
||||||
|
const render = this.#screen.on_render_labels;
|
||||||
|
if (render) this.#guarded("on_render_labels", () => render.call(this.#screen, g));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// a screen with no menu, opened by a client script
|
||||||
|
export class GuiModScreen extends GuiScreen {
|
||||||
|
#mod: string;
|
||||||
|
#screen: Screen;
|
||||||
|
#client: Client;
|
||||||
|
#ticker = new Ticker();
|
||||||
|
graphics = new ModGraphics();
|
||||||
|
// the window size on_init last saw, it runs again when it changes
|
||||||
|
#size = "";
|
||||||
|
|
||||||
|
constructor(client: Client, mod: string, screen: Screen) {
|
||||||
|
super();
|
||||||
|
this.#client = client;
|
||||||
|
this.#mod = mod;
|
||||||
|
this.#screen = screen;
|
||||||
|
}
|
||||||
|
|
||||||
|
#guarded(what: string, fn: () => void) {
|
||||||
|
try {
|
||||||
|
fn();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${this.#mod}] a screen's ${what} threw, closing it:`, e);
|
||||||
|
this.#client.close_screen(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override get typing() {
|
||||||
|
return this.graphics.typing;
|
||||||
|
}
|
||||||
|
|
||||||
|
override close_on_escape(): boolean {
|
||||||
|
let close = true;
|
||||||
|
const should = this.#screen.should_close_on_escape;
|
||||||
|
if (should) this.#guarded("should_close_on_escape", () => close = should.call(this.#screen) !== false);
|
||||||
|
return close;
|
||||||
|
}
|
||||||
|
|
||||||
|
on_tick(delta: number): void {
|
||||||
|
const size = `${canvas.width}x${canvas.height}`;
|
||||||
|
if (size !== this.#size) {
|
||||||
|
this.#size = size;
|
||||||
|
const init = this.#screen.on_init;
|
||||||
|
const [w, h] = [canvas.width / GUI_SCALE, canvas.height / GUI_SCALE];
|
||||||
|
if (init) this.#guarded("on_init", () => init.call(this.#screen, w, h));
|
||||||
|
}
|
||||||
|
const tick = this.#screen.on_tick;
|
||||||
|
if (tick) this.#ticker.run(delta, () => this.#guarded("on_tick", () => tick.call(this.#screen)));
|
||||||
|
}
|
||||||
|
|
||||||
|
on_render(): void {
|
||||||
|
this.graphics.begin();
|
||||||
|
this.#guarded("on_render", () => this.#screen.on_render(this.graphics));
|
||||||
|
this.graphics.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
on_close(): void {
|
||||||
|
const close = this.#screen.on_close;
|
||||||
|
if (close) this.#guarded("on_close", () => close.call(this.#screen));
|
||||||
|
}
|
||||||
|
|
||||||
|
override on_removed(): void {
|
||||||
|
const removed = this.#screen.on_removed;
|
||||||
|
if (removed) this.#guarded("on_removed", () => removed.call(this.#screen));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,46 +1,24 @@
|
|||||||
import { add_player_hotbar, add_player_inventory, GuiInventoryScreen, Slot } from "./gui_screen.ts";
|
import { GuiMenuScreen } from "./gui_screen.ts";
|
||||||
import { canvas, draw_rect } from "$/client/renderer/mod.ts";
|
|
||||||
import { SLOT_SIZE } from "../../common/constants.ts";
|
|
||||||
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
|
||||||
import { ClientInventories } from "../inventory.ts";
|
import { ClientInventories } from "../inventory.ts";
|
||||||
import { ClientMessage, CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
|
import { ClientMessage } from "$/common/protocol.ts";
|
||||||
|
import { player_menu } from "../menu.ts";
|
||||||
|
import type { ModGraphics } from "./mod_graphics.ts";
|
||||||
|
|
||||||
// around the slots, and between the hotbar, the rest of the inventory and what's below, like minecraft's
|
const WIDTH = 176;
|
||||||
const MARGIN = 7 * GUI_SCALE;
|
const HEIGHT = 166;
|
||||||
const GAP = 4 * GUI_SCALE;
|
|
||||||
|
|
||||||
// the recipes live on the server, which fills in the result slot
|
|
||||||
export class GuiPlayerInventory extends GuiInventoryScreen {
|
|
||||||
override inventory_width = MARGIN * 2 + SLOT_SIZE * 9;
|
|
||||||
override inventory_height = MARGIN * 2 + GAP * 2 + SLOT_SIZE * 7;
|
|
||||||
|
|
||||||
|
// menu 0's screen: the crafting grid over the inventory. the recipes live on the server, which fills in the result
|
||||||
|
export class GuiPlayerInventory extends GuiMenuScreen {
|
||||||
constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) {
|
constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) {
|
||||||
super(inventories, send);
|
super(inventories, send, player_menu(inventories), WIDTH, HEIGHT);
|
||||||
|
|
||||||
add_player_hotbar(this, MARGIN, MARGIN);
|
|
||||||
add_player_inventory(this, MARGIN, MARGIN + GAP + SLOT_SIZE);
|
|
||||||
|
|
||||||
const crafting_x = MARGIN;
|
|
||||||
const crafting_y = MARGIN + GAP * 2 + SLOT_SIZE * 4;
|
|
||||||
|
|
||||||
for (let i = 0; i < 3; i += 1) {
|
|
||||||
for (let j = 0; j < 3; j += 1) {
|
|
||||||
this.slots.push(
|
|
||||||
new Slot("crafting", j * 3 + i, crafting_x + i * SLOT_SIZE, crafting_y + j * SLOT_SIZE),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.slots.push(
|
|
||||||
new Slot("crafting", CRAFTING_RESULT_SLOT, crafting_x + 5 * SLOT_SIZE, crafting_y + 1 * SLOT_SIZE, true),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override on_render(): void {
|
render_background(g: ModGraphics): void {
|
||||||
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
|
g.panel(0, 0, WIDTH, HEIGHT);
|
||||||
|
}
|
||||||
|
|
||||||
draw_gui_sprite("panel", this.x, this.y, this.inventory_width, this.inventory_height);
|
render_labels(g: ModGraphics): void {
|
||||||
|
g.text(this.menu.title, 26, 6);
|
||||||
super.on_render();
|
g.text("Inventory", 8, 73);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+122
-116
@@ -1,84 +1,72 @@
|
|||||||
import { SLOT_SIZE } from "$/common/constants.ts";
|
import { SLOT_SIZE } from "$/common/constants.ts";
|
||||||
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
|
||||||
import { click_slot, Container } from "$/common/inventory.ts";
|
import { click_slot } from "$/common/inventory.ts";
|
||||||
import { ClientMessage, ContainerKey, CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
|
import { ClientMessage, CRAFTING_RESULT_SLOT, PLAYER_MENU } from "$/common/protocol.ts";
|
||||||
import { point_inside_rec } from "../../common/utils.ts";
|
import { point_inside_rec } from "../../common/utils.ts";
|
||||||
import { InputManager } from "../input_manager.ts";
|
import { InputManager } from "../input_manager.ts";
|
||||||
import { ClientInventories } from "../inventory.ts";
|
import { ClientInventories } from "../inventory.ts";
|
||||||
import { canvas, draw_texture_region, Texture } from "../renderer/mod.ts";
|
import { canvas, draw_rect, draw_texture_region, Texture } from "../renderer/mod.ts";
|
||||||
import { AssetManager } from "../assets.ts";
|
import { AssetManager } from "../assets.ts";
|
||||||
import { get_sprite_region } from "../sprites.ts";
|
import { get_sprite_region } from "../sprites.ts";
|
||||||
import { draw_item } from "../rendering/render_utils.ts";
|
import { draw_item } from "../rendering/render_utils.ts";
|
||||||
import { draw_tooltip, item_tooltip } from "./tooltip.ts";
|
import { draw_tooltip, item_tooltip } from "./tooltip.ts";
|
||||||
import { ModGraphics } from "./mod_graphics.ts";
|
import { ModGraphics } from "./mod_graphics.ts";
|
||||||
import { inventory_overlays } from "../mods.ts";
|
import { inventory_overlays } from "../mods.ts";
|
||||||
|
import type { ClientMenu, ClientSlot } from "../menu.ts";
|
||||||
|
|
||||||
// how far past the slot's edge its highlight goes
|
// how far past the slot's edge its highlight goes
|
||||||
const HIGHLIGHT_OVERHANG = 3 * GUI_SCALE;
|
const HIGHLIGHT_OVERHANG = 3 * GUI_SCALE;
|
||||||
|
|
||||||
export class Slot {
|
|
||||||
container: ContainerKey;
|
|
||||||
index: number;
|
|
||||||
// relative to screen top left
|
|
||||||
x: number;
|
|
||||||
y: number;
|
|
||||||
// can only be taken from, like the crafting or furnace result
|
|
||||||
output: boolean;
|
|
||||||
// a texture drawn while it's empty, like minecraft's armor slots
|
|
||||||
icon: string | undefined;
|
|
||||||
|
|
||||||
constructor(container: ContainerKey, index: number, x: number, y: number, output = false, icon?: string) {
|
|
||||||
this.container = container;
|
|
||||||
this.index = index;
|
|
||||||
this.x = x;
|
|
||||||
this.y = y;
|
|
||||||
this.output = output;
|
|
||||||
this.icon = icon;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export abstract class GuiScreen {
|
export abstract class GuiScreen {
|
||||||
x: number = 0;
|
x: number = 0;
|
||||||
y: number = 0;
|
y: number = 0;
|
||||||
|
|
||||||
abstract on_tick(_delta: number): void;
|
abstract on_tick(_delta: number): void;
|
||||||
abstract on_render(): void;
|
abstract on_render(): void;
|
||||||
|
// the player closed it
|
||||||
abstract on_close(): void;
|
abstract on_close(): void;
|
||||||
|
|
||||||
|
// it's gone for any reason, after on_close when the player closed it
|
||||||
|
on_removed(): void {}
|
||||||
|
|
||||||
// something in it has the keyboard, like a text field, so keybinds (inventory, drop) don't fire
|
// something in it has the keyboard, like a text field, so keybinds (inventory, drop) don't fire
|
||||||
get typing(): boolean {
|
get typing(): boolean {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
close_on_escape(): boolean {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// a screen of slots. the server owns the contents: clicks are sent to it and guessed locally
|
// a menu's screen, like minecraft's AbstractContainerScreen: in the middle of the window, it draws the menu's slots,
|
||||||
// so they feel instant, then whatever the server syncs back wins
|
// the item on the cursor and tooltips, and sends clicks. the server owns what's in the slots: clicks are guessed
|
||||||
export class GuiInventoryScreen extends GuiScreen {
|
// locally so they feel instant, then whatever the server syncs back wins. subclasses draw the rest
|
||||||
|
export abstract class GuiMenuScreen extends GuiScreen {
|
||||||
inventories: ClientInventories;
|
inventories: ClientInventories;
|
||||||
send: (message: ClientMessage) => void;
|
send: (message: ClientMessage) => void;
|
||||||
|
menu: ClientMenu;
|
||||||
|
// in gui pixels
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
|
||||||
slots: Slot[] = [];
|
hovering: ClientSlot | undefined;
|
||||||
hovering: Slot | undefined;
|
// what the screen and mods draw with, in gui pixels
|
||||||
inventory_width: number = 500;
|
|
||||||
inventory_height: number = 500;
|
|
||||||
// what mods draw over it, like a recipe viewer
|
|
||||||
graphics = new ModGraphics();
|
graphics = new ModGraphics();
|
||||||
|
|
||||||
constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) {
|
constructor(
|
||||||
|
inventories: ClientInventories,
|
||||||
|
send: (message: ClientMessage) => void,
|
||||||
|
menu: ClientMenu,
|
||||||
|
width: number,
|
||||||
|
height: number,
|
||||||
|
) {
|
||||||
super();
|
super();
|
||||||
this.inventories = inventories;
|
this.inventories = inventories;
|
||||||
this.send = send;
|
this.send = send;
|
||||||
}
|
this.menu = menu;
|
||||||
|
this.width = width;
|
||||||
get_container(key: ContainerKey): Container | undefined {
|
this.height = height;
|
||||||
switch (key) {
|
|
||||||
case "inventory":
|
|
||||||
return this.inventories.inventory;
|
|
||||||
case "crafting":
|
|
||||||
return this.inventories.crafting;
|
|
||||||
case "screen":
|
|
||||||
return this.inventories.screen;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override get typing() {
|
override get typing() {
|
||||||
@@ -86,40 +74,29 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
}
|
}
|
||||||
|
|
||||||
on_tick(_delta: number): void {
|
on_tick(_delta: number): void {
|
||||||
this.x = canvas.width / 2 - (this.inventory_width / 2);
|
this.x = Math.floor((canvas.width - this.width * GUI_SCALE) / 2);
|
||||||
this.y = canvas.height / 2 - (this.inventory_height / 2);
|
this.y = Math.floor((canvas.height - this.height * GUI_SCALE) / 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
on_render(): void {
|
// under the slots, from the screen's top left
|
||||||
for (const slot of this.slots) {
|
abstract render_background(g: ModGraphics): void;
|
||||||
draw_gui_sprite("slot", this.x + slot.x, this.y + slot.y);
|
// over the slots
|
||||||
}
|
abstract render_labels(g: ModGraphics): void;
|
||||||
|
|
||||||
// like minecraft's, the highlight is a bit bigger than the slot, part of it under the item and part over
|
on_render(): void {
|
||||||
const highlight = (sprite: "slot_highlight_back" | "slot_highlight_front") => {
|
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
|
||||||
if (this.hovering) {
|
const g = this.graphics;
|
||||||
const x = this.x + this.hovering.x - HIGHLIGHT_OVERHANG;
|
g.begin();
|
||||||
draw_gui_sprite(sprite, x, this.y + this.hovering.y - HIGHLIGHT_OVERHANG);
|
g.origin_x = this.x;
|
||||||
}
|
g.origin_y = this.y;
|
||||||
};
|
this.render_background(g);
|
||||||
highlight("slot_highlight_back");
|
this.#render_slots();
|
||||||
for (const slot of this.slots) {
|
this.render_labels(g);
|
||||||
const item = this.get_container(slot.container)?.get_item(slot.index);
|
|
||||||
if (item) {
|
|
||||||
draw_item(item, this.x + slot.x, this.y + slot.y);
|
|
||||||
} else if (slot.icon) {
|
|
||||||
// where an item's sprite would be
|
|
||||||
const icon = get_sprite_region(slot.icon);
|
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
|
||||||
const [x, y, size] = [this.x + slot.x + 3, this.y + slot.y + 3, SLOT_SIZE - 6];
|
|
||||||
draw_texture_region(atlas, icon.x, icon.y, icon.width, icon.height, x, y, size, size);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
highlight("slot_highlight_front");
|
|
||||||
|
|
||||||
// mods' overlays go on top and get the mouse first, then the slots get what they left
|
// mods' overlays go on top and get the mouse first, then the slots get what they left
|
||||||
|
g.origin_x = g.origin_y = 0;
|
||||||
this.#render_overlays();
|
this.#render_overlays();
|
||||||
if (this.graphics.mouse_blocked()) {
|
if (g.mouse_blocked()) {
|
||||||
this.hovering = undefined;
|
this.hovering = undefined;
|
||||||
} else {
|
} else {
|
||||||
this.handle_interaction();
|
this.handle_interaction();
|
||||||
@@ -130,28 +107,62 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
draw_item(this.inventories.cursor.item, mouse.x, mouse.y);
|
draw_item(this.inventories.cursor.item, mouse.x, mouse.y);
|
||||||
} else if (this.hovering) {
|
} else if (this.hovering) {
|
||||||
// what's in the slot under the mouse, while not carrying anything
|
// what's in the slot under the mouse, while not carrying anything
|
||||||
const item = this.get_container(this.hovering.container)?.get_item(this.hovering.index);
|
const item = this.hovering.container.get_item(this.hovering.index);
|
||||||
if (item) {
|
if (item) {
|
||||||
draw_tooltip(item_tooltip(item), mouse.x, mouse.y);
|
draw_tooltip(item_tooltip(item), mouse.x, mouse.y);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.graphics.end();
|
g.end();
|
||||||
|
}
|
||||||
|
|
||||||
|
#slot_x(slot: ClientSlot) {
|
||||||
|
return this.x + slot.x * GUI_SCALE;
|
||||||
|
}
|
||||||
|
|
||||||
|
#slot_y(slot: ClientSlot) {
|
||||||
|
return this.y + slot.y * GUI_SCALE;
|
||||||
|
}
|
||||||
|
|
||||||
|
#render_slots() {
|
||||||
|
for (const slot of this.menu.slots) {
|
||||||
|
draw_gui_sprite("slot", this.#slot_x(slot), this.#slot_y(slot));
|
||||||
|
}
|
||||||
|
|
||||||
|
// like minecraft's, the highlight is a bit bigger than the slot, part of it under the item and part over
|
||||||
|
const highlight = (sprite: "slot_highlight_back" | "slot_highlight_front") => {
|
||||||
|
if (this.hovering) {
|
||||||
|
const x = this.#slot_x(this.hovering) - HIGHLIGHT_OVERHANG;
|
||||||
|
draw_gui_sprite(sprite, x, this.#slot_y(this.hovering) - HIGHLIGHT_OVERHANG);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
highlight("slot_highlight_back");
|
||||||
|
for (const slot of this.menu.slots) {
|
||||||
|
const item = slot.container.get_item(slot.index);
|
||||||
|
if (item) {
|
||||||
|
draw_item(item, this.#slot_x(slot), this.#slot_y(slot));
|
||||||
|
} else if (slot.icon) {
|
||||||
|
// where an item's sprite would be
|
||||||
|
const icon = get_sprite_region(slot.icon);
|
||||||
|
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
||||||
|
const [x, y, size] = [this.#slot_x(slot) + 3, this.#slot_y(slot) + 3, SLOT_SIZE - 6];
|
||||||
|
draw_texture_region(atlas, icon.x, icon.y, icon.width, icon.height, x, y, size, size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
highlight("slot_highlight_front");
|
||||||
}
|
}
|
||||||
|
|
||||||
#render_overlays() {
|
#render_overlays() {
|
||||||
const g = this.graphics;
|
const hovered = this.hovering && this.hovering.container.get_item(this.hovering.index);
|
||||||
g.begin();
|
|
||||||
const hovered = this.hovering && this.get_container(this.hovering.container)?.get_item(this.hovering.index);
|
|
||||||
const view = {
|
const view = {
|
||||||
x: this.x,
|
x: this.x / GUI_SCALE,
|
||||||
y: this.y,
|
y: this.y / GUI_SCALE,
|
||||||
width: this.inventory_width,
|
width: this.width,
|
||||||
height: this.inventory_height,
|
height: this.height,
|
||||||
hovered_item: hovered ? { id: hovered.type_id, count: hovered.amount, data: hovered.data } : undefined,
|
hovered_item: hovered ? { id: hovered.type_id, count: hovered.amount, data: hovered.data } : undefined,
|
||||||
};
|
};
|
||||||
for (const entry of [...inventory_overlays]) {
|
for (const entry of [...inventory_overlays]) {
|
||||||
try {
|
try {
|
||||||
entry.overlay.on_render(g, view);
|
entry.overlay.on_render(this.graphics, view);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// a broken overlay is taken off, not left to throw every frame
|
// a broken overlay is taken off, not left to throw every frame
|
||||||
console.error(`[${entry.mod}] inventory overlay threw, removing it:`, e);
|
console.error(`[${entry.mod}] inventory overlay threw, removing it:`, e);
|
||||||
@@ -160,19 +171,32 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override on_removed(): void {
|
||||||
|
for (const entry of [...inventory_overlays]) {
|
||||||
|
try {
|
||||||
|
entry.overlay.on_close?.();
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${entry.mod}] inventory overlay's on_close threw, removing it:`, e);
|
||||||
|
inventory_overlays.splice(inventory_overlays.indexOf(entry), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
on_close(): void {
|
on_close(): void {
|
||||||
this.send({ type: "close_screen" });
|
this.send({ type: "close_menu", menu: this.menu.id });
|
||||||
|
|
||||||
// the server puts these back in the inventory, show it right away
|
// the server puts these back in the inventory, show it right away
|
||||||
const { inventory, crafting, cursor } = this.inventories;
|
const { inventory, crafting, cursor } = this.inventories;
|
||||||
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
|
if (this.menu.id === PLAYER_MENU) {
|
||||||
const item = crafting.get_item(i);
|
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
|
||||||
if (item) {
|
const item = crafting.get_item(i);
|
||||||
inventory.add_item(item);
|
if (item) {
|
||||||
crafting.set_item(i, undefined);
|
inventory.add_item(item);
|
||||||
|
crafting.set_item(i, undefined);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
crafting.set_item(CRAFTING_RESULT_SLOT, undefined);
|
||||||
}
|
}
|
||||||
crafting.set_item(CRAFTING_RESULT_SLOT, undefined);
|
|
||||||
if (cursor.item) {
|
if (cursor.item) {
|
||||||
inventory.add_item(cursor.item);
|
inventory.add_item(cursor.item);
|
||||||
cursor.item = undefined;
|
cursor.item = undefined;
|
||||||
@@ -183,9 +207,9 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
this.hovering = undefined;
|
this.hovering = undefined;
|
||||||
const mouse = InputManager.get_mouse_position();
|
const mouse = InputManager.get_mouse_position();
|
||||||
|
|
||||||
for (const slot of this.slots) {
|
for (const [index, slot] of this.menu.slots.entries()) {
|
||||||
const hovering = point_inside_rec(mouse.x, mouse.y, this.x + slot.x, this.y + slot.y, SLOT_SIZE, SLOT_SIZE);
|
const [x, y] = [this.#slot_x(slot), this.#slot_y(slot)];
|
||||||
if (!hovering) {
|
if (!point_inside_rec(mouse.x, mouse.y, x, y, SLOT_SIZE, SLOT_SIZE)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
this.hovering = slot;
|
this.hovering = slot;
|
||||||
@@ -193,40 +217,22 @@ export class GuiInventoryScreen extends GuiScreen {
|
|||||||
for (const button of [0, 2]) {
|
for (const button of [0, 2]) {
|
||||||
if (InputManager.is_mouse_pressed(button)) {
|
if (InputManager.is_mouse_pressed(button)) {
|
||||||
InputManager.consume_mouse(button);
|
InputManager.consume_mouse(button);
|
||||||
this.click(slot, button);
|
this.click(index, button);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
click(slot: Slot, button: number) {
|
click(index: number, button: number) {
|
||||||
|
const slot = this.menu.slots[index];
|
||||||
const shift = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight");
|
const shift = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight");
|
||||||
this.send({ type: "click", container: slot.container, index: slot.index, button, shift });
|
this.send({ type: "click", menu: this.menu.id, slot: index, button, shift });
|
||||||
|
|
||||||
// output slots depend on server side things like recipes, and where a shift click goes on slot filters only the
|
// output slots depend on server side things like recipes, and where a shift click goes on slot filters only the
|
||||||
// server has, just wait for the server
|
// server has, just wait for the server
|
||||||
const container = this.get_container(slot.container);
|
if (!slot.output && !shift) {
|
||||||
if (container && !slot.output && !shift) {
|
click_slot(slot.container, slot.index, this.inventories.cursor, button);
|
||||||
click_slot(container, slot.index, this.inventories.cursor, button);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// generic methods that is often needed
|
|
||||||
|
|
||||||
export function add_player_inventory(handler: GuiInventoryScreen, offset_x: number, offset_y: number) {
|
|
||||||
for (let i = 0; i < 3; ++i) {
|
|
||||||
for (let l = 0; l < 9; ++l) {
|
|
||||||
handler.slots.push(
|
|
||||||
new Slot("inventory", l + i * 9 + 9, offset_x + l * SLOT_SIZE, offset_y + i * SLOT_SIZE),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export function add_player_hotbar(handler: GuiInventoryScreen, offset_x: number, offset_y: number) {
|
|
||||||
for (let i = 0; i < 9; ++i) {
|
|
||||||
handler.slots.push(new Slot("inventory", i, offset_x + i * SLOT_SIZE, offset_y));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+64
-43
@@ -1,6 +1,6 @@
|
|||||||
// the immediate mode drawing mods' client scripts get (Graphics in common/mod_api/client.ts), on top of the renderer.
|
// the immediate mode drawing mods' client scripts get (Graphics in common/mod_api/client.ts), on top of the renderer.
|
||||||
// one per screen, so text inputs keep their text and focus while it's open
|
// one per screen, so text inputs keep their text and focus while it's open. mods work in gui pixels, GUI_SCALE canvas
|
||||||
import { SLOT_SIZE } from "$/common/constants.ts";
|
// pixels each
|
||||||
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "$/common/inventory.ts";
|
||||||
import type { Color, Graphics } from "$/common/mod_api/client.ts";
|
import type { Color, Graphics } from "$/common/mod_api/client.ts";
|
||||||
@@ -30,28 +30,39 @@ const GREY: Color = [0.66, 0.66, 0.66, 1];
|
|||||||
const INPUT_HEIGHT = 32;
|
const INPUT_HEIGHT = 32;
|
||||||
const FIELD_BORDER = GUI_ATLAS.text_field.border[0] * GUI_SCALE;
|
const FIELD_BORDER = GUI_ATLAS.text_field.border[0] * GUI_SCALE;
|
||||||
|
|
||||||
|
// gui pixels to the canvas's, see GUI_SCALE
|
||||||
|
const S = GUI_SCALE;
|
||||||
|
|
||||||
export class ModGraphics implements Graphics {
|
export class ModGraphics implements Graphics {
|
||||||
|
// where gui pixel 0, 0 is on the canvas: a menu screen's top left, or the window's
|
||||||
|
origin_x = 0;
|
||||||
|
origin_y = 0;
|
||||||
// text inputs by id, and which one has the keyboard
|
// text inputs by id, and which one has the keyboard
|
||||||
#inputs = new Map<string, TextInput>();
|
#inputs = new Map<string, TextInput>();
|
||||||
#focused: string | undefined;
|
#focused: string | undefined;
|
||||||
#tooltip: { lines: TooltipLine[]; x: number; y: number } | undefined;
|
#tooltip: { lines: TooltipLine[]; x: number; y: number } | undefined;
|
||||||
// areas the screen underneath shouldn't take the mouse in, this frame
|
// areas the screen underneath shouldn't take the mouse in this frame, on the canvas
|
||||||
#blocked: { x: number; y: number; w: number; h: number }[] = [];
|
#blocked: { x: number; y: number; w: number; h: number }[] = [];
|
||||||
#clicks_consumed = false;
|
#clicks_consumed = false;
|
||||||
|
|
||||||
|
// the whole window, in gui pixels
|
||||||
get width() {
|
get width() {
|
||||||
return canvas.width;
|
return canvas.width / S;
|
||||||
}
|
}
|
||||||
|
|
||||||
get height() {
|
get height() {
|
||||||
return canvas.height;
|
return canvas.height / S;
|
||||||
|
}
|
||||||
|
|
||||||
|
get text_height() {
|
||||||
|
return TEXT_HEIGHT * TEXT_SCALE / S;
|
||||||
}
|
}
|
||||||
|
|
||||||
get mouse() {
|
get mouse() {
|
||||||
const { x, y } = InputManager.get_mouse_position();
|
const { x, y } = InputManager.get_mouse_position();
|
||||||
return {
|
return {
|
||||||
x,
|
x: (x - this.origin_x) / S,
|
||||||
y,
|
y: (y - this.origin_y) / S,
|
||||||
down: InputManager.is_mouse_down(0),
|
down: InputManager.is_mouse_down(0),
|
||||||
pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(0),
|
pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(0),
|
||||||
right_pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(2),
|
right_pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(2),
|
||||||
@@ -77,39 +88,49 @@ export class ModGraphics implements Graphics {
|
|||||||
|
|
||||||
// whether the screen underneath should ignore the mouse
|
// whether the screen underneath should ignore the mouse
|
||||||
mouse_blocked() {
|
mouse_blocked() {
|
||||||
const { x, y } = this.mouse;
|
const { x, y } = InputManager.get_mouse_position();
|
||||||
return this.#clicks_consumed || this.#blocked.some((r) => point_inside_rec(x, y, r.x, r.y, r.w, r.h));
|
return this.#clicks_consumed || this.#blocked.some((r) => point_inside_rec(x, y, r.x, r.y, r.w, r.h));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// a gui position on the canvas
|
||||||
|
#x(x: number) {
|
||||||
|
return this.origin_x + x * S;
|
||||||
|
}
|
||||||
|
|
||||||
|
#y(y: number) {
|
||||||
|
return this.origin_y + y * S;
|
||||||
|
}
|
||||||
|
|
||||||
rect(x: number, y: number, w: number, h: number, color: Color = WHITE) {
|
rect(x: number, y: number, w: number, h: number, color: Color = WHITE) {
|
||||||
draw_rect(x, y, w, h, color);
|
draw_rect(this.#x(x), this.#y(y), w * S, h * S, color);
|
||||||
}
|
}
|
||||||
|
|
||||||
panel(x: number, y: number, w: number, h: number) {
|
panel(x: number, y: number, w: number, h: number) {
|
||||||
draw_gui_sprite("panel", x, y, w, h);
|
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 } = {}) {
|
text(text: string, x: number, y: number, options: { scale?: number; color?: Color } = {}) {
|
||||||
draw_text(text, x, y, options.scale ?? TEXT_SCALE, options.color ?? WHITE);
|
draw_text(text, this.#x(x), this.#y(y), TEXT_SCALE * (options.scale ?? 1), options.color ?? WHITE);
|
||||||
}
|
}
|
||||||
|
|
||||||
measure_text(text: string, scale = TEXT_SCALE) {
|
measure_text(text: string, scale = 1) {
|
||||||
return measure_text(text, scale);
|
return measure_text(text, TEXT_SCALE * scale) / S;
|
||||||
}
|
}
|
||||||
|
|
||||||
texture(id: string, x: number, y: number, w: number, h: number) {
|
texture(id: string, x: number, y: number, w: number, h: number, part = [0, 0, 1, 1]) {
|
||||||
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
|
||||||
const region = get_sprite_region(id);
|
const region = get_sprite_region(id);
|
||||||
|
const [u, v, pw, ph] = part;
|
||||||
draw_texture_region(
|
draw_texture_region(
|
||||||
atlas,
|
atlas,
|
||||||
region.x,
|
region.x + region.width * u,
|
||||||
region.y,
|
region.y + region.height * v,
|
||||||
region.width,
|
region.width * pw,
|
||||||
region.height,
|
region.height * ph,
|
||||||
x,
|
this.#x(x),
|
||||||
y,
|
this.#y(y),
|
||||||
w,
|
w * S,
|
||||||
h,
|
h * S,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -118,10 +139,14 @@ export class ModGraphics implements Graphics {
|
|||||||
const stack = new ItemStack(id, count);
|
const stack = new ItemStack(id, count);
|
||||||
// the count only shows when it's more than one
|
// the count only shows when it's more than one
|
||||||
if (count === 1) stack.max_amount = 1;
|
if (count === 1) stack.max_amount = 1;
|
||||||
draw_item(stack, x, y);
|
draw_item(stack, this.#x(x), this.#y(y));
|
||||||
}
|
}
|
||||||
|
|
||||||
clip(x: number, y: number, w: number, h: number, draw: () => void) {
|
clip(x: number, y: number, w: number, h: number, draw: () => void) {
|
||||||
|
this.#clip_canvas(this.#x(x), this.#y(y), w * S, h * S, draw);
|
||||||
|
}
|
||||||
|
|
||||||
|
#clip_canvas(x: number, y: number, w: number, h: number, draw: () => void) {
|
||||||
begin_clip(x, y, w, h);
|
begin_clip(x, y, w, h);
|
||||||
try {
|
try {
|
||||||
draw();
|
draw();
|
||||||
@@ -132,9 +157,10 @@ export class ModGraphics implements Graphics {
|
|||||||
|
|
||||||
button(label: string, x: number, y: number, w: number, h: number): boolean {
|
button(label: string, x: number, y: number, w: number, h: number): boolean {
|
||||||
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, h);
|
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, h);
|
||||||
draw_gui_sprite(hovered ? "button_highlighted" : "button", x, y, w, h);
|
const [cx, cy, cw, ch] = [this.#x(x), this.#y(y), w * S, h * S];
|
||||||
|
draw_gui_sprite(hovered ? "button_highlighted" : "button", cx, cy, cw, ch);
|
||||||
const text_width = measure_text(label, TEXT_SCALE);
|
const text_width = measure_text(label, TEXT_SCALE);
|
||||||
draw_text(label, x + (w - text_width) / 2, y + (h - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE, WHITE);
|
draw_text(label, cx + (cw - text_width) / 2, cy + (ch - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE, WHITE);
|
||||||
if (hovered && this.mouse.pressed) {
|
if (hovered && this.mouse.pressed) {
|
||||||
this.consume_click();
|
this.consume_click();
|
||||||
return true;
|
return true;
|
||||||
@@ -142,15 +168,17 @@ export class ModGraphics implements Graphics {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// INPUT_HEIGHT canvas pixels tall
|
||||||
text_input(id: string, x: number, y: number, w: number): string {
|
text_input(id: string, x: number, y: number, w: number): string {
|
||||||
let input = this.#inputs.get(id);
|
let input = this.#inputs.get(id);
|
||||||
if (!input) {
|
if (!input) {
|
||||||
input = new TextInput("", 256);
|
input = new TextInput("", 256);
|
||||||
this.#inputs.set(id, input);
|
this.#inputs.set(id, input);
|
||||||
}
|
}
|
||||||
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, INPUT_HEIGHT);
|
const [cx, cy, cw] = [this.#x(x), this.#y(y), w * S];
|
||||||
|
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, INPUT_HEIGHT / S);
|
||||||
if (this.#focused === id || (hovered && this.mouse.pressed)) {
|
if (this.#focused === id || (hovered && this.mouse.pressed)) {
|
||||||
input.handle_mouse({ x, y, width: w, height: INPUT_HEIGHT }, x + 6);
|
input.handle_mouse({ x: cx, y: cy, width: cw, height: INPUT_HEIGHT }, cx + 6);
|
||||||
}
|
}
|
||||||
if (this.mouse.pressed) {
|
if (this.mouse.pressed) {
|
||||||
if (hovered) {
|
if (hovered) {
|
||||||
@@ -169,15 +197,15 @@ export class ModGraphics implements Graphics {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
draw_gui_sprite(focused ? "text_field_highlighted" : "text_field", x, y, w, INPUT_HEIGHT);
|
draw_gui_sprite(focused ? "text_field_highlighted" : "text_field", cx, cy, cw, INPUT_HEIGHT);
|
||||||
// inside the field's border, so long text doesn't go over it
|
// inside the field's border, so long text doesn't go over it
|
||||||
this.clip(x + FIELD_BORDER, y + 2, w - FIELD_BORDER * 2, INPUT_HEIGHT - 4, () => {
|
this.#clip_canvas(cx + FIELD_BORDER, cy + 2, cw - FIELD_BORDER * 2, INPUT_HEIGHT - 4, () => {
|
||||||
if (focused) {
|
if (focused) {
|
||||||
input.draw_selection(x + 6, y + 6, INPUT_HEIGHT - 12);
|
input.draw_selection(cx + 6, cy + 6, INPUT_HEIGHT - 12);
|
||||||
}
|
}
|
||||||
draw_text(input.value, x + 6, y + 4, TEXT_SCALE, WHITE);
|
draw_text(input.value, cx + 6, cy + 4, TEXT_SCALE, WHITE);
|
||||||
if (focused && TextInput.caret_visible()) {
|
if (focused && TextInput.caret_visible()) {
|
||||||
draw_rect(input.caret_x(x + 6), y + 6, 2, INPUT_HEIGHT - 12, WHITE);
|
draw_rect(input.caret_x(cx + 6), cy + 6, 2, INPUT_HEIGHT - 12, WHITE);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return input.value;
|
return input.value;
|
||||||
@@ -187,10 +215,6 @@ export class ModGraphics implements Graphics {
|
|||||||
throw new Error("g.slider isn't implemented yet");
|
throw new Error("g.slider isn't implemented yet");
|
||||||
}
|
}
|
||||||
|
|
||||||
slots(): void {
|
|
||||||
throw new Error("g.slots isn't implemented yet");
|
|
||||||
}
|
|
||||||
|
|
||||||
key_pressed(key: KeyCode): boolean {
|
key_pressed(key: KeyCode): boolean {
|
||||||
return !this.typing && InputManager.is_key_pressed(key as InputKey);
|
return !this.typing && InputManager.is_key_pressed(key as InputKey);
|
||||||
}
|
}
|
||||||
@@ -202,8 +226,8 @@ export class ModGraphics implements Graphics {
|
|||||||
? { text: line, color: WHITE }
|
? { text: line, color: WHITE }
|
||||||
: { text: line.text, color: line.color ?? WHITE }
|
: { text: line.text, color: line.color ?? WHITE }
|
||||||
),
|
),
|
||||||
x,
|
x: this.#x(x),
|
||||||
y,
|
y: this.#y(y),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,11 +238,11 @@ export class ModGraphics implements Graphics {
|
|||||||
typeof line === "string" ? { text: line, color: GREY } : { text: line.text, color: line.color ?? GREY }
|
typeof line === "string" ? { text: line, color: GREY } : { text: line.text, color: line.color ?? GREY }
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
this.#tooltip = { lines, x, y };
|
this.#tooltip = { lines, x: this.#x(x), y: this.#y(y) };
|
||||||
}
|
}
|
||||||
|
|
||||||
block_mouse(x: number, y: number, w: number, h: number) {
|
block_mouse(x: number, y: number, w: number, h: number) {
|
||||||
this.#blocked.push({ x, y, w, h });
|
this.#blocked.push({ x: this.#x(x), y: this.#y(y), w: w * S, h: h * S });
|
||||||
}
|
}
|
||||||
|
|
||||||
consume_click() {
|
consume_click() {
|
||||||
@@ -227,6 +251,3 @@ export class ModGraphics implements Graphics {
|
|||||||
InputManager.consume_mouse(2);
|
InputManager.consume_mouse(2);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// how big an item is drawn, for laying out around g.item
|
|
||||||
export const ITEM_SIZE = SLOT_SIZE;
|
|
||||||
|
|||||||
@@ -4,8 +4,6 @@ import { Container, Cursor } from "$/common/inventory.ts";
|
|||||||
export class ClientInventories {
|
export class ClientInventories {
|
||||||
inventory = new Container(9 * 4);
|
inventory = new Container(9 * 4);
|
||||||
crafting = new Container(10);
|
crafting = new Container(10);
|
||||||
// the open server screen's container
|
|
||||||
screen: Container | undefined;
|
|
||||||
cursor: Cursor = { item: undefined };
|
cursor: Cursor = { item: undefined };
|
||||||
hotbar_selected = 0;
|
hotbar_selected = 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// the client's copy of a menu, like neoforge's client menu: built from what the server sent when it opened, kept up
|
||||||
|
// to date with what it syncs. clicks go to the server, which decides what they do
|
||||||
|
import { Container } from "$/common/inventory.ts";
|
||||||
|
import { CRAFTING_RESULT_SLOT, type MenuSlotInfo, PLAYER_MENU, PLAYER_MENU_CRAFTING } from "$/common/protocol.ts";
|
||||||
|
import type { ClientInventories } from "./inventory.ts";
|
||||||
|
|
||||||
|
export interface ClientSlot {
|
||||||
|
// where its item is on this client
|
||||||
|
container: Container;
|
||||||
|
index: number;
|
||||||
|
// gui pixels from the screen's top left to its frame
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
// can only be taken from, like the crafting or furnace result
|
||||||
|
output: boolean;
|
||||||
|
// a texture drawn while it's empty, like minecraft's armor slots
|
||||||
|
icon: string | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ClientMenu {
|
||||||
|
readonly id: number;
|
||||||
|
readonly type: string;
|
||||||
|
readonly title: string;
|
||||||
|
readonly open_data: unknown;
|
||||||
|
data: Record<string, number>;
|
||||||
|
slots: ClientSlot[];
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
id: number,
|
||||||
|
type: string,
|
||||||
|
title: string,
|
||||||
|
open_data: unknown,
|
||||||
|
slots: ClientSlot[],
|
||||||
|
data: Record<string, number> = {},
|
||||||
|
) {
|
||||||
|
this.id = id;
|
||||||
|
this.type = type;
|
||||||
|
this.title = title;
|
||||||
|
this.open_data = open_data;
|
||||||
|
this.slots = slots;
|
||||||
|
this.data = data;
|
||||||
|
}
|
||||||
|
|
||||||
|
// one the server opened: its slots' items come in menu_content, into a container of its own
|
||||||
|
static opened(id: number, type: string, title: string, open_data: unknown, slots: MenuSlotInfo[]) {
|
||||||
|
const items = new Container(slots.length);
|
||||||
|
return new ClientMenu(
|
||||||
|
id,
|
||||||
|
type,
|
||||||
|
title,
|
||||||
|
open_data,
|
||||||
|
slots.map((slot, index) => ({
|
||||||
|
container: items,
|
||||||
|
index,
|
||||||
|
x: slot.x,
|
||||||
|
y: slot.y,
|
||||||
|
output: slot.output === true,
|
||||||
|
icon: slot.icon,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// menu 0, the player's inventory and crafting grid, laid out for the inventory screen. its slots are the player's
|
||||||
|
// own containers, which the server syncs whether or not a menu is open
|
||||||
|
export function player_menu(inventories: ClientInventories): ClientMenu {
|
||||||
|
const slot = (container: Container, index: number, x: number, y: number, output = false): ClientSlot => ({
|
||||||
|
container,
|
||||||
|
index,
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
output,
|
||||||
|
icon: undefined,
|
||||||
|
});
|
||||||
|
const slots: ClientSlot[] = [];
|
||||||
|
for (let i = 0; i < 36; i++) {
|
||||||
|
const row = Math.floor(i / 9);
|
||||||
|
slots.push(slot(inventories.inventory, i, 7 + (i % 9) * 18, i < 9 ? 141 : 83 + (row - 1) * 18));
|
||||||
|
}
|
||||||
|
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
|
||||||
|
slots.push(slot(inventories.crafting, i, 25 + (i % 3) * 18, 16 + Math.floor(i / 3) * 18));
|
||||||
|
}
|
||||||
|
slots.push(slot(inventories.crafting, CRAFTING_RESULT_SLOT, 115, 34, true));
|
||||||
|
if (slots.length !== PLAYER_MENU_CRAFTING + CRAFTING_RESULT_SLOT + 1) throw new Error("menu 0 has the wrong slots");
|
||||||
|
return new ClientMenu(PLAYER_MENU, "", "Crafting", null, slots);
|
||||||
|
}
|
||||||
+22
-9
@@ -2,7 +2,7 @@
|
|||||||
// see docs/modding/networking/index.md
|
// see docs/modding/networking/index.md
|
||||||
import { AIR } from "$/common/constants.ts";
|
import { AIR } from "$/common/constants.ts";
|
||||||
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
||||||
import type { ClientContext, InventoryOverlay } from "$/common/mod_api/client.ts";
|
import type { ClientContext, ClientMenu, InventoryOverlay, MenuScreen } from "$/common/mod_api/client.ts";
|
||||||
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
|
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
|
||||||
import { type Bmod, read_bmod } from "$/common/bmod.ts";
|
import { type Bmod, read_bmod } from "$/common/bmod.ts";
|
||||||
import { display_name } from "$/common/utils.ts";
|
import { display_name } from "$/common/utils.ts";
|
||||||
@@ -10,6 +10,7 @@ import { tag_api } from "$/common/tags.ts";
|
|||||||
import { AIR_ID } from "$/common/protocol.ts";
|
import { AIR_ID } from "$/common/protocol.ts";
|
||||||
import type { Client } from "./client.ts";
|
import type { Client } from "./client.ts";
|
||||||
import { code_url, fetch_verified } from "./handshake.ts";
|
import { code_url, fetch_verified } from "./handshake.ts";
|
||||||
|
import { GuiModScreen } from "./gui/gui_mod_screens.ts";
|
||||||
|
|
||||||
// each loaded mod's credits file, for the credits screen
|
// each loaded mod's credits file, for the credits screen
|
||||||
export const mod_credits: { name: string; version: string; text: string }[] = [];
|
export const mod_credits: { name: string; version: string; text: string }[] = [];
|
||||||
@@ -20,6 +21,9 @@ let client: Client | undefined;
|
|||||||
// what mods draw on inventory screens, see GuiInventoryScreen
|
// what mods draw on inventory screens, see GuiInventoryScreen
|
||||||
export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = [];
|
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 }>();
|
||||||
|
|
||||||
// mod channels, see ctx.net: who listens on each channel
|
// mod channels, see ctx.net: who listens on each channel
|
||||||
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => void }[]>();
|
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => void }[]>();
|
||||||
|
|
||||||
@@ -68,6 +72,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
|
|||||||
const recipes = register_mod_data(bmods.map((bmod) => ({ id: bmod.manifest.id, data: bmod.data })));
|
const recipes = register_mod_data(bmods.map((bmod) => ({ id: bmod.manifest.id, data: bmod.data })));
|
||||||
recipe_book = recipes;
|
recipe_book = recipes;
|
||||||
inventory_overlays.length = 0;
|
inventory_overlays.length = 0;
|
||||||
|
menu_screens.clear();
|
||||||
net_handlers.clear();
|
net_handlers.clear();
|
||||||
mod_names.clear();
|
mod_names.clear();
|
||||||
for (const listing of listings) mod_names.set(listing.id, listing.name);
|
for (const listing of listings) mod_names.set(listing.id, listing.name);
|
||||||
@@ -101,12 +106,9 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
return client;
|
return client;
|
||||||
};
|
};
|
||||||
|
|
||||||
const not_yet_fn = (name: string) => () => {
|
const own = (id: string, what = "channel") => {
|
||||||
throw new Error(`[${mod}] ctx.ui.${name} isn't implemented yet (custom screens, see docs/modding_plan.md)`);
|
if (!id.startsWith(`${mod}:`)) {
|
||||||
};
|
throw new Error(`[${mod}] ${what} ${id} must be in the namespace "${mod}"`);
|
||||||
const own = (channel: string) => {
|
|
||||||
if (!channel.startsWith(`${mod}:`)) {
|
|
||||||
throw new Error(`[${mod}] channel ${channel} must be in the namespace "${mod}"`);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const known_item = (id: string) => {
|
const known_item = (id: string) => {
|
||||||
@@ -118,8 +120,19 @@ function client_context(listing: ModListing): ClientContext {
|
|||||||
return {
|
return {
|
||||||
mod: { id: mod, version: listing.version },
|
mod: { id: mod, version: listing.version },
|
||||||
ui: {
|
ui: {
|
||||||
register_screen: not_yet_fn("register_screen"),
|
register_menu_screen(type, create) {
|
||||||
open: not_yet_fn("open"),
|
own(type, "menu type");
|
||||||
|
if (menu_screens.has(type)) throw new Error(`[${mod}] ${type} already has a screen`);
|
||||||
|
menu_screens.set(type, { mod, create });
|
||||||
|
},
|
||||||
|
open(screen) {
|
||||||
|
if (typeof screen?.on_render !== "function") throw new Error(`[${mod}] a screen needs an on_render`);
|
||||||
|
const game = need_client();
|
||||||
|
game.push_screen(new GuiModScreen(game, mod, screen));
|
||||||
|
},
|
||||||
|
close() {
|
||||||
|
need_client().pop_screen();
|
||||||
|
},
|
||||||
add_inventory_overlay(overlay) {
|
add_inventory_overlay(overlay) {
|
||||||
inventory_overlays.push({ mod, overlay });
|
inventory_overlays.push({ mod, overlay });
|
||||||
},
|
},
|
||||||
|
|||||||
+48
-26
@@ -1,13 +1,14 @@
|
|||||||
import type { ServerMessage } from "$/common/protocol.ts";
|
import type { ServerMessage } from "$/common/protocol.ts";
|
||||||
import { Container, ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "$/common/inventory.ts";
|
||||||
import type { Client } from "./client.ts";
|
import type { Client } from "./client.ts";
|
||||||
import { GuiContainer } from "./gui/gui_container.ts";
|
import { GuiModMenuScreen } from "./gui/gui_mod_screens.ts";
|
||||||
|
import { ClientMenu } from "./menu.ts";
|
||||||
import { GuiChat } from "./gui/gui_chat.ts";
|
import { GuiChat } from "./gui/gui_chat.ts";
|
||||||
import { RemotePlayer } from "./entity/remote_player.ts";
|
import { RemotePlayer } from "./entity/remote_player.ts";
|
||||||
import { ItemEntity } from "./entity/item_entity.ts";
|
import { ItemEntity } from "./entity/item_entity.ts";
|
||||||
import { RemoteEntity } from "./entity/remote_entity.ts";
|
import { RemoteEntity } from "./entity/remote_entity.ts";
|
||||||
import { Player } from "./entity/player.ts";
|
import { Player } from "./entity/player.ts";
|
||||||
import { receive_mod_message } from "./mods.ts";
|
import { menu_screens, receive_mod_message } from "./mods.ts";
|
||||||
|
|
||||||
// minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as
|
// minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as
|
||||||
// fit in CHUNK_BUDGET_MS
|
// fit in CHUNK_BUDGET_MS
|
||||||
@@ -197,32 +198,24 @@ export class ClientPacketListener {
|
|||||||
client.screen.receive_suggestions(message);
|
client.screen.receive_suggestions(message);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "container": {
|
case "container":
|
||||||
let container = message.container === "screen" ? inventories.screen : inventories[message.container];
|
inventories[message.container]?.load(message.items);
|
||||||
if (message.container === "screen" && container?.size !== message.items.length) {
|
|
||||||
container = inventories.screen = new Container(message.items.length);
|
|
||||||
}
|
|
||||||
container?.load(message.items);
|
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
case "cursor":
|
case "cursor":
|
||||||
inventories.cursor.item = message.item ? ItemStack.from_data(message.item) : undefined;
|
inventories.cursor.item = message.item ? ItemStack.from_data(message.item) : undefined;
|
||||||
break;
|
break;
|
||||||
case "open_screen": {
|
case "open_menu":
|
||||||
// replace anything open locally without telling the server, it just opened this one
|
this.#open_menu(message);
|
||||||
client.screens.length = 0;
|
break;
|
||||||
const size = Math.max(0, ...message.layout.slots.map((slot) => slot.index + 1));
|
case "menu_content": {
|
||||||
inventories.screen = new Container(size);
|
const menu = this.#menu(message.id);
|
||||||
client.push_screen(
|
// every slot's item is in the menu's own container, at the slot's index
|
||||||
new GuiContainer(inventories, (m) => client.connection.send(m), message.layout, message.properties),
|
menu?.slots[0]?.container.load(message.items);
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "screen_properties": {
|
case "menu_data": {
|
||||||
const screen = client.screen;
|
const menu = this.#menu(message.id);
|
||||||
if (screen instanceof GuiContainer) {
|
if (menu) menu.data = message.data;
|
||||||
screen.properties = message.properties;
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "teleport": {
|
case "teleport": {
|
||||||
@@ -243,11 +236,40 @@ export class ClientPacketListener {
|
|||||||
case "mod":
|
case "mod":
|
||||||
receive_mod_message(message.channel, message.data);
|
receive_mod_message(message.channel, message.data);
|
||||||
break;
|
break;
|
||||||
case "close_screen":
|
case "close_menu":
|
||||||
// closed by the server (the block broke), it already put everything back
|
// closed by the server (the block broke), it already put everything back
|
||||||
client.screens = client.screens.filter((s) => !(s instanceof GuiContainer));
|
client.remove_screens((s) => s instanceof GuiModMenuScreen && s.menu.id === message.id);
|
||||||
inventories.screen = undefined;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the open menu with this id, if it's still open here
|
||||||
|
#menu(id: number): ClientMenu | undefined {
|
||||||
|
const screen = this.client.screens.find((s) => s instanceof GuiModMenuScreen && s.menu.id === id);
|
||||||
|
return (screen as GuiModMenuScreen | undefined)?.menu;
|
||||||
|
}
|
||||||
|
|
||||||
|
#open_menu(message: Extract<ServerMessage, { type: "open_menu" }>) {
|
||||||
|
const client = this.client;
|
||||||
|
const close = () => client.connection.send({ type: "close_menu", menu: message.id });
|
||||||
|
const registered = menu_screens.get(message.menu_type);
|
||||||
|
if (!registered) {
|
||||||
|
console.error(`No screen for the menu type ${message.menu_type}, closing it`);
|
||||||
|
close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const menu = ClientMenu.opened(message.id, message.menu_type, message.title, message.open_data, message.slots);
|
||||||
|
menu.data = message.data;
|
||||||
|
let screen: GuiModMenuScreen;
|
||||||
|
try {
|
||||||
|
screen = new GuiModMenuScreen(client, registered.mod, menu, registered.create);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[${registered.mod}] the ${message.menu_type} screen threw, closing it:`, e);
|
||||||
|
close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// replace anything open locally without telling the server, it just opened this one
|
||||||
|
client.remove_screens(() => true);
|
||||||
|
client.push_screen(screen);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
// commands the way minecraft's brigadier (and so fabric's command api) does them: a tree of literal words and typed
|
// commands the way minecraft's brigadier (and so neoforge's commands) does them: a tree of literal words and typed
|
||||||
// arguments, each argument type parsing its text and suggesting what could go there. the server runs them, and players
|
// arguments, each argument type parsing its text and suggesting what could go there. the server runs them, and players
|
||||||
// get its suggestions as they type. see docs/modding/misc/commands.md
|
// get its suggestions as they type. see docs/modding/misc/commands.md
|
||||||
import { EverythingRegistry } from "./everything_registry.ts";
|
import { EverythingRegistry } from "./everything_registry.ts";
|
||||||
|
|||||||
@@ -150,7 +150,7 @@ export interface BlockRegistry {
|
|||||||
compiled_states?: CompiledStateDefinition[];
|
compiled_states?: CompiledStateDefinition[];
|
||||||
}
|
}
|
||||||
|
|
||||||
// what a tool is made of, like fabric's ToolMaterial
|
// what a tool is made of, like minecraft's ToolMaterial
|
||||||
export interface ToolProperties {
|
export interface ToolProperties {
|
||||||
// like "pickaxe", matched against blocks' tool_to_break
|
// like "pickaxe", matched against blocks' tool_to_break
|
||||||
type: string;
|
type: string;
|
||||||
|
|||||||
+17
-21
@@ -299,43 +299,39 @@ function right_click(container: Container, index: number, cursor: Cursor) {
|
|||||||
slot.amount = half;
|
slot.amount = half;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// a slot of some container, menus' slots can come from several
|
||||||
|
export interface SlotRef {
|
||||||
|
container: Container;
|
||||||
|
index: number;
|
||||||
|
}
|
||||||
|
|
||||||
// shift clicking, like minecraft's moveItemStackTo: tops up stacks of the same item in these slots, in order, then
|
// shift clicking, like minecraft's moveItemStackTo: tops up stacks of the same item in these slots, in order, then
|
||||||
// fills empty ones. what doesn't fit stays in the item
|
// fills empty ones. what doesn't fit stays in the item
|
||||||
export function move_into(
|
export function move_into(item: ItemStack, slots: SlotRef[], accepts: (slot: SlotRef) => boolean = () => true) {
|
||||||
item: ItemStack,
|
for (const slot of slots) {
|
||||||
container: Container,
|
const there = slot.container.get_item(slot.index);
|
||||||
slots: number[],
|
|
||||||
accepts: (index: number) => boolean = () => true,
|
|
||||||
) {
|
|
||||||
for (const index of slots) {
|
|
||||||
const there = container.get_item(index);
|
|
||||||
if (item.amount <= 0) return;
|
if (item.amount <= 0) return;
|
||||||
if (there && there !== item && there.type_id === item.type_id && accepts(index)) {
|
if (there && there !== item && there.type_id === item.type_id && accepts(slot)) {
|
||||||
const moving = Math.min(there.max_amount - there.amount, item.amount);
|
const moving = Math.min(there.max_amount - there.amount, item.amount);
|
||||||
there.amount += moving;
|
there.amount += moving;
|
||||||
item.amount -= moving;
|
item.amount -= moving;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const index of slots) {
|
for (const slot of slots) {
|
||||||
if (item.amount <= 0) return;
|
if (item.amount <= 0) return;
|
||||||
if (!container.get_item(index) && accepts(index)) {
|
if (!slot.container.get_item(slot.index) && accepts(slot)) {
|
||||||
container.set_item(index, item.clone());
|
slot.container.set_item(slot.index, item.clone());
|
||||||
item.amount = 0;
|
item.amount = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// how many of the item move_into could put in these slots
|
// how many of the item move_into could put in these slots
|
||||||
export function room_for(
|
export function room_for(item: ItemStack, slots: SlotRef[], accepts: (slot: SlotRef) => boolean = () => true): number {
|
||||||
item: ItemStack,
|
|
||||||
container: Container,
|
|
||||||
slots: number[],
|
|
||||||
accepts: (index: number) => boolean = () => true,
|
|
||||||
): number {
|
|
||||||
let room = 0;
|
let room = 0;
|
||||||
for (const index of slots) {
|
for (const slot of slots) {
|
||||||
const there = container.get_item(index);
|
const there = slot.container.get_item(slot.index);
|
||||||
if (!accepts(index)) continue;
|
if (!accepts(slot)) continue;
|
||||||
if (!there) room += item.max_amount;
|
if (!there) room += item.max_amount;
|
||||||
else if (there.type_id === item.type_id) room += there.max_amount - there.amount;
|
else if (there.type_id === item.type_id) room += there.max_amount - there.amount;
|
||||||
}
|
}
|
||||||
|
|||||||
+54
-16
@@ -35,36 +35,69 @@ export interface ClientContext {
|
|||||||
log(...args: unknown[]): void;
|
log(...args: unknown[]): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ModScreen<Props = unknown> {
|
// a screen with no menu, only on this client, like neoforge's Screen. see docs/modding/gui/index.md
|
||||||
on_open?(): void;
|
export interface Screen {
|
||||||
on_tick?(dt: number): void;
|
// when it opens, and whenever the window changes size. in gui pixels
|
||||||
|
on_init?(width: number, height: number): void;
|
||||||
|
// 20 times a second
|
||||||
|
on_tick?(): void;
|
||||||
on_render(g: Graphics): void;
|
on_render(g: Graphics): void;
|
||||||
// the server sent new props for this screen
|
// true when not set
|
||||||
on_props?(props: Props): void;
|
should_close_on_escape?(): boolean;
|
||||||
|
// the player closed it, with escape
|
||||||
on_close?(): void;
|
on_close?(): void;
|
||||||
// return true to keep the screen open when escape is pressed
|
// it's gone for any reason, including another screen replacing it
|
||||||
on_escape?(): boolean;
|
on_removed?(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// the client side of a menu the server opened, see docs/modding/inventories/menus.md
|
||||||
|
export interface ClientMenu {
|
||||||
|
readonly type: Id;
|
||||||
|
readonly title: string;
|
||||||
|
// what the server's build function set, sent once
|
||||||
|
readonly open_data: unknown;
|
||||||
|
// the server's latest values of its add_data numbers
|
||||||
|
readonly data: Readonly<Record<string, number>>;
|
||||||
|
// like clickMenuButton, the server's on_button decides what it does
|
||||||
|
click_button(id: number): void;
|
||||||
|
close(): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// draws a menu, like neoforge's AbstractContainerScreen. the engine puts it in the middle of the window, and draws
|
||||||
|
// the menu's slots, the item on the cursor and item tooltips. g's 0, 0 is the screen's top left
|
||||||
|
export interface MenuScreen {
|
||||||
|
// in gui pixels, like imageWidth and imageHeight
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
// under the slots
|
||||||
|
on_render_background?(g: Graphics): void;
|
||||||
|
// over the slots
|
||||||
|
on_render_labels?(g: Graphics): void;
|
||||||
|
// 20 times a second, like containerTick
|
||||||
|
on_tick?(): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Color = [number, number, number, number];
|
export type Color = [number, number, number, number];
|
||||||
|
|
||||||
// immediate mode drawing, like the debug ui, styled with the gui sprites (assets/sprites/gui.png)
|
// immediate mode drawing, like the debug ui, styled with the gui sprites (assets/sprites/gui.png). everything is in
|
||||||
|
// gui pixels, like neoforge's: 18 of them are a slot
|
||||||
export interface Graphics {
|
export interface Graphics {
|
||||||
readonly width: number;
|
readonly width: number;
|
||||||
readonly height: number;
|
readonly height: number;
|
||||||
readonly mouse: { x: number; y: number; down: boolean; pressed: boolean; right_pressed: boolean };
|
readonly mouse: { x: number; y: number; down: boolean; pressed: boolean; right_pressed: boolean };
|
||||||
rect(x: number, y: number, w: number, h: number, color?: Color): void;
|
rect(x: number, y: number, w: number, h: number, color?: Color): void;
|
||||||
panel(x: number, y: number, w: number, h: number): void;
|
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;
|
text(text: string, x: number, y: number, options?: { scale?: number; color?: Color }): void;
|
||||||
measure_text(text: string, scale?: number): number;
|
measure_text(text: string, scale?: number): number;
|
||||||
texture(id: Id, x: number, y: number, w: number, h: number): void;
|
// 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;
|
||||||
item(id: Id, x: number, y: number, count?: number): void;
|
item(id: Id, x: number, y: number, count?: number): void;
|
||||||
clip(x: number, y: number, w: number, h: number, draw: () => void): void;
|
clip(x: number, y: number, w: number, h: number, draw: () => void): void;
|
||||||
button(label: string, x: number, y: number, w: number, h: number): boolean;
|
button(label: string, x: number, y: number, w: number, h: number): boolean;
|
||||||
text_input(id: string, x: number, y: number, w: number): string;
|
text_input(id: string, x: number, y: number, w: number): string;
|
||||||
slider(id: string, x: number, y: number, w: number, min: number, max: number): number;
|
slider(id: string, x: number, y: number, w: number, min: number, max: number): number;
|
||||||
// server synced slots, same rules as container screens
|
|
||||||
slots(container: string, layout: { slot: number; x: number; y: number }[], x: number, y: number): void;
|
|
||||||
// false while a text input has the keyboard
|
// false while a text input has the keyboard
|
||||||
key_pressed(key: KeyCode): boolean;
|
key_pressed(key: KeyCode): boolean;
|
||||||
// shown next to the mouse over everything else, the last one this frame wins
|
// shown next to the mouse over everything else, the last one this frame wins
|
||||||
@@ -77,10 +110,12 @@ export interface Graphics {
|
|||||||
block_mouse(x: number, y: number, w: number, h: number): void;
|
block_mouse(x: number, y: number, w: number, h: number): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
// drawn on every inventory screen (the player's inventory, chests, furnaces...), over it, like just enough items'
|
// drawn on every menu's screen (the player's inventory, chests, furnaces...), over it, like just enough items' item
|
||||||
// item list. it gets the screen's box to lay itself out around
|
// list. it gets the screen's box to lay itself out around
|
||||||
export interface InventoryOverlay {
|
export interface InventoryOverlay {
|
||||||
on_render(g: Graphics, screen: InventoryScreenView): void;
|
on_render(g: Graphics, screen: InventoryScreenView): void;
|
||||||
|
// the screen closed for any reason, like the player closing their inventory
|
||||||
|
on_close?(): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface InventoryScreenView {
|
export interface InventoryScreenView {
|
||||||
@@ -93,9 +128,12 @@ export interface InventoryScreenView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface ClientUi {
|
export interface ClientUi {
|
||||||
register_screen<Props>(id: Id, create: (props: Props) => ModScreen<Props>): void;
|
// the screen for a menu type of this mod, like RegisterMenuScreensEvent. called each time one opens
|
||||||
// open a screen that doesn't involve the server, like a settings page
|
register_menu_screen(type: Id, create: (menu: ClientMenu) => MenuScreen): void;
|
||||||
open<Props>(id: Id, props: Props): void;
|
// a screen that doesn't involve the server, like a settings page, over whatever's open
|
||||||
|
open(screen: Screen): void;
|
||||||
|
// closes the screen on top
|
||||||
|
close(): void;
|
||||||
add_inventory_overlay(overlay: InventoryOverlay): void;
|
add_inventory_overlay(overlay: InventoryOverlay): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+58
-43
@@ -18,6 +18,7 @@ export interface ServerContext {
|
|||||||
items: ItemApi;
|
items: ItemApi;
|
||||||
recipes: RecipeApi;
|
recipes: RecipeApi;
|
||||||
tags: TagApi;
|
tags: TagApi;
|
||||||
|
menus: MenuRegistry;
|
||||||
ui: ServerUi;
|
ui: ServerUi;
|
||||||
net: ServerNet;
|
net: ServerNet;
|
||||||
storage: ModStorage;
|
storage: ModStorage;
|
||||||
@@ -62,7 +63,7 @@ export interface ComponentRegistry {
|
|||||||
register_item<P>(id: Id, component: ItemComponent<P>): void;
|
register_item<P>(id: Id, component: ItemComponent<P>): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
// commands, fabric's (brigadier's) way: see common/commands.ts and docs/modding/misc/commands.md
|
// commands, brigadier's way like neoforge's: see common/commands.ts and docs/modding/misc/commands.md
|
||||||
|
|
||||||
// who ran a command
|
// who ran a command
|
||||||
export interface CommandSource {
|
export interface CommandSource {
|
||||||
@@ -79,7 +80,7 @@ export interface Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface CommandRegistry {
|
export interface CommandRegistry {
|
||||||
// a tree of literal() and argument() nodes, like fabric's dispatcher.register(literal("heal").then(...))
|
// a tree of literal() and argument() nodes, like neoforge's dispatcher.register(literal("heal").then(...))
|
||||||
register(node: CommandNode<CommandSource>): void;
|
register(node: CommandNode<CommandSource>): void;
|
||||||
register(name: string, command: Command): void;
|
register(name: string, command: Command): void;
|
||||||
literal(name: string): CommandNode<CommandSource>;
|
literal(name: string): CommandNode<CommandSource>;
|
||||||
@@ -304,7 +305,7 @@ export interface RecipeApi {
|
|||||||
list(type: Id): any[];
|
list(type: Id): any[];
|
||||||
}
|
}
|
||||||
|
|
||||||
// guis
|
// forms, not built yet: menus whose screens the engine provides, see docs/modding_plan.md
|
||||||
|
|
||||||
export interface ActionForm {
|
export interface ActionForm {
|
||||||
title: string;
|
title: string;
|
||||||
@@ -331,60 +332,74 @@ export interface ModalForm {
|
|||||||
|
|
||||||
export type FormResult<T> = ({ canceled: true } & Partial<T>) | ({ canceled: false } & T);
|
export type FormResult<T> = ({ canceled: true } & Partial<T>) | ({ canceled: false } & T);
|
||||||
|
|
||||||
|
// menus, like neoforge's: the server side of a gui, see docs/modding/inventories/menus.md
|
||||||
|
|
||||||
export type SlotFilter = "smeltable" | "fuel" | ((item: ItemStack) => boolean);
|
export type SlotFilter = "smeltable" | "fuel" | ((item: ItemStack) => boolean);
|
||||||
|
|
||||||
export interface ContainerScreenOptions {
|
export interface SlotOptions {
|
||||||
container: Container;
|
// gui pixels from the screen's top left to the slot's 18 pixel frame
|
||||||
// x and y in slot units, below the player's inventory. can be fractional
|
x: number;
|
||||||
layout: {
|
y: number;
|
||||||
slot: number;
|
// what can be put in, checked on the server
|
||||||
x: number;
|
filter?: SlotFilter;
|
||||||
y: number;
|
// can only be taken from, all at once, like the furnace result
|
||||||
// what can be put in, checked on the server
|
output_only?: boolean;
|
||||||
filter?: SlotFilter;
|
// runs when a player takes from an output_only slot, before they get it. false stops them taking it
|
||||||
// can only be taken from, all at once, like the furnace result
|
on_take?: (item: ItemStack) => boolean;
|
||||||
output_only?: boolean;
|
// a texture drawn in the slot while it's empty, like minecraft's armor slots
|
||||||
// runs when a player takes from an output_only slot, before they get it. false stops them taking it
|
icon?: Id;
|
||||||
on_take?: (item: ItemStack) => boolean;
|
|
||||||
// a texture drawn in the slot while it's empty, like minecraft's armor slots
|
|
||||||
icon?: Id;
|
|
||||||
}[];
|
|
||||||
// height of the screen's area in slots, fits the layout and bars when not set
|
|
||||||
rows?: number;
|
|
||||||
// progress bars, filled with the property value divided by the property max
|
|
||||||
bars?: {
|
|
||||||
x: number;
|
|
||||||
y: number;
|
|
||||||
value: string;
|
|
||||||
max: string;
|
|
||||||
direction: "up" | "right";
|
|
||||||
empty_texture: Id;
|
|
||||||
full_texture: Id;
|
|
||||||
}[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ScreenHandle<Props = unknown> {
|
// what a menu type's build function gets, like neoforge's server menu constructor
|
||||||
|
export interface MenuBuilder {
|
||||||
|
title: string;
|
||||||
|
// sent to the client once when it opens, any json up to 16 KB, like IContainerFactory's extra data
|
||||||
|
open_data: unknown;
|
||||||
|
// a slot of a container from ctx.containers, or of player.inventory. returns its menu slot index
|
||||||
|
add_slot(container: Container, slot: number, options: SlotOptions): number;
|
||||||
|
// the player's 36 slots, like addStandardInventorySlots: the rest of the inventory in 3 rows from x and y, the
|
||||||
|
// hotbar 58 pixels under them. added in inventory order, so inventory slot i is the returned index plus i
|
||||||
|
add_player_inventory(x: number, y: number): number;
|
||||||
|
// a number the screen shows, like DataSlot: read every tick and sent when it changes
|
||||||
|
add_data(name: string, get: () => number): void;
|
||||||
|
// checked every tick, false closes it
|
||||||
|
still_valid(check: (player: Player) => boolean): void;
|
||||||
|
// closes it when the player is over 8 blocks from the block, or it's been broken or replaced
|
||||||
|
still_valid_near(block: BlockRef): void;
|
||||||
|
// a button the client pressed, like clickMenuButton. any number can come, check it
|
||||||
|
on_button(fn: (player: Player, id: number) => void): void;
|
||||||
|
// shift clicks: the menu slot indexes the stack in this one tries, in order. the default rule when not set
|
||||||
|
quick_move(fn: (player: Player, index: number) => number[]): void;
|
||||||
|
on_tick(fn: () => void): void;
|
||||||
|
// when it closes for any reason: the player closed it, left, opened another, or it was closed
|
||||||
|
on_close(fn: () => void): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MenuHandle {
|
||||||
readonly player: Player;
|
readonly player: Player;
|
||||||
readonly open: boolean;
|
readonly open: boolean;
|
||||||
// numbers the bars show, synced to the player when they change
|
|
||||||
set_property(id: string, value: number): void;
|
|
||||||
update(props: Props): void; // custom screens only
|
|
||||||
close(): void;
|
close(): void;
|
||||||
// when it closes for any reason: the player closed it, left, opened another screen, or it was closed
|
|
||||||
on_close(fn: () => void): void;
|
on_close(fn: () => void): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MenuType<Args> {
|
||||||
|
readonly id: Id;
|
||||||
|
// like openMenu: builds a menu for the player with these args and opens it, closing whatever they had open
|
||||||
|
open(player: Player, args: Args): MenuHandle;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MenuRegistry {
|
||||||
|
// like registering a MenuType. the client script gives it a screen with ctx.ui.register_menu_screen
|
||||||
|
register<Args = undefined>(
|
||||||
|
id: Id,
|
||||||
|
build: (menu: MenuBuilder, args: Args, player: Player) => void,
|
||||||
|
): MenuType<Args>;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ServerUi {
|
export interface ServerUi {
|
||||||
message_form(player: Player, form: MessageForm): Promise<FormResult<{ selection: 0 | 1 }>>;
|
message_form(player: Player, form: MessageForm): Promise<FormResult<{ selection: 0 | 1 }>>;
|
||||||
action_form(player: Player, form: ActionForm): Promise<FormResult<{ selection: number }>>;
|
action_form(player: Player, form: ActionForm): Promise<FormResult<{ selection: number }>>;
|
||||||
modal_form(player: Player, form: ModalForm): Promise<FormResult<{ values: (boolean | number | string)[] }>>;
|
modal_form(player: Player, form: ModalForm): Promise<FormResult<{ values: (boolean | number | string)[] }>>;
|
||||||
open_container(player: Player, options: ContainerScreenOptions): ScreenHandle;
|
|
||||||
open_screen<Props>(
|
|
||||||
player: Player,
|
|
||||||
id: Id,
|
|
||||||
props: Props,
|
|
||||||
options?: { containers?: Record<string, Container> },
|
|
||||||
): ScreenHandle<Props>;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// mod channels
|
// mod channels
|
||||||
|
|||||||
+1
-1
@@ -19,7 +19,7 @@ export const NAMESPACE_PATTERN = /^[a-z0-9_]{1,32}$/;
|
|||||||
export const RESERVED_NAMESPACES = ["bworld", "engine"];
|
export const RESERVED_NAMESPACES = ["bworld", "engine"];
|
||||||
// a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md
|
// a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md
|
||||||
export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/;
|
export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/;
|
||||||
// the namespace for tags every mod shares, like neoforge's and fabric's. no mod owns it
|
// the namespace for tags every mod shares, like neoforge's. no mod owns it
|
||||||
export const SHARED_TAG_NAMESPACE = "c";
|
export const SHARED_TAG_NAMESPACE = "c";
|
||||||
export const TAG_REGISTRIES = ["blocks", "items", "entities"] as const;
|
export const TAG_REGISTRIES = ["blocks", "items", "entities"] as const;
|
||||||
export type TagRegistry = typeof TAG_REGISTRIES[number];
|
export type TagRegistry = typeof TAG_REGISTRIES[number];
|
||||||
|
|||||||
+42
-29
@@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air";
|
|||||||
|
|
||||||
// bump when a client and server of different versions can't play together.
|
// bump when a client and server of different versions can't play together.
|
||||||
// the server rejects a different version before the client downloads anything
|
// the server rejects a different version before the client downloads anything
|
||||||
export const PROTOCOL_VERSION = 13;
|
export const PROTOCOL_VERSION = 14;
|
||||||
|
|
||||||
export interface PlayerInfo {
|
export interface PlayerInfo {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -52,28 +52,24 @@ export type EntityEvent = "hurt" | "death" | "swing";
|
|||||||
// x, y, z, block id, and its state bits when they aren't 0
|
// x, y, z, block id, and its state bits when they aren't 0
|
||||||
export type BlockChange = [number, number, number, string, number?];
|
export type BlockChange = [number, number, number, string, number?];
|
||||||
|
|
||||||
// the containers a client can see and click. "screen" is whatever the open server screen shows
|
// the player's own containers, synced to them whether or not a menu is open
|
||||||
export type ContainerKey = "inventory" | "crafting" | "screen";
|
export type ContainerKey = "inventory" | "crafting";
|
||||||
|
|
||||||
export const CRAFTING_RESULT_SLOT = 9;
|
export const CRAFTING_RESULT_SLOT = 9;
|
||||||
|
|
||||||
// a screen the server opens, drawn below the player's inventory and hotbar
|
// menus, like neoforge's: the server's menu decides what every click does, clients draw it and send clicks by menu
|
||||||
export interface ScreenLayout {
|
// slot index. menu 0 is the player's own inventory and crafting grid, always there and never opened or sent, like
|
||||||
// height of the screen's own area, in slots
|
// minecraft's InventoryMenu: slots 0-35 are the inventory (the hotbar is 0-8), 36-45 the crafting grid
|
||||||
rows: number;
|
export const PLAYER_MENU = 0;
|
||||||
// x and y in slots, can be fractional
|
export const PLAYER_MENU_CRAFTING = 36;
|
||||||
// output slots can only be taken from, like the furnace result. icon is a texture drawn in the slot while it's empty
|
|
||||||
slots: { index: number; x: number; y: number; output?: boolean; icon?: string }[];
|
// one slot of an opened menu as the client draws it. x and y in gui pixels from the screen's top left, output slots
|
||||||
// progress bars filled from properties[value] / properties[max]
|
// can only be taken from, icon is a texture drawn while it's empty
|
||||||
bars: {
|
export interface MenuSlotInfo {
|
||||||
x: number;
|
x: number;
|
||||||
y: number;
|
y: number;
|
||||||
value: string;
|
output?: boolean;
|
||||||
max: string;
|
icon?: string;
|
||||||
direction: "up" | "right";
|
|
||||||
empty_texture: string;
|
|
||||||
full_texture: string;
|
|
||||||
}[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// clients send what the player is trying to do, the server decides what happens
|
// clients send what the player is trying to do, the server decides what happens
|
||||||
@@ -100,12 +96,15 @@ export type ClientMessage =
|
|||||||
// right click on a block: interact with it, or place the held block against `face`
|
// right click on a block: interact with it, or place the held block against `face`
|
||||||
| { type: "use_block"; x: number; y: number; z: number; face: Faces }
|
| { type: "use_block"; x: number; y: number; z: number; face: Faces }
|
||||||
| { type: "select_slot"; slot: number }
|
| { type: "select_slot"; slot: number }
|
||||||
// shift moves the stack to the other part of the screen instead, like minecraft's quick move
|
// a slot of the open menu, or of menu 0 when none is. shift moves the stack to the other part of the menu instead,
|
||||||
| { type: "click"; container: ContainerKey; index: number; button: number; shift?: boolean }
|
// like minecraft's quick move. clicks for a menu that isn't open any more are ignored
|
||||||
// q on a slot (the held one when no screen is open) throws one item, or the whole stack with ctrl
|
| { type: "click"; menu: number; slot: number; button: number; shift?: boolean }
|
||||||
| { type: "drop_item"; container: ContainerKey; index: number; all: boolean }
|
// q on a slot (the held one when no screen is open, in menu 0) throws one item, or the whole stack with ctrl
|
||||||
// closes the open screen, including the player's own inventory screen
|
| { type: "drop_item"; menu: number; slot: number; all: boolean }
|
||||||
| { type: "close_screen" }
|
// a button of the open menu, like minecraft's clickMenuButton. the menu decides what the number means
|
||||||
|
| { type: "menu_button"; menu: number; button: number }
|
||||||
|
// closes the open menu, or the player's own inventory screen with 0
|
||||||
|
| { type: "close_menu"; menu: number }
|
||||||
| { type: "chat"; text: string }
|
| { type: "chat"; text: string }
|
||||||
// what could come next in a command being typed, answered with suggestions. id matches them up
|
// what could come next in a command being typed, answered with suggestions. id matches them up
|
||||||
| { type: "suggest"; id: number; text: string }
|
| { type: "suggest"; id: number; text: string }
|
||||||
@@ -186,9 +185,23 @@ export type ServerMessage =
|
|||||||
| { type: "teleport"; id: number; x: number; y: number; z: number; motion?: [number, number, number] }
|
| { type: "teleport"; id: number; x: number; y: number; z: number; motion?: [number, number, number] }
|
||||||
| { type: "container"; container: ContainerKey; items: (ItemData | null)[] }
|
| { type: "container"; container: ContainerKey; items: (ItemData | null)[] }
|
||||||
| { type: "cursor"; item: ItemData | null }
|
| { type: "cursor"; item: ItemData | null }
|
||||||
| { type: "open_screen"; layout: ScreenLayout; properties: Record<string, number> }
|
// a menu opened, replacing any other. id counts 1 to 100 and around, type is the menu type whose screen draws it.
|
||||||
| { type: "screen_properties"; properties: Record<string, number> }
|
// its slots' items come in menu_content, its data's changes in menu_data
|
||||||
| { type: "close_screen" }
|
| {
|
||||||
|
type: "open_menu";
|
||||||
|
id: number;
|
||||||
|
menu_type: string;
|
||||||
|
title: string;
|
||||||
|
open_data: unknown;
|
||||||
|
slots: MenuSlotInfo[];
|
||||||
|
data: Record<string, number>;
|
||||||
|
}
|
||||||
|
// what's in every slot of the open menu, by menu slot index, when any of it changed
|
||||||
|
| { type: "menu_content"; id: number; items: (ItemData | null)[] }
|
||||||
|
// all the menu's data, when any of it changed
|
||||||
|
| { type: "menu_data"; id: number; data: Record<string, number> }
|
||||||
|
// the server closed it (the block broke, the player walked away), it already put everything back
|
||||||
|
| { type: "close_menu"; id: number }
|
||||||
// the world time, every second and when it's changed. clients count ticks in between
|
// the world time, every second and when it's changed. clients count ticks in between
|
||||||
| { type: "time"; time: number }
|
| { type: "time"; time: number }
|
||||||
// answers suggest: start is where in the text the suggestions replace from, up to the caret
|
// answers suggest: start is where in the text the suggestions replace from, up to the caret
|
||||||
|
|||||||
@@ -25,8 +25,8 @@ ctx.components.register_block("copper_tools:counter", {
|
|||||||
Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it.
|
Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it.
|
||||||
|
|
||||||
- Tile data is saved with the world, and goes away when the block is broken or replaced.
|
- Tile data is saved with the world, and goes away when the block is broken or replaced.
|
||||||
- It's **never sent to clients**. To show it to a player, open a [container screen](../inventories/menus.md), or change
|
- It's **never sent to clients**. To show it to a player, open a [menu](../inventories/menus.md), or change a block
|
||||||
a block state that the block's `variants` show.
|
state that the block's `variants` show.
|
||||||
- Only blocks with tile data run `on_tick`, `on_second` and `on_new_day`.
|
- Only blocks with tile data run `on_tick`, `on_second` and `on_new_day`.
|
||||||
|
|
||||||
## Blocks With Containers
|
## Blocks With Containers
|
||||||
|
|||||||
@@ -92,4 +92,4 @@ seed and chunk always give the same blocks. See [World Generation](../worldgen/i
|
|||||||
| Server script code | yes | **never** |
|
| Server script code | yes | **never** |
|
||||||
|
|
||||||
When a client needs to see something only the server has, the server has to send it: open a
|
When a client needs to see something only the server has, the server has to send it: open a
|
||||||
[container screen](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows.
|
[menu](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows.
|
||||||
|
|||||||
+61
-18
@@ -2,16 +2,54 @@
|
|||||||
|
|
||||||
There are a few ways for a mod to show players a GUI. Pick the first one that's enough:
|
There are a few ways for a mod to show players a GUI. Pick the first one that's enough:
|
||||||
|
|
||||||
| Way | Code | For |
|
| Way | Code | For |
|
||||||
| -------------------------------------------- | ------------- | ---------------------------------------------------------- |
|
| ----------------------------------------- | ------------------ | --------------------------------------------------------- |
|
||||||
| [Container screens](../inventories/menus.md) | server only | Inventories and machines: slots, filters, progress bars |
|
| [Menus](../inventories/menus.md) | server, and client | Inventories and machines: slots, filters, progress bars |
|
||||||
| [Inventory overlays](#inventory-overlays) | client only | Drawing next to every inventory screen, like a recipe list |
|
| [Plain screens](#plain-screens) | client only | Screens with nothing the server checks: maps, guide books |
|
||||||
| Forms, custom screens and HUD elements | not built yet | See [below](#not-built-yet) |
|
| [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) |
|
||||||
|
|
||||||
|
Everything is in **GUI pixels**, like NeoForge's: 18 of them are a slot, and the game draws each one 3 screen pixels
|
||||||
|
wide.
|
||||||
|
|
||||||
|
## Plain Screens
|
||||||
|
|
||||||
|
A screen with no menu is only on the client, like NeoForge's `Screen`. Open one with `ctx.ui.open(screen)`, over
|
||||||
|
whatever's open:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
let smelted = 0;
|
||||||
|
ctx.net.on("copper_tools:stats", (data: { smelted: number }) => {
|
||||||
|
smelted = data.smelted;
|
||||||
|
ctx.ui.open({
|
||||||
|
on_render(g) {
|
||||||
|
g.panel(g.width / 2 - 70, 20, 140, 40);
|
||||||
|
g.text(`Smelted: ${smelted}`, g.width / 2 - 60, 30);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface Screen {
|
||||||
|
on_init?(width: number, height: number): void; // opening, and whenever the window changes size
|
||||||
|
on_tick?(): void; // 20 times a second
|
||||||
|
on_render(g: Graphics): void; // every frame
|
||||||
|
should_close_on_escape?(): boolean; // true when not set
|
||||||
|
on_close?(): void; // the player closed it
|
||||||
|
on_removed?(): void; // it's gone for any reason, including another screen replacing it
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The server can't open one directly. Like a NeoForge payload handler calling `setScreen`, the server sends a
|
||||||
|
[mod channel](../networking/index.md) message, and the client script's handler opens it, as above. A screen that needs
|
||||||
|
to tell the server something sends a message back the same way. `ctx.ui.close()` closes the screen on top. A screen that
|
||||||
|
throws is closed, with the error in the console.
|
||||||
|
|
||||||
## Inventory Overlays
|
## Inventory Overlays
|
||||||
|
|
||||||
An inventory overlay draws on every inventory screen (the player's inventory, chests, furnaces and every other container
|
An inventory overlay draws on every menu's screen (the player's inventory, chests, furnaces and every mod's menus), over
|
||||||
screen), over the screen, like Just Enough Items' item list. `mods/recipe_viewer` is one.
|
the screen, like Just Enough Items' item list. `mods/recipe_viewer` is one.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import type { ClientContext } from "bworld/client";
|
import type { ClientContext } from "bworld/client";
|
||||||
@@ -20,14 +58,15 @@ export function setup(ctx: ClientContext) {
|
|||||||
ctx.ui.add_inventory_overlay({
|
ctx.ui.add_inventory_overlay({
|
||||||
on_render(g, screen) {
|
on_render(g, screen) {
|
||||||
// screen is the inventory's box, and what's in the slot under the mouse
|
// screen is the inventory's box, and what's in the slot under the mouse
|
||||||
const x = screen.x + screen.width + 16;
|
const x = screen.x + screen.width + 5;
|
||||||
if (screen.hovered_item) g.text(ctx.items.name(screen.hovered_item.id), x, 16);
|
if (screen.hovered_item) g.text(ctx.items.name(screen.hovered_item.id), x, 5);
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`on_render` runs every frame the screen is open, with a [`Graphics`](#graphics) to draw with and the screen's box:
|
`on_render` runs every frame the screen is open, with a [`Graphics`](#graphics) to draw with and the screen's box, in
|
||||||
|
GUI pixels from the window's top left:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
interface InventoryScreenView {
|
interface InventoryScreenView {
|
||||||
@@ -46,24 +85,30 @@ Overlays get the mouse before the slots:
|
|||||||
- While a `g.text_input` has the keyboard, keybinds like the inventory key don't fire. Text inputs edit like chat:
|
- While a `g.text_input` has the keyboard, keybinds like the inventory key don't fire. Text inputs edit like chat:
|
||||||
selecting with shift or the mouse, ctrl+a, and copy, cut and paste.
|
selecting with shift or the mouse, ctrl+a, and copy, cut and paste.
|
||||||
|
|
||||||
|
`on_close()`, if the overlay has one, runs when the screen closes for any reason, like the player closing their
|
||||||
|
inventory. The recipe viewer goes back to its item list then.
|
||||||
|
|
||||||
An overlay that throws is removed, with the error in the console.
|
An overlay that throws is removed, with the error in the console.
|
||||||
|
|
||||||
## Graphics
|
## Graphics
|
||||||
|
|
||||||
`Graphics` is an immediate mode drawing API: every frame, draw everything again, and ask widgets like `button` what
|
`Graphics` is an immediate mode drawing API: every frame, draw everything again, and ask widgets like `button` what
|
||||||
happened. It's styled with the game's GUI sprites.
|
happened. It's styled with the game's GUI sprites. Positions and sizes are GUI pixels, from the window's top left, or
|
||||||
|
from a menu screen's.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
interface Graphics {
|
interface Graphics {
|
||||||
readonly width: number; // the screen, in pixels
|
readonly width: number; // the window, in gui pixels
|
||||||
readonly height: number;
|
readonly height: number;
|
||||||
|
readonly text_height: number; // a line of text at scale 1
|
||||||
readonly mouse: { x: number; y: number; down: boolean; pressed: boolean; right_pressed: boolean };
|
readonly mouse: { x: number; y: number; down: boolean; pressed: boolean; right_pressed: boolean };
|
||||||
|
|
||||||
rect(x: number, y: number, w: number, h: number, color?: [r, g, b, a]): void;
|
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
|
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;
|
text(text: string, x: number, y: number, options?: { scale?: number; color?: [r, g, b, a] }): void; // scale 1 is normal
|
||||||
measure_text(text: string, scale?: number): number;
|
measure_text(text: string, scale?: number): number;
|
||||||
texture(id: string, x: number, y: number, w: number, h: number): void; // any texture
|
// 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;
|
||||||
item(id: string, x: number, y: number, count?: number): void; // an item as a slot shows it
|
item(id: string, x: number, y: number, count?: number): void; // an item as a slot shows it
|
||||||
clip(x: number, y: number, w: number, h: number, draw: () => void): void; // only draws inside the box
|
clip(x: number, y: number, w: number, h: number, draw: () => void): void; // only draws inside the box
|
||||||
|
|
||||||
@@ -81,7 +126,7 @@ interface Graphics {
|
|||||||
Colors are `[r, g, b, a]` from 0 to 1. The last `tooltip` drawn in a frame is the one shown, and `item_tooltip` shows
|
Colors are `[r, g, b, a]` from 0 to 1. The last `tooltip` drawn in a frame is the one shown, and `item_tooltip` shows
|
||||||
the game's own tooltip for an item (its name, food, durability and lore) with extra lines under it.
|
the game's own tooltip for an item (its name, food, durability and lore) with extra lines under it.
|
||||||
|
|
||||||
`slider` and `slots` are in the type but not built yet.
|
`slider` is in the type but not built yet.
|
||||||
|
|
||||||
## Reading Game State
|
## Reading Game State
|
||||||
|
|
||||||
@@ -106,9 +151,7 @@ ctx.recipes.list(type?); // every recipe as its JSON, including mods' own types
|
|||||||
The client and server APIs have types for these, but calling them throws for now:
|
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
|
- **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.
|
the server script, like Bedrock's server forms. They'll be menus whose screens the engine draws.
|
||||||
- **Custom screens** (`ctx.ui.register_screen` and `open` on the client, `open_screen` on the server): whole screens
|
|
||||||
drawn with `Graphics`, opened by the server with some props.
|
|
||||||
- **HUD elements** (`ctx.hud.register`): drawing over the world every frame.
|
- **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
|
- **Keybinds** (`ctx.input.bind`). Until then, an inventory overlay can check `g.key_pressed` while an inventory is
|
||||||
open.
|
open.
|
||||||
|
|||||||
@@ -42,4 +42,4 @@ Changes are synced to every player viewing the container, whether a script or a
|
|||||||
|
|
||||||
A player's inventory is a container too, `player.inventory`, with the hotbar in slots 0-8.
|
A player's inventory is a container too, `player.inventory`, with the hotbar in slots 0-8.
|
||||||
|
|
||||||
To let players see and use a container, open a [container screen](menus.md) for it.
|
To let players see and use a container, give them a [menu](menus.md) with its slots.
|
||||||
|
|||||||
@@ -1,99 +1,197 @@
|
|||||||
# Container Screens
|
# Menus
|
||||||
|
|
||||||
A container screen shows a [container](containers.md)'s slots to a player, above their own inventory and hotbar, so they
|
Menus are how players use [containers](containers.md), like NeoForge's. A GUI has two halves:
|
||||||
can move items in and out. Chests, furnaces, the smithing table and Farmer's Delight's cooking pot are all container
|
|
||||||
screens. They're defined entirely by the server script, so they need no client code.
|
|
||||||
|
|
||||||
Every click goes to the server, which applies it following the screen's rules, and everyone viewing the container sees
|
- The **menu** lives in the server script. It decides which slots the player can click, what goes in them, the numbers
|
||||||
the result.
|
the screen shows, what its buttons do, and when it closes.
|
||||||
|
- The **screen** lives in the client script. It only draws the menu and sends the player's clicks.
|
||||||
|
|
||||||
## Opening a Screen
|
Every click goes to the server, which applies it following the menu's rules, so a modified client can only do what the
|
||||||
|
menu allows. Chests, furnaces, the smithing table, Farmer's Delight's cooking pot and Curios are all menus.
|
||||||
|
|
||||||
Usually from a block's `on_interact`:
|
## Registering a Menu Type
|
||||||
|
|
||||||
|
A menu type is registered in the server script with a function that builds each menu when it opens, like NeoForge's
|
||||||
|
`MenuType` and its server menu constructor. It gets the menu to build, whatever the code opening it passes, and the
|
||||||
|
player:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
ctx.components.register_block("copper_tools:smelter", {
|
// server.ts
|
||||||
on_create(block) {
|
export function setup(ctx: ServerContext) {
|
||||||
block.data = { container: ctx.containers.create(3).id, progress: 0 };
|
const smelter = ctx.menus.register<BlockRef>("copper_tools:smelter", (menu, block, player) => {
|
||||||
},
|
const container = ctx.containers.get(block.data.container)!;
|
||||||
on_interact(block, _params, player) {
|
menu.title = "Smelter";
|
||||||
const screen = ctx.ui.open_container(player, {
|
menu.add_slot(container, 0, { x: 55, y: 16, filter: "smeltable" });
|
||||||
container: ctx.containers.get(block.data.container)!,
|
menu.add_slot(container, 1, { x: 55, y: 52, filter: "fuel" });
|
||||||
layout: [
|
menu.add_slot(container, 2, { x: 115, y: 34, output_only: true });
|
||||||
{ slot: 0, x: 3, y: 0, filter: "smeltable" },
|
menu.add_player_inventory(7, 84);
|
||||||
{ slot: 1, x: 3, y: 2, filter: "fuel" },
|
menu.add_data("progress", () => block.data.progress);
|
||||||
{ slot: 2, x: 5, y: 1, output_only: true },
|
menu.add_data("progress_max", () => 200);
|
||||||
],
|
menu.still_valid_near(block);
|
||||||
bars: [{
|
});
|
||||||
x: 4,
|
|
||||||
y: 1,
|
ctx.components.register_block("copper_tools:smelter", {
|
||||||
value: "progress",
|
on_create(block) {
|
||||||
max: "progress_max",
|
block.data = { container: ctx.containers.create(3).id, progress: 0 };
|
||||||
direction: "right",
|
},
|
||||||
empty_texture: "bworld:arrow_empty",
|
on_interact(block, _params, player) {
|
||||||
full_texture: "bworld:arrow_full",
|
smelter.open(player, block);
|
||||||
}],
|
return true;
|
||||||
});
|
},
|
||||||
screen.set_property("progress", block.data.progress);
|
});
|
||||||
screen.set_property("progress_max", 200);
|
}
|
||||||
return true;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Give the block `"interactive": true` so clients don't guess that the click places a block.
|
Give the block `"interactive": true` so clients don't guess that the click places a block.
|
||||||
|
|
||||||
## Layout
|
`open(player, args)` builds a menu for the player and opens it, closing whatever they had open. A build function that
|
||||||
|
throws opens nothing. Menu type ids are in the mod's namespace, and each needs a [screen](#screens) in the client
|
||||||
|
script.
|
||||||
|
|
||||||
`layout` lists which of the container's slots to show, and where:
|
## Slots
|
||||||
|
|
||||||
| Field | Meaning |
|
`add_slot(container, slot, options)` adds one slot of a container from `ctx.containers`, or of `player.inventory`. It
|
||||||
|
returns the slot's **menu slot index**: slots are numbered in the order they're added, whatever container they're from.
|
||||||
|
|
||||||
|
| Option | Meaning |
|
||||||
| ------------- | ----------------------------------------------------------------------------------------------------------------- |
|
| ------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||||
| `slot` | The container's slot. |
|
| `x`, `y` | Where its 18 pixel frame goes, in GUI pixels from the screen's top left. |
|
||||||
| `x`, `y` | Where, in slot units from the top left of the screen's area. Can be fractional. |
|
|
||||||
| `filter` | What can be put in: `"smeltable"` (has a furnace recipe), `"fuel"`, or a function `(item) => boolean`. |
|
| `filter` | What can be put in: `"smeltable"` (has a furnace recipe), `"fuel"`, or a function `(item) => boolean`. |
|
||||||
| `output_only` | Can only be taken from, all at once, like the furnace result. |
|
| `output_only` | Can only be taken from, all at once, like the furnace result. |
|
||||||
| `on_take` | For `output_only` slots: runs when a player takes from it, before they get the item. Return `false` to stop them. |
|
| `on_take` | For `output_only` slots: runs when a player takes from it, before they get the item. Return `false` to stop them. |
|
||||||
| `icon` | A texture drawn in the slot while it's empty, like Minecraft's armor slots. |
|
| `icon` | A texture drawn in the slot while it's empty, like Minecraft's armor slots. |
|
||||||
|
|
||||||
`rows` sets the height of the screen's area in slots. By default it fits the slots and bars.
|
`add_player_inventory(x, y)` adds the player's 36 slots, like NeoForge's `addStandardInventorySlots`: the rest of the
|
||||||
|
inventory in 3 rows from `x` and `y`, and the hotbar 58 pixels under them. They're added in inventory order, so
|
||||||
|
inventory slot `i` is the returned index plus `i`.
|
||||||
|
|
||||||
`filter`, `output_only` and `on_take` run **on the server**, so players can't put the wrong items in by editing their
|
`filter`, `output_only` and `on_take` run **on the server**, so players can't put the wrong items in by editing their
|
||||||
client. `on_take` is the place to use up a recipe's inputs, so taking the result and spending the inputs happen in the
|
client. `on_take` is the place to use up a recipe's inputs, so taking the result and spending the inputs happen in the
|
||||||
same step, like the smithing table does.
|
same step, like the smithing table does.
|
||||||
|
|
||||||
Shift clicking follows the same rules. A stack shift clicked in the player's inventory goes into the screen's slots in
|
### Shift Clicking
|
||||||
`layout` order, only those whose `filter` takes it and never `output_only` ones: first onto stacks of the same item,
|
|
||||||
then into empty slots. A stack shift clicked in the screen goes to the player's inventory, and an `output_only` slot
|
|
||||||
only gives its item that way when it all fits, after `on_take` agrees.
|
|
||||||
|
|
||||||
## Progress Bars
|
Shift clicking a slot moves its stack to the other part of the menu, like NeoForge's `quickMoveStack`:
|
||||||
|
|
||||||
`bars` draws progress bars, filled with one property divided by another:
|
- From the player's inventory, it goes into the menu's other slots in the order they were added, only those whose
|
||||||
|
`filter` takes it and never `output_only` ones: first onto stacks of the same item, then into empty slots. A menu with
|
||||||
|
no such slots moves it between the hotbar and the rest of the inventory.
|
||||||
|
- From the menu's other slots, it goes to the player's inventory, filling the hotbar from the right first. An
|
||||||
|
`output_only` slot only gives its item when it all fits, after `on_take` agrees.
|
||||||
|
|
||||||
| Field | Meaning |
|
`menu.quick_move((player, index) => number[])` replaces the rule: return the menu slot indexes the stack in `index`
|
||||||
| ------------------------------- | ----------------------------------------------------------------- |
|
tries, in order. Filters and `output_only` still apply.
|
||||||
| `x`, `y` | Where, in slot units. |
|
|
||||||
| `value`, `max` | Names of properties set with `screen.set_property(name, number)`. |
|
|
||||||
| `direction` | `"up"`, like the furnace's fire, or `"right"`, like its arrow. |
|
|
||||||
| `empty_texture`, `full_texture` | The textures for the empty and full bar. |
|
|
||||||
|
|
||||||
Properties are synced when they change, so a component can update them every tick.
|
## Data
|
||||||
|
|
||||||
## The Screen Handle
|
`add_data(name, get)` is a number the screen shows, like NeoForge's `DataSlot`. `get` runs every tick, and the value is
|
||||||
|
sent to the player when it changes. Values are finite numbers. The screen reads them from `menu.data`.
|
||||||
|
|
||||||
`open_container` returns a handle:
|
## Buttons
|
||||||
|
|
||||||
|
A screen can send a button press with `menu.click_button(id)`, like NeoForge's `clickMenuButton`. The menu decides what
|
||||||
|
an id means:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
interface ScreenHandle {
|
menu.on_button((player, id) => {
|
||||||
|
if (id === 0) container.set(2, undefined);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
Buttons only come from the player who has the menu open, at most 60 a second together with their mod messages. Any
|
||||||
|
number can come, so check it. Anything richer than a number, like typed text, goes through a
|
||||||
|
[mod channel](../networking/index.md), where the server should check the player has the menu open before trusting it.
|
||||||
|
|
||||||
|
## Open Data
|
||||||
|
|
||||||
|
`menu.open_data` is any JSON up to 16 KB, sent to the client once when the menu opens, like NeoForge's
|
||||||
|
`IContainerFactory` extra data. A chest sends how many rows it has, so its screen knows how tall to be.
|
||||||
|
|
||||||
|
## Closing
|
||||||
|
|
||||||
|
One menu is open per player. It closes when the player closes it, leaves, dies or opens another one, when a script calls
|
||||||
|
`close()`, when a container it shows is deleted, and when a `still_valid` check fails:
|
||||||
|
|
||||||
|
- `menu.still_valid((player) => boolean)` is checked every tick.
|
||||||
|
- `menu.still_valid_near(block)` closes it once the player is over 8 blocks from the block, or the block is broken or
|
||||||
|
replaced, like NeoForge's `stillValid` with a `ContainerLevelAccess`.
|
||||||
|
|
||||||
|
`menu.on_close(fn)` runs when it closes for any reason. `menu.on_tick(fn)` runs every tick while it's open.
|
||||||
|
|
||||||
|
`open` returns a handle:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface MenuHandle {
|
||||||
readonly player: Player;
|
readonly player: Player;
|
||||||
readonly open: boolean;
|
readonly open: boolean;
|
||||||
set_property(id: string, value: number): void;
|
|
||||||
close(): void;
|
close(): void;
|
||||||
on_close(fn: () => void): void; // when it closes for any reason
|
on_close(fn: () => void): void; // when it closes for any reason
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
A screen closes when the player closes it, leaves, or opens another screen, when a script calls `close()`, and when its
|
## Screens
|
||||||
container is deleted. To keep a furnace's bars moving for everyone looking at it, keep the handles of open screens and
|
|
||||||
drop them in `on_close`, like the base game's furnace in `mods/bworld/scripts/server.ts`.
|
The client script gives each of the mod's menu types a screen, like NeoForge's `RegisterMenuScreensEvent` and
|
||||||
|
`AbstractContainerScreen`. The function runs each time one opens, with the client's copy of the menu:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// client.ts
|
||||||
|
export function setup(ctx: ClientContext) {
|
||||||
|
ctx.ui.register_menu_screen("copper_tools:smelter", (menu) => ({
|
||||||
|
width: 176,
|
||||||
|
height: 166,
|
||||||
|
on_render_background(g) {
|
||||||
|
g.panel(0, 0, 176, 166);
|
||||||
|
const done = menu.data.progress / menu.data.progress_max || 0;
|
||||||
|
g.texture("bworld:arrow_full", 85, 34, 18 * done, 18, [0, 0, done, 1]);
|
||||||
|
},
|
||||||
|
on_render_labels(g) {
|
||||||
|
g.text(menu.title, 8, 6);
|
||||||
|
g.text("Inventory", 8, 73);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The engine puts the screen in the middle of the window, and draws the menu's slots, the item on the cursor and item
|
||||||
|
tooltips. The screen draws everything else with [`Graphics`](../gui/index.md#graphics), from its own top left:
|
||||||
|
|
||||||
|
| Field | Meaning |
|
||||||
|
| ---------------------- | ------------------------------------------------------------------ |
|
||||||
|
| `width`, `height` | Its size in GUI pixels, like `imageWidth` and `imageHeight`. |
|
||||||
|
| `on_render_background` | Every frame, under the slots: a panel, textures, progress bars. |
|
||||||
|
| `on_render_labels` | Every frame, over the slots: the title, labels, buttons. |
|
||||||
|
| `on_tick` | 20 times a second while it's open, like `containerTick`. Optional. |
|
||||||
|
|
||||||
|
The menu it gets:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface ClientMenu {
|
||||||
|
readonly type: string;
|
||||||
|
readonly title: string;
|
||||||
|
readonly open_data: unknown;
|
||||||
|
readonly data: Readonly<Record<string, number>>; // the server's latest add_data values
|
||||||
|
click_button(id: number): void;
|
||||||
|
close(): void;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
When the server opens a menu type the client has no screen for, the client closes it again, with an error in its
|
||||||
|
console. A screen that throws is closed the same way.
|
||||||
|
|
||||||
|
## Messages
|
||||||
|
|
||||||
|
How menus go over the network, for anyone working on the engine. Menus have ids from 1 to 100, counting up and around
|
||||||
|
for each player like Minecraft's. Menu 0 is the player's own inventory (slots 0 to 35, the hotbar first) and crafting
|
||||||
|
grid (36 to 45), always there and never sent.
|
||||||
|
|
||||||
|
| Message | Way | What |
|
||||||
|
| -------------------- | ------ | ------------------------------------------------------------------------------- |
|
||||||
|
| `open_menu` | server | The id, type, title, open data, each slot's position, and the data. |
|
||||||
|
| `menu_content` | server | Every slot's item, by menu slot index, when any changed. |
|
||||||
|
| `menu_data` | server | All the data, when any changed. |
|
||||||
|
| `close_menu` | both | The server closed it, or the player did. 0 is their inventory screen. |
|
||||||
|
| `click`, `drop_item` | client | A menu slot index of the open menu (or menu 0). Ones for other ids are ignored. |
|
||||||
|
| `menu_button` | client | A button of the open menu. |
|
||||||
|
|
||||||
|
The code is in `server/game/menu.ts` and `client/menu.ts`.
|
||||||
|
|||||||
+13
-167
@@ -26,15 +26,17 @@ A mod is built from up to three layers. Most mods only need the first one or two
|
|||||||
**Built:** the mod loader and `.bmod` files (packing, loading from `server_mods/`, sending players a copy without the
|
**Built:** the mod loader and `.bmod` files (packing, loading from `server_mods/`, sending players a copy without the
|
||||||
server and worldgen scripts), delivery to clients (hashed downloads, the confirm screen for other sites, credits), the
|
server and worldgen scripts), delivery to clients (hashed downloads, the confirm screen for other sites, credits), the
|
||||||
data layer (blocks, block models with variants, items, recipes including mods' own types, entities and entity models,
|
data layer (blocks, block models with variants, items, recipes including mods' own types, entities and entity models,
|
||||||
ores), server scripts (components, events, commands, timers, storage, recipes, containers, container screens, displayed
|
ores), server scripts (components, events, commands, timers, storage, recipes, containers, displayed items), menus like
|
||||||
items), client scripts (item and recipe lookups, inventory overlays with `Graphics`), mod channels, worldgen features
|
NeoForge's (menu types, slots, data, buttons and `still_valid` on the server, menu screens on the client, and the
|
||||||
and ores, the base game's block behavior as a mod, and world time.
|
player's inventory as menu 0), client scripts (item and recipe lookups, plain screens, inventory overlays, `Graphics` in
|
||||||
|
GUI pixels), mod channels, worldgen features and ores, the base game's block behavior and screens as a mod, and world
|
||||||
|
time. See [Menus](modding/inventories/menus.md) and [Screens](modding/gui/index.md).
|
||||||
|
|
||||||
The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.ts`, `common/bmod.ts`,
|
The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.ts`, `common/bmod.ts`,
|
||||||
`server/game/mod_runtime.ts`, `server/load_bmods.ts`, `client/mods.ts` and `common/worldgen_loader.ts`.
|
`server/game/mod_runtime.ts`, `server/game/menu.ts`, `server/load_bmods.ts`, `client/mods.ts`, `client/menu.ts` and
|
||||||
|
`common/worldgen_loader.ts`.
|
||||||
|
|
||||||
**In the API types but throwing:** forms, custom screens, HUD elements, keybinds, `g.slider`, `g.slots`,
|
**In the API types but throwing:** forms, HUD elements, keybinds, `g.slider`, `register_terrain`.
|
||||||
`register_terrain`.
|
|
||||||
|
|
||||||
**Not built at all:** common scripts, the registry freeze and hash, overrides, engine access.
|
**Not built at all:** common scripts, the registry freeze and hash, overrides, engine access.
|
||||||
|
|
||||||
@@ -44,6 +46,7 @@ The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.t
|
|||||||
- Mods can't throw a `CommandError` the server recognizes: it's checked with `instanceof`, and the class isn't in the
|
- Mods can't throw a `CommandError` the server recognizes: it's checked with `instanceof`, and the class isn't in the
|
||||||
API, so a mod's bundled copy is a different class. Export it from `bworld/server`, or recognize it by `name`.
|
API, so a mod's bundled copy is a different class. Export it from `bworld/server`, or recognize it by `name`.
|
||||||
- Tools only lose durability when their owner dies. Nothing else uses it.
|
- Tools only lose durability when their owner dies. Nothing else uses it.
|
||||||
|
- The GUI scale is always 3: screens work in GUI pixels like NeoForge's, but there's no option to change it yet.
|
||||||
|
|
||||||
## Planned API
|
## Planned API
|
||||||
|
|
||||||
@@ -197,168 +200,11 @@ function hook<T, K extends keyof T>(target: T, method: K, handlers: {
|
|||||||
confirm screen for other sites lists which mods use it.
|
confirm screen for other sites lists which mods use it.
|
||||||
- Prefer the Game API. Many mods hooking the same thing is a sign it should become part of the Game API.
|
- Prefer the Game API. Many mods hooking the same thing is a sign it should become part of the Game API.
|
||||||
|
|
||||||
### Menus
|
|
||||||
|
|
||||||
GUIs follow NeoForge's split between a menu and a screen. The **menu** lives on the server: which slots the player can
|
|
||||||
click, the numbers the screen shows, the buttons it has, and when it closes. The **screen** lives on the client and only
|
|
||||||
draws the menu and sends clicks. Every click is checked by the server's menu, so a modified client can only do what the
|
|
||||||
menu allows.
|
|
||||||
|
|
||||||
A menu type is registered in the server script with a function that builds each menu when it opens, like NeoForge's
|
|
||||||
`MenuType` and its server menu constructor:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// server.ts
|
|
||||||
const smelter = ctx.menus.register("copper_tools:smelter", (menu, block: BlockRef) => {
|
|
||||||
const container = ctx.containers.get(block.data.container)!;
|
|
||||||
// like Slot: x and y in GUI pixels from the screen's top left
|
|
||||||
menu.add_slot(container, 0, { x: 56, y: 17, filter: "smeltable" });
|
|
||||||
menu.add_slot(container, 1, { x: 56, y: 53, filter: "fuel" });
|
|
||||||
menu.add_slot(container, 2, { x: 116, y: 35, output_only: true });
|
|
||||||
menu.add_player_inventory(8, 84); // like addStandardInventorySlots
|
|
||||||
// like DataSlot: read every tick, and sent when it changes
|
|
||||||
menu.add_data("progress", () => block.data.progress);
|
|
||||||
menu.add_data("progress_max", () => 200);
|
|
||||||
// like stillValid with a ContainerLevelAccess: closes when the player is over 8 blocks away or the block is gone
|
|
||||||
menu.still_valid_near(block);
|
|
||||||
// like clickMenuButton
|
|
||||||
menu.on_button((player, id) => {
|
|
||||||
if (id === 0) ctx.containers.get(block.data.container)!.set(2, undefined);
|
|
||||||
});
|
|
||||||
menu.title = "Smelter";
|
|
||||||
});
|
|
||||||
|
|
||||||
// in the block's on_interact
|
|
||||||
smelter.open(player, block);
|
|
||||||
```
|
|
||||||
|
|
||||||
```ts
|
|
||||||
interface MenuBuilder {
|
|
||||||
title: string;
|
|
||||||
// sent to the client once when it opens, at most 16 KB of JSON, like IContainerFactory's extra data
|
|
||||||
open_data: unknown;
|
|
||||||
// slot fields are the same as container screens' layout (filter, output_only, on_take, icon). returns its index
|
|
||||||
add_slot(container: Container, slot: number, options: SlotOptions & { x: number; y: number }): number;
|
|
||||||
add_player_inventory(x: number, y: number): void;
|
|
||||||
add_data(name: string, get: () => number): void;
|
|
||||||
still_valid(check: (player: Player) => boolean): void; // checked every tick
|
|
||||||
still_valid_near(block: BlockRef): void;
|
|
||||||
on_button(fn: (player: Player, id: number) => void): void;
|
|
||||||
// shift clicks: return the slot indexes to try, in order. by default it's the container screens' rule
|
|
||||||
quick_move(fn: (player: Player, index: number) => number[]): void;
|
|
||||||
on_tick(fn: () => void): void;
|
|
||||||
on_close(fn: () => void): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MenuType<Args> {
|
|
||||||
readonly id: Id;
|
|
||||||
open(player: Player, args: Args): MenuHandle; // like openMenu with a MenuProvider
|
|
||||||
}
|
|
||||||
|
|
||||||
// what open_container returns today, without set_property and update: data comes from add_data
|
|
||||||
interface MenuHandle {
|
|
||||||
readonly player: Player;
|
|
||||||
readonly open: boolean;
|
|
||||||
close(): void;
|
|
||||||
on_close(fn: () => void): void;
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
- Slots, data and open data are the whole client side of a menu, like NeoForge's client menu built from what the server
|
|
||||||
sends. Data values are finite numbers, compared and sent at the end of each tick.
|
|
||||||
- Button ids are integers the client sends with `menu.click_button(id)`. They only come from the player who has the menu
|
|
||||||
open, and the menu decides what an id means. Anything richer, like typed text, goes through a mod channel (see below),
|
|
||||||
where the server checks the player has this menu open before trusting it.
|
|
||||||
- One menu is open per player. Opening another closes the first, and closing runs `on_close` whatever the reason.
|
|
||||||
- `ctx.ui.open_container` stays, as the menu the engine draws itself: its layout in slot units under the player's
|
|
||||||
inventory, like vanilla's chest screen. It needs no client code.
|
|
||||||
|
|
||||||
### Menu Screens
|
|
||||||
|
|
||||||
The client script gives each menu type a screen, like NeoForge's `RegisterMenuScreensEvent` and
|
|
||||||
`AbstractContainerScreen`. The engine places the screen in the middle, and draws its slots, the held item and item
|
|
||||||
tooltips. The screen draws everything else:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// client.ts
|
|
||||||
ctx.ui.register_menu_screen("copper_tools:smelter", (menu) => ({
|
|
||||||
width: 176, // like imageWidth and imageHeight
|
|
||||||
height: 166,
|
|
||||||
// under the slots. x and y are from the screen's top left, like leftPos and topPos
|
|
||||||
on_render_background(g) {
|
|
||||||
g.texture("copper_tools:smelter_gui", 0, 0, 176, 166);
|
|
||||||
g.texture("bworld:arrow_full", 79, 34, 24 * menu.data.progress / menu.data.progress_max, 17);
|
|
||||||
},
|
|
||||||
// over the slots
|
|
||||||
on_render_labels(g) {
|
|
||||||
g.text(menu.title, 8, 6);
|
|
||||||
if (g.button("Empty", 120, 60, 40, 16)) menu.click_button(0);
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
```
|
|
||||||
|
|
||||||
```ts
|
|
||||||
interface ClientMenu {
|
|
||||||
readonly type: Id;
|
|
||||||
readonly title: string;
|
|
||||||
readonly open_data: unknown;
|
|
||||||
readonly data: Readonly<Record<string, number>>; // the server's latest values
|
|
||||||
click_button(id: number): void;
|
|
||||||
close(): void;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MenuScreen {
|
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
on_render_background?(g: Graphics): void;
|
|
||||||
on_render_labels?(g: Graphics): void;
|
|
||||||
on_tick?(): void; // like containerTick
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
A server opening a menu type its client has no screen for closes it again, with an error in the client's console naming
|
|
||||||
the mod. `check-mods` warns about menu types a mod registers without a screen.
|
|
||||||
|
|
||||||
### Plain Screens
|
|
||||||
|
|
||||||
For screens with no slots and nothing the server needs to check: maps, settings, a guide book. Like NeoForge's `Screen`,
|
|
||||||
they're only on the client, opened with `ctx.ui.open(screen)`:
|
|
||||||
|
|
||||||
```ts
|
|
||||||
// client.ts
|
|
||||||
ctx.ui.open({
|
|
||||||
on_init(width, height) {}, // opening, and whenever the window or GUI scale changes
|
|
||||||
on_render(g) {
|
|
||||||
g.panel(g.width / 2 - 100, 20, 200, 120);
|
|
||||||
g.text(`Smelted: ${smelted}`, g.width / 2 - 90, 30);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
```
|
|
||||||
|
|
||||||
```ts
|
|
||||||
interface Screen {
|
|
||||||
on_init?(width: number, height: number): void;
|
|
||||||
on_tick?(): void; // 20 times a second
|
|
||||||
on_render(g: Graphics): void;
|
|
||||||
on_key?(key: KeyCode): boolean; // true when it used the key
|
|
||||||
should_close_on_escape?(): boolean; // true when not set
|
|
||||||
on_close?(): void; // the player closed it
|
|
||||||
on_removed?(): void; // it's gone for any reason, including another screen replacing it
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
There's no registry for them and no `open_screen` on the server. A server that wants a player to see one sends a mod
|
|
||||||
channel message, and the client script's handler opens it, like a NeoForge payload handler calling `setScreen`. A screen
|
|
||||||
that needs to tell the server something does it the same way.
|
|
||||||
|
|
||||||
Screens of every kind work in GUI pixels, like NeoForge's: the window's size divided by the GUI scale players pick in
|
|
||||||
the options, so `g.width` and `g.height` are in those pixels and a screen looks the same at any window size.
|
|
||||||
|
|
||||||
### Forms
|
### Forms
|
||||||
|
|
||||||
NeoForge has nothing like Bedrock's server forms, but they're the quickest way to ask a player something, so they stay,
|
NeoForge has nothing like Bedrock's server forms, but they're the quickest way to ask a player something, so they stay,
|
||||||
built on menus: each kind of form is a menu whose screen the engine provides, so they need no client code. The types are
|
built on [menus](modding/inventories/menus.md): each kind of form is a menu whose screen the engine provides, so they
|
||||||
in `common/mod_api/server.ts` (`message_form`, `action_form`, `modal_form`).
|
need no client code. The types are in `common/mod_api/server.ts` (`message_form`, `action_form`, `modal_form`).
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
const result = await ctx.ui.action_form(player, {
|
const result = await ctx.ui.action_form(player, {
|
||||||
@@ -459,8 +305,8 @@ manifest and its checks, and making the engine hookable where mods will want it.
|
|||||||
client and a worldgen method, hooks on one method run in priority order, and a throwing hook is logged without breaking
|
client and a worldgen method, hooks on one method run in priority order, and a throwing hook is logged without breaking
|
||||||
the game.
|
the game.
|
||||||
|
|
||||||
**Phase 4: the rest of the Game API.** Keybinds, menus and menu screens, plain screens, forms built on menus, and HUD
|
**Phase 4: the rest of the Game API.** Keybinds, forms built on menus, and HUD elements. More events: items picked up
|
||||||
elements. More events: items picked up and dropped, containers clicked, players moving between chunks, entities.
|
and dropped, containers clicked, players moving between chunks, entities.
|
||||||
|
|
||||||
**Phase 5: gameplay out of the engine.** Everything marked phase 5 in the table above moves into `mods/bworld`. Mining
|
**Phase 5: gameplay out of the engine.** Everything marked phase 5 in the table above moves into `mods/bworld`. Mining
|
||||||
rules become something `mods/bworld` sets, with the engine asking it on both sides so clients still predict breaking.
|
rules become something `mods/bworld` sets, with the engine asking it on both sides so clients still predict breaking.
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
"game_version": ">=0.1.0",
|
"game_version": ">=0.1.0",
|
||||||
"credits": "CREDITS.md",
|
"credits": "CREDITS.md",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"server": "scripts/server.ts"
|
"server": "scripts/server.ts",
|
||||||
|
"client": "scripts/client.ts"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// the screens of the base game's menus, see scripts/server.ts for their slots. in gui pixels, like minecraft's
|
||||||
|
import type { ClientContext, ClientMenu, Graphics, MenuScreen } from "bworld/client";
|
||||||
|
|
||||||
|
const WIDTH = 176;
|
||||||
|
// like minecraft's 176x166 container screens
|
||||||
|
const HEIGHT = 166;
|
||||||
|
|
||||||
|
export function setup(ctx: ClientContext) {
|
||||||
|
ctx.ui.register_menu_screen("bworld:storage", chest_screen);
|
||||||
|
ctx.ui.register_menu_screen("bworld:furnace", furnace_screen);
|
||||||
|
ctx.ui.register_menu_screen("bworld:smithing_table", smithing_screen);
|
||||||
|
}
|
||||||
|
|
||||||
|
// a panel with the menu's title and the inventory's label over its rows, drawing anything else over it
|
||||||
|
function container_screen(menu: ClientMenu, height: number, draw?: (g: Graphics) => void): MenuScreen {
|
||||||
|
return {
|
||||||
|
width: WIDTH,
|
||||||
|
height,
|
||||||
|
on_render_background(g) {
|
||||||
|
g.panel(0, 0, WIDTH, height);
|
||||||
|
draw?.(g);
|
||||||
|
},
|
||||||
|
on_render_labels(g) {
|
||||||
|
g.text(menu.title, 8, 6);
|
||||||
|
g.text("Inventory", 8, height - 93);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function chest_screen(menu: ClientMenu): MenuScreen {
|
||||||
|
const { rows } = menu.open_data as { rows: number };
|
||||||
|
return container_screen(menu, 114 + rows * 18);
|
||||||
|
}
|
||||||
|
|
||||||
|
function furnace_screen(menu: ClientMenu): MenuScreen {
|
||||||
|
return container_screen(menu, HEIGHT, (g) => {
|
||||||
|
// the fuel left burns down, the progress fills to the right
|
||||||
|
bar(g, 55, 34, "up", menu.data.fuel, menu.data.fuel_max, "bworld:fire_empty", "bworld:fire_full");
|
||||||
|
bar(g, 85, 34, "right", menu.data.progress, menu.data.progress_max, "bworld:arrow_empty", "bworld:arrow_full");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function smithing_screen(menu: ClientMenu): MenuScreen {
|
||||||
|
return container_screen(menu, HEIGHT, (g) => {
|
||||||
|
g.texture("bworld:arrow_empty", 88, 34, 18, 18);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// an 18 pixel square progress bar, value / max of full drawn over empty
|
||||||
|
function bar(
|
||||||
|
g: Graphics,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
direction: "up" | "right",
|
||||||
|
value = 0,
|
||||||
|
max = 0,
|
||||||
|
empty: string,
|
||||||
|
full: string,
|
||||||
|
) {
|
||||||
|
const size = 18;
|
||||||
|
const done = max > 0 ? Math.max(0, Math.min(1, value / max)) : 0;
|
||||||
|
g.texture(empty, x, y, size, size);
|
||||||
|
if (direction === "right") {
|
||||||
|
g.texture(full, x, y, size * done, size, [0, 0, done, 1]);
|
||||||
|
} else {
|
||||||
|
g.texture(full, x, y + size * (1 - done), size, size * done, [0, 1 - done, 1, done]);
|
||||||
|
}
|
||||||
|
}
|
||||||
+92
-115
@@ -1,5 +1,5 @@
|
|||||||
// the base game's block and item behavior, written against the same api as any other mod
|
// the base game's block and item behavior, written against the same api as any other mod
|
||||||
import type { BlockRef, Container, EntityRef, Player, ScreenHandle, ServerContext } from "bworld/server";
|
import type { BlockRef, Container, EntityRef, Player, ServerContext } from "bworld/server";
|
||||||
|
|
||||||
export function setup(ctx: ServerContext) {
|
export function setup(ctx: ServerContext) {
|
||||||
register_hoeable(ctx);
|
register_hoeable(ctx);
|
||||||
@@ -51,19 +51,30 @@ function drop_contents(ctx: ServerContext, block: BlockRef) {
|
|||||||
ctx.containers.delete(container.id);
|
ctx.containers.delete(container.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// a chest
|
// the menus' layouts are in gui pixels, like minecraft's: their screens are in scripts/client.ts. the player's
|
||||||
|
// inventory goes at the bottom, its rows from INVENTORY_Y and the hotbar under them
|
||||||
|
const INVENTORY_Y = 84;
|
||||||
|
|
||||||
|
// a chest, like minecraft's ChestMenu: rows of 9 over the inventory
|
||||||
function register_storage(ctx: ServerContext) {
|
function register_storage(ctx: ServerContext) {
|
||||||
|
const menu_type = ctx.menus.register<{ block: BlockRef; rows: number }>("bworld:storage", (menu, args) => {
|
||||||
|
const { block, rows } = args;
|
||||||
|
const container = block_container(ctx, block, rows * 9);
|
||||||
|
menu.title = "Chest";
|
||||||
|
menu.open_data = { rows };
|
||||||
|
for (let slot = 0; slot < rows * 9; slot++) {
|
||||||
|
menu.add_slot(container, slot, { x: 7 + (slot % 9) * 18, y: 17 + Math.floor(slot / 9) * 18 });
|
||||||
|
}
|
||||||
|
menu.add_player_inventory(7, 31 + rows * 18);
|
||||||
|
menu.still_valid_near(block);
|
||||||
|
});
|
||||||
|
|
||||||
ctx.components.register_block<{ rows: number }>("bworld:storage", {
|
ctx.components.register_block<{ rows: number }>("bworld:storage", {
|
||||||
on_create(block, params) {
|
on_create(block, params) {
|
||||||
block_container(ctx, block, params.rows * 9);
|
block_container(ctx, block, params.rows * 9);
|
||||||
},
|
},
|
||||||
on_interact(block, params, player) {
|
on_interact(block, params, player) {
|
||||||
const size = params.rows * 9;
|
menu_type.open(player, { block, rows: params.rows });
|
||||||
ctx.ui.open_container(player, {
|
|
||||||
container: block_container(ctx, block, size),
|
|
||||||
layout: Array.from({ length: size }, (_, slot) => ({ slot, x: slot % 9, y: Math.floor(slot / 9) })),
|
|
||||||
rows: params.rows,
|
|
||||||
});
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
on_break(block) {
|
on_break(block) {
|
||||||
@@ -84,44 +95,26 @@ interface FurnaceData {
|
|||||||
fuel_max: number;
|
fuel_max: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
const FURNACE_BARS = [
|
|
||||||
{
|
|
||||||
x: 3.5,
|
|
||||||
y: 1,
|
|
||||||
value: "fuel",
|
|
||||||
max: "fuel_max",
|
|
||||||
direction: "up" as const,
|
|
||||||
empty_texture: "bworld:fire_empty",
|
|
||||||
full_texture: "bworld:fire_full",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
x: 4.5,
|
|
||||||
y: 1,
|
|
||||||
value: "progress",
|
|
||||||
max: "progress_max",
|
|
||||||
direction: "right" as const,
|
|
||||||
empty_texture: "bworld:arrow_empty",
|
|
||||||
full_texture: "bworld:arrow_full",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
function register_furnace(ctx: ServerContext) {
|
function register_furnace(ctx: ServerContext) {
|
||||||
// who's looking at each furnace, by position, to keep their bars moving
|
|
||||||
const viewers = new Map<string, Set<ScreenHandle>>();
|
|
||||||
const key = (block: BlockRef) => `${block.x},${block.y},${block.z}`;
|
|
||||||
|
|
||||||
const furnace_data = (block: BlockRef): FurnaceData => {
|
const furnace_data = (block: BlockRef): FurnaceData => {
|
||||||
const container = block_container(ctx, block, 3);
|
const container = block_container(ctx, block, 3);
|
||||||
block.data = { progress: 0, progress_max: 0, fuel: 0, fuel_max: 0, ...block.data, container: container.id };
|
block.data = { progress: 0, progress_max: 0, fuel: 0, fuel_max: 0, ...block.data, container: container.id };
|
||||||
return block.data;
|
return block.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
const show = (screen: ScreenHandle, data: FurnaceData) => {
|
// like minecraft's FurnaceMenu, the screen shows the fuel left and the progress with bars
|
||||||
screen.set_property("progress", data.progress);
|
const menu_type = ctx.menus.register<BlockRef>("bworld:furnace", (menu, block) => {
|
||||||
screen.set_property("progress_max", data.progress_max);
|
const container = ctx.containers.get(furnace_data(block).container)!;
|
||||||
screen.set_property("fuel", data.fuel);
|
menu.title = "Furnace";
|
||||||
screen.set_property("fuel_max", data.fuel_max);
|
menu.add_slot(container, 0, { x: 55, y: 16 });
|
||||||
};
|
menu.add_slot(container, 1, { x: 55, y: 52, filter: "fuel" });
|
||||||
|
menu.add_slot(container, 2, { x: 115, y: 34, output_only: true });
|
||||||
|
menu.add_player_inventory(7, INVENTORY_Y);
|
||||||
|
for (const field of ["progress", "progress_max", "fuel", "fuel_max"] as const) {
|
||||||
|
menu.add_data(field, () => (block.data as FurnaceData | undefined)?.[field] ?? 0);
|
||||||
|
}
|
||||||
|
menu.still_valid_near(block);
|
||||||
|
});
|
||||||
|
|
||||||
// there's somewhere for the result to go
|
// there's somewhere for the result to go
|
||||||
const can_smelt = (container: Container, output: { id: string; count: number }) => {
|
const can_smelt = (container: Container, output: { id: string; count: number }) => {
|
||||||
@@ -134,22 +127,8 @@ function register_furnace(ctx: ServerContext) {
|
|||||||
furnace_data(block);
|
furnace_data(block);
|
||||||
},
|
},
|
||||||
on_interact(block, _params, player) {
|
on_interact(block, _params, player) {
|
||||||
const data = furnace_data(block);
|
furnace_data(block);
|
||||||
const screen = ctx.ui.open_container(player, {
|
menu_type.open(player, block);
|
||||||
container: ctx.containers.get(data.container)!,
|
|
||||||
layout: [
|
|
||||||
{ slot: 0, x: 3.5, y: 0 },
|
|
||||||
{ slot: 1, x: 3.5, y: 2, filter: "fuel" },
|
|
||||||
{ slot: 2, x: 5.5, y: 1, output_only: true },
|
|
||||||
],
|
|
||||||
rows: 3,
|
|
||||||
bars: FURNACE_BARS,
|
|
||||||
});
|
|
||||||
show(screen, data);
|
|
||||||
const screens = viewers.get(key(block)) ?? new Set();
|
|
||||||
viewers.set(key(block), screens);
|
|
||||||
screens.add(screen);
|
|
||||||
screen.on_close(() => screens.delete(screen));
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
on_break(block) {
|
on_break(block) {
|
||||||
@@ -198,8 +177,6 @@ function register_furnace(ctx: ServerContext) {
|
|||||||
if (ctx.world.get_state(block.x, block.y, block.z, "lit") !== lit) {
|
if (ctx.world.get_state(block.x, block.y, block.z, "lit") !== lit) {
|
||||||
ctx.world.set_state(block.x, block.y, block.z, "lit", lit);
|
ctx.world.set_state(block.x, block.y, block.z, "lit", lit);
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const screen of viewers.get(key(block)) ?? []) show(screen, data);
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -213,67 +190,67 @@ const ADDITION = 2;
|
|||||||
const RESULT = 3;
|
const RESULT = 3;
|
||||||
|
|
||||||
function register_smithing_table(ctx: ServerContext) {
|
function register_smithing_table(ctx: ServerContext) {
|
||||||
ctx.components.register_block("bworld:smithing_table", {
|
const menu_type = ctx.menus.register<BlockRef>("bworld:smithing_table", (menu, block, player) => {
|
||||||
on_interact(_block, _params, player) {
|
const container = ctx.containers.create(4);
|
||||||
const container = ctx.containers.create(4);
|
|
||||||
|
|
||||||
// the recipe the inputs make, with enough material
|
// the recipe the inputs make, with enough material
|
||||||
const match = () => {
|
const match = () => {
|
||||||
const tool = container.get(TOOL);
|
const tool = container.get(TOOL);
|
||||||
const material = container.get(MATERIAL);
|
const material = container.get(MATERIAL);
|
||||||
const addition = container.get(ADDITION);
|
const addition = container.get(ADDITION);
|
||||||
if (!tool || !material) return undefined;
|
if (!tool || !material) return undefined;
|
||||||
const recipe = ctx.recipes.smithing(tool.id, material.id, addition?.id);
|
const recipe = ctx.recipes.smithing(tool.id, material.id, addition?.id);
|
||||||
if (!recipe || material.count < recipe.material_count) return undefined;
|
if (!recipe || material.count < recipe.material_count) return undefined;
|
||||||
return { ...recipe, tool, material, addition };
|
return { ...recipe, tool, material, addition };
|
||||||
};
|
};
|
||||||
|
|
||||||
// the result slot shows what taking it would give, the upgraded tool keeps the old one's data
|
// the result slot shows what taking it would give, the upgraded tool keeps the old one's data
|
||||||
const show_result = () => {
|
const show_result = () => {
|
||||||
|
const recipe = match();
|
||||||
|
const shown = container.get(RESULT);
|
||||||
|
if (!recipe) {
|
||||||
|
if (shown) container.set(RESULT, undefined);
|
||||||
|
} else if (shown?.id !== recipe.result) {
|
||||||
|
container.set(RESULT, { id: recipe.result, count: 1, data: recipe.tool.data });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const stop = container.on_change((slot) => {
|
||||||
|
if (slot !== RESULT) show_result();
|
||||||
|
});
|
||||||
|
|
||||||
|
menu.title = "Smithing";
|
||||||
|
menu.add_slot(container, TOOL, { x: 25, y: 34 });
|
||||||
|
menu.add_slot(container, MATERIAL, { x: 43, y: 34 });
|
||||||
|
menu.add_slot(container, ADDITION, { x: 61, y: 34 });
|
||||||
|
menu.add_slot(container, RESULT, {
|
||||||
|
x: 115,
|
||||||
|
y: 34,
|
||||||
|
output_only: true,
|
||||||
|
// the inputs are used up in the same step, so they can't be taken out after
|
||||||
|
on_take(item) {
|
||||||
const recipe = match();
|
const recipe = match();
|
||||||
const shown = container.get(RESULT);
|
if (!recipe || recipe.result !== item.id) return false;
|
||||||
if (!recipe) {
|
recipe.tool.count -= 1;
|
||||||
if (shown) container.set(RESULT, undefined);
|
recipe.material.count -= recipe.material_count;
|
||||||
} else if (shown?.id !== recipe.result) {
|
if (recipe.addition) recipe.addition.count -= 1;
|
||||||
container.set(RESULT, { id: recipe.result, count: 1, data: recipe.tool.data });
|
return true;
|
||||||
}
|
},
|
||||||
};
|
});
|
||||||
const stop = container.on_change((slot) => {
|
menu.add_player_inventory(7, INVENTORY_Y);
|
||||||
if (slot !== RESULT) show_result();
|
menu.still_valid_near(block);
|
||||||
});
|
menu.on_close(() => {
|
||||||
|
stop();
|
||||||
|
for (const slot of [TOOL, MATERIAL, ADDITION]) {
|
||||||
|
const item = container.get(slot);
|
||||||
|
if (item) player.give_item(item.id, item.count, item.data);
|
||||||
|
}
|
||||||
|
ctx.containers.delete(container.id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
const screen = ctx.ui.open_container(player, {
|
ctx.components.register_block("bworld:smithing_table", {
|
||||||
container,
|
on_interact(block, _params, player) {
|
||||||
layout: [
|
menu_type.open(player, block);
|
||||||
{ slot: TOOL, x: 1.5, y: 0.5 },
|
|
||||||
{ slot: MATERIAL, x: 2.5, y: 0.5 },
|
|
||||||
{ slot: ADDITION, x: 3.5, y: 0.5 },
|
|
||||||
{
|
|
||||||
slot: RESULT,
|
|
||||||
x: 5.5,
|
|
||||||
y: 0.5,
|
|
||||||
output_only: true,
|
|
||||||
// the inputs are used up in the same step, so they can't be taken out after
|
|
||||||
on_take(item) {
|
|
||||||
const recipe = match();
|
|
||||||
if (!recipe || recipe.result !== item.id) return false;
|
|
||||||
recipe.tool.count -= 1;
|
|
||||||
recipe.material.count -= recipe.material_count;
|
|
||||||
if (recipe.addition) recipe.addition.count -= 1;
|
|
||||||
return true;
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
rows: 2,
|
|
||||||
});
|
|
||||||
screen.on_close(() => {
|
|
||||||
stop();
|
|
||||||
for (const slot of [TOOL, MATERIAL, ADDITION]) {
|
|
||||||
const item = container.get(slot);
|
|
||||||
if (item) player.give_item(item.id, item.count, item.data);
|
|
||||||
}
|
|
||||||
ctx.containers.delete(container.id);
|
|
||||||
});
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -305,7 +282,7 @@ interface CropDrops {
|
|||||||
bonus?: string;
|
bonus?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
// a crop, like a fabric CropBlock: its "age" state is its stage, and it grows one day every morning its farmland was
|
// a crop, like minecraft's CropBlock: its "age" state is its stage, and it grows one day every morning its farmland was
|
||||||
// watered the day before. see docs/modding/blocks/crops.md
|
// watered the day before. see docs/modding/blocks/crops.md
|
||||||
interface CropParams {
|
interface CropParams {
|
||||||
// watered mornings from planting to fully grown
|
// watered mornings from planting to fully grown
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
// the curios button next to every inventory screen, or G like curios' keybind, asks the server to show the slots
|
// the curios button next to every inventory screen, or G like curios' keybind, asks the server to open the curios
|
||||||
|
// menu, and its screen
|
||||||
import type { ClientContext } from "bworld/client";
|
import type { ClientContext } from "bworld/client";
|
||||||
import { active_slots } from "./slots.ts";
|
import { active_slots } from "./slots.ts";
|
||||||
|
|
||||||
const GAP = 16;
|
// in gui pixels
|
||||||
const WIDTH = 120;
|
const GAP = 5;
|
||||||
const HEIGHT = 32;
|
const BUTTON_WIDTH = 40;
|
||||||
|
const BUTTON_HEIGHT = 11;
|
||||||
|
const WIDTH = 176;
|
||||||
|
|
||||||
export function setup(ctx: ClientContext) {
|
export function setup(ctx: ClientContext) {
|
||||||
// no item goes in any slot, so there's nothing to show
|
// no item goes in any slot, so there's nothing to show
|
||||||
@@ -12,10 +15,26 @@ export function setup(ctx: ClientContext) {
|
|||||||
|
|
||||||
ctx.ui.add_inventory_overlay({
|
ctx.ui.add_inventory_overlay({
|
||||||
on_render(g, screen) {
|
on_render(g, screen) {
|
||||||
const clicked = g.button("Curios", screen.x - WIDTH - GAP, screen.y, WIDTH, HEIGHT);
|
const clicked = g.button("Curios", screen.x - BUTTON_WIDTH - GAP, screen.y, BUTTON_WIDTH, BUTTON_HEIGHT);
|
||||||
if (clicked || g.key_pressed("KeyG")) {
|
if (clicked || g.key_pressed("KeyG")) {
|
||||||
ctx.net.send("curios:open", {});
|
ctx.net.send("curios:open", {});
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
ctx.ui.register_menu_screen("curios:curios", (menu) => {
|
||||||
|
const { rows } = menu.open_data as { rows: number };
|
||||||
|
const height = 114 + rows * 18;
|
||||||
|
return {
|
||||||
|
width: WIDTH,
|
||||||
|
height,
|
||||||
|
on_render_background(g) {
|
||||||
|
g.panel(0, 0, WIDTH, height);
|
||||||
|
},
|
||||||
|
on_render_labels(g) {
|
||||||
|
g.text(menu.title, 8, 6);
|
||||||
|
g.text("Inventory", 8, height - 93);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -72,6 +72,27 @@ export function setup(ctx: ServerContext) {
|
|||||||
applied.delete(player.id);
|
applied.delete(player.id);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// like curios' CuriosContainer: the slot types in rows of 9, each row centered, over the inventory. the screen is
|
||||||
|
// in scripts/client.ts
|
||||||
|
const rows = Math.ceil(active.length / 9);
|
||||||
|
const menu_type = ctx.menus.register("curios:curios", (menu, _args, player) => {
|
||||||
|
const curios = curios_of(player);
|
||||||
|
menu.title = "Curios";
|
||||||
|
menu.open_data = { rows };
|
||||||
|
for (const [i, slot] of active.entries()) {
|
||||||
|
const row = Math.floor(i / 9);
|
||||||
|
const in_row = Math.min(9, active.length - row * 9);
|
||||||
|
menu.add_slot(curios, SLOTS.indexOf(slot), {
|
||||||
|
x: 7 + ((9 - in_row) / 2 + (i % 9)) * 18,
|
||||||
|
y: 17 + row * 18,
|
||||||
|
filter: (item) => fits(ctx.tags, slot, item.id),
|
||||||
|
icon: `curios:empty_${slot}_slot`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
menu.add_player_inventory(7, 31 + rows * 18);
|
||||||
|
});
|
||||||
|
|
||||||
|
// the curios button, curios' client asks for its menu like the java mod's packet does
|
||||||
ctx.net.on("curios:open", (player) => {
|
ctx.net.on("curios:open", (player) => {
|
||||||
if (active.length === 0) return;
|
if (active.length === 0) return;
|
||||||
const curios = curios_of(player);
|
const curios = curios_of(player);
|
||||||
@@ -83,21 +104,7 @@ export function setup(ctx: ServerContext) {
|
|||||||
curios.set(index, undefined);
|
curios.set(index, undefined);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// in rows of 9, each row centered
|
menu_type.open(player, undefined);
|
||||||
ctx.ui.open_container(player, {
|
|
||||||
container: curios,
|
|
||||||
layout: active.map((slot, i) => {
|
|
||||||
const row = Math.floor(i / 9);
|
|
||||||
const in_row = Math.min(9, active.length - row * 9);
|
|
||||||
return {
|
|
||||||
slot: SLOTS.indexOf(slot),
|
|
||||||
x: (9 - in_row) / 2 + (i % 9),
|
|
||||||
y: row,
|
|
||||||
filter: (item) => fits(ctx.tags, slot, item.id),
|
|
||||||
icon: `curios:empty_${slot}_slot`,
|
|
||||||
};
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
ctx.events.after.player_death.subscribe(({ player }) => {
|
ctx.events.after.player_death.subscribe(({ player }) => {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
],
|
],
|
||||||
"credits": "CREDITS.md",
|
"credits": "CREDITS.md",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"server": "scripts/server.ts"
|
"server": "scripts/server.ts",
|
||||||
|
"client": "scripts/client.ts"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// the cooking pot's screen, like the java mod's CookingPotScreen. its slots are in scripts/server.ts, in gui pixels
|
||||||
|
import type { ClientContext, Graphics } from "bworld/client";
|
||||||
|
|
||||||
|
const WIDTH = 176;
|
||||||
|
const HEIGHT = 166;
|
||||||
|
|
||||||
|
export function setup(ctx: ClientContext) {
|
||||||
|
ctx.ui.register_menu_screen("farmersdelight:cooking_pot", (menu) => ({
|
||||||
|
width: WIDTH,
|
||||||
|
height: HEIGHT,
|
||||||
|
on_render_background(g) {
|
||||||
|
g.panel(0, 0, WIDTH, HEIGHT);
|
||||||
|
// lit under the ingredients while something heats the pot, the arrow fills as the meal cooks
|
||||||
|
bar(g, 47, 53, "up", menu.data.heated, 1, "bworld:fire_empty", "bworld:fire_full");
|
||||||
|
bar(
|
||||||
|
g,
|
||||||
|
95,
|
||||||
|
25,
|
||||||
|
"right",
|
||||||
|
menu.data.progress,
|
||||||
|
menu.data.progress_max,
|
||||||
|
"bworld:arrow_empty",
|
||||||
|
"bworld:arrow_full",
|
||||||
|
);
|
||||||
|
},
|
||||||
|
on_render_labels(g) {
|
||||||
|
g.text(menu.title, 8, 6);
|
||||||
|
g.text("Inventory", 8, 73);
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// an 18 pixel square progress bar, value / max of full drawn over empty
|
||||||
|
function bar(
|
||||||
|
g: Graphics,
|
||||||
|
x: number,
|
||||||
|
y: number,
|
||||||
|
direction: "up" | "right",
|
||||||
|
value = 0,
|
||||||
|
max = 0,
|
||||||
|
empty: string,
|
||||||
|
full: string,
|
||||||
|
) {
|
||||||
|
const size = 18;
|
||||||
|
const done = max > 0 ? Math.max(0, Math.min(1, value / max)) : 0;
|
||||||
|
g.texture(empty, x, y, size, size);
|
||||||
|
if (direction === "right") {
|
||||||
|
g.texture(full, x, y, size * done, size, [0, 0, done, 1]);
|
||||||
|
} else {
|
||||||
|
g.texture(full, x, y + size * (1 - done), size, size * done, [0, 1 - done, 1, done]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
// CookingPotBlockEntity, cooks its recipes while something hot is under it, keeps the meal, and serves it into the
|
// CookingPotBlockEntity, cooks its recipes while something hot is under it, keeps the meal, and serves it into the
|
||||||
// container the meal needs (a bowl), or straight out when it needs none. the cutting board, like its
|
// container the meal needs (a bowl), or straight out when it needs none. the cutting board, like its
|
||||||
// CuttingBoardBlockEntity, holds a stack of anything and cuts it one at a time with the right tool
|
// CuttingBoardBlockEntity, holds a stack of anything and cuts it one at a time with the right tool
|
||||||
import type { BlockRef, Container, ItemStack, ScreenHandle, ServerContext } from "bworld/server";
|
import type { BlockRef, Container, ItemStack, ServerContext } from "bworld/server";
|
||||||
|
|
||||||
export function setup(ctx: ServerContext) {
|
export function setup(ctx: ServerContext) {
|
||||||
register_stove(ctx);
|
register_stove(ctx);
|
||||||
@@ -91,27 +91,6 @@ interface PotData {
|
|||||||
meal_container: string;
|
meal_container: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
const POT_BARS = [
|
|
||||||
{
|
|
||||||
x: 2.2,
|
|
||||||
y: 2,
|
|
||||||
value: "heat",
|
|
||||||
max: "heat_max",
|
|
||||||
direction: "up" as const,
|
|
||||||
empty_texture: "bworld:fire_empty",
|
|
||||||
full_texture: "bworld:fire_full",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
x: 4.6,
|
|
||||||
y: 0.5,
|
|
||||||
value: "progress",
|
|
||||||
max: "progress_max",
|
|
||||||
direction: "right" as const,
|
|
||||||
empty_texture: "bworld:arrow_empty",
|
|
||||||
full_texture: "bworld:arrow_full",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// an ingredient: an item, or a #tag of items any of which will do
|
// an ingredient: an item, or a #tag of items any of which will do
|
||||||
function item_or_tag(ctx: ServerContext, where: string, id: unknown) {
|
function item_or_tag(ctx: ServerContext, where: string, id: unknown) {
|
||||||
if (typeof id === "string" && id.startsWith("#")) {
|
if (typeof id === "string" && id.startsWith("#")) {
|
||||||
@@ -186,9 +165,6 @@ function matches(ingredients: string[][], items: string[], used = new Set<number
|
|||||||
|
|
||||||
function register_cooking_pot(ctx: ServerContext) {
|
function register_cooking_pot(ctx: ServerContext) {
|
||||||
const recipes = load_recipes(ctx);
|
const recipes = load_recipes(ctx);
|
||||||
// who's looking at each pot, by position, to keep their bars moving
|
|
||||||
const viewers = new Map<string, Set<ScreenHandle>>();
|
|
||||||
const key = (block: BlockRef) => `${block.x},${block.y},${block.z}`;
|
|
||||||
|
|
||||||
const pot_data = (block: BlockRef): PotData => {
|
const pot_data = (block: BlockRef): PotData => {
|
||||||
const existing = block.data?.container && ctx.containers.get(block.data.container);
|
const existing = block.data?.container && ctx.containers.get(block.data.container);
|
||||||
@@ -204,12 +180,24 @@ function register_cooking_pot(ctx: ServerContext) {
|
|||||||
return state === undefined || ctx.world.get_state(block.x, block.y - 1, block.z, state) === 1;
|
return state === undefined || ctx.world.get_state(block.x, block.y - 1, block.z, state) === 1;
|
||||||
};
|
};
|
||||||
|
|
||||||
const show = (screen: ScreenHandle, data: PotData, heated: boolean) => {
|
// like the java mod's CookingPotMenu, in gui pixels: the ingredients in 2 rows of 3, the meal, and the containers
|
||||||
screen.set_property("progress", data.cook_time);
|
// and served meal under it. the screen is in scripts/client.ts
|
||||||
screen.set_property("progress_max", data.cook_time_total);
|
const menu_type = ctx.menus.register<BlockRef>("farmersdelight:cooking_pot", (menu, block) => {
|
||||||
screen.set_property("heat", heated ? 1 : 0);
|
const container = ctx.containers.get(pot_data(block).container)!;
|
||||||
screen.set_property("heat_max", 1);
|
menu.title = "Cooking Pot";
|
||||||
};
|
for (let slot = 0; slot < INGREDIENT_SLOTS; slot++) {
|
||||||
|
menu.add_slot(container, slot, { x: 29 + (slot % 3) * 18, y: 16 + Math.floor(slot / 3) * 18 });
|
||||||
|
}
|
||||||
|
// the meal stays in the pot until it's served
|
||||||
|
menu.add_slot(container, MEAL_SLOT, { x: 122, y: 25, output_only: true, on_take: () => false });
|
||||||
|
menu.add_slot(container, CONTAINER_SLOT, { x: 90, y: 52 });
|
||||||
|
menu.add_slot(container, OUTPUT_SLOT, { x: 122, y: 52, output_only: true });
|
||||||
|
menu.add_player_inventory(7, 84);
|
||||||
|
menu.add_data("progress", () => (block.data as PotData | undefined)?.cook_time ?? 0);
|
||||||
|
menu.add_data("progress_max", () => (block.data as PotData | undefined)?.cook_time_total ?? 0);
|
||||||
|
menu.add_data("heated", () => is_heated(block) ? 1 : 0);
|
||||||
|
menu.still_valid_near(block);
|
||||||
|
});
|
||||||
|
|
||||||
// there's room in the meal slot for what it makes
|
// there's room in the meal slot for what it makes
|
||||||
const can_cook = (container: Container, recipe: CookingRecipe) => {
|
const can_cook = (container: Container, recipe: CookingRecipe) => {
|
||||||
@@ -275,26 +263,7 @@ function register_cooking_pot(ctx: ServerContext) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
const screen = ctx.ui.open_container(player, {
|
menu_type.open(player, block);
|
||||||
container,
|
|
||||||
layout: [
|
|
||||||
...Array.from(
|
|
||||||
{ length: INGREDIENT_SLOTS },
|
|
||||||
(_, slot) => ({ slot, x: 1.2 + slot % 3, y: Math.floor(slot / 3) }),
|
|
||||||
),
|
|
||||||
// the meal stays in the pot until it's served
|
|
||||||
{ slot: MEAL_SLOT, x: 6.4, y: 0.5, output_only: true, on_take: () => false },
|
|
||||||
{ slot: CONTAINER_SLOT, x: 4.6, y: 2 },
|
|
||||||
{ slot: OUTPUT_SLOT, x: 6.4, y: 2, output_only: true },
|
|
||||||
],
|
|
||||||
rows: 3,
|
|
||||||
bars: POT_BARS,
|
|
||||||
});
|
|
||||||
show(screen, data, is_heated(block));
|
|
||||||
const screens = viewers.get(key(block)) ?? new Set();
|
|
||||||
viewers.set(key(block), screens);
|
|
||||||
screens.add(screen);
|
|
||||||
screen.on_close(() => screens.delete(screen));
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
on_break(block) {
|
on_break(block) {
|
||||||
@@ -324,8 +293,6 @@ function register_cooking_pot(ctx: ServerContext) {
|
|||||||
data.cook_time = Math.max(0, data.cook_time - 2);
|
data.cook_time = Math.max(0, data.cook_time - 2);
|
||||||
}
|
}
|
||||||
serve(data, container);
|
serve(data, container);
|
||||||
|
|
||||||
for (const screen of viewers.get(key(block)) ?? []) show(screen, data, heated);
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,12 +3,11 @@
|
|||||||
// with any mod's, and draws the ones it doesn't know as their items in, then what comes out
|
// with any mod's, and draws the ones it doesn't know as their items in, then what comes out
|
||||||
import type { ClientContext, Color, Graphics, InventoryScreenView, TagApi } from "bworld/client";
|
import type { ClientContext, Color, Graphics, InventoryScreenView, TagApi } from "bworld/client";
|
||||||
|
|
||||||
// items and slots are drawn this big
|
// in gui pixels. items and slots are drawn this big
|
||||||
const CELL = 54;
|
const CELL = 18;
|
||||||
const GAP = 16;
|
const GAP = 5;
|
||||||
const TEXT = 22;
|
const LINE = 10;
|
||||||
const LINE = 30;
|
const BUTTON = 11;
|
||||||
const BUTTON = 32;
|
|
||||||
// catppuccin mocha, like the engine's gui: crust, pink, subtext 0 and blue
|
// catppuccin mocha, like the engine's gui: crust, pink, subtext 0 and blue
|
||||||
const SLOT_COLOR: Color = [0.07, 0.07, 0.11, 0.6];
|
const SLOT_COLOR: Color = [0.07, 0.07, 0.11, 0.6];
|
||||||
const HOVER_COLOR: Color = [0.96, 0.76, 0.91, 0.35];
|
const HOVER_COLOR: Color = [0.96, 0.76, 0.91, 0.35];
|
||||||
@@ -67,6 +66,12 @@ class RecipeViewer {
|
|||||||
if (this.#view && g.key_pressed("Backspace")) this.#back();
|
if (this.#view && g.key_pressed("Backspace")) this.#back();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the recipe views go with the inventory, it opens again on the item list
|
||||||
|
on_close() {
|
||||||
|
this.#view = undefined;
|
||||||
|
this.#history = [];
|
||||||
|
}
|
||||||
|
|
||||||
#open(item: string, mode: Mode) {
|
#open(item: string, mode: Mode) {
|
||||||
if (this.#find(item, mode).length === 0) return;
|
if (this.#find(item, mode).length === 0) return;
|
||||||
if (this.#view) this.#history.push(this.#view);
|
if (this.#view) this.#history.push(this.#view);
|
||||||
@@ -106,7 +111,7 @@ class RecipeViewer {
|
|||||||
this.#page = (this.#page + 1) % pages;
|
this.#page = (this.#page + 1) % pages;
|
||||||
}
|
}
|
||||||
const label = `${this.#page + 1}/${pages}`;
|
const label = `${this.#page + 1}/${pages}`;
|
||||||
g.text(label, left + (columns * CELL - g.measure_text(label)) / 2, GAP + (BUTTON - TEXT) / 2);
|
g.text(label, left + (columns * CELL - g.measure_text(label)) / 2, GAP + (BUTTON - g.text_height) / 2);
|
||||||
|
|
||||||
let hovered: string | undefined;
|
let hovered: string | undefined;
|
||||||
items.slice(this.#page * per_page, (this.#page + 1) * per_page).forEach((id, i) => {
|
items.slice(this.#page * per_page, (this.#page + 1) * per_page).forEach((id, i) => {
|
||||||
@@ -184,7 +189,7 @@ class RecipeViewer {
|
|||||||
view.page = (view.page + 1) % page_count;
|
view.page = (view.page + 1) % page_count;
|
||||||
}
|
}
|
||||||
const label = `${view.page + 1}/${page_count}`;
|
const label = `${view.page + 1}/${page_count}`;
|
||||||
g.text(label, x + (width - g.measure_text(label)) / 2, bottom + (BUTTON - TEXT) / 2, {
|
g.text(label, x + (width - g.measure_text(label)) / 2, bottom + (BUTTON - g.text_height) / 2, {
|
||||||
color: LABEL_COLOR,
|
color: LABEL_COLOR,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -270,7 +275,7 @@ class RecipeViewer {
|
|||||||
cell(output, x + 5 * CELL, made.length > 1 ? top + i * CELL : top + CELL / 2)
|
cell(output, x + 5 * CELL, made.length > 1 ? top + i * CELL : top + CELL / 2)
|
||||||
);
|
);
|
||||||
if (typeof recipe.cook_time === "number") {
|
if (typeof recipe.cook_time === "number") {
|
||||||
g.text(seconds(recipe.cook_time), x + 5 * CELL, top + CELL * 1.5 + (CELL - TEXT) / 2, {
|
g.text(seconds(recipe.cook_time), x + 5 * CELL, top + CELL * 1.5 + (CELL - g.text_height) / 2, {
|
||||||
color: LABEL_COLOR,
|
color: LABEL_COLOR,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+95
-152
@@ -11,21 +11,10 @@ import {
|
|||||||
TICKS_PER_SECOND,
|
TICKS_PER_SECOND,
|
||||||
} from "$/common/constants.ts";
|
} from "$/common/constants.ts";
|
||||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
||||||
import {
|
import { Container, ItemData, ItemStack } from "$/common/inventory.ts";
|
||||||
can_take_output,
|
|
||||||
click_slot,
|
|
||||||
Container,
|
|
||||||
ItemData,
|
|
||||||
ItemStack,
|
|
||||||
move_into,
|
|
||||||
room_for,
|
|
||||||
take_output,
|
|
||||||
} from "$/common/inventory.ts";
|
|
||||||
import {
|
import {
|
||||||
AIR_ID,
|
AIR_ID,
|
||||||
ClientMessage,
|
ClientMessage,
|
||||||
ContainerKey,
|
|
||||||
CRAFTING_RESULT_SLOT,
|
|
||||||
MAX_CHAT_LENGTH,
|
MAX_CHAT_LENGTH,
|
||||||
MAX_NAME_LENGTH,
|
MAX_NAME_LENGTH,
|
||||||
PROTOCOL_VERSION,
|
PROTOCOL_VERSION,
|
||||||
@@ -58,8 +47,9 @@ import {
|
|||||||
word,
|
word,
|
||||||
} from "$/common/commands.ts";
|
} from "$/common/commands.ts";
|
||||||
import type { GameLoop } from "./game_loop.ts";
|
import type { GameLoop } from "./game_loop.ts";
|
||||||
import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
|
import { update_crafting_result } from "./crafting.ts";
|
||||||
import { INVENTORY_SIZE, OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts";
|
import type { Menu } from "./menu.ts";
|
||||||
|
import { SavedPlayer, ServerPlayer } from "./player.ts";
|
||||||
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
|
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
|
||||||
import { ServerWorld, Tile } from "./world.ts";
|
import { ServerWorld, Tile } from "./world.ts";
|
||||||
import type { WorldSave } from "./saves.ts";
|
import type { WorldSave } from "./saves.ts";
|
||||||
@@ -274,7 +264,7 @@ export class GameServer {
|
|||||||
if (!player) {
|
if (!player) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.#close_screen(player);
|
this.#close_menu(player);
|
||||||
this.#saved_players[player.name] = player.save_player();
|
this.#saved_players[player.name] = player.save_player();
|
||||||
this.world.dirty = true;
|
this.world.dirty = true;
|
||||||
this.#players.delete(conn);
|
this.#players.delete(conn);
|
||||||
@@ -345,6 +335,7 @@ export class GameServer {
|
|||||||
this.#tick_entities();
|
this.#tick_entities();
|
||||||
|
|
||||||
this.mods.tick();
|
this.mods.tick();
|
||||||
|
this.#tick_menus();
|
||||||
this.mods.check_watched_containers();
|
this.mods.check_watched_containers();
|
||||||
|
|
||||||
for (const [conn, pending] of this.#pending) {
|
for (const [conn, pending] of this.#pending) {
|
||||||
@@ -609,7 +600,7 @@ export class GameServer {
|
|||||||
return { id, container };
|
return { id, container };
|
||||||
}
|
}
|
||||||
|
|
||||||
// anyone looking at it gets their screen closed
|
// anyone with a menu showing it gets it closed
|
||||||
delete_container(id: string) {
|
delete_container(id: string) {
|
||||||
const container = this.containers.get(id);
|
const container = this.containers.get(id);
|
||||||
if (!container) {
|
if (!container) {
|
||||||
@@ -618,29 +609,46 @@ export class GameServer {
|
|||||||
this.containers.delete(id);
|
this.containers.delete(id);
|
||||||
this.world.dirty = true;
|
this.world.dirty = true;
|
||||||
for (const player of this.#players.values()) {
|
for (const player of this.#players.values()) {
|
||||||
if (player.screen?.container === container) {
|
if (player.menu?.uses(container)) {
|
||||||
this.close_screen(player);
|
this.close_menu(player);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// screens
|
// menus
|
||||||
|
|
||||||
open_screen(player: ServerPlayer, screen: OpenScreen) {
|
// the id a new menu for this player gets, 1 to 100 and around, like minecraft's containerCounter
|
||||||
this.#close_screen(player);
|
next_menu_id(player: ServerPlayer): number {
|
||||||
player.screen = screen;
|
player.menu_id = player.menu_id % 100 + 1;
|
||||||
this.#send(player, { type: "open_screen", layout: screen.layout, properties: { ...screen.properties } });
|
return player.menu_id;
|
||||||
player.sent.set("properties", JSON.stringify(screen.properties));
|
}
|
||||||
player.sent.delete("screen");
|
|
||||||
|
// replaces whatever they had open
|
||||||
|
open_menu(player: ServerPlayer, menu: Menu) {
|
||||||
|
this.#close_menu(player);
|
||||||
|
player.menu = menu;
|
||||||
|
const data = menu.data_values();
|
||||||
|
this.#send(player, {
|
||||||
|
type: "open_menu",
|
||||||
|
id: menu.id,
|
||||||
|
menu_type: menu.type,
|
||||||
|
title: menu.title,
|
||||||
|
open_data: menu.open_data,
|
||||||
|
slots: menu.slot_info(),
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
player.sent.set("menu_data", JSON.stringify(data));
|
||||||
|
player.sent.delete("menu_content");
|
||||||
}
|
}
|
||||||
|
|
||||||
// closes it for the player too, not just on the server
|
// closes it for the player too, not just on the server
|
||||||
close_screen(player: ServerPlayer) {
|
close_menu(player: ServerPlayer) {
|
||||||
if (!player.screen) {
|
const menu = player.menu;
|
||||||
|
if (!menu) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.#close_screen(player);
|
this.#close_menu(player);
|
||||||
this.#send(player, { type: "close_screen" });
|
this.#send(player, { type: "close_menu", id: menu.id });
|
||||||
}
|
}
|
||||||
|
|
||||||
// version 2 saves had chests and furnaces in the engine, with their fields in data and their items in
|
// version 2 saves had chests and furnaces in the engine, with their fields in data and their items in
|
||||||
@@ -692,7 +700,13 @@ export class GameServer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#join(conn: number, raw_name: unknown, view_distance: number) {
|
#join(conn: number, raw_name: unknown, view_distance: number) {
|
||||||
const player = new ServerPlayer(this.entities, conn, this.#unique_name(raw_name), view_distance);
|
const player = new ServerPlayer(
|
||||||
|
this.entities,
|
||||||
|
conn,
|
||||||
|
this.#unique_name(raw_name),
|
||||||
|
view_distance,
|
||||||
|
() => this.recipes.shaped,
|
||||||
|
);
|
||||||
const saved = this.#saved_players[player.name];
|
const saved = this.#saved_players[player.name];
|
||||||
if (saved) {
|
if (saved) {
|
||||||
player.load_player(saved);
|
player.load_player(saved);
|
||||||
@@ -784,13 +798,21 @@ export class GameServer {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case "click":
|
case "click":
|
||||||
this.#click(player, message.container, message.index, message.button, message.shift === true);
|
this.#click(player, message.menu, message.slot, message.button, message.shift === true);
|
||||||
break;
|
break;
|
||||||
case "drop_item":
|
case "drop_item":
|
||||||
this.#drop_item(player, message.container, message.index, message.all === true);
|
this.#drop_item(player, message.menu, message.slot, message.all === true);
|
||||||
break;
|
break;
|
||||||
case "close_screen":
|
case "menu_button":
|
||||||
this.#close_screen(player);
|
if (player.menu && message.menu === player.menu.id && is_int(message.button)) {
|
||||||
|
this.mods.menu_button(player, player.menu, message.button);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "close_menu":
|
||||||
|
// one that's already gone, the server closed it, or menu 0: the inventory screen
|
||||||
|
if (message.menu === (player.menu?.id ?? 0)) {
|
||||||
|
this.#close_menu(player);
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
case "chat":
|
case "chat":
|
||||||
this.#chat(player, message.text);
|
this.#chat(player, message.text);
|
||||||
@@ -989,113 +1011,31 @@ export class GameServer {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#drop_item(player: ServerPlayer, key: unknown, index: unknown, all: boolean) {
|
#drop_item(player: ServerPlayer, id: unknown, slot: unknown, all: boolean) {
|
||||||
if (!is_int(index)) {
|
const menu = player.container_menu;
|
||||||
|
if (id !== menu.id || !is_int(slot)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const container = this.#get_container(player, key as ContainerKey);
|
const thrown = menu.drop(slot, all);
|
||||||
// the crafting result isn't an item yet, minecraft crafts it first but that's not supported
|
if (thrown) {
|
||||||
if (
|
this.throw_item(player, thrown);
|
||||||
!container || index < 0 || index >= container.size || (key === "crafting" && index === CRAFTING_RESULT_SLOT)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const item = container.get_item(index);
|
|
||||||
if (!item) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const thrown = item.clone();
|
|
||||||
thrown.amount = all ? item.amount : 1;
|
|
||||||
item.amount -= thrown.amount;
|
|
||||||
container.set_item(index, item.amount > 0 ? item : undefined);
|
|
||||||
if (key === "crafting") {
|
|
||||||
update_crafting_result(container, this.recipes.shaped);
|
|
||||||
}
|
|
||||||
this.throw_item(player, thrown);
|
|
||||||
}
|
|
||||||
|
|
||||||
#click(player: ServerPlayer, key: unknown, index: unknown, button: unknown, shift: boolean) {
|
|
||||||
if (!is_int(index) || !is_int(button)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const container = this.#get_container(player, key as ContainerKey);
|
|
||||||
if (!container || index < 0 || index >= container.size) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shift) {
|
|
||||||
this.#quick_move(player, key as ContainerKey, container, index);
|
|
||||||
} else if (key === "crafting" && index === CRAFTING_RESULT_SLOT) {
|
|
||||||
const result = container.get_item(CRAFTING_RESULT_SLOT);
|
|
||||||
if (result && take_output(result, player.cursor)) {
|
|
||||||
consume_recipe_items(container);
|
|
||||||
}
|
|
||||||
} else if (key === "screen" && player.screen?.layout.slots.find((s) => s.index === index)?.output) {
|
|
||||||
const item = container.get_item(index);
|
|
||||||
const allowed = (item: ItemStack) => player.screen?.on_take.get(index)?.(item) ?? true;
|
|
||||||
if (item && can_take_output(item, player.cursor) && allowed(item) && take_output(item, player.cursor)) {
|
|
||||||
container.set_item(index, undefined);
|
|
||||||
}
|
|
||||||
} else if (
|
|
||||||
key === "screen" && player.cursor.item && !(player.screen?.filters.get(index)?.(player.cursor.item) ?? true)
|
|
||||||
) {
|
|
||||||
// the slot doesn't take what the cursor holds
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
click_slot(container, index, player.cursor, button);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (key === "crafting") {
|
|
||||||
update_crafting_result(container, this.recipes.shaped);
|
|
||||||
}
|
|
||||||
if (key === "screen" || (shift && player.screen)) {
|
|
||||||
this.world.dirty = true;
|
this.world.dirty = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// shift click, like minecraft's quick move: the stack goes to the other part of the screen, as much as fits. with a
|
// clicks for a menu that's already closed are ignored, like minecraft's
|
||||||
// container open that's between it and the inventory, otherwise between the hotbar and the rest of the inventory
|
#click(player: ServerPlayer, id: unknown, slot: unknown, button: unknown, shift: boolean) {
|
||||||
#quick_move(player: ServerPlayer, key: ContainerKey, container: Container, index: number) {
|
const menu = player.container_menu;
|
||||||
const inventory = player.inventory;
|
if (id !== menu.id || !is_int(slot) || !is_int(button) || slot < 0 || slot >= menu.slots.length) {
|
||||||
const hotbar = Array.from({ length: 9 }, (_, i) => i);
|
|
||||||
const main = Array.from({ length: INVENTORY_SIZE - 9 }, (_, i) => i + 9);
|
|
||||||
// like minecraft, what comes out of a container fills the hotbar from the right first
|
|
||||||
const from_container = [...main, ...hotbar].reverse();
|
|
||||||
const item = container.get_item(index);
|
|
||||||
if (!item) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (shift) {
|
||||||
if (key === "crafting" && index === CRAFTING_RESULT_SLOT) {
|
menu.quick_move(slot);
|
||||||
// crafts as many as fit, while the grid keeps making the same thing
|
|
||||||
const id = item.type_id;
|
|
||||||
let result: ItemStack | undefined = item;
|
|
||||||
while (result?.type_id === id && room_for(result, inventory, from_container) >= result.amount) {
|
|
||||||
move_into(result.clone(), inventory, from_container);
|
|
||||||
consume_recipe_items(container);
|
|
||||||
update_crafting_result(container, this.recipes.shaped);
|
|
||||||
result = container.get_item(CRAFTING_RESULT_SLOT);
|
|
||||||
}
|
|
||||||
} else if (key === "crafting") {
|
|
||||||
move_into(item, inventory, [...main, ...hotbar]);
|
|
||||||
} else if (key === "screen") {
|
|
||||||
const screen = player.screen!;
|
|
||||||
const output = screen.layout.slots.find((s) => s.index === index)?.output;
|
|
||||||
if (!output) {
|
|
||||||
move_into(item, inventory, from_container);
|
|
||||||
} else if (
|
|
||||||
room_for(item, inventory, from_container) >= item.amount && (screen.on_take.get(index)?.(item) ?? true)
|
|
||||||
) {
|
|
||||||
move_into(item.clone(), inventory, from_container);
|
|
||||||
container.set_item(index, undefined);
|
|
||||||
}
|
|
||||||
} else if (player.screen) {
|
|
||||||
const screen = player.screen;
|
|
||||||
const inputs = screen.layout.slots.filter((s) => !s.output).map((s) => s.index);
|
|
||||||
move_into(item, screen.container, inputs, (i) => screen.filters.get(i)?.(item) ?? true);
|
|
||||||
} else {
|
} else {
|
||||||
move_into(item, inventory, index < 9 ? main : hotbar);
|
menu.click(slot, button, player.cursor);
|
||||||
|
}
|
||||||
|
if (menu !== player.inventory_menu) {
|
||||||
|
this.world.dirty = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1346,12 +1286,12 @@ export class GameServer {
|
|||||||
.finally(() => player.downloading_skin = false);
|
.finally(() => player.downloading_skin = false);
|
||||||
}
|
}
|
||||||
|
|
||||||
#close_screen(player: ServerPlayer) {
|
#close_menu(player: ServerPlayer) {
|
||||||
const screen = player.screen;
|
const menu = player.menu;
|
||||||
player.screen = undefined;
|
player.menu = undefined;
|
||||||
for (const fn of screen?.on_close ?? []) fn();
|
for (const fn of menu?.on_close ?? []) fn();
|
||||||
player.sent.delete("screen");
|
player.sent.delete("menu_content");
|
||||||
player.sent.delete("properties");
|
player.sent.delete("menu_data");
|
||||||
|
|
||||||
// the crafting grid and whatever the cursor holds go back into the inventory
|
// the crafting grid and whatever the cursor holds go back into the inventory
|
||||||
for (let i = 0; i < 9; i++) {
|
for (let i = 0; i < 9; i++) {
|
||||||
@@ -1400,7 +1340,7 @@ export class GameServer {
|
|||||||
#kill(player: ServerPlayer, source: DamageSource) {
|
#kill(player: ServerPlayer, source: DamageSource) {
|
||||||
const cause = source.cause;
|
const cause = source.cause;
|
||||||
const { x, y, z } = player;
|
const { x, y, z } = player;
|
||||||
this.close_screen(player);
|
this.close_menu(player);
|
||||||
for (let i = 0; i < player.inventory.size; i++) {
|
for (let i = 0; i < player.inventory.size; i++) {
|
||||||
const item = player.inventory.get_item(i);
|
const item = player.inventory.get_item(i);
|
||||||
if (item) {
|
if (item) {
|
||||||
@@ -1555,14 +1495,16 @@ export class GameServer {
|
|||||||
|
|
||||||
// helpers
|
// helpers
|
||||||
|
|
||||||
#get_container(player: ServerPlayer, key: ContainerKey): Container | undefined {
|
// the open menus' still_valid and on_tick
|
||||||
switch (key) {
|
#tick_menus() {
|
||||||
case "inventory":
|
for (const player of this.#players.values()) {
|
||||||
return player.inventory;
|
const menu = player.menu;
|
||||||
case "crafting":
|
if (!menu) continue;
|
||||||
return player.crafting;
|
if (!menu.still_valid.every((valid) => valid())) {
|
||||||
case "screen":
|
this.close_menu(player);
|
||||||
return player.screen?.container;
|
continue;
|
||||||
|
}
|
||||||
|
for (const fn of menu.on_tick) fn();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1590,11 +1532,12 @@ export class GameServer {
|
|||||||
const attack_speed = player.attribute(ATTRIBUTES.attack_speed);
|
const attack_speed = player.attribute(ATTRIBUTES.attack_speed);
|
||||||
sync("attack_speed", attack_speed, () => ({ type: "attack_speed", value: attack_speed }));
|
sync("attack_speed", attack_speed, () => ({ type: "attack_speed", value: attack_speed }));
|
||||||
|
|
||||||
if (player.screen) {
|
const menu = player.menu;
|
||||||
const items = player.screen.container.to_synced_data();
|
if (menu) {
|
||||||
sync("screen", items, () => ({ type: "container", container: "screen", items }));
|
const items = menu.content();
|
||||||
const properties = { ...player.screen.properties };
|
sync("menu_content", items, () => ({ type: "menu_content", id: menu.id, items }));
|
||||||
sync("properties", properties, () => ({ type: "screen_properties", properties }));
|
const data = menu.data_values();
|
||||||
|
sync("menu_data", data, () => ({ type: "menu_data", id: menu.id, data }));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
// menus, like neoforge's AbstractContainerMenu: what a player can do in a gui. the server's menu decides what every
|
||||||
|
// click does, clients only draw it. see docs/modding/inventories/menus.md
|
||||||
|
import {
|
||||||
|
can_take_output,
|
||||||
|
click_slot,
|
||||||
|
type Container,
|
||||||
|
type Cursor,
|
||||||
|
type ItemData,
|
||||||
|
type ItemStack,
|
||||||
|
move_into,
|
||||||
|
room_for,
|
||||||
|
take_output,
|
||||||
|
} from "$/common/inventory.ts";
|
||||||
|
import { CRAFTING_RESULT_SLOT, type MenuSlotInfo, PLAYER_MENU, PLAYER_MENU_CRAFTING } from "$/common/protocol.ts";
|
||||||
|
import type { GridRecipe } from "$/common/mod_data.ts";
|
||||||
|
import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
|
||||||
|
|
||||||
|
export interface MenuSlot {
|
||||||
|
container: Container;
|
||||||
|
index: number;
|
||||||
|
// gui pixels from the screen's top left, for the client
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
// what can be put in
|
||||||
|
filter?: (item: ItemStack) => boolean;
|
||||||
|
// can only be taken from, all at once, like the furnace result
|
||||||
|
output?: boolean;
|
||||||
|
// asked before a player takes from an output slot, false stops them
|
||||||
|
on_take?: (item: ItemStack) => boolean;
|
||||||
|
// drawn in the slot while it's empty
|
||||||
|
icon?: string;
|
||||||
|
// one of the player's own inventory slots, this one
|
||||||
|
inventory?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Menu {
|
||||||
|
readonly id: number;
|
||||||
|
readonly type: string;
|
||||||
|
title = "";
|
||||||
|
// sent once when it opens
|
||||||
|
open_data: unknown = null;
|
||||||
|
slots: MenuSlot[] = [];
|
||||||
|
// numbers the screen shows, read every tick and sent when they change, like DataSlot
|
||||||
|
data = new Map<string, () => number>();
|
||||||
|
// checked every tick, any false closes it, like stillValid
|
||||||
|
still_valid: (() => boolean)[] = [];
|
||||||
|
on_button: ((button: number) => void)[] = [];
|
||||||
|
// the menu slots a shift click on a slot tries, in order. the default rule when not set
|
||||||
|
quick_move_order: ((index: number) => number[]) | undefined;
|
||||||
|
on_tick: (() => void)[] = [];
|
||||||
|
on_close: (() => void)[] = [];
|
||||||
|
// after anything a click changed, like the crafting grid working out its result
|
||||||
|
on_changed: (() => void) | undefined;
|
||||||
|
|
||||||
|
constructor(id: number, type: string) {
|
||||||
|
this.id = id;
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
accepts(slot: MenuSlot, item: ItemStack): boolean {
|
||||||
|
return !slot.output && (slot.filter?.(item) ?? true);
|
||||||
|
}
|
||||||
|
|
||||||
|
click(index: number, button: number, cursor: Cursor) {
|
||||||
|
const slot = this.slots[index];
|
||||||
|
if (!slot) return;
|
||||||
|
if (slot.output) {
|
||||||
|
const item = slot.container.get_item(slot.index);
|
||||||
|
if (item && can_take_output(item, cursor) && (slot.on_take?.(item) ?? true) && take_output(item, cursor)) {
|
||||||
|
slot.container.set_item(slot.index, undefined);
|
||||||
|
}
|
||||||
|
} else if (cursor.item && !this.accepts(slot, cursor.item)) {
|
||||||
|
// the slot doesn't take what the cursor holds
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
click_slot(slot.container, slot.index, cursor, button);
|
||||||
|
}
|
||||||
|
this.on_changed?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
// shift click, like minecraft's quickMoveStack: the stack goes to the other part of the menu, as much as fits. an
|
||||||
|
// output slot only gives its item when it all fits
|
||||||
|
quick_move(index: number) {
|
||||||
|
const slot = this.slots[index];
|
||||||
|
const item = slot?.container.get_item(slot.index);
|
||||||
|
if (!item) return;
|
||||||
|
const targets = this.quick_move_targets(index).filter((i) => i !== index).map((i) => this.slots[i])
|
||||||
|
.filter((target) => target !== undefined);
|
||||||
|
const accepts = (target: { container: Container; index: number }) => this.accepts(target as MenuSlot, item);
|
||||||
|
if (!slot.output) {
|
||||||
|
move_into(item, targets, accepts);
|
||||||
|
} else if (room_for(item, targets, accepts) >= item.amount && (slot.on_take?.(item) ?? true)) {
|
||||||
|
move_into(item.clone(), targets, accepts);
|
||||||
|
slot.container.set_item(slot.index, undefined);
|
||||||
|
}
|
||||||
|
this.on_changed?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
// what's in the player's inventory goes into the menu's own slots that take it, what's in those goes to the
|
||||||
|
// inventory. with nothing to go into, between the hotbar and the rest of the inventory
|
||||||
|
quick_move_targets(index: number): number[] {
|
||||||
|
if (this.quick_move_order) return this.quick_move_order(index);
|
||||||
|
const slot = this.slots[index];
|
||||||
|
const inventory = this.slots.map((s, i) => ({ s, i })).filter(({ s }) => s.inventory !== undefined)
|
||||||
|
.sort((a, b) => a.s.inventory! - b.s.inventory!);
|
||||||
|
const hotbar = inventory.filter(({ s }) => s.inventory! < 9).map(({ i }) => i);
|
||||||
|
const main = inventory.filter(({ s }) => s.inventory! >= 9).map(({ i }) => i);
|
||||||
|
if (slot.inventory === undefined) {
|
||||||
|
// like minecraft, what comes out of a container fills the hotbar from the right first
|
||||||
|
return [...main, ...hotbar].reverse();
|
||||||
|
}
|
||||||
|
const inputs = this.slots.flatMap((s, i) => s.inventory === undefined && !s.output ? [i] : []);
|
||||||
|
if (inputs.length > 0) return inputs;
|
||||||
|
return slot.inventory < 9 ? main : hotbar;
|
||||||
|
}
|
||||||
|
|
||||||
|
// q on a slot: takes one item out, or the whole stack, for the server to throw. not from output slots
|
||||||
|
drop(index: number, all: boolean): ItemStack | undefined {
|
||||||
|
const slot = this.slots[index];
|
||||||
|
const item = slot && !slot.output ? slot.container.get_item(slot.index) : undefined;
|
||||||
|
if (!item) return undefined;
|
||||||
|
const thrown = item.clone();
|
||||||
|
thrown.amount = all ? item.amount : 1;
|
||||||
|
item.amount -= thrown.amount;
|
||||||
|
slot.container.set_item(slot.index, item.amount > 0 ? item : undefined);
|
||||||
|
this.on_changed?.();
|
||||||
|
return thrown;
|
||||||
|
}
|
||||||
|
|
||||||
|
uses(container: Container): boolean {
|
||||||
|
return this.slots.some((slot) => slot.container === container);
|
||||||
|
}
|
||||||
|
|
||||||
|
slot_info(): MenuSlotInfo[] {
|
||||||
|
return this.slots.map(({ x, y, output, icon }) => ({
|
||||||
|
x,
|
||||||
|
y,
|
||||||
|
...(output ? { output: true } : {}),
|
||||||
|
...(icon ? { icon } : {}),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
// what players are sent, with lore
|
||||||
|
content(): (ItemData | null)[] {
|
||||||
|
return this.slots.map((slot) => slot.container.get_item(slot.index)?.to_synced_data() ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
data_values(): Record<string, number> {
|
||||||
|
const values: Record<string, number> = {};
|
||||||
|
for (const [name, get] of this.data) {
|
||||||
|
const value = get();
|
||||||
|
values[name] = typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// menu 0, the player's own inventory and crafting grid, like minecraft's InventoryMenu. clients know its layout, so
|
||||||
|
// it's never sent
|
||||||
|
export class PlayerMenu extends Menu {
|
||||||
|
#crafting: Container;
|
||||||
|
#recipes: () => GridRecipe[];
|
||||||
|
|
||||||
|
constructor(inventory: Container, crafting: Container, recipes: () => GridRecipe[]) {
|
||||||
|
super(PLAYER_MENU, "");
|
||||||
|
this.#crafting = crafting;
|
||||||
|
this.#recipes = recipes;
|
||||||
|
for (let i = 0; i < inventory.size; i++) {
|
||||||
|
this.slots.push({ container: inventory, index: i, x: 0, y: 0, inventory: i });
|
||||||
|
}
|
||||||
|
for (let i = 0; i < crafting.size; i++) {
|
||||||
|
this.slots.push({ container: crafting, index: i, x: 0, y: 0 });
|
||||||
|
}
|
||||||
|
const result = this.slots[PLAYER_MENU_CRAFTING + CRAFTING_RESULT_SLOT];
|
||||||
|
result.output = true;
|
||||||
|
// taking the result uses up the grid
|
||||||
|
result.on_take = () => {
|
||||||
|
consume_recipe_items(crafting);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
this.on_changed = () => update_crafting_result(crafting, this.#recipes());
|
||||||
|
}
|
||||||
|
|
||||||
|
override quick_move(index: number) {
|
||||||
|
if (index !== PLAYER_MENU_CRAFTING + CRAFTING_RESULT_SLOT) {
|
||||||
|
super.quick_move(index);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// crafts as many as fit, while the grid keeps making the same thing
|
||||||
|
const targets = this.quick_move_targets(index).map((i) => this.slots[i]);
|
||||||
|
const id = this.#crafting.get_item(CRAFTING_RESULT_SLOT)?.type_id;
|
||||||
|
let result = this.#crafting.get_item(CRAFTING_RESULT_SLOT);
|
||||||
|
while (result && result.type_id === id && room_for(result, targets) >= result.amount) {
|
||||||
|
move_into(result.clone(), targets);
|
||||||
|
consume_recipe_items(this.#crafting);
|
||||||
|
update_crafting_result(this.#crafting, this.#recipes());
|
||||||
|
result = this.#crafting.get_item(CRAFTING_RESULT_SLOT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// the inventory moves between the hotbar and the rest, never into the grid. the grid and its result go to the
|
||||||
|
// inventory, the rest first
|
||||||
|
override quick_move_targets(index: number): number[] {
|
||||||
|
const main = Array.from({ length: PLAYER_MENU_CRAFTING - 9 }, (_, i) => i + 9);
|
||||||
|
const hotbar = Array.from({ length: 9 }, (_, i) => i);
|
||||||
|
if (index >= PLAYER_MENU_CRAFTING) {
|
||||||
|
return index === PLAYER_MENU_CRAFTING + CRAFTING_RESULT_SLOT
|
||||||
|
? [...main, ...hotbar].reverse()
|
||||||
|
: [...main, ...hotbar];
|
||||||
|
}
|
||||||
|
return index < 9 ? main : hotbar;
|
||||||
|
}
|
||||||
|
}
|
||||||
+141
-74
@@ -11,13 +11,14 @@ import type {
|
|||||||
CommandRegistry,
|
CommandRegistry,
|
||||||
CommandSource,
|
CommandSource,
|
||||||
Container,
|
Container,
|
||||||
ContainerScreenOptions,
|
|
||||||
EntityRef,
|
EntityRef,
|
||||||
EventSignal,
|
EventSignal,
|
||||||
ItemComponent,
|
ItemComponent,
|
||||||
ItemStack,
|
ItemStack,
|
||||||
|
MenuBuilder,
|
||||||
|
MenuHandle,
|
||||||
|
MenuType,
|
||||||
Player,
|
Player,
|
||||||
ScreenHandle,
|
|
||||||
ServerAfterEvents,
|
ServerAfterEvents,
|
||||||
ServerBeforeEvents,
|
ServerBeforeEvents,
|
||||||
ServerContext,
|
ServerContext,
|
||||||
@@ -40,12 +41,12 @@ import {
|
|||||||
} from "$/common/commands.ts";
|
} from "$/common/commands.ts";
|
||||||
import { AIR_ID } from "$/common/protocol.ts";
|
import { AIR_ID } from "$/common/protocol.ts";
|
||||||
import type { GameServer } from "./game_server.ts";
|
import type { GameServer } from "./game_server.ts";
|
||||||
import type { OpenScreen, ServerPlayer } from "./player.ts";
|
import type { ServerPlayer } from "./player.ts";
|
||||||
|
import { Menu, type MenuSlot } from "./menu.ts";
|
||||||
import { MAX_HEALTH } from "./vitals.ts";
|
import { MAX_HEALTH } from "./vitals.ts";
|
||||||
import type { Entity } from "./entity/entity.ts";
|
import type { Entity } from "./entity/entity.ts";
|
||||||
import { create_entity } from "./entity/entity_types.ts";
|
import { create_entity } from "./entity/entity_types.ts";
|
||||||
import { attribute_type, type AttributeType, MODIFIER_OPERATIONS } from "./entity/attributes.ts";
|
import { attribute_type, type AttributeType, MODIFIER_OPERATIONS } from "./entity/attributes.ts";
|
||||||
import type { ScreenLayout } from "$/common/protocol.ts";
|
|
||||||
|
|
||||||
// a list of handlers that can't break each other: one throwing is logged under its mod and the rest still run
|
// a list of handlers that can't break each other: one throwing is logged under its mod and the rest still run
|
||||||
export class Signal<T> {
|
export class Signal<T> {
|
||||||
@@ -146,20 +147,33 @@ export class ModRuntime {
|
|||||||
|
|
||||||
// a player's client sent a mod message. clients are untrusted: too big or too many are dropped
|
// a player's client sent a mod message. clients are untrusted: too big or too many are dropped
|
||||||
receive(player: ServerPlayer, channel: string, data: unknown) {
|
receive(player: ServerPlayer, channel: string, data: unknown) {
|
||||||
|
if (!this.#count_message(player)) return;
|
||||||
|
if ((JSON.stringify(data) ?? "").length > MAX_MOD_MESSAGE_LENGTH) return;
|
||||||
|
for (const { mod, handler } of this.#net_handlers.get(channel) ?? []) {
|
||||||
|
run_guarded(mod, `a ${channel} handler`, () => handler(this.player(player), data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// a client pressed a button of its open menu. buttons count as mod messages, clients are untrusted
|
||||||
|
menu_button(player: ServerPlayer, menu: Menu, button: number) {
|
||||||
|
if (!this.#count_message(player)) return;
|
||||||
|
for (const fn of [...menu.on_button]) fn(button);
|
||||||
|
}
|
||||||
|
|
||||||
|
// false once a player has sent too many this second
|
||||||
|
#count_message(player: ServerPlayer): boolean {
|
||||||
const second = Math.floor(Date.now() / 1000);
|
const second = Math.floor(Date.now() / 1000);
|
||||||
let counts = this.#net_counts.get(player);
|
let counts = this.#net_counts.get(player);
|
||||||
if (!counts || counts.second !== second) {
|
if (!counts || counts.second !== second) {
|
||||||
counts = { second, count: 0 };
|
counts = { second, count: 0 };
|
||||||
this.#net_counts.set(player, counts);
|
this.#net_counts.set(player, counts);
|
||||||
}
|
}
|
||||||
if (++counts.count > MAX_MOD_MESSAGES_PER_SECOND) return;
|
return ++counts.count <= MAX_MOD_MESSAGES_PER_SECOND;
|
||||||
if ((JSON.stringify(data) ?? "").length > MAX_MOD_MESSAGE_LENGTH) return;
|
|
||||||
for (const { mod, handler } of this.#net_handlers.get(channel) ?? []) {
|
|
||||||
run_guarded(mod, `a ${channel} handler`, () => handler(this.player(player), data));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// the other way, for apis that take a player
|
// the other way, for apis that take a player
|
||||||
#server_players = new WeakMap<Player, ServerPlayer>();
|
#server_players = new WeakMap<Player, ServerPlayer>();
|
||||||
|
// menu types by id, every mod's
|
||||||
|
#menu_types = new Set<string>();
|
||||||
game!: GameServer;
|
game!: GameServer;
|
||||||
|
|
||||||
// imports each server script and calls its setup, in load order
|
// imports each server script and calls its setup, in load order
|
||||||
@@ -555,12 +569,22 @@ export class ModRuntime {
|
|||||||
},
|
},
|
||||||
delete: (id) => game().delete_container(id),
|
delete: (id) => game().delete_container(id),
|
||||||
},
|
},
|
||||||
|
menus: {
|
||||||
|
register: <Args>(id: string, build: (menu: MenuBuilder, args: Args, player: Player) => void) => {
|
||||||
|
own(id, "menu type");
|
||||||
|
if (this.#menu_types.has(id)) throw new Error(`[${mod}] menu type ${id} is already registered`);
|
||||||
|
this.#menu_types.add(id);
|
||||||
|
const type: MenuType<Args> = {
|
||||||
|
id,
|
||||||
|
open: (player, args) => this.#open_menu(mod, id, player, (menu) => build(menu, args, player)),
|
||||||
|
};
|
||||||
|
return type;
|
||||||
|
},
|
||||||
|
},
|
||||||
ui: {
|
ui: {
|
||||||
open_container: (player, options) => this.#open_container(mod, player, options),
|
|
||||||
message_form: not_yet(mod, "ui.message_form", "see docs/modding_plan.md"),
|
message_form: not_yet(mod, "ui.message_form", "see docs/modding_plan.md"),
|
||||||
action_form: not_yet(mod, "ui.action_form", "see docs/modding_plan.md"),
|
action_form: not_yet(mod, "ui.action_form", "see docs/modding_plan.md"),
|
||||||
modal_form: not_yet(mod, "ui.modal_form", "see docs/modding_plan.md"),
|
modal_form: not_yet(mod, "ui.modal_form", "see docs/modding_plan.md"),
|
||||||
open_screen: not_yet(mod, "ui.open_screen", "see docs/modding_plan.md"),
|
|
||||||
},
|
},
|
||||||
net: {
|
net: {
|
||||||
on: (channel, handler) => {
|
on: (channel, handler) => {
|
||||||
@@ -598,89 +622,125 @@ export class ModRuntime {
|
|||||||
return ctx;
|
return ctx;
|
||||||
}
|
}
|
||||||
|
|
||||||
#open_container(mod: string, player: Player, options: ContainerScreenOptions): ScreenHandle {
|
// builds a menu with the mod's function and opens it. a build that throws opens nothing
|
||||||
|
#open_menu(mod: string, type: string, player: Player, build: (menu: MenuBuilder) => void): MenuHandle {
|
||||||
const game = this.game;
|
const game = this.game;
|
||||||
const server_player = this.#server_players.get(player);
|
const server_player = this.#server_players.get(player);
|
||||||
if (!server_player || !game.players().includes(server_player)) {
|
if (!server_player || !game.players().includes(server_player)) {
|
||||||
throw new Error(`${player.name} isn't online`);
|
throw new Error(`${player.name} isn't online`);
|
||||||
}
|
}
|
||||||
const container = game.containers.get(options.container.id);
|
const menu = new Menu(game.next_menu_id(server_player), type);
|
||||||
if (!container) {
|
const guarded = <T>(what: string, fn: () => T) => run_guarded(mod, what, fn);
|
||||||
throw new Error("open_container needs a container from ctx.containers");
|
|
||||||
}
|
|
||||||
|
|
||||||
const filters = new Map<number, (item: EngineItemStack) => boolean>();
|
build({
|
||||||
const on_take = new Map<number, (item: EngineItemStack) => boolean>();
|
get title() {
|
||||||
for (const { slot, filter, on_take: take } of options.layout) {
|
return menu.title;
|
||||||
if (take) {
|
},
|
||||||
on_take.set(slot, (item) => run_guarded(mod, "an on_take", () => take(item_api(item))) === true);
|
set title(value) {
|
||||||
}
|
menu.title = String(value);
|
||||||
if (!Number.isInteger(slot) || slot < 0 || slot >= container.size) {
|
},
|
||||||
throw new Error(`slot ${slot} isn't in the container, it has ${container.size}`);
|
get open_data() {
|
||||||
}
|
return menu.open_data;
|
||||||
if (filter === "smeltable") {
|
},
|
||||||
filters.set(slot, (item) => game.recipes.furnace.has(item.type_id));
|
set open_data(value) {
|
||||||
} else if (filter === "fuel") {
|
menu.open_data = structuredClone(value) ?? null;
|
||||||
filters.set(slot, (item) => game.recipes.fuel.has(item.type_id));
|
},
|
||||||
} else if (typeof filter === "function") {
|
add_slot(container, slot, options) {
|
||||||
filters.set(slot, (item) => run_guarded(mod, "a slot filter", () => filter(item_api(item))) === true);
|
const engine = engine_containers.get(container);
|
||||||
}
|
if (!engine) throw new Error("add_slot needs a container from ctx.containers or player.inventory");
|
||||||
|
if (!Number.isInteger(slot) || slot < 0 || slot >= engine.size) {
|
||||||
|
throw new Error(`slot ${slot} isn't in the container, it has ${engine.size}`);
|
||||||
|
}
|
||||||
|
if (![options?.x, options?.y].every((n) => typeof n === "number" && Number.isFinite(n))) {
|
||||||
|
throw new Error(`slot ${slot} needs an x and y`);
|
||||||
|
}
|
||||||
|
const { filter, on_take } = options;
|
||||||
|
const added: MenuSlot = { container: engine, index: slot, x: options.x, y: options.y };
|
||||||
|
if (filter === "smeltable") {
|
||||||
|
added.filter = (item) => game.recipes.furnace.has(item.type_id);
|
||||||
|
} else if (filter === "fuel") {
|
||||||
|
added.filter = (item) => game.recipes.fuel.has(item.type_id);
|
||||||
|
} else if (typeof filter === "function") {
|
||||||
|
added.filter = (item) => guarded("a slot filter", () => filter(item_api(item))) === true;
|
||||||
|
}
|
||||||
|
if (options.output_only) added.output = true;
|
||||||
|
if (on_take) added.on_take = (item) => guarded("an on_take", () => on_take(item_api(item))) === true;
|
||||||
|
if (options.icon) added.icon = String(options.icon);
|
||||||
|
if (engine === server_player.inventory) added.inventory = slot;
|
||||||
|
menu.slots.push(added);
|
||||||
|
return menu.slots.length - 1;
|
||||||
|
},
|
||||||
|
add_player_inventory(x, y) {
|
||||||
|
const first = menu.slots.length;
|
||||||
|
for (let i = 0; i < server_player.inventory.size; i++) {
|
||||||
|
// the rest of the inventory in rows from x and y, the hotbar under it like minecraft's
|
||||||
|
const row = i < 9 ? 0 : Math.floor(i / 9) - 1;
|
||||||
|
menu.slots.push({
|
||||||
|
container: server_player.inventory,
|
||||||
|
index: i,
|
||||||
|
x: x + (i % 9) * 18,
|
||||||
|
y: i < 9 ? y + 58 : y + row * 18,
|
||||||
|
inventory: i,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return first;
|
||||||
|
},
|
||||||
|
add_data(name, get) {
|
||||||
|
menu.data.set(String(name), () => guarded(`menu data ${name}`, get) ?? 0);
|
||||||
|
},
|
||||||
|
still_valid(check) {
|
||||||
|
menu.still_valid.push(() => guarded("a still_valid", () => check(player)) !== false);
|
||||||
|
},
|
||||||
|
still_valid_near(block) {
|
||||||
|
const { id, x, y, z } = block;
|
||||||
|
menu.still_valid.push(() => {
|
||||||
|
const [dx, dy, dz] = [
|
||||||
|
server_player.x - x - 0.5,
|
||||||
|
server_player.y - y - 0.5,
|
||||||
|
server_player.z - z - 0.5,
|
||||||
|
];
|
||||||
|
return dx * dx + dy * dy + dz * dz <= MENU_REACH * MENU_REACH &&
|
||||||
|
game.world.get_block_id(x, y, z) === id;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
on_button(fn) {
|
||||||
|
menu.on_button.push((button) => guarded("an on_button", () => fn(player, button)));
|
||||||
|
},
|
||||||
|
quick_move(fn) {
|
||||||
|
menu.quick_move_order = (index) => {
|
||||||
|
const order = guarded("a quick_move", () => fn(player, index));
|
||||||
|
return Array.isArray(order) ? order.filter((i) => Number.isInteger(i)) : [];
|
||||||
|
};
|
||||||
|
},
|
||||||
|
on_tick(fn) {
|
||||||
|
menu.on_tick.push(() => guarded("a menu on_tick", fn));
|
||||||
|
},
|
||||||
|
on_close(fn) {
|
||||||
|
menu.on_close.push(() => guarded("a menu on_close", fn));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if ((JSON.stringify(menu.open_data) ?? "").length > MAX_MOD_MESSAGE_LENGTH) {
|
||||||
|
throw new Error(`the open_data of ${type} is over 16 KB`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const bars = options.bars ?? [];
|
|
||||||
const bottom = Math.max(0, ...options.layout.map((s) => s.y + 1), ...bars.map((b) => b.y + 1));
|
|
||||||
const layout: ScreenLayout = {
|
|
||||||
rows: options.rows ?? Math.ceil(bottom),
|
|
||||||
slots: options.layout.map(({ slot, x, y, output_only, icon }) => ({
|
|
||||||
index: slot,
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
...(output_only ? { output: true } : {}),
|
|
||||||
...(icon ? { icon } : {}),
|
|
||||||
})),
|
|
||||||
bars: bars.map(({ x, y, value, max, direction, empty_texture, full_texture }) => ({
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
value,
|
|
||||||
max,
|
|
||||||
direction,
|
|
||||||
empty_texture,
|
|
||||||
full_texture,
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
|
|
||||||
let open = true;
|
let open = true;
|
||||||
const screen: OpenScreen = {
|
menu.on_close.unshift(() => open = false);
|
||||||
container,
|
game.open_menu(server_player, menu);
|
||||||
layout,
|
|
||||||
properties: {},
|
|
||||||
filters,
|
|
||||||
on_take,
|
|
||||||
on_close: [() => open = false],
|
|
||||||
};
|
|
||||||
game.open_screen(server_player, screen);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
player,
|
player,
|
||||||
get open() {
|
get open() {
|
||||||
return open;
|
return open;
|
||||||
},
|
},
|
||||||
set_property(id, value) {
|
|
||||||
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
||||||
throw new Error(`property ${id} must be a number, not ${value}`);
|
|
||||||
}
|
|
||||||
screen.properties[id] = value;
|
|
||||||
},
|
|
||||||
update: not_yet(mod, "update", "custom screens, see docs/modding_plan.md"),
|
|
||||||
close() {
|
close() {
|
||||||
if (server_player.screen === screen) game.close_screen(server_player);
|
if (server_player.menu === menu) game.close_menu(server_player);
|
||||||
},
|
},
|
||||||
on_close(fn) {
|
on_close(fn) {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
run_guarded(mod, "a screen on_close", fn);
|
guarded("a menu on_close", fn);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
screen.on_close.push(() => run_guarded(mod, "a screen on_close", fn));
|
menu.on_close.push(() => guarded("a menu on_close", fn));
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -722,6 +782,8 @@ function not_yet(mod: string, name: string, why: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const MAX_CONTAINER_SIZE = 256;
|
const MAX_CONTAINER_SIZE = 256;
|
||||||
|
// how far a player can be from a block whose menu they have open, like minecraft's stillValid
|
||||||
|
const MENU_REACH = 8;
|
||||||
// what a client may send on mod channels, see docs/modding/networking/index.md
|
// what a client may send on mod channels, see docs/modding/networking/index.md
|
||||||
const MAX_MOD_MESSAGE_LENGTH = 16 * 1024;
|
const MAX_MOD_MESSAGE_LENGTH = 16 * 1024;
|
||||||
const MAX_MOD_MESSAGES_PER_SECOND = 60;
|
const MAX_MOD_MESSAGES_PER_SECOND = 60;
|
||||||
@@ -772,9 +834,12 @@ function new_stack(item: ItemStack): EngineItemStack {
|
|||||||
return stack;
|
return stack;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// the engine container behind each one mods get, for menus' slots
|
||||||
|
const engine_containers = new WeakMap<Container, EngineContainer>();
|
||||||
|
|
||||||
// an engine container as mods see it
|
// an engine container as mods see it
|
||||||
function container_api(game: GameServer, id: string, container: EngineContainer): Container {
|
function container_api(game: GameServer, id: string, container: EngineContainer): Container {
|
||||||
return {
|
const api: Container = {
|
||||||
id,
|
id,
|
||||||
size: container.size,
|
size: container.size,
|
||||||
get: (slot) => {
|
get: (slot) => {
|
||||||
@@ -794,6 +859,8 @@ function container_api(game: GameServer, id: string, container: EngineContainer)
|
|||||||
},
|
},
|
||||||
on_change: (fn) => game.mods.watch_container(running_mod || "unknown", container, fn),
|
on_change: (fn) => game.mods.watch_container(running_mod || "unknown", container, fn),
|
||||||
};
|
};
|
||||||
|
engine_containers.set(api, container);
|
||||||
|
return api;
|
||||||
}
|
}
|
||||||
|
|
||||||
function player_api(game: GameServer, player: ServerPlayer): Player {
|
function player_api(game: GameServer, player: ServerPlayer): Player {
|
||||||
|
|||||||
+22
-16
@@ -1,6 +1,8 @@
|
|||||||
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
|
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
|
||||||
import { Container, Cursor, ItemData, ItemStack } from "$/common/inventory.ts";
|
import { Container, Cursor, ItemData, ItemStack } from "$/common/inventory.ts";
|
||||||
import { PlayerInfo, ScreenLayout } from "$/common/protocol.ts";
|
import type { GridRecipe } from "$/common/mod_data.ts";
|
||||||
|
import { Menu, PlayerMenu } from "./menu.ts";
|
||||||
|
import { PlayerInfo } from "$/common/protocol.ts";
|
||||||
import { EXHAUSTION, type SavedVitals, Vitals } from "./vitals.ts";
|
import { EXHAUSTION, type SavedVitals, Vitals } from "./vitals.ts";
|
||||||
import { PlayerChunks } from "./player_chunks.ts";
|
import { PlayerChunks } from "./player_chunks.ts";
|
||||||
import { ATTRIBUTES, type AttributeType } from "./entity/attributes.ts";
|
import { ATTRIBUTES, type AttributeType } from "./entity/attributes.ts";
|
||||||
@@ -10,19 +12,6 @@ import { LivingEntity } from "./entity/living_entity.ts";
|
|||||||
export const INVENTORY_SIZE = 9 * 4;
|
export const INVENTORY_SIZE = 9 * 4;
|
||||||
export const CRAFTING_SIZE = 10;
|
export const CRAFTING_SIZE = 10;
|
||||||
|
|
||||||
// a container screen a mod opened for this player, see ctx.ui.open_container
|
|
||||||
export interface OpenScreen {
|
|
||||||
container: Container;
|
|
||||||
layout: ScreenLayout;
|
|
||||||
// what the bars show, synced when they change
|
|
||||||
properties: Record<string, number>;
|
|
||||||
// what can go into each slot, checked when the player clicks
|
|
||||||
filters: Map<number, (item: ItemStack) => boolean>;
|
|
||||||
// asked before a player takes from an output slot
|
|
||||||
on_take: Map<number, (item: ItemStack) => boolean>;
|
|
||||||
on_close: (() => void)[];
|
|
||||||
}
|
|
||||||
|
|
||||||
// what's saved about a player between sessions, by name
|
// what's saved about a player between sessions, by name
|
||||||
export interface SavedPlayer {
|
export interface SavedPlayer {
|
||||||
x: number;
|
x: number;
|
||||||
@@ -71,7 +60,12 @@ export class ServerPlayer extends LivingEntity {
|
|||||||
crafting = new Container(CRAFTING_SIZE);
|
crafting = new Container(CRAFTING_SIZE);
|
||||||
cursor: Cursor = { item: undefined };
|
cursor: Cursor = { item: undefined };
|
||||||
selected_slot = 0;
|
selected_slot = 0;
|
||||||
screen: OpenScreen | undefined;
|
// menu 0, always there
|
||||||
|
inventory_menu: PlayerMenu;
|
||||||
|
// the menu they have open, like minecraft's containerMenu without the inventory menu
|
||||||
|
menu: Menu | undefined;
|
||||||
|
// the last menu id given out, they go 1 to 100 and around
|
||||||
|
menu_id = 0;
|
||||||
// base64 png, see /skin. undefined is the default skin
|
// base64 png, see /skin. undefined is the default skin
|
||||||
skin: string | undefined;
|
skin: string | undefined;
|
||||||
// the skin is for the model with 3 pixel wide arms
|
// the skin is for the model with 3 pixel wide arms
|
||||||
@@ -84,11 +78,23 @@ export class ServerPlayer extends LivingEntity {
|
|||||||
// the chunks their client has and still needs
|
// the chunks their client has and still needs
|
||||||
chunks: PlayerChunks;
|
chunks: PlayerChunks;
|
||||||
|
|
||||||
constructor(level: EntityLevel, conn: number, name: string, view_distance: number) {
|
constructor(
|
||||||
|
level: EntityLevel,
|
||||||
|
conn: number,
|
||||||
|
name: string,
|
||||||
|
view_distance: number,
|
||||||
|
recipes: () => GridRecipe[] = () => [],
|
||||||
|
) {
|
||||||
super(level);
|
super(level);
|
||||||
this.conn = conn;
|
this.conn = conn;
|
||||||
this.name = name;
|
this.name = name;
|
||||||
this.chunks = new PlayerChunks(view_distance);
|
this.chunks = new PlayerChunks(view_distance);
|
||||||
|
this.inventory_menu = new PlayerMenu(this.inventory, this.crafting, recipes);
|
||||||
|
}
|
||||||
|
|
||||||
|
// the open menu, or menu 0 when none is
|
||||||
|
get container_menu(): Menu {
|
||||||
|
return this.menu ?? this.inventory_menu;
|
||||||
}
|
}
|
||||||
|
|
||||||
override default_attributes(): [AttributeType, number?][] {
|
override default_attributes(): [AttributeType, number?][] {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ A bworld mod. `MODS.md` at the root of the bworld repo links to the modding docs
|
|||||||
| `textures/*.png` | 16×16 textures, named `example_mod:<file name>`. |
|
| `textures/*.png` | 16×16 textures, named `example_mod:<file name>`. |
|
||||||
| `worldgen/ores.json` | Ores to generate (optional, not included here). |
|
| `worldgen/ores.json` | Ores to generate (optional, not included here). |
|
||||||
| `scripts/server.ts` | Game logic: block components, commands, events. Never sent to players. |
|
| `scripts/server.ts` | Game logic: block components, commands, events. Never sent to players. |
|
||||||
| `scripts/client.ts` | Sent to players: custom screens, HUD, keybinds. |
|
| `scripts/client.ts` | Sent to players: menu screens, screens, HUD, keybinds. |
|
||||||
| `scripts/worldgen.ts` | Terrain features. Runs on the server and every client and must be deterministic. |
|
| `scripts/worldgen.ts` | Terrain features. Runs on the server and every client and must be deterministic. |
|
||||||
| `CREDITS.md` | Licenses and thanks, shown on the About page. |
|
| `CREDITS.md` | Licenses and thanks, shown on the About page. |
|
||||||
|
|
||||||
|
|||||||
+10
-9
@@ -1,7 +1,7 @@
|
|||||||
// artifacts: items worn in curios slots that change the wearer's attributes, see mods/artifacts
|
// artifacts: items worn in curios slots that change the wearer's attributes, see mods/artifacts
|
||||||
import { assertEquals } from "@std/assert";
|
import { assertEquals } from "@std/assert";
|
||||||
import { ATTRIBUTES } from "$/server/game/entity/attributes.ts";
|
import { ATTRIBUTES } from "$/server/game/entity/attributes.ts";
|
||||||
import { test_game } from "./helpers.ts";
|
import { menu_items, opened_menu, test_game } from "./helpers.ts";
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
type Msg = any;
|
type Msg = any;
|
||||||
@@ -18,16 +18,17 @@ async function setup() {
|
|||||||
Deno.test("the power glove and feral claws go in the hands slot, and only work while worn", async () => {
|
Deno.test("the power glove and feral claws go in the hands slot, and only work while worn", async () => {
|
||||||
const t = await setup();
|
const t = await setup();
|
||||||
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
||||||
const screen = t.take(1).find((m: Msg) => m.type === "open_screen");
|
const menu = opened_menu(t.take(1));
|
||||||
assertEquals(screen.layout.slots.map((s: Msg) => s.icon), ["curios:empty_hands_slot"]);
|
// the hands slot, then the inventory's
|
||||||
|
assertEquals(menu.slots.map((s: Msg) => s.icon).filter(Boolean), ["curios:empty_hands_slot"]);
|
||||||
|
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true });
|
t.send(1, { type: "click", menu: menu.id, slot: 1, button: 0, shift: true });
|
||||||
t.game.tick();
|
t.game.tick();
|
||||||
assertEquals(t.alice.attribute(ATTRIBUTES.attack_damage), 1 + 4);
|
assertEquals(t.alice.attribute(ATTRIBUTES.attack_damage), 1 + 4);
|
||||||
|
|
||||||
// swapped for the claws by hand: the glove's damage goes, the claws' speed comes
|
// swapped for the claws by hand: the glove's damage goes, the claws' speed comes
|
||||||
t.send(1, { type: "click", container: "inventory", index: 1, button: 0 });
|
t.send(1, { type: "click", menu: menu.id, slot: 2, button: 0 });
|
||||||
t.send(1, { type: "click", container: "screen", index: 6, button: 0 });
|
t.send(1, { type: "click", menu: menu.id, slot: 0, button: 0 });
|
||||||
t.game.tick();
|
t.game.tick();
|
||||||
assertEquals(t.alice.attribute(ATTRIBUTES.attack_damage), 1);
|
assertEquals(t.alice.attribute(ATTRIBUTES.attack_damage), 1);
|
||||||
assertEquals(t.alice.attribute(ATTRIBUTES.attack_speed), 4 * 1.3);
|
assertEquals(t.alice.attribute(ATTRIBUTES.attack_speed), 4 * 1.3);
|
||||||
@@ -36,9 +37,9 @@ Deno.test("the power glove and feral claws go in the hands slot, and only work w
|
|||||||
Deno.test("worn artifacts work again after rejoining, and say what they do", async () => {
|
Deno.test("worn artifacts work again after rejoining, and say what they do", async () => {
|
||||||
const t = await setup();
|
const t = await setup();
|
||||||
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true });
|
const { id } = opened_menu(t.take(1));
|
||||||
const curios = t.take(1).filter((m: Msg) => m.type === "container" && m.container === "screen").at(-1).items;
|
t.send(1, { type: "click", menu: id, slot: 1, button: 0, shift: true });
|
||||||
assertEquals(curios[6].lore, "When worn:\n+4 Attack Damage");
|
assertEquals(menu_items(t.take(1))[0].lore, "When worn:\n+4 Attack Damage");
|
||||||
|
|
||||||
t.game.on_disconnect(1);
|
t.game.on_disconnect(1);
|
||||||
t.join(1, "alice");
|
t.join(1, "alice");
|
||||||
|
|||||||
+58
-54
@@ -2,7 +2,7 @@
|
|||||||
import { assert, assertEquals } from "@std/assert";
|
import { assert, assertEquals } from "@std/assert";
|
||||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
||||||
import { display_name, get_state_value } from "$/common/utils.ts";
|
import { display_name, get_state_value } from "$/common/utils.ts";
|
||||||
import { test_game } from "./helpers.ts";
|
import { menu_data, menu_items, opened_menu, test_game } from "./helpers.ts";
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
type Msg = any;
|
type Msg = any;
|
||||||
@@ -30,10 +30,18 @@ function slot_of(messages: Msg[], id: string) {
|
|||||||
return slot;
|
return slot;
|
||||||
}
|
}
|
||||||
|
|
||||||
// picks a whole inventory stack up and puts it into a slot of the open screen
|
// clicks a slot of the open menu
|
||||||
function move_to_screen(t: Game, from: number, to: number) {
|
function click(t: Game, menu: Msg, slot: number) {
|
||||||
t.send(1, { type: "click", container: "inventory", index: from, button: 0 });
|
t.send(1, { type: "click", menu: menu.id, slot, button: 0 });
|
||||||
t.send(1, { type: "click", container: "screen", index: to, button: 0 });
|
}
|
||||||
|
|
||||||
|
// the menu slot of an inventory slot: the base game's menus add the player's inventory last
|
||||||
|
const inventory_slot = (menu: Msg, index: number) => menu.slots.length - 36 + index;
|
||||||
|
|
||||||
|
// picks a whole inventory stack up and puts it into a slot of the open menu
|
||||||
|
function move_to_menu(t: Game, menu: Msg, from: number, to: number) {
|
||||||
|
click(t, menu, inventory_slot(menu, from));
|
||||||
|
click(t, menu, to);
|
||||||
}
|
}
|
||||||
|
|
||||||
Deno.test("a hoe turns grass and dirt into hoed dirt, anything else places nothing", async () => {
|
Deno.test("a hoe turns grass and dirt into hoed dirt, anything else places nothing", async () => {
|
||||||
@@ -62,27 +70,28 @@ Deno.test("a chest keeps items, shows them to everyone, and drops them when brok
|
|||||||
const coal = slot_of(t.take(1), "bworld:coal");
|
const coal = slot_of(t.take(1), "bworld:coal");
|
||||||
|
|
||||||
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
const opened = t.take(1).find((m) => m.type === "open_screen");
|
const opened = opened_menu(t.take(1));
|
||||||
assertEquals(opened.layout.rows, 3);
|
assertEquals(opened.menu_type, "bworld:storage");
|
||||||
assertEquals(opened.layout.slots.length, 27);
|
assertEquals(opened.open_data, { rows: 3 });
|
||||||
|
assertEquals(opened.slots.length, 27 + 36);
|
||||||
// nothing got placed on top
|
// nothing got placed on top
|
||||||
assertEquals(t.game.world.get_block_id(1, 101, 0), "bworld:air");
|
assertEquals(t.game.world.get_block_id(1, 101, 0), "bworld:air");
|
||||||
|
|
||||||
move_to_screen(t, coal, 4);
|
move_to_menu(t, opened, coal, 4);
|
||||||
assertEquals(last_container(t.take(1), "screen")[4], { id: "bworld:coal", count: 10 });
|
assertEquals(menu_items(t.take(1))[4], { id: "bworld:coal", count: 10 });
|
||||||
t.send(1, { type: "close_screen" });
|
t.send(1, { type: "close_menu", menu: opened.id });
|
||||||
|
|
||||||
// still there after opening it again, and after saving and loading
|
// still there after opening it again, and after saving and loading
|
||||||
const loaded = await test_game("mods", t.game.save());
|
const loaded = await test_game("mods", t.game.save());
|
||||||
loaded.join(1, "alice");
|
loaded.join(1, "alice");
|
||||||
loaded.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
|
loaded.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
|
||||||
loaded.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
loaded.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
assertEquals(last_container(loaded.take(1), "screen")[4], { id: "bworld:coal", count: 10 });
|
assertEquals(menu_items(loaded.take(1))[4], { id: "bworld:coal", count: 10 });
|
||||||
|
|
||||||
// breaking it closes the screen and drops the chest and what was inside
|
// breaking it closes the menu and drops the chest and what was inside
|
||||||
loaded.send(1, { type: "break_block", x: 1, y: 100, z: 0 });
|
loaded.send(1, { type: "break_block", x: 1, y: 100, z: 0 });
|
||||||
const messages = loaded.take(1);
|
const messages = loaded.take(1);
|
||||||
assert(messages.some((m) => m.type === "close_screen"));
|
assert(messages.some((m) => m.type === "close_menu"));
|
||||||
const dropped = loaded.game.item_entities().map((e) => e.item.to_data());
|
const dropped = loaded.game.item_entities().map((e) => e.item.to_data());
|
||||||
assertEquals(
|
assertEquals(
|
||||||
dropped.sort((a, b) => a.id.localeCompare(b.id)),
|
dropped.sort((a, b) => a.id.localeCompare(b.id)),
|
||||||
@@ -98,36 +107,35 @@ Deno.test("a furnace burns fuel to smelt, shows its progress, and only lets the
|
|||||||
const coal = slot_of(messages, "bworld:coal");
|
const coal = slot_of(messages, "bworld:coal");
|
||||||
|
|
||||||
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
const opened = t.take(1).find((m) => m.type === "open_screen");
|
const opened = opened_menu(t.take(1));
|
||||||
assertEquals(opened.layout.slots.map((s: Msg) => s.index), [0, 1, 2]);
|
assertEquals(opened.slots.slice(0, 3).map((s: Msg) => s.output ?? false), [false, false, true]);
|
||||||
assertEquals(opened.layout.slots[2].output, true);
|
assertEquals(Object.keys(opened.data), ["progress", "progress_max", "fuel", "fuel_max"]);
|
||||||
assertEquals(opened.layout.bars.map((b: Msg) => b.value), ["fuel", "progress"]);
|
|
||||||
|
|
||||||
move_to_screen(t, ore, 0);
|
move_to_menu(t, opened, ore, 0);
|
||||||
move_to_screen(t, coal, 1);
|
move_to_menu(t, opened, coal, 1);
|
||||||
t.take(1);
|
t.take(1);
|
||||||
|
|
||||||
// iron takes 200 ticks
|
// iron takes 200 ticks
|
||||||
for (let i = 0; i < 100; i++) t.game.tick();
|
for (let i = 0; i < 100; i++) t.game.tick();
|
||||||
const halfway = t.take(1).filter((m) => m.type === "screen_properties").at(-1).properties;
|
const halfway = menu_data(t.take(1));
|
||||||
assertEquals(halfway.progress_max, 200);
|
assertEquals(halfway.progress_max, 200);
|
||||||
assert(halfway.progress >= 98 && halfway.progress <= 100, `progress ${halfway.progress}`);
|
assert(halfway.progress >= 98 && halfway.progress <= 100, `progress ${halfway.progress}`);
|
||||||
assertEquals(halfway.fuel_max, 1000);
|
assertEquals(halfway.fuel_max, 1000);
|
||||||
|
|
||||||
for (let i = 0; i < 110; i++) t.game.tick();
|
for (let i = 0; i < 110; i++) t.game.tick();
|
||||||
const screen = last_container(t.take(1), "screen");
|
const items = menu_items(t.take(1));
|
||||||
assertEquals(screen[0], { id: "bworld:iron_ore", count: 1 });
|
assertEquals(items[0], { id: "bworld:iron_ore", count: 1 });
|
||||||
assertEquals(screen[1], null, "the coal got used");
|
assertEquals(items[1], null, "the coal got used");
|
||||||
assertEquals(screen[2], { id: "bworld:iron_ingot", count: 1 });
|
assertEquals(items[2], { id: "bworld:iron_ingot", count: 1 });
|
||||||
|
|
||||||
// nothing can be put into the result slot, but the result can be taken
|
// nothing can be put into the result slot, but the result can be taken
|
||||||
t.send(1, { type: "click", container: "screen", index: 0, button: 0 });
|
click(t, opened, 0);
|
||||||
t.send(1, { type: "click", container: "screen", index: 2, button: 0 });
|
click(t, opened, 2);
|
||||||
assertEquals(last_container(t.take(1), "screen")[2], { id: "bworld:iron_ingot", count: 1 });
|
assertEquals(menu_items(t.take(1))[2], { id: "bworld:iron_ingot", count: 1 });
|
||||||
t.send(1, { type: "click", container: "screen", index: 0, button: 0 });
|
click(t, opened, 0);
|
||||||
t.send(1, { type: "click", container: "screen", index: 2, button: 0 });
|
click(t, opened, 2);
|
||||||
const after = t.take(1);
|
const after = t.take(1);
|
||||||
assertEquals(last_container(after, "screen")[2], null);
|
assertEquals(menu_items(after)[2], null);
|
||||||
assertEquals(after.filter((m) => m.type === "cursor").at(-1).item, { id: "bworld:iron_ingot", count: 1 });
|
assertEquals(after.filter((m) => m.type === "cursor").at(-1).item, { id: "bworld:iron_ingot", count: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -192,31 +200,26 @@ Deno.test("a smithing table upgrades a wooden pickaxe with 5 stone, using up exa
|
|||||||
const stone = slot_of(messages, "bworld:stone");
|
const stone = slot_of(messages, "bworld:stone");
|
||||||
|
|
||||||
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
const opened = t.take(1).find((m) => m.type === "open_screen");
|
const opened = opened_menu(t.take(1));
|
||||||
assertEquals(opened.layout.slots.map((s: Msg) => [s.index, s.output ?? false]), [
|
assertEquals(opened.slots.slice(0, 4).map((s: Msg) => s.output ?? false), [false, false, false, true]);
|
||||||
[0, false],
|
|
||||||
[1, false],
|
|
||||||
[2, false],
|
|
||||||
[3, true],
|
|
||||||
]);
|
|
||||||
|
|
||||||
// with only the tool there's nothing to take
|
// with only the tool there's nothing to take
|
||||||
move_to_screen(t, pickaxe, 0);
|
move_to_menu(t, opened, pickaxe, 0);
|
||||||
t.game.tick();
|
t.game.tick();
|
||||||
t.send(1, { type: "click", container: "screen", index: 3, button: 0 });
|
click(t, opened, 3);
|
||||||
assertEquals(t.take(1).filter((m) => m.type === "cursor").at(-1)?.item ?? null, null);
|
assertEquals(t.take(1).filter((m) => m.type === "cursor").at(-1)?.item ?? null, null);
|
||||||
|
|
||||||
// the result shows up once there's enough stone, and taking it uses up the pickaxe and 5 stone
|
// the result shows up once there's enough stone, and taking it uses up the pickaxe and 5 stone
|
||||||
move_to_screen(t, stone, 1);
|
move_to_menu(t, opened, stone, 1);
|
||||||
t.game.tick();
|
t.game.tick();
|
||||||
assertEquals(last_container(t.take(1), "screen")[3], { id: "bworld:stone_pickaxe", count: 1 });
|
assertEquals(menu_items(t.take(1))[3], { id: "bworld:stone_pickaxe", count: 1 });
|
||||||
t.send(1, { type: "click", container: "screen", index: 3, button: 0 });
|
click(t, opened, 3);
|
||||||
messages = t.take(1);
|
messages = t.take(1);
|
||||||
assertEquals(messages.filter((m) => m.type === "cursor").at(-1).item, { id: "bworld:stone_pickaxe", count: 1 });
|
assertEquals(messages.filter((m) => m.type === "cursor").at(-1).item, { id: "bworld:stone_pickaxe", count: 1 });
|
||||||
assertEquals(last_container(messages, "screen"), [null, { id: "bworld:stone", count: 2 }, null, null]);
|
assertEquals(menu_items(messages).slice(0, 4), [null, { id: "bworld:stone", count: 2 }, null, null]);
|
||||||
|
|
||||||
// closing gives back the leftover stone, and the cursor's pickaxe goes into the inventory
|
// closing gives back the leftover stone, and the cursor's pickaxe goes into the inventory
|
||||||
t.send(1, { type: "close_screen" });
|
t.send(1, { type: "close_menu", menu: opened.id });
|
||||||
const inventory = last_container(t.take(1), "inventory").filter((i: Msg) => i);
|
const inventory = last_container(t.take(1), "inventory").filter((i: Msg) => i);
|
||||||
assertEquals(
|
assertEquals(
|
||||||
inventory.sort((a: Msg, b: Msg) => a.id.localeCompare(b.id)),
|
inventory.sort((a: Msg, b: Msg) => a.id.localeCompare(b.id)),
|
||||||
@@ -230,23 +233,24 @@ Deno.test("a smithing result can't be taken once its inputs are gone, even befor
|
|||||||
t.game.set_block(1, 100, 0, "bworld:smithing_table");
|
t.game.set_block(1, 100, 0, "bworld:smithing_table");
|
||||||
const messages = t.take(1);
|
const messages = t.take(1);
|
||||||
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
move_to_screen(t, slot_of(messages, "bworld:wood_pickaxe"), 0);
|
const opened = opened_menu(t.take(1));
|
||||||
move_to_screen(t, slot_of(messages, "bworld:stone"), 1);
|
move_to_menu(t, opened, slot_of(messages, "bworld:wood_pickaxe"), 0);
|
||||||
|
move_to_menu(t, opened, slot_of(messages, "bworld:stone"), 1);
|
||||||
t.game.tick();
|
t.game.tick();
|
||||||
|
|
||||||
// take the pickaxe back out and try the result in the same tick
|
// take the pickaxe back out and try the result in the same tick
|
||||||
t.send(1, { type: "click", container: "screen", index: 0, button: 0 });
|
click(t, opened, 0);
|
||||||
t.send(1, { type: "click", container: "inventory", index: 20, button: 0 });
|
click(t, opened, inventory_slot(opened, 20));
|
||||||
t.send(1, { type: "click", container: "screen", index: 3, button: 0 });
|
click(t, opened, 3);
|
||||||
const cursor = t.take(1).filter((m) => m.type === "cursor").at(-1).item;
|
const cursor = t.take(1).filter((m) => m.type === "cursor").at(-1).item;
|
||||||
assertEquals(cursor, null);
|
assertEquals(cursor, null);
|
||||||
|
|
||||||
// and an extra item in the third slot doesn't match a recipe without one
|
// and an extra item in the third slot doesn't match a recipe without one
|
||||||
t.send(1, { type: "click", container: "inventory", index: 20, button: 0 });
|
click(t, opened, inventory_slot(opened, 20));
|
||||||
t.send(1, { type: "click", container: "screen", index: 0, button: 0 });
|
click(t, opened, 0);
|
||||||
t.send(1, { type: "chat", text: "/give bworld:coal 1" });
|
t.send(1, { type: "chat", text: "/give bworld:coal 1" });
|
||||||
const coal = slot_of(t.take(1), "bworld:coal");
|
const coal = slot_of(t.take(1), "bworld:coal");
|
||||||
move_to_screen(t, coal, 2);
|
move_to_menu(t, opened, coal, 2);
|
||||||
t.game.tick();
|
t.game.tick();
|
||||||
assertEquals(last_container(t.take(1), "screen")[3], null);
|
assertEquals(menu_items(t.take(1))[3], null);
|
||||||
});
|
});
|
||||||
|
|||||||
+12
-2
@@ -43,7 +43,7 @@ Deno.test("packing a mod keeps its data, scripts, textures and credits, and give
|
|||||||
|
|
||||||
const bworld = read_bmod(Deno.readFileSync(`${folder}/bworld.bmod`), "bworld.bmod");
|
const bworld = read_bmod(Deno.readFileSync(`${folder}/bworld.bmod`), "bworld.bmod");
|
||||||
assertEquals(bworld.data.blocks.length, 42);
|
assertEquals(bworld.data.blocks.length, 42);
|
||||||
assertEquals(Object.keys(bworld.scripts), ["server"]);
|
assertEquals(Object.keys(bworld.scripts), ["server", "client"]);
|
||||||
|
|
||||||
Deno.removeSync(sources, { recursive: true });
|
Deno.removeSync(sources, { recursive: true });
|
||||||
Deno.removeSync(folder, { recursive: true });
|
Deno.removeSync(folder, { recursive: true });
|
||||||
@@ -240,7 +240,17 @@ Deno.test("the atlas fits textures of any size, tallest first, without overlappi
|
|||||||
Deno.test("a mod with only data packs and reads", () => {
|
Deno.test("a mod with only data packs and reads", () => {
|
||||||
const bmod = {
|
const bmod = {
|
||||||
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
|
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
|
||||||
data: { blocks: [], models: [], items: [], recipes: [], ores: [], spawns: [], entities: [], entity_models: [], tags: [] },
|
data: {
|
||||||
|
blocks: [],
|
||||||
|
models: [],
|
||||||
|
items: [],
|
||||||
|
recipes: [],
|
||||||
|
ores: [],
|
||||||
|
spawns: [],
|
||||||
|
entities: [],
|
||||||
|
entity_models: [],
|
||||||
|
tags: [],
|
||||||
|
},
|
||||||
scripts: {},
|
scripts: {},
|
||||||
textures: new Map(),
|
textures: new Map(),
|
||||||
};
|
};
|
||||||
|
|||||||
+17
-15
@@ -1,6 +1,6 @@
|
|||||||
// curios: accessory slots for items in the curios tags, opened over mod channels, see mods/curios
|
// curios: accessory slots for items in the curios tags, opened over mod channels, see mods/curios
|
||||||
import { assert, assertEquals } from "@std/assert";
|
import { assert, assertEquals } from "@std/assert";
|
||||||
import { copy_dir, test_game } from "./helpers.ts";
|
import { copy_dir, menu_items, opened_menu, test_game } from "./helpers.ts";
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
type Msg = any;
|
type Msg = any;
|
||||||
@@ -35,40 +35,42 @@ async function setup() {
|
|||||||
Deno.test("the curios screen shows the slot types some item goes in, with their icons", async () => {
|
Deno.test("the curios screen shows the slot types some item goes in, with their icons", async () => {
|
||||||
const t = await setup();
|
const t = await setup();
|
||||||
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
||||||
const screen = t.take(1).find((m) => m.type === "open_screen");
|
const menu = opened_menu(t.take(1));
|
||||||
assertEquals(screen.layout.slots, [
|
assertEquals(menu.menu_type, "curios:curios");
|
||||||
{ index: 0, x: 3.5, y: 0, icon: "curios:empty_curio_slot" },
|
// in the middle of the row, then the player's inventory
|
||||||
{ index: 7, x: 4.5, y: 0, icon: "curios:empty_ring_slot" },
|
assertEquals(menu.slots.slice(0, 2), [
|
||||||
|
{ x: 70, y: 17, icon: "curios:empty_curio_slot" },
|
||||||
|
{ x: 88, y: 17, icon: "curios:empty_ring_slot" },
|
||||||
]);
|
]);
|
||||||
|
assertEquals(menu.slots.length, 2 + 36);
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("items only go in the slots they fit, and fall out when the player dies", async () => {
|
Deno.test("items only go in the slots they fit, and fall out when the player dies", async () => {
|
||||||
const t = await setup();
|
const t = await setup();
|
||||||
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
||||||
t.take(1);
|
const { id } = opened_menu(t.take(1));
|
||||||
|
|
||||||
// coal fits nowhere, the ring only in the ring slot, and #curios:curio items in any slot, the curio slot first
|
// coal fits nowhere, the ring only in the ring slot, and #curios:curio items in any slot, the curio slot first.
|
||||||
t.send(1, { type: "click", container: "inventory", index: 2, button: 0, shift: true });
|
// the inventory's slots come after the 2 curios ones
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true });
|
for (const index of [2, 0, 1]) t.send(1, { type: "click", menu: id, slot: 2 + index, button: 0, shift: true });
|
||||||
t.send(1, { type: "click", container: "inventory", index: 1, button: 0, shift: true });
|
|
||||||
const messages = t.take(1);
|
const messages = t.take(1);
|
||||||
assertEquals(last_container(messages, "inventory").slice(0, 3), [null, null, { id: "bworld:coal", count: 1 }]);
|
assertEquals(last_container(messages, "inventory").slice(0, 3), [null, null, { id: "bworld:coal", count: 1 }]);
|
||||||
const curios = last_container(messages, "screen");
|
const curios = menu_items(messages);
|
||||||
assertEquals(curios[0], { id: "jewelry:amulet", count: 1 });
|
assertEquals(curios[0], { id: "jewelry:amulet", count: 1 });
|
||||||
assertEquals(curios[7], { id: "jewelry:ring", count: 1 });
|
assertEquals(curios[1], { id: "jewelry:ring", count: 1 });
|
||||||
|
|
||||||
const player = t.game.players()[0];
|
const player = t.game.players()[0];
|
||||||
t.game.damage_player(player, 100, "fall");
|
t.game.damage_player(player, 100, "fall");
|
||||||
const dropped = t.game.item_entities().map((e) => e.item.type_id).sort();
|
const dropped = t.game.item_entities().map((e) => e.item.type_id).sort();
|
||||||
assertEquals(dropped, ["bworld:coal", "jewelry:amulet", "jewelry:ring"]);
|
assertEquals(dropped, ["bworld:coal", "jewelry:amulet", "jewelry:ring"]);
|
||||||
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
||||||
assertEquals(last_container(t.take(1), "screen").filter(Boolean), []);
|
assertEquals(menu_items(t.take(1)).filter(Boolean), []);
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("mod messages that are too big or too many are dropped", async () => {
|
Deno.test("mod messages that are too big or too many are dropped", async () => {
|
||||||
const t = await setup();
|
const t = await setup();
|
||||||
t.send(1, { type: "mod", channel: "curios:open", data: "x".repeat(20_000) });
|
t.send(1, { type: "mod", channel: "curios:open", data: "x".repeat(20_000) });
|
||||||
assertEquals(t.take(1).filter((m) => m.type === "open_screen"), []);
|
assertEquals(t.take(1).filter((m) => m.type === "open_menu"), []);
|
||||||
for (let i = 0; i < 100; i++) t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
for (let i = 0; i < 100; i++) t.send(1, { type: "mod", channel: "curios:open", data: {} });
|
||||||
assert(t.take(1).filter((m) => m.type === "open_screen").length < 100);
|
assert(t.take(1).filter((m) => m.type === "open_menu").length < 100);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -107,3 +107,16 @@ export function copy_dir(from: string, to: string) {
|
|||||||
Deno.copyFileSync(from, to);
|
Deno.copyFileSync(from, to);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// menus, see server/game/menu.ts. menu 0 is the player's inventory (slots 0-35) and crafting grid (36-45)
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
type Msg = any;
|
||||||
|
|
||||||
|
// the last menu opened among messages
|
||||||
|
export const opened_menu = (messages: Msg[]) => messages.findLast((m) => m.type === "open_menu");
|
||||||
|
|
||||||
|
// what the open menu's slots last held among messages, by menu slot index
|
||||||
|
export const menu_items = (messages: Msg[]) => messages.findLast((m) => m.type === "menu_content")?.items;
|
||||||
|
|
||||||
|
// what the open menu's data last was among messages
|
||||||
|
export const menu_data = (messages: Msg[]) => messages.findLast((m) => m.type === "menu_data")?.data;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { assert, assertEquals } from "@std/assert";
|
import { assert, assertEquals } from "@std/assert";
|
||||||
|
import { CRAFTING_RESULT_SLOT, PLAYER_MENU_CRAFTING } from "$/common/protocol.ts";
|
||||||
import { ItemStack } from "$/common/inventory.ts";
|
import { ItemStack } from "$/common/inventory.ts";
|
||||||
import { test_game } from "./helpers.ts";
|
import { test_game } from "./helpers.ts";
|
||||||
|
|
||||||
@@ -95,7 +96,7 @@ Deno.test("q throws one of an item the way the player looks, ctrl throws the who
|
|||||||
send(1, { type: "chat", text: "/give bworld:stone 5" });
|
send(1, { type: "chat", text: "/give bworld:stone 5" });
|
||||||
take(1);
|
take(1);
|
||||||
|
|
||||||
send(1, { type: "drop_item", container: "inventory", index: 0, all: false });
|
send(1, { type: "drop_item", menu: 0, slot: 0, all: false });
|
||||||
const [thrown] = game.item_entities();
|
const [thrown] = game.item_entities();
|
||||||
assertEquals(thrown.item.amount, 1);
|
assertEquals(thrown.item.amount, 1);
|
||||||
assert(thrown.vz < -5 && Math.abs(thrown.vx) < 1, "thrown forwards");
|
assert(thrown.vz < -5 && Math.abs(thrown.vx) < 1, "thrown forwards");
|
||||||
@@ -105,13 +106,13 @@ Deno.test("q throws one of an item the way the player looks, ctrl throws the who
|
|||||||
assert(thrown.z < -1, "it flew away from the player");
|
assert(thrown.z < -1, "it flew away from the player");
|
||||||
assertEquals(game.item_entities().length, 1, "and isn't picked straight back up");
|
assertEquals(game.item_entities().length, 1, "and isn't picked straight back up");
|
||||||
|
|
||||||
send(1, { type: "drop_item", container: "inventory", index: 0, all: true });
|
send(1, { type: "drop_item", menu: 0, slot: 0, all: true });
|
||||||
assertEquals(game.item_entities().map((entity) => entity.item.amount).sort(), [1, 4]);
|
assertEquals(game.item_entities().map((entity) => entity.item.amount).sort(), [1, 4]);
|
||||||
assertEquals(inventory_count(take(1), "bworld:stone"), 0);
|
assertEquals(inventory_count(take(1), "bworld:stone"), 0);
|
||||||
|
|
||||||
// empty slots and the crafting result don't throw anything
|
// empty slots and the crafting result don't throw anything
|
||||||
send(1, { type: "drop_item", container: "inventory", index: 0, all: true });
|
send(1, { type: "drop_item", menu: 0, slot: 0, all: true });
|
||||||
send(1, { type: "drop_item", container: "crafting", index: 9, all: true });
|
send(1, { type: "drop_item", menu: 0, slot: PLAYER_MENU_CRAFTING + CRAFTING_RESULT_SLOT, all: true });
|
||||||
assertEquals(game.item_entities().length, 2);
|
assertEquals(game.item_entities().length, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { generate_raw_chunk } from "$/common/generation.ts";
|
|||||||
import { block_variant } from "$/common/block_models.ts";
|
import { block_variant } from "$/common/block_models.ts";
|
||||||
import { load_worldgen } from "$/common/worldgen_loader.ts";
|
import { load_worldgen } from "$/common/worldgen_loader.ts";
|
||||||
import { create_mod } from "$/tools/new_mod.ts";
|
import { create_mod } from "$/tools/new_mod.ts";
|
||||||
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
|
import { PLAYER_MENU_CRAFTING, PROTOCOL_VERSION } from "$/common/protocol.ts";
|
||||||
import { copy_dir, test_game } from "./helpers.ts";
|
import { copy_dir, test_game } from "./helpers.ts";
|
||||||
|
|
||||||
// mods/bworld plus a mod made from the template, in a temp folder
|
// mods/bworld plus a mod made from the template, in a temp folder
|
||||||
@@ -101,8 +101,9 @@ Deno.test("a mod made from the template loads and runs", async () => {
|
|||||||
// the shaped recipe: 4 example items in a square
|
// the shaped recipe: 4 example items in a square
|
||||||
send(1, { type: "chat", text: "/give copper_tools:example_item 4" });
|
send(1, { type: "chat", text: "/give copper_tools:example_item 4" });
|
||||||
const items_slot = inventory_of(take(1)).findIndex((i: Msg) => i?.id === "copper_tools:example_item");
|
const items_slot = inventory_of(take(1)).findIndex((i: Msg) => i?.id === "copper_tools:example_item");
|
||||||
send(1, { type: "click", container: "inventory", index: items_slot, button: 0 });
|
// the player's own menu: the inventory, then the crafting grid
|
||||||
for (const slot of [0, 1, 3, 4]) send(1, { type: "click", container: "crafting", index: slot, button: 2 });
|
send(1, { type: "click", menu: 0, slot: items_slot, button: 0 });
|
||||||
|
for (const slot of [0, 1, 3, 4]) send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING + slot, button: 2 });
|
||||||
const crafting = take(1).filter((m) => m.container === "crafting").at(-1).items;
|
const crafting = take(1).filter((m) => m.container === "crafting").at(-1).items;
|
||||||
assertEquals(crafting[9]?.id, "copper_tools:example_block");
|
assertEquals(crafting[9]?.id, "copper_tools:example_block");
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { assert, assertEquals } from "@std/assert";
|
import { assert, assertEquals } from "@std/assert";
|
||||||
import { copy_dir, sent_block, test_game } from "./helpers.ts";
|
import { copy_dir, menu_data, menu_items, opened_menu, sent_block, test_game } from "./helpers.ts";
|
||||||
import type { WorldSave } from "$/server/game/saves.ts";
|
import type { WorldSave } from "$/server/game/saves.ts";
|
||||||
|
|
||||||
// a mod that uses every part of the server api worth testing, and writes down what happened in its storage
|
// a mod that uses every part of the server api worth testing, and writes down what happened in its storage
|
||||||
const SERVER_SCRIPT = `
|
const SERVER_SCRIPT = `
|
||||||
import type { ServerContext } from "bworld/server";
|
import type { BlockRef, ServerContext } from "bworld/server";
|
||||||
export function setup(ctx: ServerContext) {
|
export function setup(ctx: ServerContext) {
|
||||||
const log = (key: string, value: unknown = 1) => {
|
const log = (key: string, value: unknown = 1) => {
|
||||||
const all = ctx.storage.get<Record<string, unknown[]>>("log") ?? {};
|
const all = ctx.storage.get<Record<string, unknown[]>>("log") ?? {};
|
||||||
@@ -26,16 +26,22 @@ export function setup(ctx: ServerContext) {
|
|||||||
on_click(block, _params, player) { log("click", [block.id, player.name]); },
|
on_click(block, _params, player) { log("click", [block.id, player.name]); },
|
||||||
});
|
});
|
||||||
// a box that only takes coal, counts how often it's opened, and gives up its items when broken
|
// a box that only takes coal, counts how often it's opened, and gives up its items when broken
|
||||||
|
const coal_box = ctx.menus.register<BlockRef>("testmod:coal_box", (menu, block) => {
|
||||||
|
const container = ctx.containers.get(block.data.container)!;
|
||||||
|
menu.title = "Coal Box";
|
||||||
|
menu.add_slot(container, 0, { x: 7, y: 17, filter: (item) => item.id === "bworld:coal" });
|
||||||
|
menu.add_slot(container, 1, { x: 25, y: 17 });
|
||||||
|
menu.add_player_inventory(7, 49);
|
||||||
|
menu.add_data("opened", () => block.data.opened);
|
||||||
|
menu.on_button((player, id) => log("button", [player.name, id]));
|
||||||
|
menu.still_valid_near(block);
|
||||||
|
});
|
||||||
ctx.components.register_block("testmod:coal_box", {
|
ctx.components.register_block("testmod:coal_box", {
|
||||||
on_interact(block, _params, player) {
|
on_interact(block, _params, player) {
|
||||||
block.data ??= { container: ctx.containers.create(2).id, opened: 0 };
|
block.data ??= { container: ctx.containers.create(2).id, opened: 0 };
|
||||||
block.data.opened += 1;
|
block.data.opened += 1;
|
||||||
const screen = ctx.ui.open_container(player, {
|
const menu = coal_box.open(player, block);
|
||||||
container: ctx.containers.get(block.data.container)!,
|
menu.on_close(() => log("closed", menu.open));
|
||||||
layout: [{ slot: 0, x: 0, y: 0, filter: (item) => item.id === "bworld:coal" }, { slot: 1, x: 1, y: 0 }],
|
|
||||||
});
|
|
||||||
screen.set_property("opened", block.data.opened);
|
|
||||||
screen.on_close(() => log("closed", screen.open));
|
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
on_break(block) {
|
on_break(block) {
|
||||||
@@ -75,7 +81,7 @@ export function setup(ctx: ServerContext) {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// fabric's way
|
// brigadier's way, like neoforge's
|
||||||
const { literal, argument, types } = ctx.commands;
|
const { literal, argument, types } = ctx.commands;
|
||||||
ctx.commands.register(
|
ctx.commands.register(
|
||||||
literal("shout")
|
literal("shout")
|
||||||
@@ -278,7 +284,7 @@ Deno.test("/tps reports the loop, and mods can't take engine commands", async ()
|
|||||||
Deno.removeSync(clash, { recursive: true });
|
Deno.removeSync(clash, { recursive: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("mods build commands fabric's way: typed arguments, suggestions, requirements and aliases", async () => {
|
Deno.test("mods build commands brigadier's way, like neoforge's: typed arguments, suggestions, requirements and aliases", async () => {
|
||||||
const { join, send, take, dir } = await setup();
|
const { join, send, take, dir } = await setup();
|
||||||
join(2, "bob");
|
join(2, "bob");
|
||||||
take(1);
|
take(1);
|
||||||
@@ -319,7 +325,7 @@ Deno.test("mods build commands fabric's way: typed arguments, suggestions, requi
|
|||||||
Deno.removeSync(dir, { recursive: true });
|
Deno.removeSync(dir, { recursive: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("container screens: filters, properties, closing, saving, and dropping what's inside", async () => {
|
Deno.test("menus: filters, data, buttons, closing, saving, and dropping what's inside", async () => {
|
||||||
const { game, send, take, log, dir } = await setup();
|
const { game, send, take, log, dir } = await setup();
|
||||||
game.set_block(1, 100, 0, "testmod:coal_box");
|
game.set_block(1, 100, 0, "testmod:coal_box");
|
||||||
send(1, { type: "chat", text: "/give bworld:coal 3" });
|
send(1, { type: "chat", text: "/give bworld:coal 3" });
|
||||||
@@ -328,38 +334,58 @@ Deno.test("container screens: filters, properties, closing, saving, and dropping
|
|||||||
|
|
||||||
send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
let messages = take(1);
|
let messages = take(1);
|
||||||
const opened = messages.find((m) => m.type === "open_screen");
|
const opened = opened_menu(messages);
|
||||||
assertEquals(opened.layout, { rows: 1, slots: [{ index: 0, x: 0, y: 0 }, { index: 1, x: 1, y: 0 }], bars: [] });
|
assertEquals(opened.menu_type, "testmod:coal_box");
|
||||||
assertEquals(messages.find((m) => m.type === "screen_properties").properties, { opened: 1 });
|
assertEquals(opened.title, "Coal Box");
|
||||||
|
assertEquals(opened.slots.slice(0, 2), [{ x: 7, y: 17 }, { x: 25, y: 17 }]);
|
||||||
|
// the hotbar's first slot, under the rest of the inventory
|
||||||
|
assertEquals(opened.slots[2], { x: 7, y: 49 + 58 });
|
||||||
|
assertEquals(opened.data, { opened: 1 });
|
||||||
|
|
||||||
// stone doesn't go into the coal slot, but does into the other one. coal goes in
|
// stone doesn't go into the coal slot, but does into the other one. coal goes in. the inventory's slots come after
|
||||||
const screen = (messages: { type: string; container?: string; items?: unknown[] }[]) =>
|
// the box's 2
|
||||||
messages.filter((m) => m.type === "container" && m.container === "screen").at(-1)?.items;
|
const click = (slot: number, menu = opened.id) => send(1, { type: "click", menu, slot, button: 0 });
|
||||||
send(1, { type: "click", container: "inventory", index: 1, button: 0 });
|
click(2 + 1);
|
||||||
send(1, { type: "click", container: "screen", index: 0, button: 0 });
|
click(0);
|
||||||
send(1, { type: "click", container: "screen", index: 1, button: 0 });
|
click(1);
|
||||||
send(1, { type: "click", container: "inventory", index: 0, button: 0 });
|
click(2 + 0);
|
||||||
send(1, { type: "click", container: "screen", index: 0, button: 0 });
|
click(0);
|
||||||
messages = take(1);
|
messages = take(1);
|
||||||
assertEquals(screen(messages), [{ id: "bworld:coal", count: 3 }, { id: "bworld:stone", count: 1 }]);
|
assertEquals(menu_items(messages).slice(0, 2), [{ id: "bworld:coal", count: 3 }, { id: "bworld:stone", count: 1 }]);
|
||||||
|
|
||||||
send(1, { type: "close_screen" });
|
// clicks and buttons for a menu that isn't open are ignored
|
||||||
|
click(0, opened.id + 1);
|
||||||
|
assertEquals(take(1).filter((m) => m.type === "cursor"), []);
|
||||||
|
send(1, { type: "menu_button", menu: opened.id + 1, button: 7 });
|
||||||
|
send(1, { type: "menu_button", menu: opened.id, button: 3 });
|
||||||
|
assertEquals(log().button, [["alice", 3]]);
|
||||||
|
|
||||||
|
send(1, { type: "close_menu", menu: opened.id });
|
||||||
assertEquals(log().closed, [false]);
|
assertEquals(log().closed, [false]);
|
||||||
|
|
||||||
|
// walking away closes it
|
||||||
|
send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
|
game.teleport(game.players()[0], 20.5, 100, 0.5);
|
||||||
|
game.tick();
|
||||||
|
assert(take(1).some((m) => m.type === "close_menu"));
|
||||||
|
assertEquals(log().closed, [false, false]);
|
||||||
|
|
||||||
// the items and the block's data are saved
|
// the items and the block's data are saved
|
||||||
const loaded = await test_game(dir, game.save());
|
const loaded = await test_game(dir, game.save());
|
||||||
loaded.join(1, "alice");
|
loaded.join(1, "alice");
|
||||||
loaded.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
|
loaded.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
|
||||||
loaded.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
loaded.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
messages = loaded.take(1);
|
messages = loaded.take(1);
|
||||||
assertEquals(screen(messages), [{ id: "bworld:coal", count: 3 }, { id: "bworld:stone", count: 1 }]);
|
assertEquals(menu_items(messages).slice(0, 2), [{ id: "bworld:coal", count: 3 }, { id: "bworld:stone", count: 1 }]);
|
||||||
assertEquals(messages.find((m) => m.type === "screen_properties").properties, { opened: 2 });
|
assertEquals(opened_menu(messages).data, { opened: 3 });
|
||||||
|
loaded.game.tick();
|
||||||
|
assertEquals(menu_data(loaded.take(1)), undefined, "data is only sent again when it changes");
|
||||||
|
|
||||||
// breaking it closes the screen, runs on_close, and drops what was inside
|
// breaking it closes the menu, runs on_close, and drops what was inside
|
||||||
loaded.send(1, { type: "break_block", x: 1, y: 100, z: 0 });
|
loaded.send(1, { type: "break_block", x: 1, y: 100, z: 0 });
|
||||||
assert(loaded.take(1).some((m) => m.type === "close_screen"));
|
assert(loaded.take(1).some((m) => m.type === "close_menu"));
|
||||||
const logged = loaded.game.mods.storage.testmod.log as Record<string, unknown[]>;
|
const logged = loaded.game.mods.storage.testmod.log as Record<string, unknown[]>;
|
||||||
assertEquals(logged.closed, [false, false]);
|
assertEquals(logged.closed, [false, false, false]);
|
||||||
const dropped = loaded.game.item_entities().map((e) => e.item.to_data().id).sort();
|
const dropped = loaded.game.item_entities().map((e) => e.item.to_data().id).sort();
|
||||||
assertEquals(dropped, ["bworld:coal", "bworld:stone"]);
|
assertEquals(dropped, ["bworld:coal", "bworld:stone"]);
|
||||||
assertEquals(loaded.game.containers.size, 0);
|
assertEquals(loaded.game.containers.size, 0);
|
||||||
|
|||||||
+26
-22
@@ -1,7 +1,7 @@
|
|||||||
// shift clicking a slot moves its stack to the other part of the screen, like minecraft's quick move
|
// shift clicking a slot moves its stack to the other part of the screen, like minecraft's quick move
|
||||||
import { assertEquals } from "@std/assert";
|
import { assertEquals } from "@std/assert";
|
||||||
import { CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
|
import { CRAFTING_RESULT_SLOT, PLAYER_MENU_CRAFTING } from "$/common/protocol.ts";
|
||||||
import { test_game } from "./helpers.ts";
|
import { menu_items, opened_menu, test_game } from "./helpers.ts";
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
type Msg = any;
|
type Msg = any;
|
||||||
@@ -24,13 +24,13 @@ async function setup(items: [string, number][] = []) {
|
|||||||
|
|
||||||
Deno.test("without a container open, shift clicking moves between the hotbar and the rest of the inventory", async () => {
|
Deno.test("without a container open, shift clicking moves between the hotbar and the rest of the inventory", async () => {
|
||||||
const t = await setup([["bworld:coal", 10], ["bworld:stick", 5]]);
|
const t = await setup([["bworld:coal", 10], ["bworld:stick", 5]]);
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true });
|
t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true });
|
||||||
let inventory = last_container(t.take(1), "inventory");
|
let inventory = last_container(t.take(1), "inventory");
|
||||||
assertEquals(inventory[0], null);
|
assertEquals(inventory[0], null);
|
||||||
assertEquals(inventory[9], { id: "bworld:coal", count: 10 });
|
assertEquals(inventory[9], { id: "bworld:coal", count: 10 });
|
||||||
|
|
||||||
// back down it goes to the first free hotbar slot, the sticks are in the second
|
// back down it goes to the first free hotbar slot, the sticks are in the second
|
||||||
t.send(1, { type: "click", container: "inventory", index: 9, button: 0, shift: true });
|
t.send(1, { type: "click", menu: 0, slot: 9, button: 0, shift: true });
|
||||||
inventory = last_container(t.take(1), "inventory");
|
inventory = last_container(t.take(1), "inventory");
|
||||||
assertEquals(inventory[0], { id: "bworld:coal", count: 10 });
|
assertEquals(inventory[0], { id: "bworld:coal", count: 10 });
|
||||||
assertEquals(inventory[1], { id: "bworld:stick", count: 5 });
|
assertEquals(inventory[1], { id: "bworld:stick", count: 5 });
|
||||||
@@ -40,9 +40,9 @@ Deno.test("without a container open, shift clicking moves between the hotbar and
|
|||||||
Deno.test("shift clicking tops up stacks of the same item before using empty slots", async () => {
|
Deno.test("shift clicking tops up stacks of the same item before using empty slots", async () => {
|
||||||
const t = await setup([["bworld:coal", 20]]);
|
const t = await setup([["bworld:coal", 20]]);
|
||||||
// half of it to the main inventory by hand, then the other half shift clicked onto it
|
// half of it to the main inventory by hand, then the other half shift clicked onto it
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 2 });
|
t.send(1, { type: "click", menu: 0, slot: 0, button: 2 });
|
||||||
t.send(1, { type: "click", container: "inventory", index: 9, button: 0 });
|
t.send(1, { type: "click", menu: 0, slot: 9, button: 0 });
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true });
|
t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true });
|
||||||
const inventory = last_container(t.take(1), "inventory");
|
const inventory = last_container(t.take(1), "inventory");
|
||||||
assertEquals(inventory[0], null);
|
assertEquals(inventory[0], null);
|
||||||
assertEquals(inventory[9], { id: "bworld:coal", count: 20 });
|
assertEquals(inventory[9], { id: "bworld:coal", count: 20 });
|
||||||
@@ -53,16 +53,18 @@ Deno.test("with a chest open, shift clicking moves between it and the inventory"
|
|||||||
const t = await setup([["bworld:coal", 10]]);
|
const t = await setup([["bworld:coal", 10]]);
|
||||||
t.game.set_block(1, 100, 0, "bworld:chest");
|
t.game.set_block(1, 100, 0, "bworld:chest");
|
||||||
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
|
const { id } = opened_menu(t.take(1));
|
||||||
|
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 0, shift: true });
|
// the chest's 27 slots, then the inventory's
|
||||||
|
t.send(1, { type: "click", menu: id, slot: 27, button: 0, shift: true });
|
||||||
let messages = t.take(1);
|
let messages = t.take(1);
|
||||||
assertEquals(last_container(messages, "inventory")[0], null);
|
assertEquals(last_container(messages, "inventory")[0], null);
|
||||||
assertEquals(last_container(messages, "screen")[0], { id: "bworld:coal", count: 10 });
|
assertEquals(menu_items(messages)[0], { id: "bworld:coal", count: 10 });
|
||||||
|
|
||||||
// like minecraft, out of a container it fills the hotbar from the right
|
// like minecraft, out of a container it fills the hotbar from the right
|
||||||
t.send(1, { type: "click", container: "screen", index: 0, button: 0, shift: true });
|
t.send(1, { type: "click", menu: id, slot: 0, button: 0, shift: true });
|
||||||
messages = t.take(1);
|
messages = t.take(1);
|
||||||
assertEquals(last_container(messages, "screen")[0], null);
|
assertEquals(menu_items(messages)[0], null);
|
||||||
assertEquals(last_container(messages, "inventory")[8], { id: "bworld:coal", count: 10 });
|
assertEquals(last_container(messages, "inventory")[8], { id: "bworld:coal", count: 10 });
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -70,11 +72,13 @@ Deno.test("shift clicking into a furnace goes by its slot filters, and takes the
|
|||||||
const t = await setup([["bworld:iron_ore", 1], ["bworld:coal", 1], ["bworld:stick", 1]]);
|
const t = await setup([["bworld:iron_ore", 1], ["bworld:coal", 1], ["bworld:stick", 1]]);
|
||||||
t.game.set_block(1, 100, 0, "bworld:furnace");
|
t.game.set_block(1, 100, 0, "bworld:furnace");
|
||||||
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" });
|
||||||
|
const { id } = opened_menu(t.take(1));
|
||||||
|
|
||||||
// the ore goes in the input, the coal in the fuel slot, and sticks fit neither so they stay
|
// the ore goes in the input, the coal in the fuel slot, and sticks fit neither so they stay. the furnace's 3 slots
|
||||||
for (const index of [0, 1, 2]) t.send(1, { type: "click", container: "inventory", index, button: 0, shift: true });
|
// come before the inventory's
|
||||||
|
for (const index of [0, 1, 2]) t.send(1, { type: "click", menu: id, slot: 3 + index, button: 0, shift: true });
|
||||||
let messages = t.take(1);
|
let messages = t.take(1);
|
||||||
assertEquals(last_container(messages, "screen"), [
|
assertEquals(menu_items(messages).slice(0, 3), [
|
||||||
{ id: "bworld:iron_ore", count: 1 },
|
{ id: "bworld:iron_ore", count: 1 },
|
||||||
{ id: "bworld:coal", count: 1 },
|
{ id: "bworld:coal", count: 1 },
|
||||||
null,
|
null,
|
||||||
@@ -82,18 +86,18 @@ Deno.test("shift clicking into a furnace goes by its slot filters, and takes the
|
|||||||
assertEquals(last_container(messages, "inventory")[2], { id: "bworld:stick", count: 1 });
|
assertEquals(last_container(messages, "inventory")[2], { id: "bworld:stick", count: 1 });
|
||||||
|
|
||||||
for (let i = 0; i < 210; i++) t.game.tick();
|
for (let i = 0; i < 210; i++) t.game.tick();
|
||||||
t.send(1, { type: "click", container: "screen", index: 2, button: 0, shift: true });
|
t.send(1, { type: "click", menu: id, slot: 2, button: 0, shift: true });
|
||||||
messages = t.take(1);
|
messages = t.take(1);
|
||||||
assertEquals(last_container(messages, "screen")[2], null);
|
assertEquals(menu_items(messages)[2], null);
|
||||||
assertEquals(last_container(messages, "inventory")[8], { id: "bworld:iron_ingot", count: 1 });
|
assertEquals(last_container(messages, "inventory")[8], { id: "bworld:iron_ingot", count: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test("shift clicking the crafting result crafts as many as fit", async () => {
|
Deno.test("shift clicking the crafting result crafts as many as fit", async () => {
|
||||||
const t = await setup([["bworld:log", 3]]);
|
const t = await setup([["bworld:log", 3]]);
|
||||||
// the logs into the grid, then the result shift clicked: 3 crafts of 2 planks
|
// the logs into the grid, then the result shift clicked: 3 crafts of 2 planks
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 0 });
|
t.send(1, { type: "click", menu: 0, slot: 0, button: 0 });
|
||||||
t.send(1, { type: "click", container: "crafting", index: 0, button: 0 });
|
t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING, button: 0 });
|
||||||
t.send(1, { type: "click", container: "crafting", index: CRAFTING_RESULT_SLOT, button: 0, shift: true });
|
t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING + CRAFTING_RESULT_SLOT, button: 0, shift: true });
|
||||||
const messages = t.take(1);
|
const messages = t.take(1);
|
||||||
assertEquals(last_container(messages, "crafting").every((item: Msg) => item === null), true);
|
assertEquals(last_container(messages, "crafting").every((item: Msg) => item === null), true);
|
||||||
assertEquals(last_container(messages, "inventory")[8], { id: "bworld:planks", count: 6 });
|
assertEquals(last_container(messages, "inventory")[8], { id: "bworld:planks", count: 6 });
|
||||||
@@ -101,9 +105,9 @@ Deno.test("shift clicking the crafting result crafts as many as fit", async () =
|
|||||||
|
|
||||||
Deno.test("shift clicking the crafting grid puts its items back in the inventory", async () => {
|
Deno.test("shift clicking the crafting grid puts its items back in the inventory", async () => {
|
||||||
const t = await setup([["bworld:log", 3]]);
|
const t = await setup([["bworld:log", 3]]);
|
||||||
t.send(1, { type: "click", container: "inventory", index: 0, button: 0 });
|
t.send(1, { type: "click", menu: 0, slot: 0, button: 0 });
|
||||||
t.send(1, { type: "click", container: "crafting", index: 4, button: 0 });
|
t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING + 4, button: 0 });
|
||||||
t.send(1, { type: "click", container: "crafting", index: 4, button: 0, shift: true });
|
t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_CRAFTING + 4, button: 0, shift: true });
|
||||||
const messages = t.take(1);
|
const messages = t.take(1);
|
||||||
assertEquals(last_container(messages, "crafting").every((item: Msg) => item === null), true);
|
assertEquals(last_container(messages, "crafting").every((item: Msg) => item === null), true);
|
||||||
assertEquals(last_container(messages, "inventory")[9], { id: "bworld:log", count: 3 });
|
assertEquals(last_container(messages, "inventory")[9], { id: "bworld:log", count: 3 });
|
||||||
|
|||||||
Reference in New Issue
Block a user