Change whole gui system
This commit is contained in:
+95
-152
@@ -11,21 +11,10 @@ import {
|
||||
TICKS_PER_SECOND,
|
||||
} from "$/common/constants.ts";
|
||||
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everything_registry.ts";
|
||||
import {
|
||||
can_take_output,
|
||||
click_slot,
|
||||
Container,
|
||||
ItemData,
|
||||
ItemStack,
|
||||
move_into,
|
||||
room_for,
|
||||
take_output,
|
||||
} from "$/common/inventory.ts";
|
||||
import { Container, ItemData, ItemStack } from "$/common/inventory.ts";
|
||||
import {
|
||||
AIR_ID,
|
||||
ClientMessage,
|
||||
ContainerKey,
|
||||
CRAFTING_RESULT_SLOT,
|
||||
MAX_CHAT_LENGTH,
|
||||
MAX_NAME_LENGTH,
|
||||
PROTOCOL_VERSION,
|
||||
@@ -58,8 +47,9 @@ import {
|
||||
word,
|
||||
} from "$/common/commands.ts";
|
||||
import type { GameLoop } from "./game_loop.ts";
|
||||
import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
|
||||
import { INVENTORY_SIZE, OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts";
|
||||
import { update_crafting_result } from "./crafting.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 { ServerWorld, Tile } from "./world.ts";
|
||||
import type { WorldSave } from "./saves.ts";
|
||||
@@ -274,7 +264,7 @@ export class GameServer {
|
||||
if (!player) {
|
||||
return;
|
||||
}
|
||||
this.#close_screen(player);
|
||||
this.#close_menu(player);
|
||||
this.#saved_players[player.name] = player.save_player();
|
||||
this.world.dirty = true;
|
||||
this.#players.delete(conn);
|
||||
@@ -345,6 +335,7 @@ export class GameServer {
|
||||
this.#tick_entities();
|
||||
|
||||
this.mods.tick();
|
||||
this.#tick_menus();
|
||||
this.mods.check_watched_containers();
|
||||
|
||||
for (const [conn, pending] of this.#pending) {
|
||||
@@ -609,7 +600,7 @@ export class GameServer {
|
||||
return { id, container };
|
||||
}
|
||||
|
||||
// anyone looking at it gets their screen closed
|
||||
// anyone with a menu showing it gets it closed
|
||||
delete_container(id: string) {
|
||||
const container = this.containers.get(id);
|
||||
if (!container) {
|
||||
@@ -618,29 +609,46 @@ export class GameServer {
|
||||
this.containers.delete(id);
|
||||
this.world.dirty = true;
|
||||
for (const player of this.#players.values()) {
|
||||
if (player.screen?.container === container) {
|
||||
this.close_screen(player);
|
||||
if (player.menu?.uses(container)) {
|
||||
this.close_menu(player);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// screens
|
||||
// menus
|
||||
|
||||
open_screen(player: ServerPlayer, screen: OpenScreen) {
|
||||
this.#close_screen(player);
|
||||
player.screen = screen;
|
||||
this.#send(player, { type: "open_screen", layout: screen.layout, properties: { ...screen.properties } });
|
||||
player.sent.set("properties", JSON.stringify(screen.properties));
|
||||
player.sent.delete("screen");
|
||||
// the id a new menu for this player gets, 1 to 100 and around, like minecraft's containerCounter
|
||||
next_menu_id(player: ServerPlayer): number {
|
||||
player.menu_id = player.menu_id % 100 + 1;
|
||||
return player.menu_id;
|
||||
}
|
||||
|
||||
// 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
|
||||
close_screen(player: ServerPlayer) {
|
||||
if (!player.screen) {
|
||||
close_menu(player: ServerPlayer) {
|
||||
const menu = player.menu;
|
||||
if (!menu) {
|
||||
return;
|
||||
}
|
||||
this.#close_screen(player);
|
||||
this.#send(player, { type: "close_screen" });
|
||||
this.#close_menu(player);
|
||||
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
|
||||
@@ -692,7 +700,13 @@ export class GameServer {
|
||||
}
|
||||
|
||||
#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];
|
||||
if (saved) {
|
||||
player.load_player(saved);
|
||||
@@ -784,13 +798,21 @@ export class GameServer {
|
||||
}
|
||||
break;
|
||||
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;
|
||||
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;
|
||||
case "close_screen":
|
||||
this.#close_screen(player);
|
||||
case "menu_button":
|
||||
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;
|
||||
case "chat":
|
||||
this.#chat(player, message.text);
|
||||
@@ -989,113 +1011,31 @@ export class GameServer {
|
||||
);
|
||||
}
|
||||
|
||||
#drop_item(player: ServerPlayer, key: unknown, index: unknown, all: boolean) {
|
||||
if (!is_int(index)) {
|
||||
#drop_item(player: ServerPlayer, id: unknown, slot: unknown, all: boolean) {
|
||||
const menu = player.container_menu;
|
||||
if (id !== menu.id || !is_int(slot)) {
|
||||
return;
|
||||
}
|
||||
const container = this.#get_container(player, key as ContainerKey);
|
||||
// the crafting result isn't an item yet, minecraft crafts it first but that's not supported
|
||||
if (
|
||||
!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)) {
|
||||
const thrown = menu.drop(slot, all);
|
||||
if (thrown) {
|
||||
this.throw_item(player, thrown);
|
||||
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
|
||||
// container open that's between it and the inventory, otherwise between the hotbar and the rest of the inventory
|
||||
#quick_move(player: ServerPlayer, key: ContainerKey, container: Container, index: number) {
|
||||
const inventory = player.inventory;
|
||||
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) {
|
||||
// clicks for a menu that's already closed are ignored, like minecraft's
|
||||
#click(player: ServerPlayer, id: unknown, slot: unknown, button: unknown, shift: boolean) {
|
||||
const menu = player.container_menu;
|
||||
if (id !== menu.id || !is_int(slot) || !is_int(button) || slot < 0 || slot >= menu.slots.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (key === "crafting" && index === CRAFTING_RESULT_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);
|
||||
if (shift) {
|
||||
menu.quick_move(slot);
|
||||
} 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);
|
||||
}
|
||||
|
||||
#close_screen(player: ServerPlayer) {
|
||||
const screen = player.screen;
|
||||
player.screen = undefined;
|
||||
for (const fn of screen?.on_close ?? []) fn();
|
||||
player.sent.delete("screen");
|
||||
player.sent.delete("properties");
|
||||
#close_menu(player: ServerPlayer) {
|
||||
const menu = player.menu;
|
||||
player.menu = undefined;
|
||||
for (const fn of menu?.on_close ?? []) fn();
|
||||
player.sent.delete("menu_content");
|
||||
player.sent.delete("menu_data");
|
||||
|
||||
// the crafting grid and whatever the cursor holds go back into the inventory
|
||||
for (let i = 0; i < 9; i++) {
|
||||
@@ -1400,7 +1340,7 @@ export class GameServer {
|
||||
#kill(player: ServerPlayer, source: DamageSource) {
|
||||
const cause = source.cause;
|
||||
const { x, y, z } = player;
|
||||
this.close_screen(player);
|
||||
this.close_menu(player);
|
||||
for (let i = 0; i < player.inventory.size; i++) {
|
||||
const item = player.inventory.get_item(i);
|
||||
if (item) {
|
||||
@@ -1555,14 +1495,16 @@ export class GameServer {
|
||||
|
||||
// helpers
|
||||
|
||||
#get_container(player: ServerPlayer, key: ContainerKey): Container | undefined {
|
||||
switch (key) {
|
||||
case "inventory":
|
||||
return player.inventory;
|
||||
case "crafting":
|
||||
return player.crafting;
|
||||
case "screen":
|
||||
return player.screen?.container;
|
||||
// the open menus' still_valid and on_tick
|
||||
#tick_menus() {
|
||||
for (const player of this.#players.values()) {
|
||||
const menu = player.menu;
|
||||
if (!menu) continue;
|
||||
if (!menu.still_valid.every((valid) => valid())) {
|
||||
this.close_menu(player);
|
||||
continue;
|
||||
}
|
||||
for (const fn of menu.on_tick) fn();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1590,11 +1532,12 @@ export class GameServer {
|
||||
const attack_speed = player.attribute(ATTRIBUTES.attack_speed);
|
||||
sync("attack_speed", attack_speed, () => ({ type: "attack_speed", value: attack_speed }));
|
||||
|
||||
if (player.screen) {
|
||||
const items = player.screen.container.to_synced_data();
|
||||
sync("screen", items, () => ({ type: "container", container: "screen", items }));
|
||||
const properties = { ...player.screen.properties };
|
||||
sync("properties", properties, () => ({ type: "screen_properties", properties }));
|
||||
const menu = player.menu;
|
||||
if (menu) {
|
||||
const items = menu.content();
|
||||
sync("menu_content", items, () => ({ type: "menu_content", id: menu.id, items }));
|
||||
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,
|
||||
CommandSource,
|
||||
Container,
|
||||
ContainerScreenOptions,
|
||||
EntityRef,
|
||||
EventSignal,
|
||||
ItemComponent,
|
||||
ItemStack,
|
||||
MenuBuilder,
|
||||
MenuHandle,
|
||||
MenuType,
|
||||
Player,
|
||||
ScreenHandle,
|
||||
ServerAfterEvents,
|
||||
ServerBeforeEvents,
|
||||
ServerContext,
|
||||
@@ -40,12 +41,12 @@ import {
|
||||
} from "$/common/commands.ts";
|
||||
import { AIR_ID } from "$/common/protocol.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 type { Entity } from "./entity/entity.ts";
|
||||
import { create_entity } from "./entity/entity_types.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
|
||||
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
|
||||
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);
|
||||
let counts = this.#net_counts.get(player);
|
||||
if (!counts || counts.second !== second) {
|
||||
counts = { second, count: 0 };
|
||||
this.#net_counts.set(player, counts);
|
||||
}
|
||||
if (++counts.count > MAX_MOD_MESSAGES_PER_SECOND) 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));
|
||||
}
|
||||
return ++counts.count <= MAX_MOD_MESSAGES_PER_SECOND;
|
||||
}
|
||||
|
||||
// the other way, for apis that take a player
|
||||
#server_players = new WeakMap<Player, ServerPlayer>();
|
||||
// menu types by id, every mod's
|
||||
#menu_types = new Set<string>();
|
||||
game!: GameServer;
|
||||
|
||||
// imports each server script and calls its setup, in load order
|
||||
@@ -555,12 +569,22 @@ export class ModRuntime {
|
||||
},
|
||||
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: {
|
||||
open_container: (player, options) => this.#open_container(mod, player, options),
|
||||
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"),
|
||||
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: {
|
||||
on: (channel, handler) => {
|
||||
@@ -598,89 +622,125 @@ export class ModRuntime {
|
||||
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 server_player = this.#server_players.get(player);
|
||||
if (!server_player || !game.players().includes(server_player)) {
|
||||
throw new Error(`${player.name} isn't online`);
|
||||
}
|
||||
const container = game.containers.get(options.container.id);
|
||||
if (!container) {
|
||||
throw new Error("open_container needs a container from ctx.containers");
|
||||
}
|
||||
const menu = new Menu(game.next_menu_id(server_player), type);
|
||||
const guarded = <T>(what: string, fn: () => T) => run_guarded(mod, what, fn);
|
||||
|
||||
const filters = new Map<number, (item: EngineItemStack) => boolean>();
|
||||
const on_take = new Map<number, (item: EngineItemStack) => boolean>();
|
||||
for (const { slot, filter, on_take: take } of options.layout) {
|
||||
if (take) {
|
||||
on_take.set(slot, (item) => run_guarded(mod, "an on_take", () => take(item_api(item))) === true);
|
||||
}
|
||||
if (!Number.isInteger(slot) || slot < 0 || slot >= container.size) {
|
||||
throw new Error(`slot ${slot} isn't in the container, it has ${container.size}`);
|
||||
}
|
||||
if (filter === "smeltable") {
|
||||
filters.set(slot, (item) => game.recipes.furnace.has(item.type_id));
|
||||
} else if (filter === "fuel") {
|
||||
filters.set(slot, (item) => game.recipes.fuel.has(item.type_id));
|
||||
} else if (typeof filter === "function") {
|
||||
filters.set(slot, (item) => run_guarded(mod, "a slot filter", () => filter(item_api(item))) === true);
|
||||
}
|
||||
build({
|
||||
get title() {
|
||||
return menu.title;
|
||||
},
|
||||
set title(value) {
|
||||
menu.title = String(value);
|
||||
},
|
||||
get open_data() {
|
||||
return menu.open_data;
|
||||
},
|
||||
set open_data(value) {
|
||||
menu.open_data = structuredClone(value) ?? null;
|
||||
},
|
||||
add_slot(container, slot, options) {
|
||||
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;
|
||||
const screen: OpenScreen = {
|
||||
container,
|
||||
layout,
|
||||
properties: {},
|
||||
filters,
|
||||
on_take,
|
||||
on_close: [() => open = false],
|
||||
};
|
||||
game.open_screen(server_player, screen);
|
||||
menu.on_close.unshift(() => open = false);
|
||||
game.open_menu(server_player, menu);
|
||||
|
||||
return {
|
||||
player,
|
||||
get 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() {
|
||||
if (server_player.screen === screen) game.close_screen(server_player);
|
||||
if (server_player.menu === menu) game.close_menu(server_player);
|
||||
},
|
||||
on_close(fn) {
|
||||
if (!open) {
|
||||
run_guarded(mod, "a screen on_close", fn);
|
||||
guarded("a menu on_close", fn);
|
||||
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;
|
||||
// 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
|
||||
const MAX_MOD_MESSAGE_LENGTH = 16 * 1024;
|
||||
const MAX_MOD_MESSAGES_PER_SECOND = 60;
|
||||
@@ -772,9 +834,12 @@ function new_stack(item: ItemStack): EngineItemStack {
|
||||
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
|
||||
function container_api(game: GameServer, id: string, container: EngineContainer): Container {
|
||||
return {
|
||||
const api: Container = {
|
||||
id,
|
||||
size: container.size,
|
||||
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),
|
||||
};
|
||||
engine_containers.set(api, container);
|
||||
return api;
|
||||
}
|
||||
|
||||
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 { 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 { PlayerChunks } from "./player_chunks.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 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
|
||||
export interface SavedPlayer {
|
||||
x: number;
|
||||
@@ -71,7 +60,12 @@ export class ServerPlayer extends LivingEntity {
|
||||
crafting = new Container(CRAFTING_SIZE);
|
||||
cursor: Cursor = { item: undefined };
|
||||
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
|
||||
skin: string | undefined;
|
||||
// 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
|
||||
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);
|
||||
this.conn = conn;
|
||||
this.name = name;
|
||||
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?][] {
|
||||
|
||||
Reference in New Issue
Block a user