Change whole gui system

This commit is contained in:
2026-10-01 16:22:02 -03:00
parent 013a4fbb97
commit deba36260e
48 changed files with 1925 additions and 1302 deletions
+2 -2
View File
@@ -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.
- 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
a block state that the block's `variants` show.
- It's **never sent to clients**. To show it to a player, open a [menu](../inventories/menus.md), or change a block
state that the block's `variants` show.
- Only blocks with tile data run `on_tick`, `on_second` and `on_new_day`.
## Blocks With Containers
+1 -1
View File
@@ -92,4 +92,4 @@ seed and chunk always give the same blocks. See [World Generation](../worldgen/i
| Server script code | yes | **never** |
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
View File
@@ -2,16 +2,54 @@
There are a few ways for a mod to show players a GUI. Pick the first one that's enough:
| Way | Code | For |
| -------------------------------------------- | ------------- | ---------------------------------------------------------- |
| [Container screens](../inventories/menus.md) | server only | Inventories and machines: slots, filters, progress bars |
| [Inventory overlays](#inventory-overlays) | client only | Drawing next to every inventory screen, like a recipe list |
| Forms, custom screens and HUD elements | not built yet | See [below](#not-built-yet) |
| Way | Code | For |
| ----------------------------------------- | ------------------ | --------------------------------------------------------- |
| [Menus](../inventories/menus.md) | server, and client | Inventories and machines: slots, filters, progress bars |
| [Plain screens](#plain-screens) | client only | Screens with nothing the server checks: maps, guide books |
| [Inventory overlays](#inventory-overlays) | client only | Drawing next to every menu's screen, like a recipe list |
| Forms and HUD elements | not built yet | See [below](#not-built-yet) |
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
An inventory overlay draws on every inventory screen (the player's inventory, chests, furnaces and every other container
screen), over the screen, like Just Enough Items' item list. `mods/recipe_viewer` is one.
An inventory overlay draws on every menu's screen (the player's inventory, chests, furnaces and every mod's menus), over
the screen, like Just Enough Items' item list. `mods/recipe_viewer` is one.
```ts
import type { ClientContext } from "bworld/client";
@@ -20,14 +58,15 @@ export function setup(ctx: ClientContext) {
ctx.ui.add_inventory_overlay({
on_render(g, screen) {
// screen is the inventory's box, and what's in the slot under the mouse
const x = screen.x + screen.width + 16;
if (screen.hovered_item) g.text(ctx.items.name(screen.hovered_item.id), x, 16);
const x = screen.x + screen.width + 5;
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
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:
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.
## Graphics
`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
interface Graphics {
readonly width: number; // the screen, in pixels
readonly width: number; // the window, in gui pixels
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 };
rect(x: number, y: number, w: number, h: number, color?: [r, g, b, a]): void;
panel(x: number, y: number, w: number, h: number): void; // the game's panel background
text(text: string, x: number, y: number, options?: { scale?: number; color?: [r, g, b, a] }): void;
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;
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
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
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
@@ -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:
- **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.
- **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.
the server script, like Bedrock's server forms. They'll be menus whose screens the engine draws.
- **HUD elements** (`ctx.hud.register`): drawing over the world every frame.
- **Keybinds** (`ctx.input.bind`). Until then, an inventory overlay can check `g.key_pressed` while an inventory is
open.
+1 -1
View File
@@ -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.
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.
+159 -61
View File
@@ -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
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.
Menus are how players use [containers](containers.md), like NeoForge's. A GUI has two halves:
Every click goes to the server, which applies it following the screen's rules, and everyone viewing the container sees
the result.
- The **menu** lives in the server script. It decides which slots the player can click, what goes in them, the numbers
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
ctx.components.register_block("copper_tools:smelter", {
on_create(block) {
block.data = { container: ctx.containers.create(3).id, progress: 0 };
},
on_interact(block, _params, player) {
const screen = ctx.ui.open_container(player, {
container: ctx.containers.get(block.data.container)!,
layout: [
{ slot: 0, x: 3, y: 0, filter: "smeltable" },
{ slot: 1, x: 3, y: 2, filter: "fuel" },
{ slot: 2, x: 5, y: 1, output_only: true },
],
bars: [{
x: 4,
y: 1,
value: "progress",
max: "progress_max",
direction: "right",
empty_texture: "bworld:arrow_empty",
full_texture: "bworld:arrow_full",
}],
});
screen.set_property("progress", block.data.progress);
screen.set_property("progress_max", 200);
return true;
},
});
// server.ts
export function setup(ctx: ServerContext) {
const smelter = ctx.menus.register<BlockRef>("copper_tools:smelter", (menu, block, player) => {
const container = ctx.containers.get(block.data.container)!;
menu.title = "Smelter";
menu.add_slot(container, 0, { x: 55, y: 16, filter: "smeltable" });
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, 84);
menu.add_data("progress", () => block.data.progress);
menu.add_data("progress_max", () => 200);
menu.still_valid_near(block);
});
ctx.components.register_block("copper_tools:smelter", {
on_create(block) {
block.data = { container: ctx.containers.create(3).id, progress: 0 };
},
on_interact(block, _params, player) {
smelter.open(player, block);
return true;
},
});
}
```
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, in slot units from the top left of the screen's area. Can be fractional. |
| `x`, `y` | Where its 18 pixel frame goes, in GUI pixels from the screen's top left. |
| `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. |
| `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. |
`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
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.
Shift clicking follows the same rules. A stack shift clicked in the player's inventory goes into the screen's slots in
`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.
### Shift Clicking
## 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 |
| ------------------------------- | ----------------------------------------------------------------- |
| `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. |
`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.
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
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 open: boolean;
set_property(id: string, value: number): void;
close(): void;
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
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`.
## Screens
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`.