Compare commits

...
10 Commits
Author SHA1 Message Date
paula 7f4a8719de Recipe viewer 2026-09-27 01:25:47 -03:00
paula e4c9a2f7f4 Add cooking pot from farmer's delight ! 2026-09-27 01:08:50 -03:00
paula 52587aabf7 Don't use names for item suggestions 2026-09-27 00:45:00 -03:00
paula 8c7ca92891 Improve commands 2026-09-27 00:38:55 -03:00
paula 535bd36d91 Render a hand 2026-09-27 00:18:16 -03:00
paula a2cf590315 Fix crop drops being able to roll 0 2026-09-27 00:17:40 -03:00
paula aef8836f15 3d models for items 2026-09-26 21:45:18 -03:00
paula 7e5bcaa239 Add a bunch of crops and farmer's delight crops 2026-09-26 21:35:17 -03:00
paula 8d9c85d379 Health and hunger system 2026-09-26 21:07:36 -03:00
paula 0fa6ec4ed3 Improve crops system 2026-09-26 18:32:38 -03:00
144 changed files with 5155 additions and 251 deletions
+203 -10
View File
@@ -26,7 +26,7 @@ bworld's modding takes from three places:
- [Mod layout](#mod-layout)
- [manifest.json](#manifestjson)
- [Identifiers](#identifiers)
- Data: [Textures](#textures), [Blocks](#blocks), [Block models](#block-models), [Items](#items),
- Data: [Textures](#textures), [Blocks](#blocks), [Block models](#block-models), [Crops](#crops), [Items](#items),
[Recipes](#recipes), [Overrides](#overrides)
- Game API: [Common scripts](#common-scripts), [Server scripts](#server-scripts), [Client scripts](#client-scripts),
[GUIs](#guis), [Mod channels](#mod-channels), [World generation](#world-generation)
@@ -250,6 +250,8 @@ program**, so the server and each client can number blocks differently. Saves an
| `item` | `true` | `register_block_item` | Also register an item that places this block, with the same id. |
| `interactive` | `false` | `interactive` | Right clicking it does something (opens a screen), so clients don't guess it places a block. |
| `replaceable` | `false` | new | Placing a block into it replaces it, like water. |
| `place_in` | see meaning | `place_in` | Block ids it can be placed into, replacing them, like `["bworld:water"]` for rice. Air and `replaceable` blocks when not set. |
| `place_on` | anywhere | `place_on` | Block ids it can stand on, like `["bworld:hoed_dirt"]` for crops. Players can't place it anywhere else, and it breaks (with its drops) when the block under it becomes something else, like Minecraft's `canSurvive`. |
| `states` | none | `states` | Up to 16 bits of named state, like `hoed_dirt` has now. |
| `components` | none | `components` | Custom components with parameters, handled by server scripts. |
@@ -332,11 +334,66 @@ texture per face. `models/slab.json`:
| `elements[].faces` | `top`, `bottom`, `north`, `south`, `west` and `east`. Faces are only drawn from the front, so a flat plane needs one face each way. |
| `faces.*.texture` | A variable (`"#side"`, filled in by the block's `textures`) or a texture id. |
| `faces.*.uv` | `[u1, v1, u2, v2]`, the part of the texture in pixels. Defaults to the part the face covers. |
| `faces.*.rotation` | Turns the texture on the face clockwise by 0, 90, 180 or 270 degrees. |
| `faces.*.cullface` | Hidden when the neighbor on that side is a solid block. Only for faces on the block's edge. |
Faces flat against the block's edge get smooth lighting and ambient occlusion like a full block's. Anything inside the
block is lit evenly with the block's own light.
## Crops
Like a Fabric `CropBlock`, a crop is a block with an `age` state and a seeds item that places it, so adding one is only
data. The base game's `bworld:crop` component (in `mods/bworld/scripts/server.ts`) does the growing, with Stardew
Valley's clock: every morning at 06:00 a crop whose farmland was watered the day before grows a day, and it shows the
stage for how far along it is. `mods/farmersdelight` adds its cabbages, onions, tomatoes and rice this way.
`blocks/cabbages.json`, with its `variants` giving one texture per age (see [Block models](#block-models)):
```json
{
"format_version": 1,
"block": {
"id": "farmersdelight:cabbages",
"model": "engine:cross",
"render_layer": "cutout",
"collision": false,
"mining": { "toughness": 0 },
"item": false,
"place_on": ["bworld:hoed_dirt"],
"states": [{ "name": "age", "bits": 3, "default": 0 }],
"components": {
"bworld:crop": {
"days": 12,
"stages": 8,
"fertilizer": "bworld:bone_meal",
"drops": {
"young": "farmersdelight:cabbage_seeds",
"mature": "farmersdelight:cabbage",
"bonus": "farmersdelight:cabbage_seeds"
}
}
}
}
}
```
and `items/cabbage_seeds.json` with `"places": "farmersdelight:cabbages"`.
| Param | Meaning |
| --------------- | ------------------------------------------------------------------------------------------------------------ |
| `days` | Watered mornings from planting to fully grown. |
| `stages` | How many ages it shows, 0 to `stages - 1`, spread evenly over `days`. The `age` state must fit them. |
| `drops` | Like a crop's loot table: `young` (not grown yet), `mature` (grown), and `bonus`, 1 to 4 of an item when grown, like wheat's seeds (Minecraft's 1 plus 3 tries at 57%). `young` and `mature` can be one id or a list. |
| `fertilizer` | An item that grows it a day right away, like bone meal. |
| `regrow_days`, `harvest` | Picked by right clicking once grown, dropping `harvest.item` (`count` is `[min, max]`), then grown again after `regrow_days`, like tomatoes. |
| `water` | `"farmland"` (the default): needs watered farmland under it. `"always"`: grows every morning, like rice in water. |
| `upper` | `{ block, stages, supporting_age }`: its last stages grow a second block on top, like rice's panicles. The top block uses the `bworld:crop_top` component with `{ stages, drops }`; breaking it harvests the whole plant. |
| `leaves` | What the spot becomes after it's broken, like water where rice was. |
Players place blocks into the block they click when it's `replaceable`, like Minecraft, so rice (with
`"place_in": ["bworld:water"]`) is planted by clicking water. Food that places a block, like potatoes, is planted when
clicked on somewhere it can go and eaten otherwise.
## Items
`items/copper_pickaxe.json`:
@@ -363,6 +420,7 @@ block is lit evenly with the block's own light.
| `tool` | none | `tool_type` | Tool type used by blocks' `mining.tool`. |
| `places` | none | `block_id` | Block placed when used on a block face. |
| `max_stack` | `64` | new | Largest stack size. |
| `food` | none | `food` | Makes it edible: `{ "nutrition": 3, "saturation_modifier": 0.6 }`, with Minecraft's meanings (hunger points out of 20, and saturation of nutrition × modifier × 2). Optional `always_edible` (eaten even when full) and `returns` (an item left in the hand, like a bowl). Players eat it by right clicking while hungry. |
| `lore` | none | `lore` | Tooltip text under the name. `\n` starts a new line. |
| `components` | none | `on_create` / `get_lore` | Custom item components, handled by server scripts. |
@@ -421,8 +479,29 @@ A shaped recipe, for the crafting grid in the player's inventory screen:
```
Two furnace recipes with the same `input`, two smithing recipes with the same tool, material and addition, or two
shaped recipes with the same pattern and key, are a load error. Mods can add recipe types of their own for their
machines, see [Common scripts](#common-scripts).
shaped recipes with the same pattern and key, are a load error.
Mods can use recipe types of their own for their machines: any `type` with a namespace, like Farmer's Delight's
`farmersdelight:cooking` for its cooking pot. The engine only stores them, the mod's server script reads them with
`ctx.recipes.list("farmersdelight:cooking")` and checks the rest of the fields itself (throwing in `setup` makes a bad
recipe a load error). Other mods can add recipes of that type too. `recipes/cooking_cabbage_rolls.json`:
```json
{
"format_version": 1,
"recipe": {
"type": "farmersdelight:cooking",
"ingredients": ["farmersdelight:cabbage", ["bworld:carrot", "bworld:potato", "farmersdelight:onion"]],
"result": { "id": "farmersdelight:cabbage_rolls", "count": 1 },
"cook_time": 100
}
}
```
The cooking pot takes up to 6 `ingredients` in any slots, each an item id or a list of ids any of which will do. The
optional `container` (like `"bworld:bowl"`) is what the meal is served in, and `cook_time` is in ticks, 200 when not
set. It cooks while the block under it is hot: a lit stove (placed lit, relit with coal, put out with a shovel), or a
burning furnace, whose `lit` state is 1 while it has fuel.
## Overrides
@@ -607,11 +686,14 @@ ctx.components.register_block("copper_tools:oxidizes", {
| `on_interact(block, params, player)` | A player right clicks it. | `true` if handled, so no block gets placed |
| `on_tick(block, params, dt)` | Every tick (20 per second) near a player. | ignored |
| `on_second(block, params, dt)` | Every second near a player. | ignored |
| `on_new_day(block, params, day)` | Every morning at 06:00, anywhere in the world. | ignored |
`block` is `{ id, x, y, z, data }`. `data` is tile data: any JSON value, `undefined` until a handler sets it, saved with
the world and **never sent to clients**. To show tile data to a player, open a screen with it (see [GUIs](#guis)).
`on_tick` and `on_second` only run for blocks that have tile data, so a component that ticks from the start sets
`block.data` in `on_create`. They run within 6 chunks of a player. `dt` is in seconds: 0.05 for `on_tick`, 1 for
`on_tick`, `on_second` and `on_new_day` only run for blocks that have tile data, so a component that ticks from the
start sets `block.data` in `on_create`. `on_new_day` runs for every such block in the world, near a player or not, so
things like crops keep growing while nobody's around (see the base game's farming in `mods/bworld/scripts/server.ts`).
When time jumps forward past several mornings (`/time add`), each one runs, up to 64. They run within 6 chunks of a player. `dt` is in seconds: 0.05 for `on_tick`, 1 for
`on_second`.
The server runs a fixed 20 ticks per second. When a tick takes too long, the next ones run back to back until it has
@@ -641,10 +723,13 @@ events** fire once it has happened.
| `block_place` | ✓ | ✓ | `player`, `block`, `face`, `item` |
| `block_interact` | ✓ | ✓ | `player`, `block`, `item` |
| `chat_send` | ✓ | ✓ | `player`, `message` (before events can change `message`) |
| `player_damage` | ✓ | | `player`, `amount`, `cause` (before events can change `amount`) |
| `player_death` | | ✓ | `player`, `cause`. They've dropped what they carried and respawn right after |
| `player_join` | | ✓ | `player` |
| `player_leave` | | ✓ | `player` |
| `server_start` | | ✓ | none |
| `tick` | | ✓ | `dt` in seconds, 20 times per second |
| `new_day` | | ✓ | `day`, at 06:00 after every block's `on_new_day` |
These fire for **every** player's actions, because they all go through the server. When a before event cancels a break
or place, the server tells that player's client to undo what it already showed.
@@ -655,6 +740,7 @@ or place, the server tells that player's client to undo what it already showed.
interface ServerWorld {
get_block(x: number, y: number, z: number): string | undefined; // undefined when the chunk isn't loaded
set_block(x: number, y: number, z: number, id: string): boolean; // runs on_break / on_create, synced to everyone
break_block(x: number, y: number, z: number): boolean; // like breaking it by hand: on_break, then its drops
get_state(x: number, y: number, z: number, name: string): number | undefined;
set_state(x: number, y: number, z: number, name: string, value: number): boolean;
get_block_data<T>(x: number, y: number, z: number): T | undefined;
@@ -662,6 +748,7 @@ interface ServerWorld {
is_loaded(x: number, z: number): boolean;
readonly seed: string;
readonly time: number; // world time, see below
readonly day: number; // days since the world started, going up at 06:00, 0 on the first day
set_time(time: number): void; // synced to every player
}
@@ -676,6 +763,14 @@ interface Player {
give_item(id: string, count?: number, data?: unknown): void;
send_message(text: string): void;
teleport(x: number, y: number, z: number): void;
readonly health: number; // out of max_health, 20
readonly max_health: number;
readonly food: number; // hunger, out of 20
readonly saturation: number; // never above food
damage(amount: number, cause?: string): void; // cause shows in events and the death message
heal(amount: number): void;
feed(nutrition: number, saturation_modifier: number): void; // like eating
add_exhaustion(amount: number): void; // 4 costs a point of saturation, or of hunger once it's gone
}
interface PlayerList {
@@ -699,6 +794,13 @@ interface ModStorage {
}
```
**Health and hunger** follow Minecraft's rules (`server/game/vitals.ts`). Sprinting, swimming, jumping, breaking blocks,
taking damage and healing add exhaustion, and every 4 of it costs a point of saturation, or of hunger once saturation
is gone. A full stomach heals: quickly while there's saturation, slowly with at least 18 hunger. At 0 hunger players
lose health every 4 seconds, down to half a heart. Falls hurt 1 per block after the first 3, unless they land in water,
and below the world players die. Dying drops everything they carried and respawns them at spawn with full health and
hunger.
**World time** counts ticks since 06:00 of day 1 and never wraps around. A day (06:00 to 18:00) is 36000 ticks, 30
minutes, and a night (18:00 to 06:00) is 12000 ticks, 10 minutes, so in game hours are shorter at night. Dusk is the
first minute of the night and dawn the last, so it's bright all day. `common/time.ts` has `clock`, `format_clock`,
@@ -710,6 +812,55 @@ as the clients. Blocks in unloaded chunks can't be read or changed, and don't ti
### Commands
Commands work like Fabric's, which are Minecraft's Brigadier: a tree of literal words and typed arguments. Each
argument type reads its text and suggests what could go there, and players see those suggestions above the chat box as
they type (Tab puts one in, Up and Down pick). The tree is in `common/commands.ts`.
```ts
const { literal, argument, types } = ctx.commands;
ctx.commands.register(
literal("heal")
.describe("Heals a player")
.requires((source) => source.player.name === ctx.storage.get("owner"))
.executes((context) => heal(context.source.player, 20))
.then(
argument("amount", types.integer(1, 20))
.executes((context) => heal(context.source.player, context.get<number>("amount")))
.then(
argument("target", types.player())
.executes((context) => heal(context.get<Player>("target"), context.get<number>("amount"))),
),
),
);
```
| Builder | What it does |
| --------------------------- | --------------------------------------------------------------------------------------------------- |
| `literal(name)` | A word that has to be typed as is. Words are tried before arguments. |
| `argument(name, type)` | A value read by `type`, then `context.get(name)` in `executes`. |
| `.then(node)` | What can come next. |
| `.executes(fn)` | Runs when the command ends here. Without it, ending here says what's missing. |
| `.requires(fn)` | Only for sources it's true for. Others can't run it, and don't see it suggested. |
| `.suggests(fn)` | `(partial, source) => [{ text, tooltip? }]` in place of the argument type's own suggestions. |
| `.describe(text)` | Shown by `/help`. |
`context.source` has the `player` who typed it and `send_message(text)` to answer them. Throwing
`new CommandError(message)` tells the player what's wrong. Any other error is logged with the mod's id and the player
is told something went wrong.
| `types.` | Reads | Suggests |
| ------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------ |
| `integer(min?, max?)` | a whole number | |
| `number(min?, max?)` | any number | |
| `boolean()` | `true` or `false` | both |
| `word()` | one word | |
| `greedy_string()` | the rest of the line, spaces and all. Nothing can come after it | |
| `choice([...])` | one of the given words | them |
| `item()` and `block()` | an id. `carrot` works too while only one mod has a `carrot` | ids |
| `player()` | an online player's name, as a `Player` | online players |
The simple form is still there, it's a command taking the rest of the line split on spaces:
```ts
ctx.commands.register("heal", {
description: "Heal yourself",
@@ -720,8 +871,18 @@ ctx.commands.register("heal", {
});
```
Commands run on the server when a player types `/name` in chat. Two mods using the same name, or a mod using one of the
engine's (`give`, `time` and `tps`, until phase 5 moves `give` and `time` into `mods/bworld`), is a load error. `/copper_tools:heal` always works as the unambiguous form.
Commands run on the server when a player types `/name` in chat, and the client asks the server for suggestions. Two
mods using the same name, or a mod using one of the engine's (`give`, `time`, `tps` and `help`), is a load error.
`/copper_tools:heal` always works as the unambiguous form.
The engine's commands:
| Command | What it does |
| --------------------------------------------------------- | ----------------------------------------------------------------------- |
| `/give <item> [<count>]` | Gives you an item |
| `/time`, `/time set <day\|noon\|sunset\|night\|midnight\|ticks>`, `/time add <ticks>` | Shows or changes the time. Times of day are the next one, time never goes back |
| `/tps` | How the game loop keeps up |
| `/help [<command>]` | Every command's usage, or one's |
## Client scripts
@@ -744,11 +905,37 @@ interface ClientContext {
net: ClientNet; // see Mod channels
player: { readonly name: string; readonly position: { x: number; y: number; z: number } };
world: { get_block(x: number, y: number, z: number): string | undefined }; // read only, what the client sees
// every item any mod registered, in load order: ids(), exists(id), name(id) ("Cooked Rice"), mod(id) (its mod's name)
items: ClientItems;
// every recipe as its json, including mods' own types, in load order
recipes: { list(type?: string): RecipeJson[] };
log(...args: unknown[]): void;
}
```
Only `ctx.player`, `ctx.world` and `ctx.log` work so far, the rest is phase 4.
`ctx.player`, `ctx.world`, `ctx.items`, `ctx.recipes`, `ctx.log` and `ctx.ui.add_inventory_overlay` work so far, the rest
is phase 4.
### Inventory overlays
`ctx.ui.add_inventory_overlay` draws on every inventory screen (the player's inventory, chests, furnaces and other
container screens) with [`Graphics`](#3-custom-screens-client-code), over the screen, like Just Enough Items' item list.
`mods/recipe_viewer` is one.
```ts
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;
g.text(screen.hovered_item ? ctx.items.name(screen.hovered_item.id) : "", x, 16);
},
});
```
Overlays get the mouse before the slots. A click they use (`g.button`, or `g.consume_click()`) doesn't reach the slots,
and `g.block_mouse(x, y, w, h)` keeps the slots from taking the mouse under something drawn over them. While a
`g.text_input` has the keyboard, keybinds like the inventory key don't fire. An overlay that throws is removed, with the
error in the console.
Client scripts are for presentation. They can't change the world or inventories; they ask the server over a
[mod channel](#mod-channels). Anything they show should be treated as a view of the server's state. Everything in a
@@ -941,7 +1128,7 @@ interface ModScreen {
interface Graphics {
readonly width: number;
readonly height: number;
readonly mouse: { x: number; y: number; down: boolean; 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?: [number, number, number, number]): void;
panel(x: number, y: number, w: number, h: number): void; // nine slice background
text(text: string, x: number, y: number, options?: { scale?: number; color?: number[] }): void;
@@ -954,10 +1141,16 @@ interface Graphics {
slider(id: string, x: number, y: number, w: number, min: number, max: number): number;
// server synced slots, same behavior as container screens
slots(container: string, layout: { slot: number; x: number; y: number }[], x: number, y: number): void;
key_pressed(key: KeyCode): boolean;
key_pressed(key: KeyCode): boolean; // false while a text input has the keyboard
tooltip(lines: (string | { text: string; color?: Color })[], x: number, y: number): void; // over everything
item_tooltip(id: string, x: number, y: number, extra?: (string | { text: string; color?: Color })[]): void;
consume_click(): void; // nothing under it gets the click
block_mouse(x: number, y: number, w: number, h: number): void; // the screen underneath ignores the mouse there
}
```
Everything but `slider` and `slots` works, for [inventory overlays](#inventory-overlays).
Custom screens can also show server containers. The server passes them in when opening:
`ctx.ui.open_screen(player, id, props, { containers: { input: container } })`, and the screen draws them with
`g.slots("input", layout, x, y)`. Clicks still go to the server and follow the container rules, so a custom screen can't
+22
View File
@@ -49,9 +49,31 @@ export async function build_atlas(textures: Map<string, Uint8Array>) {
}
}));
// which pixels of each texture can be seen, for the 3d models of dropped items (see item_model.ts)
const pixels = ctx.getImageData(0, 0, size, size).data;
opaque.clear();
for (const [id, region] of Object.entries(regions)) {
const mask = new Uint8Array(TEXTURE_SIZE * TEXTURE_SIZE);
for (let py = 0; py < TEXTURE_SIZE; py++) {
for (let px = 0; px < TEXTURE_SIZE; px++) {
const i = ((region.y * TEXTURE_SIZE + py) * size + region.x * TEXTURE_SIZE + px) * 4;
mask[py * TEXTURE_SIZE + px] = pixels[i + 3] > 0 ? 1 : 0;
}
}
opaque.set(id, mask);
}
return { image: canvas.transferToImageBitmap(), regions };
}
// by texture id, TEXTURE_SIZE * TEXTURE_SIZE of 1 (can be seen) or 0, row by row from the top
const opaque = new Map<string, Uint8Array>();
// which pixels of a texture aren't fully see-through, undefined before the atlas is built or for unknown textures
export function opaque_pixels(texture_id: string): Uint8Array | undefined {
return opaque.get(texture_id);
}
// the engine's own textures, which come with the client instead of a mod. see build_engine_textures in build.ts
export async function engine_textures(): Promise<Map<string, Uint8Array>> {
const names: string[] = await (await fetch("/assets/textures/index.json")).json();
+11 -1
View File
@@ -150,7 +150,8 @@ export class Client {
#handle_keybinds(closed_screen: boolean) {
const player = this.player;
if (!closed_screen) {
// typing into a screen's text field, keys are letters, not keybinds
if (!closed_screen && !this.screen?.typing) {
this.#handle_keys();
}
@@ -185,6 +186,10 @@ export class Client {
if (InputManager.is_key_pressed(options.key_chat) && !this.screen) {
this.push_screen(new GuiChat(this));
}
// straight into a command, like minecraft
if (InputManager.is_key_pressed("Slash") && !this.screen) {
this.push_screen(new GuiChat(this, "/"));
}
// browsers eat the escape that lets go of the mouse, so losing the mouse pauses too
const lost_mouse = InputManager.take_lost_pointer_lock();
if (InputManager.is_key_pressed("Escape")) {
@@ -235,6 +240,11 @@ export class Client {
return;
}
// the held item swings on every click, and keeps swinging while breaking, like minecraft
if (InputManager.is_mouse_pressed(0) || InputManager.is_mouse_pressed(2) || (attacking && hit)) {
this.game_renderer.hand.swing();
}
if (hit) {
if (InputManager.is_mouse_pressed(0)) {
this.game_mode.start_destroy_block(hit);
+4
View File
@@ -10,6 +10,10 @@ const SEND_POSITION_TICKS = 2;
export class LocalPlayer extends Player {
client: Client;
inventories = new ClientInventories();
// what the server says, see server/game/vitals.ts. out of 20
health = 20;
food = 20;
saturation = 5;
move_speed = 4;
// blocks per second, peaks about 1.25 blocks up with the entity's gravity and drag
+14 -8
View File
@@ -3,7 +3,8 @@ import { AIR, FACE_OFFSETS, TICK_DELTA } from "$/common/constants.ts";
import type { Client } from "./client.ts";
import type { BlockHitResult } from "./level/client_level.ts";
import type { Container } from "$/common/inventory.ts";
import type { ContainerKey } from "$/common/protocol.ts";
import { AIR_ID, type ContainerKey } from "$/common/protocol.ts";
import { can_place, placement_target } from "$/common/utils.ts";
// breaking and using blocks against a server, like minecraft's MultiPlayerGameMode. the client times breaking
// and guesses the results so they feel instant, the server decides what really happens
@@ -53,17 +54,22 @@ export class MultiPlayerGameMode {
const level = this.client.level;
this.client.connection.send({ type: "use_block", x: hit.x, y: hit.y, z: hit.z, face: hit.face });
// guess that it places the held block, unless the block does something when used
// guess that it places the held block, unless the block does something when used. the same rules as the server:
// into the clicked block when it's replaceable, and only where place_in and place_on allow
const block_info = EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)!;
const offset = FACE_OFFSETS[hit.face];
const target = { x: hit.x + offset.x, y: hit.y + offset.y, z: hit.z + offset.z };
const target_id = level.get_block(target.x, target.y, target.z);
const replaceable = target_id === AIR ||
EverythingRegistry.get_by_id<BlockRegistry>("blocks", target_id)?.replaceable;
const target = placement_target(hit.x, hit.y, hit.z, FACE_OFFSETS[hit.face], block_info);
const current = level.get_block(target.x, target.y, target.z);
const below = level.get_block(target.x, target.y - 1, target.z);
const below_id = EverythingRegistry.get_by_id<BlockRegistry>("blocks", below)?.id ?? AIR_ID;
const held = this.#held_item();
// items with components might do something else on the server, like on_use
const place_id = held?.components ? undefined : held?.block_id;
if (!block_info.interactive && place_id && replaceable) {
const placeable = place_id !== undefined && can_place(
EverythingRegistry.get<BlockRegistry>("blocks", place_id),
current === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", current),
below_id,
);
if (!block_info.interactive && place_id && placeable) {
level.add_block({ ...target, id: place_id });
const slot = this.#held_slot();
slot.amount = slot.amount! - 1;
+133 -8
View File
@@ -1,32 +1,60 @@
import { GuiScreen } from "./gui_screen.ts";
import { canvas, draw_rect, draw_text } from "$/client/renderer/mod.ts";
import { canvas, draw_rect, draw_text, measure_text } from "$/client/renderer/mod.ts";
import { InputManager } from "../input_manager.ts";
import type { Client } from "../client.ts";
import { MAX_CHAT_LENGTH } from "$/common/protocol.ts";
import { TextInput } from "./widgets.ts";
import { MAX_CHAT_LENGTH, type ServerMessage } from "$/common/protocol.ts";
import type { Suggestion } from "$/common/commands.ts";
import { TEXT_HEIGHT, TextInput } from "./widgets.ts";
const SCALE = 2;
const INPUT_HEIGHT = 32;
// how many suggestions show at once, the list scrolls with the selection past that
const VISIBLE_SUGGESTIONS = 10;
const ROW_HEIGHT = TEXT_HEIGHT * SCALE + 2;
const PADDING = 4;
const TOOLTIP_GAP = 16;
const SELECTED: [number, number, number, number] = [1, 1, 0.33, 1];
const TOOLTIP_COLOR: [number, number, number, number] = [0.6, 0.6, 0.6, 1];
export class GuiChat extends GuiScreen {
client: Client;
input = new TextInput("", MAX_CHAT_LENGTH);
input: TextInput;
constructor(client: Client) {
// what the server suggests for the command being typed, like minecraft's CommandSuggestions. they replace the
// text from start up to the caret
suggestions: Suggestion[] = [];
suggestions_start = 0;
// highlighted with the arrows, tab puts it in. -1 is none yet
selected = -1;
// the text up to the caret suggestions were last asked for, and the id of that request. only its answer is used
#asked = "";
#request_id = 0;
// tab just put in a suggestion, so another tab goes to the next one instead of asking again
#cycling = false;
constructor(client: Client, text = "") {
super();
this.client = client;
this.input = new TextInput(text, MAX_CHAT_LENGTH);
}
override on_render(): void {
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
const y = canvas.height - 32;
const y = canvas.height - INPUT_HEIGHT;
this.client.chat.render(true, y - 8);
draw_rect(0, y, canvas.width, canvas.height, [0, 0, 0, 0.4]);
draw_text(this.input.value, 0, y, 2, [1, 1, 1]);
draw_rect(this.input.caret_x(0, 2), y + 4, 1, 32 - 4);
draw_text(this.input.value, 0, y, SCALE, [1, 1, 1]);
draw_rect(this.input.caret_x(0, SCALE), y + 4, 1, INPUT_HEIGHT - 4);
this.#render_suggestions(y);
}
override on_tick(_delta: number): void {
this.#handle_suggestion_keys();
this.input.handle_keys();
this.#ask_for_suggestions();
if (InputManager.is_key_pressed("Enter")) {
this.submit();
}
@@ -41,4 +69,101 @@ export class GuiChat extends GuiScreen {
}
this.client.pop_screen();
}
// from the packet listener
receive_suggestions(message: Extract<ServerMessage, { type: "suggestions" }>) {
if (message.id !== this.#request_id) {
return;
}
this.suggestions = message.suggestions;
this.suggestions_start = message.start;
this.selected = -1;
this.#cycling = false;
}
#handle_suggestion_keys() {
const count = this.suggestions.length;
if (count === 0) {
return;
}
if (InputManager.is_key_pressed("ArrowUp")) {
this.selected = this.selected <= 0 ? count - 1 : this.selected - 1;
this.#cycling = false;
}
if (InputManager.is_key_pressed("ArrowDown")) {
this.selected = (this.selected + 1) % count;
this.#cycling = false;
}
if (InputManager.is_key_pressed("Tab")) {
const back = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight");
if (this.selected === -1) {
this.selected = back ? count - 1 : 0;
} else if (this.#cycling) {
this.selected = (this.selected + (back ? count - 1 : 1)) % count;
}
this.#apply(this.suggestions[this.selected]);
this.#cycling = true;
}
}
// puts it in place of what's typed from start to the caret
#apply(suggestion: Suggestion) {
const value = this.input.value;
const caret = this.input.caret;
const start = Math.min(this.suggestions_start, caret);
this.input.value = (value.slice(0, start) + suggestion.text + value.slice(caret)).slice(0, MAX_CHAT_LENGTH);
this.input.caret = Math.min(start + suggestion.text.length, this.input.value.length);
// the list stays for tabbing through, it's asked for again once they type
this.#asked = this.input.value.slice(0, this.input.caret);
}
// only commands have suggestions, and only when what's before the caret changed
#ask_for_suggestions() {
const before_caret = this.input.value.slice(0, this.input.caret);
if (before_caret === this.#asked) {
return;
}
this.#asked = before_caret;
this.#request_id += 1;
this.suggestions = [];
this.selected = -1;
this.#cycling = false;
if (before_caret.startsWith("/")) {
this.client.connection.send({ type: "suggest", id: this.#request_id, text: before_caret });
}
}
// a list going up from the input, lined up under the word it replaces
#render_suggestions(input_y: number) {
const count = this.suggestions.length;
if (count === 0) {
return;
}
const first = Math.max(0, Math.min(this.selected - VISIBLE_SUGGESTIONS + 1, count - VISIBLE_SUGGESTIONS));
const shown = this.suggestions.slice(first, first + VISIBLE_SUGGESTIONS);
const text_width = Math.max(...shown.map((s) => measure_text(s.text, SCALE)));
const tooltip_width = Math.max(0, ...shown.map((s) => s.tooltip ? measure_text(s.tooltip, SCALE) : 0));
const width = text_width + (tooltip_width > 0 ? TOOLTIP_GAP + tooltip_width : 0) + PADDING * 2;
const height = shown.length * ROW_HEIGHT + PADDING * 2;
const start = Math.min(this.suggestions_start, this.input.value.length);
const x = Math.max(
0,
Math.min(measure_text(this.input.value.slice(0, start), SCALE) - PADDING, canvas.width - width),
);
const y = input_y - height;
draw_rect(x, y, width, height, [0, 0, 0, 0.9]);
shown.forEach((suggestion, i) => {
const row_y = y + PADDING + i * ROW_HEIGHT;
const selected = first + i === this.selected;
draw_text(suggestion.text, x + PADDING, row_y, SCALE, selected ? SELECTED : [0.8, 0.8, 0.8, 1]);
if (suggestion.tooltip) {
draw_text(suggestion.tooltip, x + PADDING + text_width + TOOLTIP_GAP, row_y, SCALE, TOOLTIP_COLOR);
}
});
// more above or below
if (first > 0) draw_rect(x, y, width, 1, [1, 1, 1, 0.6]);
if (first + shown.length < count) draw_rect(x, y + height - 1, width, 1, [1, 1, 1, 0.6]);
}
}
+44 -2
View File
@@ -8,6 +8,8 @@ import { ClientInventories } from "../inventory.ts";
import { canvas, Texture } from "../renderer/mod.ts";
import { draw_item, draw_nine_slice } from "../rendering/render_utils.ts";
import { draw_tooltip, item_tooltip } from "./tooltip.ts";
import { ModGraphics } from "./mod_graphics.ts";
import { inventory_overlays } from "../mods.ts";
export class Slot {
container: ContainerKey;
@@ -34,6 +36,11 @@ export abstract class GuiScreen {
abstract on_tick(_delta: number): void;
abstract on_render(): void;
abstract on_close(): void;
// something in it has the keyboard, like a text field, so keybinds (inventory, drop) don't fire
get typing(): boolean {
return false;
}
}
// a screen of slots. the server owns the contents: clicks are sent to it and guessed locally
@@ -46,6 +53,8 @@ export class GuiInventoryScreen extends GuiScreen {
hovering: Slot | undefined;
inventory_width: number = 500;
inventory_height: number = 500;
// what mods draw over it, like a recipe viewer
graphics = new ModGraphics();
constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) {
super();
@@ -64,11 +73,13 @@ export class GuiInventoryScreen extends GuiScreen {
}
}
override get typing() {
return this.graphics.typing;
}
on_tick(_delta: number): void {
this.x = canvas.width / 2 - (this.inventory_width / 2);
this.y = canvas.height / 2 - (this.inventory_height / 2);
this.handle_interaction();
}
on_render(): void {
@@ -100,6 +111,14 @@ export class GuiInventoryScreen extends GuiScreen {
}
}
// mods' overlays go on top and get the mouse first, then the slots get what they left
this.#render_overlays();
if (this.graphics.mouse_blocked()) {
this.hovering = undefined;
} else {
this.handle_interaction();
}
const mouse = InputManager.get_mouse_position();
if (this.inventories.cursor.item) {
draw_item(this.inventories.cursor.item, mouse.x, mouse.y);
@@ -110,6 +129,29 @@ export class GuiInventoryScreen extends GuiScreen {
draw_tooltip(item_tooltip(item), mouse.x, mouse.y);
}
}
this.graphics.end();
}
#render_overlays() {
const g = this.graphics;
g.begin();
const hovered = this.hovering && this.get_container(this.hovering.container)?.get_item(this.hovering.index);
const view = {
x: this.x,
y: this.y,
width: this.inventory_width,
height: this.inventory_height,
hovered_item: hovered ? { id: hovered.type_id, count: hovered.amount, data: hovered.data } : undefined,
};
for (const entry of [...inventory_overlays]) {
try {
entry.overlay.on_render(g, view);
} catch (e) {
// a broken overlay is taken off, not left to throw every frame
console.error(`[${entry.mod}] inventory overlay threw, removing it:`, e);
inventory_overlays.splice(inventory_overlays.indexOf(entry), 1);
}
}
}
on_close(): void {
+43 -3
View File
@@ -3,7 +3,7 @@ import { AssetManager } from "$/client/assets.ts";
import type { Client } from "$/client/client.ts";
import type { ClientInventories } from "$/client/inventory.ts";
import { draw_item, draw_nine_slice } from "$/client/rendering/render_utils.ts";
import { canvas, draw_rect_stroke, draw_text, measure_text, Texture } from "$/client/renderer/mod.ts";
import { canvas, draw_rect, draw_rect_stroke, draw_text, measure_text, Texture } from "$/client/renderer/mod.ts";
import { display_name } from "$/common/utils.ts";
import { TEXT_HEIGHT, TEXT_SCALE } from "./widgets.ts";
@@ -13,6 +13,16 @@ const CROSSHAIR_SIZE = 8;
const HELD_NAME_MS = 2000;
const HELD_NAME_FADE_MS = 500;
const HELD_NAME_GAP = 12;
// the health and hunger bars, side by side just above the hotbar
const BAR_HEIGHT = 14;
const BAR_GAP = 8;
const BAR_BORDER = 2;
const MAX_VITAL = 20;
const HEALTH_COLOR: [number, number, number, number] = [0.84, 0.12, 0.12, 1];
const FOOD_COLOR: [number, number, number, number] = [0.55, 0.33, 0.14, 1];
const SATURATION_COLOR: [number, number, number, number] = [1, 0.84, 0.25, 1];
const BAR_BACKGROUND: [number, number, number, number] = [0.1, 0.08, 0.08, 0.75];
const BAR_OUTLINE: [number, number, number, number] = [0, 0, 0, 0.8];
// what's drawn over the world while playing, like minecraft's Gui: hotbar, crosshair and chat
export class Hud {
@@ -22,6 +32,7 @@ export class Hud {
render(client: Client) {
this.#render_hotbar(client.player.inventories);
this.#render_vitals(client);
this.#render_held_name(client.player.inventories);
this.#render_crosshair();
client.chat.render(false);
@@ -81,14 +92,43 @@ export class Hud {
}
const alpha = Math.min(1, (HELD_NAME_MS - shown_for) / HELD_NAME_FADE_MS);
const name = display_name(item.type_id);
const hotbar_top = canvas.height - (PADDING * 2 + SLOT_SIZE);
const bars_top = canvas.height - (PADDING * 2 + SLOT_SIZE) - BAR_GAP - BAR_HEIGHT;
const x = (canvas.width - measure_text(name, TEXT_SCALE)) / 2;
const y = hotbar_top - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE;
const y = bars_top - HELD_NAME_GAP - TEXT_HEIGHT * TEXT_SCALE;
// a shadow so it reads over bright sky and snow
draw_text(name, x + TEXT_SCALE, y + TEXT_SCALE, TEXT_SCALE, [0.15, 0.15, 0.15, alpha]);
draw_text(name, x, y, TEXT_SCALE, [1, 1, 1, alpha]);
}
// health on the left, hunger on the right, like minecraft's hearts and drumsticks. saturation is a gold border
// around as much of the hunger bar as there's saturation, it's never more than the hunger
#render_vitals(client: Client) {
const player = client.player;
const hotbar_width = PADDING * 2 + SLOT_SIZE * 9;
const bar_width = (hotbar_width - BAR_GAP) / 2;
const left = canvas.width / 2 - hotbar_width / 2;
const y = canvas.height - (PADDING * 2 + SLOT_SIZE) - BAR_GAP - BAR_HEIGHT;
this.#bar(left, y, bar_width, player.health / MAX_VITAL, HEALTH_COLOR);
const food_x = left + bar_width + BAR_GAP;
this.#bar(food_x, y, bar_width, player.food / MAX_VITAL, FOOD_COLOR);
const saturation = Math.min(player.saturation, player.food) / MAX_VITAL;
if (saturation > 0) {
const width = Math.max(BAR_BORDER * 2, bar_width * saturation);
draw_rect(food_x, y, width, BAR_BORDER, SATURATION_COLOR);
draw_rect(food_x, y + BAR_HEIGHT - BAR_BORDER, width, BAR_BORDER, SATURATION_COLOR);
draw_rect(food_x, y, BAR_BORDER, BAR_HEIGHT, SATURATION_COLOR);
draw_rect(food_x + width - BAR_BORDER, y, BAR_BORDER, BAR_HEIGHT, SATURATION_COLOR);
}
}
#bar(x: number, y: number, width: number, fraction: number, color: [number, number, number, number]) {
draw_rect(x - 1, y - 1, width + 2, BAR_HEIGHT + 2, BAR_OUTLINE);
draw_rect(x, y, width, BAR_HEIGHT, BAR_BACKGROUND);
draw_rect(x, y, width * Math.max(0, Math.min(1, fraction)), BAR_HEIGHT, color);
}
#render_crosshair() {
draw_rect_stroke(
(canvas.width - CROSSHAIR_SIZE) / 2,
+224
View File
@@ -0,0 +1,224 @@
// 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
import { SLOT_SIZE, TEXTURE_SIZE } from "$/common/constants.ts";
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import { ItemStack } from "$/common/inventory.ts";
import type { Color, Graphics } from "$/common/mod_api/client.ts";
import type { KeyCode } from "$/common/mod_api/shared.ts";
import { point_inside_rec } from "$/common/utils.ts";
import { AssetManager } from "$/client/assets.ts";
import { InputManager, type KeyCode as InputKey } from "$/client/input_manager.ts";
import {
begin_clip,
canvas,
draw_rect,
draw_text,
draw_texture_region,
end_clip,
measure_text,
Texture,
} from "$/client/renderer/mod.ts";
import { draw_item, draw_nine_slice } from "$/client/rendering/render_utils.ts";
import { get_sprite_region } from "$/client/sprites.ts";
import { draw_tooltip, item_tooltip, type TooltipLine } from "./tooltip.ts";
import { TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts";
const WHITE: Color = [1, 1, 1, 1];
const GREY: Color = [0.66, 0.66, 0.66, 1];
const INPUT_HEIGHT = 32;
export class ModGraphics implements Graphics {
// text inputs by id, and which one has the keyboard
#inputs = new Map<string, TextInput>();
#focused: string | undefined;
#tooltip: { lines: TooltipLine[]; x: number; y: number } | undefined;
// areas the screen underneath shouldn't take the mouse in, this frame
#blocked: { x: number; y: number; w: number; h: number }[] = [];
#clicks_consumed = false;
get width() {
return canvas.width;
}
get height() {
return canvas.height;
}
get mouse() {
const { x, y } = InputManager.get_mouse_position();
return {
x,
y,
down: InputManager.is_mouse_down(0),
pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(0),
right_pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(2),
};
}
// a text input has the keyboard, so keybinds like the inventory key shouldn't fire
get typing() {
return this.#focused !== undefined;
}
// call before a frame's drawing
begin() {
this.#tooltip = undefined;
this.#blocked = [];
this.#clicks_consumed = false;
}
// call after, draws the tooltip over everything
end() {
if (this.#tooltip) draw_tooltip(this.#tooltip.lines, this.#tooltip.x, this.#tooltip.y);
}
// whether the screen underneath should ignore the mouse
mouse_blocked() {
const { x, y } = this.mouse;
return this.#clicks_consumed || this.#blocked.some((r) => point_inside_rec(x, y, r.x, r.y, r.w, r.h));
}
rect(x: number, y: number, w: number, h: number, color: Color = WHITE) {
draw_rect(x, y, w, h, color);
}
panel(x: number, y: number, w: number, h: number) {
draw_nine_slice(AssetManager.instance.get<Texture>("bworld:ui"), 160, 0, 16, 16, 4, 4, 4, 4, x, y, w, h);
}
text(text: string, x: number, y: number, options: { scale?: number; color?: Color } = {}) {
draw_text(text, x, y, options.scale ?? TEXT_SCALE, options.color ?? WHITE);
}
measure_text(text: string, scale = TEXT_SCALE) {
return measure_text(text, scale);
}
texture(id: string, x: number, y: number, w: number, h: number) {
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const region = get_sprite_region(id);
draw_texture_region(
atlas,
region.x * TEXTURE_SIZE,
region.y * TEXTURE_SIZE,
TEXTURE_SIZE,
TEXTURE_SIZE,
x,
y,
w,
h,
);
}
item(id: string, x: number, y: number, count = 1) {
if (!EverythingRegistry.get<ItemRegistry>("items", id)) throw new Error(`unknown item ${id}`);
const stack = new ItemStack(id, count);
// the count only shows when it's more than one
if (count === 1) stack.max_amount = 1;
draw_item(stack, x, y);
}
clip(x: number, y: number, w: number, h: number, draw: () => void) {
begin_clip(x, y, w, h);
try {
draw();
} finally {
end_clip();
}
}
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 [sx, sy] = hovered ? [224, 16] : [176, 0];
draw_nine_slice(AssetManager.instance.get<Texture>("bworld:ui"), sx, sy, 16, 16, 4, 4, 4, 4, x, y, w, h);
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);
if (hovered && this.mouse.pressed) {
this.consume_click();
return true;
}
return false;
}
text_input(id: string, x: number, y: number, w: number): string {
let input = this.#inputs.get(id);
if (!input) {
input = new TextInput("", 256);
this.#inputs.set(id, input);
}
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, INPUT_HEIGHT);
if (this.mouse.pressed) {
if (hovered) {
this.#focused = id;
this.consume_click();
} else if (this.#focused === id) {
this.#focused = undefined;
}
}
const focused = this.#focused === id;
if (focused) {
// what was typed this frame goes in before enter or escape lets go of the keyboard
input.handle_keys();
if (InputManager.is_key_pressed("Escape") || InputManager.is_key_pressed("Enter")) {
this.#focused = undefined;
}
}
draw_rect(x, y, w, INPUT_HEIGHT, focused ? WHITE : GREY);
draw_rect(x + 2, y + 2, w - 4, INPUT_HEIGHT - 4, [0, 0, 0, 1]);
this.clip(x + 2, y + 2, w - 4, INPUT_HEIGHT - 4, () => {
draw_text(input.value, x + 6, y + 4, TEXT_SCALE, WHITE);
if (focused && TextInput.caret_visible()) {
draw_rect(input.caret_x(x + 6), y + 6, 2, INPUT_HEIGHT - 12, WHITE);
}
});
return input.value;
}
slider(): number {
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 {
return !this.typing && InputManager.is_key_pressed(key as InputKey);
}
tooltip(lines: (string | { text: string; color?: Color })[], x: number, y: number) {
this.#tooltip = {
lines: lines.map((line) =>
typeof line === "string"
? { text: line, color: WHITE }
: { text: line.text, color: line.color ?? WHITE }
),
x,
y,
};
}
item_tooltip(id: string, x: number, y: number, extra: (string | { text: string; color?: Color })[] = []) {
const lines = [
...item_tooltip(new ItemStack(id, 1)),
...extra.map((line) =>
typeof line === "string" ? { text: line, color: GREY } : { text: line.text, color: line.color ?? GREY }
),
];
this.#tooltip = { lines, x, y };
}
block_mouse(x: number, y: number, w: number, h: number) {
this.#blocked.push({ x, y, w, h });
}
consume_click() {
this.#clicks_consumed = true;
InputManager.consume_mouse(0);
InputManager.consume_mouse(2);
}
}
// how big an item is drawn, for laying out around g.item
export const ITEM_SIZE = SLOT_SIZE;
+6 -1
View File
@@ -9,6 +9,7 @@ type Color = [number, number, number, number];
const NAME_COLOR: Color = [1, 1, 1, 1];
const LORE_COLOR: Color = [0.66, 0.66, 0.66, 1];
const FOOD_COLOR: Color = [0.85, 0.6, 0.35, 1];
const BACKGROUND: Color = [0.06, 0.02, 0.1, 0.94];
const BORDER: Color = [0.31, 0.1, 0.6, 1];
const BORDER_WIDTH = 2;
@@ -25,7 +26,11 @@ export interface TooltipLine {
// its name, the item's lore from its json, then what the server's scripts said about this stack
export function item_tooltip(item: ItemStack): TooltipLine[] {
const lines: TooltipLine[] = [{ text: display_name(item.type_id), color: NAME_COLOR }];
const static_lore = EverythingRegistry.get<ItemRegistry>("items", item.type_id)?.lore;
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
if (info?.food) {
lines.push({ text: `Restores ${info.food.nutrition} hunger`, color: FOOD_COLOR });
}
const static_lore = info?.lore;
for (const lore of [static_lore, item.lore]) {
for (const text of lore?.split("\n") ?? []) {
lines.push({ text, color: LORE_COLOR });
+1
View File
@@ -58,6 +58,7 @@ export type KeyCode =
| "Home"
| "End"
| "Backspace"
| "Slash"
| "Delete"
// f
| "F1"
+45 -4
View File
@@ -1,11 +1,12 @@
// loads the mods the server lists: downloads their .bmod files, registers their data, then runs their client scripts.
// see "Delivery to clients" in MODS.md
import { AIR } from "$/common/constants.ts";
import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts";
import type { ClientContext } from "$/common/mod_api/client.ts";
import { ModListing, ModLoadError, register_mod_data } from "$/common/mod_loader.ts";
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import type { ClientContext, InventoryOverlay } from "$/common/mod_api/client.ts";
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
import { type Bmod, read_bmod } from "$/common/bmod.ts";
import type { OreJson } from "$/common/mod_data.ts";
import { display_name } from "$/common/utils.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { Client } from "./client.ts";
import { code_url, fetch_verified } from "./handshake.ts";
@@ -19,6 +20,13 @@ export const worldgen_mods: { scripts: { mod: string; url: string }[]; ores: Ore
// set once the game is running, mods can't look at it during setup
let client: Client | undefined;
// what mods draw on inventory screens, see GuiInventoryScreen
export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = [];
// the loaded mods' recipes, and their names by id
let recipe_book = new RecipeBook();
const mod_names = new Map<string, string>();
export function set_mods_client(game_client: Client) {
client = game_client;
}
@@ -47,6 +55,10 @@ 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 })));
recipe_book = recipes;
inventory_overlays.length = 0;
mod_names.clear();
for (const listing of listings) mod_names.set(listing.id, listing.name);
worldgen_mods.ores = recipes.ores;
worldgen_mods.scripts = bmods.flatMap((bmod) =>
@@ -80,9 +92,24 @@ function client_context(listing: ModListing): ClientContext {
return client;
};
const not_yet_fn = (name: string) => () => {
throw new Error(`[${mod}] ctx.ui.${name} isn't implemented yet (Custom screens in MODS.md)`);
};
const known_item = (id: string) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
if (!item) throw new Error(`[${mod}] unknown item ${id}`);
return item;
};
return {
mod: { id: mod, version: listing.version },
ui: not_yet("ui", "step 7") as ClientContext["ui"],
ui: {
register_screen: not_yet_fn("register_screen"),
open: not_yet_fn("open"),
add_inventory_overlay(overlay) {
inventory_overlays.push({ mod, overlay });
},
},
hud: not_yet("hud", "step 7") as ClientContext["hud"],
input: not_yet("input", "step 8") as ClientContext["input"],
net: not_yet("net", "step 8") as ClientContext["net"],
@@ -105,6 +132,20 @@ function client_context(listing: ModListing): ClientContext {
return need_client().level.time;
},
},
items: {
ids: () => EverythingRegistry.entries("items").map(([id]) => id),
exists: (id) => EverythingRegistry.get("items", id) !== undefined,
name: (id) => (known_item(id), display_name(id)),
mod(id) {
known_item(id);
const namespace = id.split(":")[0];
return mod_names.get(namespace) ?? namespace;
},
},
recipes: {
list: (type) =>
structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all),
},
log: (...args) => console.log(`[${mod}]`, ...args),
};
}
+11
View File
@@ -2,6 +2,7 @@ import type { ServerMessage } from "$/common/protocol.ts";
import { Container, ItemStack } from "$/common/inventory.ts";
import type { Client } from "./client.ts";
import { GuiContainer } from "./gui/gui_container.ts";
import { GuiChat } from "./gui/gui_chat.ts";
import { RemotePlayer } from "./entity/remote_player.ts";
import { ItemEntity } from "./entity/item_entity.ts";
@@ -34,6 +35,11 @@ export class ClientPacketListener {
case "time":
level.time = message.time;
break;
case "vitals":
client.player.health = message.health;
client.player.food = message.food;
client.player.saturation = message.saturation;
break;
case "player_leave":
level.remove_entity(message.id);
break;
@@ -81,6 +87,11 @@ export class ClientPacketListener {
case "chat":
client.chat.add(message.from ? `<${message.from}> ${message.text}` : message.text);
break;
case "suggestions":
if (client.screen instanceof GuiChat) {
client.screen.receive_suggestions(message);
}
break;
case "container": {
let container = message.container === "screen" ? inventories.screen : inventories[message.container];
if (message.container === "screen" && container?.size !== message.items.length) {
+15
View File
@@ -333,6 +333,21 @@ export function begin_mode_3d(new_camera: Camera) {
write_mvp();
}
// 3d drawing in front of the camera instead of in the world, for the item in the player's hand: x right, y up, looking
// down -z. depth is cleared first, so it's never hidden inside a wall, like minecraft's first person hand
export function begin_view_model(fov: number) {
flush_batch();
if (pass) {
pass.end();
pass = undefined;
}
pending_depth_clear = true;
mode3d = true;
mat4.perspectiveZO(mvp, fov, canvas.width / canvas.height, 0.01, 10);
write_mvp();
}
export function end_mode_3d() {
if (!mode3d) {
return;
+3
View File
@@ -4,6 +4,7 @@ import { daylight } from "$/common/time.ts";
import { Hud } from "$/client/gui/hud.ts";
import { DebugOverlay } from "$/client/gui/debug_overlay.ts";
import { LevelRenderer } from "./level_renderer.ts";
import { HandRenderer } from "./hand_renderer.ts";
// the sky at noon and in the middle of the night
const DAY_SKY = [0.69, 0.8, 1];
@@ -16,6 +17,7 @@ export class GameRenderer {
level_renderer = new LevelRenderer();
hud = new Hud();
debug_overlay = new DebugOverlay();
hand = new HandRenderer();
// what the lightmap was last made for, so it's only rebuilt when the light changes
#lightmap_daylight = -1;
@@ -43,6 +45,7 @@ export class GameRenderer {
this.level_renderer.render_entities(client.level, client.player, partial_tick);
this.level_renderer.render_translucent(client.level, camera);
end_mode_3d();
this.hand.render(client.player.inventories);
this.hud.render(client);
client.screen?.on_render();
+77
View File
@@ -0,0 +1,77 @@
// the item the player is holding, drawn in the lower right in front of the camera like minecraft's
// ItemInHandRenderer. empty hands show nothing
import { mat4, vec3 } from "gl-matrix";
import type { ItemStack } from "$/common/inventory.ts";
import { AssetManager } from "$/client/assets.ts";
import type { ClientInventories } from "$/client/inventory.ts";
import { begin_view_model, end_mode_3d, flush_batch, set_current_texture, Texture } from "$/client/renderer/mod.ts";
import { item_block, push_item } from "./item_renderer.ts";
// wider than the world's field of view, like minecraft's fixed 70 degrees for the hand
const FOV = 70 * Math.PI / 180;
// where the item sits in front of the camera (x right, y up, looking down -z) and how it's turned, in radians
const ITEM_POSE = { x: 0.72, y: -0.46, z: -1.15, yaw: -1.25, roll: 0.42, pitch: 0, scale: 0.58 };
const BLOCK_POSE = { x: 0.72, y: -0.52, z: -1.15, yaw: Math.PI / 4, roll: 0, pitch: 0.45, scale: 0.3 };
// a new item rises into place, like minecraft's equip animation
const EQUIP_MS = 180;
// clicking swings it down and back
const SWING_MS = 300;
const SWING_ANGLE = 0.9;
export class HandRenderer {
// what was held last frame, as slot and item id, and when it changed
#held = "";
#equipped_at = -Infinity;
#swung_at = -Infinity;
swing() {
const now = performance.now();
// clicking again mid swing doesn't restart it, like minecraft
if (now - this.#swung_at > SWING_MS / 2) {
this.#swung_at = now;
}
}
render(inventories: ClientInventories) {
const item = inventories.inventory.get_item(inventories.hotbar_selected);
const held = item ? `${inventories.hotbar_selected} ${item.type_id}` : "";
const now = performance.now();
if (held !== this.#held) {
this.#held = held;
this.#equipped_at = now;
}
if (!item) {
return;
}
const equip = Math.min(1, (now - this.#equipped_at) / EQUIP_MS);
const swing_progress = Math.min(1, (now - this.#swung_at) / SWING_MS);
const swing = Math.sin(swing_progress * Math.PI);
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
begin_view_model(FOV);
set_current_texture(atlas.tex);
push_item(atlas, item, pose(item, (1 - equip) * 0.6, swing));
flush_batch();
end_mode_3d();
}
}
// from the item's model to in front of the camera. lower drops it out of sight, swing tips it forward and in
function pose(item: ItemStack, lower: number, swing: number) {
const p = item_block(item) ? BLOCK_POSE : ITEM_POSE;
const matrix = mat4.create();
mat4.translate(matrix, matrix, [p.x - swing * 0.25, p.y - lower + swing * 0.1, p.z - swing * 0.2]);
mat4.rotateX(matrix, matrix, p.pitch - swing * SWING_ANGLE);
mat4.rotateY(matrix, matrix, p.yaw);
mat4.rotateZ(matrix, matrix, p.roll);
mat4.scale(matrix, matrix, [p.scale, p.scale, p.scale]);
// turn around the model's middle, not its bottom
mat4.translate(matrix, matrix, [0, -0.5, 0]);
const point = vec3.create();
return (x: number, y: number, z: number): [number, number, number] => {
vec3.transformMat4(point, [x, y, z], matrix);
return [point[0], point[1], point[2]];
};
}
+114
View File
@@ -0,0 +1,114 @@
// the 3d model of a flat item, like minecraft's item/generated: its sprite on the front and back, one pixel apart, with
// a side face along every edge between a pixel that can be seen and one that can't (or the sprite's border)
import { TEXTURE_SIZE } from "$/common/constants.ts";
import { opaque_pixels } from "$/client/atlas.ts";
export interface ItemQuad {
// 4 corners counter clockwise seen from outside. x from -0.5 to 0.5 and y from 0 to 1 across the sprite, z its
// thickness around 0
corners: [number, number, number][];
// u v per corner, in pixels of the sprite (0 to TEXTURE_SIZE, v down)
uvs: [number, number][];
shade: number;
}
// one pixel of a 16 pixel sprite
const PIXEL = 1 / TEXTURE_SIZE;
const HALF_THICKNESS = PIXEL / 2;
// keeps lookups off the neighboring sprite, and side faces in the middle of their pixel
const FACE_PAD = 0.02;
const SIDE_PAD = 0.25;
// darker to the sides and bottom, so the edges show
const SIDE_SHADE = 0.7;
const TOP_SHADE = 0.9;
const BOTTOM_SHADE = 0.5;
const cache = new Map<string, ItemQuad[]>();
// cached per texture, the atlas is built once per page. without its pixels (not built yet) it's only the front and back
export function item_model(texture_id: string): ItemQuad[] {
let model = cache.get(texture_id);
if (!model) {
const mask = opaque_pixels(texture_id);
model = extrude_item(mask);
if (mask) cache.set(texture_id, model);
}
return model;
}
// the model for a sprite's opaque pixels (see opaque_pixels in atlas.ts)
export function extrude_item(mask: Uint8Array | undefined): ItemQuad[] {
const t = HALF_THICKNESS;
const lo = FACE_PAD;
const hi = TEXTURE_SIZE - FACE_PAD;
const quads: ItemQuad[] = [
// the front, and the back mirrored so it reads the same way round as minecraft's
quad([[-0.5, 0, t], [0.5, 0, t], [0.5, 1, t], [-0.5, 1, t]], [[lo, hi], [hi, hi], [hi, lo], [lo, lo]], [
0,
0,
1,
], 1),
quad([[0.5, 0, -t], [-0.5, 0, -t], [-0.5, 1, -t], [0.5, 1, -t]], [[hi, hi], [lo, hi], [lo, lo], [hi, lo]], [
0,
0,
-1,
], 1),
];
if (!mask) return quads;
const seen = (px: number, py: number) =>
px >= 0 && py >= 0 && px < TEXTURE_SIZE && py < TEXTURE_SIZE && mask[py * TEXTURE_SIZE + px] === 1;
for (let py = 0; py < TEXTURE_SIZE; py++) {
for (let px = 0; px < TEXTURE_SIZE; px++) {
if (!seen(px, py)) continue;
const x0 = px * PIXEL - 0.5;
const x1 = x0 + PIXEL;
const y1 = 1 - py * PIXEL;
const y0 = y1 - PIXEL;
// the whole side face is this pixel's color
const u0 = px + SIDE_PAD;
const u1 = px + 1 - SIDE_PAD;
const v0 = py + SIDE_PAD;
const v1 = py + 1 - SIDE_PAD;
const uvs: [number, number][] = [[u0, v1], [u1, v1], [u1, v0], [u0, v0]];
if (!seen(px - 1, py)) {
quads.push(quad([[x0, y0, -t], [x0, y0, t], [x0, y1, t], [x0, y1, -t]], uvs, [-1, 0, 0], SIDE_SHADE));
}
if (!seen(px + 1, py)) {
quads.push(quad([[x1, y0, t], [x1, y0, -t], [x1, y1, -t], [x1, y1, t]], uvs, [1, 0, 0], SIDE_SHADE));
}
if (!seen(px, py - 1)) {
quads.push(quad([[x0, y1, t], [x1, y1, t], [x1, y1, -t], [x0, y1, -t]], uvs, [0, 1, 0], TOP_SHADE));
}
if (!seen(px, py + 1)) {
quads.push(quad([[x0, y0, -t], [x1, y0, -t], [x1, y0, t], [x0, y0, t]], uvs, [0, -1, 0], BOTTOM_SHADE));
}
}
}
return quads;
}
// a quad facing normal: the corners are put in the order that faces that way, since faces are only drawn from the front
function quad(
corners: [number, number, number][],
uvs: [number, number][],
normal: [number, number, number],
shade: number,
): ItemQuad {
const [a, b, c] = corners;
const e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
const e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
const facing = (e1[1] * e2[2] - e1[2] * e2[1]) * normal[0] +
(e1[2] * e2[0] - e1[0] * e2[2]) * normal[1] +
(e1[0] * e2[1] - e1[1] * e2[0]) * normal[2];
if (facing < 0) {
return {
corners: [corners[0], corners[3], corners[2], corners[1]],
uvs: [uvs[0], uvs[3], uvs[2], uvs[1]],
shade,
};
}
return { corners, uvs, shade };
}
+48 -59
View File
@@ -3,8 +3,10 @@ import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everyt
import { AssetManager } from "$/client/assets.ts";
import { get_sprite_region } from "$/client/sprites.ts";
import type { ItemEntity } from "$/client/entity/item_entity.ts";
import type { ItemStack } from "$/common/inventory.ts";
import { push_vertex, Texture } from "$/client/renderer/mod.ts";
import { block_item_texture, cube_face_texture } from "$/common/block_models.ts";
import { item_model } from "./item_model.ts";
// how big items on the ground are drawn, minecraft's ground transform
const BLOCK_SCALE = 0.25;
@@ -37,78 +39,65 @@ function copies(amount: number) {
return 1;
}
// a point of an item's model to where it's drawn. models are 1 across, from y 0 to 1, centered on x and z
export type ItemTransform = (x: number, y: number, z: number) => [number, number, number];
// the atlas has to be the current texture
export function render_item_entity(entity: ItemEntity, partial_tick: number) {
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const item_info = EverythingRegistry.get<ItemRegistry>("items", entity.item.type_id);
// blocks that aren't cubes, like plants, are drawn as their item's sprite
let block_info = item_info?.block_id
? EverythingRegistry.get<BlockRegistry>("blocks", item_info.block_id)
: undefined;
if (block_info && block_item_texture(block_info) !== undefined) block_info = undefined;
// spinning and bobbing, like minecraft's ItemEntityRenderer
const time = entity.age + partial_tick;
const angle = time / 20 + entity.bob_offset;
const bob = Math.sin(time / 10 + entity.bob_offset) * 0.1 + 0.1;
const { x, y, z } = entity.render_position(partial_tick);
const scale = block_info ? BLOCK_SCALE : ITEM_SCALE;
for (let i = 0; i < copies(entity.item.amount); i++) {
const [ox, oy, oz] = COPY_OFFSETS[i];
const base = { x: x + ox * scale, y: y + bob + oy * scale * 0.5, z: z + oz * scale };
if (block_info) {
push_block(atlas, block_info, base, scale, angle);
} else {
push_sprite(atlas, item_texture(entity, item_info), base, scale, angle);
}
}
}
// a small cube turned around its middle
function push_block(
atlas: Texture,
block: BlockRegistry,
base: { x: number; y: number; z: number },
size: number,
angle: number,
) {
const sin = Math.sin(angle);
const cos = Math.cos(angle);
const corner = (cx: number, cy: number, cz: number) => {
const lx = (cx - 0.5) * size;
const lz = (cz - 0.5) * size;
return [base.x + lx * cos - lz * sin, base.y + cy * size, base.z + lx * sin + lz * cos];
};
for (const face of CUBE_FACES) {
const region = get_sprite_region(cube_face_texture(block, face.texture));
push_textured_quad(atlas, region, face.corners.map(([cx, cy, cz]) => corner(cx, cy, cz)), face.shade);
const scale = item_block(entity.item) ? BLOCK_SCALE : ITEM_SCALE;
for (let i = 0; i < copies(entity.item.amount); i++) {
const [ox, oy, oz] = COPY_OFFSETS[i];
const bx = x + ox * scale;
const by = y + bob + oy * scale * 0.5;
const bz = z + oz * scale;
push_item(atlas, entity.item, (lx, ly, lz) => [
bx + (lx * cos - lz * sin) * scale,
by + ly * scale,
bz + (lx * sin + lz * cos) * scale,
]);
}
}
// a flat sprite standing up and turning, drawn from both sides
function push_sprite(
atlas: Texture,
texture_id: string,
base: { x: number; y: number; z: number },
size: number,
angle: number,
) {
// the full block an item places, drawn as a cube. blocks that aren't cubes, like plants, are drawn as their sprite
export function item_block(item: ItemStack): BlockRegistry | undefined {
const item_info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
const block = item_info?.block_id ? EverythingRegistry.get<BlockRegistry>("blocks", item_info.block_id) : undefined;
return block && block_item_texture(block) === undefined ? block : undefined;
}
// an item's model: a cube for blocks, its sprite made 3d for everything else (see item_model.ts)
export function push_item(atlas: Texture, item: ItemStack, transform: ItemTransform) {
const block = item_block(item);
if (block) {
for (const face of CUBE_FACES) {
const region = get_sprite_region(cube_face_texture(block, face.texture));
const corners = face.corners.map(([cx, cy, cz]) => transform(cx - 0.5, cy, cz - 0.5));
push_textured_quad(atlas, region, corners, face.shade);
}
return;
}
const texture_id = item_texture(item);
const region = get_sprite_region(texture_id);
const dx = Math.cos(angle) * size / 2;
const dz = Math.sin(angle) * size / 2;
const bottom = base.y;
const top = base.y + size;
const front = [
[base.x - dx, bottom, base.z - dz],
[base.x + dx, bottom, base.z + dz],
[base.x + dx, top, base.z + dz],
[base.x - dx, top, base.z - dz],
];
push_textured_quad(atlas, region, front, 1);
// the back is the same quad the other way round, mirrored so it isn't drawn backwards
push_textured_quad(atlas, region, [front[1], front[0], front[3], front[2]], 1);
const u = (pixels: number) => (region.x * TEXTURE_SIZE + pixels) / atlas.width;
const v = (pixels: number) => (region.y * TEXTURE_SIZE + pixels) / atlas.height;
for (const quad of item_model(texture_id)) {
for (const i of [0, 1, 2, 0, 2, 3]) {
const [px, py, pz] = transform(...quad.corners[i]);
const [pu, pv] = quad.uvs[i];
push_vertex(px, py, pz, u(pu), v(pv), quad.shade, quad.shade, quad.shade, 1);
}
}
}
function push_textured_quad(atlas: Texture, region: { x: number; y: number }, corners: number[][], shade: number) {
@@ -124,10 +113,10 @@ function push_textured_quad(atlas: Texture, region: { x: number; y: number }, co
}
}
function item_texture(entity: ItemEntity, item_info: ItemRegistry | undefined) {
const texture_id = item_info?.texture_id;
function item_texture(item: ItemStack) {
const texture_id = EverythingRegistry.get<ItemRegistry>("items", item.type_id)?.texture_id;
if (typeof texture_id === "function") {
return texture_id(entity.item);
return texture_id(item);
}
return texture_id ?? "engine:missing";
}
+5 -1
View File
@@ -11,6 +11,8 @@ export interface ModelFaceJson {
texture: string;
// the part of the texture, [u1, v1, u2, v2] in pixels (0-16). defaults to the part the face covers
uv?: [number, number, number, number];
// turns the texture on the face clockwise: 0, 90, 180 or 270
rotation?: number;
// hidden when the neighbor on this side hides faces (a solid block)
cullface?: ModelFace;
}
@@ -234,6 +236,8 @@ export function bake_model(model: ModelJson, textures: BlockTextures | undefined
if (!face_json) continue;
const index = FACE_INDEX[face];
const uv = face_json.uv ?? default_uv(face, element.from, element.to);
// each corner takes the uv of the corner a quarter turn along, per 90 degrees
const uv_turns = Math.round((face_json.rotation ?? 0) / 90) % 4;
const positions: number[] = [];
const uvs: number[] = [];
@@ -242,7 +246,7 @@ export function bake_model(model: ModelJson, textures: BlockTextures | undefined
point = rotate(point);
for (let t = 0; t < turns; t++) point = [1 - point[2], point[1], point[0]];
positions.push(...point);
const [cu, cv] = CORNER_UVS[k];
const [cu, cv] = CORNER_UVS[(k + uv_turns) % 4];
uvs.push(cu ? uv[2] : uv[0], cv ? uv[3] : uv[1]);
});
+375
View File
@@ -0,0 +1,375 @@
// commands the way minecraft's brigadier (and so fabric's command api) 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
// get its suggestions as they type. see "Commands" in MODS.md
import { EverythingRegistry } from "./everything_registry.ts";
export interface Suggestion {
text: string;
// shown next to it, like an item's name
tooltip?: string;
}
// what went wrong, told to the player who typed it
export class CommandError extends Error {
constructor(message: string) {
super(message);
this.name = "CommandError";
}
}
// how an argument reads its text, and what could go there
export interface ArgumentType<T = unknown, S = unknown> {
// takes the rest of the line, spaces and all, like a chat message
readonly greedy?: boolean;
// throws CommandError when the text doesn't fit
parse(text: string, source: S): T;
suggest?(partial: string, source: S): Suggestion[];
}
export interface CommandContext<S> {
source: S;
// the value of an argument by its name, as its type parsed it
get<T>(name: string): T;
// what was typed, without the /
input: string;
}
export type CommandFunction<S> = (context: CommandContext<S>) => void;
// a word or an argument, and what can follow it. like brigadier's builders, the methods chain:
// literal("give").then(argument("item", item()).executes(...))
export class CommandNode<S = unknown> {
readonly children: CommandNode<S>[] = [];
command?: CommandFunction<S>;
requirement?: (source: S) => boolean;
suggestion_provider?: (partial: string, source: S) => Suggestion[];
// for /help
description?: string;
constructor(readonly name: string, readonly type?: ArgumentType<unknown, S>) {}
then(child: CommandNode<S>): this {
this.children.push(child);
// words before arguments, so a literal wins over an argument that would take the same word
this.children.sort((a, b) => Number(a.type !== undefined) - Number(b.type !== undefined));
return this;
}
executes(command: CommandFunction<S>): this {
this.command = command;
return this;
}
// only for sources this is true for, like operators. others can't run it or see it suggested
requires(requirement: (source: S) => boolean): this {
this.requirement = requirement;
return this;
}
// suggestions for this argument instead of its type's
suggests(provider: (partial: string, source: S) => Suggestion[]): this {
this.suggestion_provider = provider;
return this;
}
describe(description: string): this {
this.description = description;
return this;
}
get is_literal() {
return this.type === undefined;
}
}
export function literal<S = unknown>(name: string): CommandNode<S> {
return new CommandNode<S>(name);
}
export function argument<T, S = unknown>(name: string, type: ArgumentType<T, S>): CommandNode<S> {
return new CommandNode<S>(name, type as ArgumentType<unknown, S>);
}
interface Token {
text: string;
start: number;
}
interface Failure {
// how far it got, the error from the furthest attempt is the one worth showing
at: number;
message: string;
}
export class CommandDispatcher<S> {
readonly root = new CommandNode<S>("");
// adds a command at the top. a second one with the same name is an error, use then() to add to an existing one
register(node: CommandNode<S>): CommandNode<S> {
if (!node.is_literal) throw new Error("commands start with a word, use literal()");
if (this.get(node.name)) throw new Error(`/${node.name} already exists`);
this.root.then(node);
return node;
}
get(name: string): CommandNode<S> | undefined {
return this.root.children.find((child) => child.name === name);
}
// runs what was typed, without the /. throws CommandError saying what's wrong
execute(input: string, source: S) {
const tokens = tokenize(input);
const failures: Failure[] = [];
const found = this.#parse(this.root, tokens, 0, new Map(), source, input, failures);
if (!found) {
const failure = failures.sort((a, b) => b.at - a.at)[0];
throw new CommandError(failure?.message ?? `Unknown command /${tokens[0]?.text ?? ""}`);
}
const args = found.args;
found.command({
source,
input,
get<T>(name: string) {
if (!args.has(name)) throw new Error(`there's no argument "${name}"`);
return args.get(name) as T;
},
});
}
// what could come at the end of input, for the word being typed: start is where it begins in input
suggest(input: string, source: S): { start: number; suggestions: Suggestion[] } {
const tokens = tokenize(input);
const partial = tokens.pop() ?? { text: "", start: input.length };
const nodes = this.#walk(this.root, tokens, 0, source);
const seen = new Set<string>();
const suggestions: Suggestion[] = [];
for (const node of nodes) {
for (const child of node.children) {
if (child.requirement && !safe(() => child.requirement!(source), false)) continue;
let found: Suggestion[];
if (child.is_literal) {
found = child.name.startsWith(partial.text) ? [{ text: child.name }] : [];
} else {
const provider = child.suggestion_provider ?? child.type!.suggest?.bind(child.type);
found = provider ? safe(() => provider(partial.text, source), []) : [];
}
for (const suggestion of found) {
if (seen.has(suggestion.text)) continue;
seen.add(suggestion.text);
suggestions.push(suggestion);
}
}
}
suggestions.sort((a, b) => a.text.localeCompare(b.text));
return { start: partial.start, suggestions };
}
// how to use a command, like brigadier's smart usage: "give <item> [<count>]"
usage(node: CommandNode<S>, source: S): string {
const own = node.is_literal ? node.name : `<${node.name}>`;
const children = node.children.filter((child) =>
!child.requirement || safe(() => child.requirement!(source), false)
);
if (children.length === 0) return own;
const inner = children.length === 1
? this.usage(children[0], source)
: children.map((child) => child.is_literal ? child.name : `<${child.name}>`).join("|");
if (node.command) return `${own} [${inner}]`;
return children.length === 1 ? `${own} ${inner}` : `${own} (${inner})`;
}
#parse(
node: CommandNode<S>,
tokens: Token[],
index: number,
args: Map<string, unknown>,
source: S,
input: string,
failures: Failure[],
): { command: CommandFunction<S>; args: Map<string, unknown> } | undefined {
if (index === tokens.length) {
if (node.command) return { command: node.command, args };
failures.push({ at: index, message: `Not enough: /${this.usage(this.#top(node, tokens), source)}` });
return undefined;
}
const token = tokens[index];
for (const child of node.children) {
if (child.requirement && !safe(() => child.requirement!(source), false)) continue;
if (child.is_literal) {
if (child.name !== token.text) continue;
const found = this.#parse(child, tokens, index + 1, args, source, input, failures);
if (found) return found;
continue;
}
const type = child.type!;
const text = type.greedy ? input.slice(token.start) : token.text;
let value: unknown;
try {
value = type.parse(text, source);
} catch (e) {
failures.push({ at: index, message: e instanceof CommandError ? e.message : `Can't read "${text}"` });
continue;
}
const next = new Map(args).set(child.name, value);
const found = this.#parse(
child,
tokens,
type.greedy ? tokens.length : index + 1,
next,
source,
input,
failures,
);
if (found) return found;
}
if (index === 0) {
failures.push({ at: 0, message: `Unknown command /${token.text}` });
} else {
failures.push({
at: index,
message: `Didn't expect "${token.text}": /${this.usage(this.#top(node, tokens), source)}`,
});
}
return undefined;
}
// the nodes reachable after the whole tokens, where the next word could go
#walk(node: CommandNode<S>, tokens: Token[], index: number, source: S): CommandNode<S>[] {
if (index === tokens.length) return [node];
const reached: CommandNode<S>[] = [];
for (const child of node.children) {
if (child.requirement && !safe(() => child.requirement!(source), false)) continue;
if (child.is_literal) {
if (child.name === tokens[index].text) reached.push(...this.#walk(child, tokens, index + 1, source));
} else if (
!child.type!.greedy && safe(() => (child.type!.parse(tokens[index].text, source), true), false)
) {
reached.push(...this.#walk(child, tokens, index + 1, source));
}
}
return reached;
}
// the command a parse was in, for its usage
#top(node: CommandNode<S>, tokens: Token[]): CommandNode<S> {
return node === this.root ? node : this.get(tokens[0]?.text ?? "") ?? node;
}
}
// words split on single spaces, remembering where each starts. "a b" has an empty word between, which nothing matches
function tokenize(input: string): Token[] {
const tokens: Token[] = [];
let start = 0;
for (const text of input.split(" ")) {
tokens.push({ text, start });
start += text.length + 1;
}
return tokens;
}
function safe<T>(fn: () => T, fallback: T): T {
try {
return fn();
} catch {
return fallback;
}
}
// argument types, like brigadier's and minecraft's
export function integer(min = -Infinity, max = Infinity): ArgumentType<number> {
return {
parse(text) {
const value = Number(text);
if (!/^-?\d+$/.test(text) || !Number.isSafeInteger(value)) {
throw new CommandError(`"${text}" isn't a whole number`);
}
if (value < min) throw new CommandError(`${value} is too small, the least is ${min}`);
if (value > max) throw new CommandError(`${value} is too big, the most is ${max}`);
return value;
},
};
}
export function number(min = -Infinity, max = Infinity): ArgumentType<number> {
return {
parse(text) {
const value = Number(text);
if (text === "" || !Number.isFinite(value)) throw new CommandError(`"${text}" isn't a number`);
if (value < min) throw new CommandError(`${value} is too small, the least is ${min}`);
if (value > max) throw new CommandError(`${value} is too big, the most is ${max}`);
return value;
},
};
}
export function boolean(): ArgumentType<boolean> {
return {
parse(text) {
if (text === "true") return true;
if (text === "false") return false;
throw new CommandError(`"${text}" isn't true or false`);
},
suggest: (partial) => ["true", "false"].filter((b) => b.startsWith(partial)).map((text) => ({ text })),
};
}
// one word, anything without spaces
export function word(): ArgumentType<string> {
return {
parse(text) {
if (text === "") throw new CommandError("Expected a word");
return text;
},
};
}
// the rest of the line
export function greedy_string(): ArgumentType<string> {
return { greedy: true, parse: (text) => text };
}
// one of a few words, suggested
export function choice<T extends string>(options: readonly T[]): ArgumentType<T> {
return {
parse(text) {
if (!options.includes(text as T)) throw new CommandError(`"${text}" isn't one of ${options.join(", ")}`);
return text as T;
},
suggest: (partial) => options.filter((o) => o.startsWith(partial)).map((text) => ({ text })),
};
}
// an id from a registry. without a namespace it's whichever id has that name, as long as only one does
function registry_id(registry: string, what: string): ArgumentType<string> {
return {
parse(text) {
if (text.includes(":")) {
if (!EverythingRegistry.get(registry, text)) throw new CommandError(`There's no ${what} ${text}`);
return text;
}
const matches = EverythingRegistry.entries(registry).map(([id]) => id).filter((id) =>
id.endsWith(`:${text}`)
);
if (matches.length === 0) throw new CommandError(`There's no ${what} called ${text}`);
if (matches.length > 1) throw new CommandError(`Which one? ${matches.join(", ")}`);
return matches[0];
},
// full ids starting with it, or whose name part does, like minecraft
suggest(partial) {
return EverythingRegistry.entries(registry)
.map(([id]) => id)
.filter((id) => id !== "bworld:air" && (id.startsWith(partial) || id.split(":")[1].startsWith(partial)))
.map((id) => ({ text: id }));
},
};
}
export function item(): ArgumentType<string> {
return registry_id("items", "item");
}
export function block(): ArgumentType<string> {
return registry_id("blocks", "block");
}
+18
View File
@@ -129,12 +129,29 @@ export interface BlockRegistry {
interactive?: boolean;
// placing a block into it replaces it, like water
replaceable?: boolean;
// the blocks it can stand on, like crops on farmland. it can't be placed elsewhere, and breaks when the block
// under it becomes something else. anything when not set
place_on?: string[];
// the blocks it can be placed into, replacing them, like rice into water. air and replaceable blocks when not set
place_in?: string[];
// custom components from mods and their params, the server runs them
components?: Record<string, unknown>;
compiled_states?: CompiledStateDefinition[];
}
// what eating an item does, like minecraft's food properties
export interface FoodProperties {
// hunger points it restores, a bar is 20
nutrition: number;
// saturation it gives is nutrition * saturation_modifier * 2, like minecraft. bread's is 0.6
saturation_modifier: number;
// can be eaten when not hungry
always_edible?: boolean;
// what's left in the hand after, like a bowl after soup
returns?: string;
}
export interface ItemRegistry<T = unknown | undefined> {
texture_id: string | ((item: ItemStack<T>) => string);
// what players see, like "Iron Ingot". made from the id when not set, see display_name in common/utils.ts
@@ -143,6 +160,7 @@ export interface ItemRegistry<T = unknown | undefined> {
tool_type?: string;
max_stack?: number;
lore?: string;
food?: FoodProperties;
components?: Record<string, unknown>;
on_create?(item: ItemStack<T>): void;
+41 -2
View File
@@ -1,5 +1,5 @@
// what client scripts get, see "Client scripts" and "GUIs" in MODS.md
import type { Id, KeyCode, ModInfo, Position } from "./shared.ts";
import type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts";
export type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts";
@@ -16,6 +16,20 @@ export interface ClientContext {
// ticks since 06:00 of day 1, see ServerWorld.time
readonly time: number;
};
// every item any mod registered, in load order
items: {
ids(): Id[];
exists(id: Id): boolean;
// what players see, like "Cooked Rice"
name(id: Id): string;
// the mod that registered it
mod(id: Id): string;
};
// every recipe as its json (see Recipes in MODS.md), including mods' own types, in load order. copies
recipes: {
// deno-lint-ignore no-explicit-any
list(type?: Id): any[];
};
log(...args: unknown[]): void;
}
@@ -36,7 +50,7 @@ export type Color = [number, number, number, number];
export interface Graphics {
readonly width: number;
readonly height: number;
readonly mouse: { x: number; y: number; down: boolean; 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;
panel(x: number, y: number, w: number, h: number): void;
text(text: string, x: number, y: number, options?: { scale?: number; color?: Color }): void;
@@ -49,13 +63,38 @@ export interface Graphics {
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
key_pressed(key: KeyCode): boolean;
// shown next to the mouse over everything else, the last one this frame wins
tooltip(lines: (string | { text: string; color?: Color })[], x: number, y: number): void;
// the game's tooltip for an item (its name, food, lore), with extra lines under it
item_tooltip(id: Id, x: number, y: number, extra?: (string | { text: string; color?: Color })[]): void;
// the click was used, so nothing under it (like slots) gets it
consume_click(): void;
// the screen underneath ignores the mouse over this area this frame, for something drawn over it
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'
// item list. it gets the screen's box to lay itself out around
export interface InventoryOverlay {
on_render(g: Graphics, screen: InventoryScreenView): void;
}
export interface InventoryScreenView {
readonly x: number;
readonly y: number;
readonly width: number;
readonly height: number;
// what's in the slot under the mouse
readonly hovered_item: ItemStack | undefined;
}
export interface ClientUi {
register_screen<Props>(id: Id, create: (props: Props) => ModScreen<Props>): void;
// open a screen that doesn't involve the server, like a settings page
open<Props>(id: Id, props: Props): void;
add_inventory_overlay(overlay: InventoryOverlay): void;
}
export interface HudRegistry {
+71 -1
View File
@@ -1,5 +1,8 @@
// what server scripts get, see "Server scripts" in MODS.md
import type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
import type { ArgumentType, CommandNode } from "../commands.ts";
export type { ArgumentType, CommandContext, CommandNode, Suggestion } from "../commands.ts";
export type { EventSignal, Face, Id, ItemStack, ModInfo, Position } from "./shared.ts";
@@ -42,6 +45,8 @@ export interface BlockComponent<P = any> {
on_interact?(block: BlockRef, params: P, player: Player): boolean;
on_tick?(block: BlockRef, params: P, dt: number): void;
on_second?(block: BlockRef, params: P, dt: number): void;
// every morning at 06:00, for every block with data in the world, near a player or not. day is ServerWorld.day
on_new_day?(block: BlockRef, params: P, day: number): void;
}
// deno-lint-ignore no-explicit-any
@@ -56,8 +61,16 @@ export interface ComponentRegistry {
register_item<P>(id: Id, component: ItemComponent<P>): void;
}
// commands
// commands, fabric's (brigadier's) way: see common/commands.ts and "Commands" in MODS.md
// who ran a command
export interface CommandSource {
readonly player: Player;
// answers them in chat
send_message(text: string): void;
}
// the simple way: the words after the name, split on spaces
export interface Command {
description: string;
usage: string;
@@ -65,7 +78,25 @@ export interface Command {
}
export interface CommandRegistry {
// a tree of literal() and argument() nodes, like fabric's dispatcher.register(literal("heal").then(...))
register(node: CommandNode<CommandSource>): void;
register(name: string, command: Command): void;
literal(name: string): CommandNode<CommandSource>;
argument<T>(name: string, type: ArgumentType<T, CommandSource>): CommandNode<CommandSource>;
// argument types. they parse their text and suggest what could go there as players type
types: {
integer(min?: number, max?: number): ArgumentType<number, CommandSource>;
number(min?: number, max?: number): ArgumentType<number, CommandSource>;
boolean(): ArgumentType<boolean, CommandSource>;
word(): ArgumentType<string, CommandSource>;
greedy_string(): ArgumentType<string, CommandSource>;
choice<T extends string>(options: readonly T[]): ArgumentType<T, CommandSource>;
// an item or block id. without a namespace, whichever has that name
item(): ArgumentType<Id, CommandSource>;
block(): ArgumentType<Id, CommandSource>;
// an online player's name
player(): ArgumentType<Player, CommandSource>;
};
}
// events
@@ -93,6 +124,19 @@ export interface BlockInteractEvent {
readonly item: ItemStack | undefined;
}
export interface PlayerDamageEvent {
readonly player: Player;
// before events can change it
amount: number;
// what hurt them: "fall", "void", "starve", or what a mod passed to damage
readonly cause: string;
}
export interface PlayerDeathEvent {
readonly player: Player;
readonly cause: string;
}
export interface ChatSendEvent {
readonly player: Player;
message: string;
@@ -103,6 +147,7 @@ export interface ServerBeforeEvents {
block_place: EventSignal<BlockPlaceEvent & Cancelable>;
block_interact: EventSignal<BlockInteractEvent & Cancelable>;
chat_send: EventSignal<ChatSendEvent & Cancelable>;
player_damage: EventSignal<PlayerDamageEvent & Cancelable>;
}
export interface ServerAfterEvents {
@@ -112,8 +157,12 @@ export interface ServerAfterEvents {
chat_send: EventSignal<Readonly<ChatSendEvent>>;
player_join: EventSignal<{ readonly player: Player }>;
player_leave: EventSignal<{ readonly player: Player }>;
// they drop what they carried and respawn right after
player_death: EventSignal<PlayerDeathEvent>;
server_start: EventSignal<Record<never, never>>;
tick: EventSignal<{ readonly dt: number }>;
// 06:00, after every block's on_new_day
new_day: EventSignal<{ readonly day: number }>;
}
// world and players
@@ -121,6 +170,8 @@ export interface ServerAfterEvents {
export interface ServerWorld {
get_block(x: number, y: number, z: number): Id | undefined; // undefined when the chunk isn't loaded
set_block(x: number, y: number, z: number, id: Id): boolean; // runs on_break / on_create, synced to everyone
// like breaking it by hand without a tool: on_break, then its drops. false when there was nothing to break
break_block(x: number, y: number, z: number): boolean;
get_state(x: number, y: number, z: number, name: string): number | undefined;
set_state(x: number, y: number, z: number, name: string, value: number): boolean;
get_block_data<T>(x: number, y: number, z: number): T | undefined;
@@ -130,6 +181,8 @@ export interface ServerWorld {
readonly seed: string;
// ticks since 06:00 of day 1. a day is 36000 ticks (06:00 to 18:00), a night 12000
readonly time: number;
// days since the world started, going up at 06:00 each morning: 0 on the first day
readonly day: number;
set_time(time: number): void;
}
@@ -144,6 +197,18 @@ export interface Player {
give_item(id: Id, count?: number, data?: unknown): void;
send_message(text: string): void;
teleport(x: number, y: number, z: number): void;
// health and hunger, like minecraft: 20 each, saturation is never above hunger
readonly health: number;
readonly max_health: number;
readonly food: number;
readonly saturation: number;
// cause is for events and the death message, like "fall"
damage(amount: number, cause?: string): void;
heal(amount: number): void;
// like eating: nutrition in hunger points, saturation_modifier like minecraft's (bread's is 0.6)
feed(nutrition: number, saturation_modifier: number): void;
// tires them out: 4 costs a point of saturation, or of hunger once it's gone
add_exhaustion(amount: number): void;
}
export interface PlayerList {
@@ -187,6 +252,8 @@ export interface ItemApi {
exists(id: Id): boolean;
// how many fit in one slot
max_stack(id: Id): number;
// the tool type it is, like "pickaxe" or "shovel", from the item's "tool"
tool(id: Id): string | undefined;
}
export interface RecipeApi {
@@ -196,6 +263,9 @@ export interface RecipeApi {
is_smeltable(item: Id): boolean;
// the smithing recipe for these items, whatever the material's count. addition is the optional third item
smithing(tool: Id, material: Id, addition?: Id): { result: Id; material_count: number } | undefined;
// every recipe of a mod's own type, like "farmersdelight:cooking", as its json. copies, in load order
// deno-lint-ignore no-explicit-any
list(type: Id): any[];
}
// guis
+4
View File
@@ -107,6 +107,9 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
}
}
if (json.drops) uses(file, json.drops, "item");
for (const id of [...(json.place_on ?? []), ...(json.place_in ?? [])]) {
if (id !== "bworld:air") uses(file, id, "block");
}
}
for (const { file, json } of mod.models) {
if ((model_owners.get(json.id)?.length ?? 0) > 1 || BUILTIN_MODELS[json.id]) {
@@ -127,6 +130,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
}
uses(file, json.texture, "texture");
if (json.places) uses(file, json.places, "block");
if (json.food?.returns) uses(file, json.food.returns, "item");
}
for (const { file, json } of mod.recipes) {
switch (json.type) {
+57 -2
View File
@@ -3,6 +3,7 @@
import {
type BlockRegistry,
type BlockStateDefinition,
type FoodProperties,
type ItemRegistry,
RENDER_LAYERS,
type RenderLayer,
@@ -48,6 +49,8 @@ export interface BlockJson {
item?: boolean;
interactive?: boolean;
replaceable?: boolean;
place_on?: string[];
place_in?: string[];
states?: BlockStateDefinition[];
components?: Record<string, unknown>;
}
@@ -67,6 +70,7 @@ export interface ItemJson {
tool?: string;
places?: string;
max_stack?: number;
food?: FoodProperties;
name?: string;
lore?: string;
components?: Record<string, unknown>;
@@ -88,7 +92,20 @@ export type RecipeJson =
material: { id: string; count: number };
addition?: string;
result: string;
};
}
// a mod's own recipe type, like "farmersdelight:cooking" for its cooking pot. the engine only stores these, the mod's
// server script reads them with ctx.recipes.list and checks the rest
| ModRecipeJson;
export interface ModRecipeJson {
type: `${string}:${string}`;
[field: string]: unknown;
}
// a recipe type a mod made up, as opposed to the engine's shaped, furnace, fuel and smithing
export function is_mod_recipe(recipe: RecipeJson): recipe is ModRecipeJson {
return recipe.type.includes(":");
}
// the crafting grid's format, see server/game/crafting.ts
export interface GridRecipe {
@@ -120,6 +137,8 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso
if (!has_item) json.item = false;
if (block.interactive) json.interactive = true;
if (block.replaceable) json.replaceable = true;
if (block.place_on) json.place_on = block.place_on;
if (block.place_in) json.place_in = block.place_in;
if (block.states) json.states = block.states;
if (block.components) json.components = block.components;
return json;
@@ -148,6 +167,8 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it
if (json.drops !== undefined) block.drop_table = json.drops;
if (json.interactive) block.interactive = true;
if (json.replaceable) block.replaceable = true;
if (json.place_on) block.place_on = json.place_on;
if (json.place_in) block.place_in = json.place_in;
if (json.states) block.states = json.states;
if (json.components) block.components = json.components;
return { block, has_item: json.item ?? true };
@@ -163,6 +184,7 @@ export function item_to_json(id: string, item: ItemRegistry): ItemJson {
if (item.tool_type !== undefined) json.tool = item.tool_type;
if (item.block_id !== undefined) json.places = item.block_id;
if (item.max_stack !== undefined) json.max_stack = item.max_stack;
if (item.food !== undefined) json.food = item.food;
if (item.name !== undefined) json.name = item.name;
if (item.lore !== undefined) json.lore = item.lore;
if (item.components) json.components = item.components;
@@ -174,6 +196,7 @@ export function item_from_json(json: ItemJson): ItemRegistry {
if (json.tool !== undefined) item.tool_type = json.tool;
if (json.places !== undefined) item.block_id = json.places;
if (json.max_stack !== undefined) item.max_stack = json.max_stack;
if (json.food !== undefined) item.food = json.food;
if (json.name !== undefined) item.name = json.name;
if (json.lore !== undefined) item.lore = json.lore;
if (json.components) item.components = json.components;
@@ -337,6 +360,15 @@ export function validate_block(json: unknown): Problems {
}
}
if (json.drops !== undefined) problems.push(...validate_id(json.drops, "drops"));
for (const key of ["place_on", "place_in"]) {
const list = json[key];
if (list === undefined) continue;
if (!Array.isArray(list) || list.length === 0) {
problems.push(`${key} must be a list of block ids`);
} else {
for (const id of list) problems.push(...validate_id(id, key));
}
}
if (json.states !== undefined) {
const states = json.states;
if (!Array.isArray(states)) {
@@ -398,6 +430,9 @@ export function validate_model(json: unknown): Problems {
if (face.uv !== undefined && (!Array.isArray(face.uv) || face.uv.length !== 4)) {
problems.push(`${where}.faces.${side}.uv must be [u1, v1, u2, v2] in pixels`);
}
if (face.rotation !== undefined && ![0, 90, 180, 270].includes(face.rotation as number)) {
problems.push(`${where}.faces.${side}.rotation must be 0, 90, 180 or 270`);
}
if (face.cullface !== undefined && !MODEL_FACES.includes(face.cullface as ModelFace)) {
problems.push(`${where}.faces.${side}.cullface isn't one of ${MODEL_FACES.join(", ")}`);
}
@@ -424,6 +459,20 @@ export function validate_item(json: unknown): Problems {
if (json.max_stack !== undefined && (!Number.isInteger(json.max_stack) || (json.max_stack as number) < 1)) {
problems.push("max_stack must be a positive whole number");
}
if (json.food !== undefined) {
const food = json.food;
if (
!is_object(food) || !Number.isInteger(food.nutrition) || (food.nutrition as number) < 0 ||
typeof food.saturation_modifier !== "number" || food.saturation_modifier < 0
) {
problems.push("food must be { nutrition, saturation_modifier }, nutrition a whole number");
} else {
if (food.always_edible !== undefined && typeof food.always_edible !== "boolean") {
problems.push("food.always_edible must be true or false");
}
if (food.returns !== undefined) problems.push(...validate_id(food.returns, "food.returns"));
}
}
return problems;
}
@@ -472,7 +521,13 @@ export function validate_recipe(json: unknown): Problems {
if (json.addition !== undefined) problems.push(...validate_id(json.addition, "addition"));
break;
default:
problems.push('type must be "shaped", "furnace", "fuel" or "smithing"');
if (typeof json.type !== "string" || !json.type.includes(":")) {
problems.push(
'type must be "shaped", "furnace", "fuel", "smithing" or a mod\'s own type like "farmersdelight:cooking"',
);
} else {
problems.push(...validate_id(json.type, "type"));
}
}
return problems;
}
+13
View File
@@ -5,8 +5,10 @@ import {
BlockJson,
grid_recipe_from_json,
GridRecipe,
is_mod_recipe,
item_from_json,
ItemJson,
ModRecipeJson,
OreJson,
RecipeJson,
} from "./mod_data.ts";
@@ -40,6 +42,10 @@ export class RecipeBook {
furnace = new Map<string, { output: { id: string; count: number }; cook_time: number }>();
fuel = new Map<string, number>();
smithing: Extract<RecipeJson, { type: "smithing" }>[] = [];
// recipes of mods' own types, by type
by_type = new Map<string, ModRecipeJson[]>();
// every recipe as its json, in load order, for recipe viewers
all: RecipeJson[] = [];
ores: OreJson[] = [];
}
@@ -77,6 +83,13 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
}
for (const recipe of data.recipes) {
recipes.all.push(recipe);
if (is_mod_recipe(recipe)) {
const list = recipes.by_type.get(recipe.type) ?? [];
recipes.by_type.set(recipe.type, list);
list.push(recipe);
continue;
}
switch (recipe.type) {
case "shaped":
recipes.shaped.push(grid_recipe_from_json(recipe));
+9 -3
View File
@@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 4;
export const PROTOCOL_VERSION = 6;
export interface PlayerInfo {
id: string;
@@ -75,7 +75,9 @@ export type ClientMessage =
| { type: "drop_item"; container: ContainerKey; index: number; all: boolean }
// closes the open screen, including the player's own inventory screen
| { type: "close_screen" }
| { type: "chat"; text: string };
| { type: "chat"; text: string }
// what could come next in a command being typed, answered with suggestions. id matches them up
| { type: "suggest"; id: number; text: string };
export type ServerMessage =
// what to download before joining, see "Delivery to clients" in MODS.md
@@ -123,7 +125,11 @@ export type ServerMessage =
| { type: "screen_properties"; properties: Record<string, number> }
| { type: "close_screen" }
// 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
| { type: "suggestions"; id: number; start: number; suggestions: { text: string; tooltip?: string }[] }
// the player's own health, hunger and saturation, when they change
| { type: "vitals"; health: number; food: number; saturation: number };
export const MAX_NAME_LENGTH = 16;
export const MAX_CHAT_LENGTH = 256;
+30
View File
@@ -118,6 +118,36 @@ function compile_block_states(block_info: BlockRegistry) {
});
}
// whether a block can be at a spot with below under it, see place_on
export function can_stand_on(block: BlockRegistry | undefined, below: string): boolean {
return !block?.place_on || block.place_on.includes(below);
}
// where a block placed by clicking a face of another goes: into the clicked block when it can be replaced (like water),
// like minecraft, otherwise next to it
export function placement_target(
x: number,
y: number,
z: number,
offset: { x: number; y: number; z: number },
clicked: BlockRegistry | undefined,
) {
return clicked?.replaceable ? { x, y, z } : { x: x + offset.x, y: y + offset.y, z: z + offset.z };
}
// whether a player can place block where current is now, with below under it. current is undefined for air
export function can_place(
block: BlockRegistry | undefined,
current: BlockRegistry | undefined,
below: string,
): boolean {
if (!block) return false;
const into = current?.id ?? "bworld:air";
const replaceable = !current || current.replaceable === true;
const in_ok = block.place_in ? block.place_in.includes(into) : replaceable;
return in_ok && can_stand_on(block, below);
}
// numeric so looking chunks up doesnt allocate a string every time, fine for |x|, |z| < 32768
export function chunk_key(x: number, z: number) {
return (x + 32768) * 65536 + (z + 32768);
+60
View File
@@ -0,0 +1,60 @@
{
"format_version": 1,
"block": {
"id": "bworld:carrots",
"textures": {
"crop": "bworld:carrot_stage_0"
},
"model": "engine:crop",
"variants": {
"age=0": {
"textures": {
"crop": "bworld:carrot_stage_0"
}
},
"age=1": {
"textures": {
"crop": "bworld:carrot_stage_1"
}
},
"age=2": {
"textures": {
"crop": "bworld:carrot_stage_2"
}
},
"age=3": {
"textures": {
"crop": "bworld:carrot_stage_3"
}
}
},
"render_layer": "cutout",
"collision": false,
"mining": {
"toughness": 0
},
"item": false,
"place_on": [
"bworld:hoed_dirt"
],
"states": [
{
"name": "age",
"bits": 2,
"default": 0
}
],
"components": {
"bworld:crop": {
"days": 3,
"stages": 4,
"fertilizer": "bworld:bone_meal",
"drops": {
"young": "bworld:carrot",
"mature": "bworld:carrot",
"bonus": "bworld:carrot"
}
}
}
}
}
+7
View File
@@ -13,6 +13,13 @@
},
"drops": "bworld:furnace",
"interactive": true,
"states": [
{
"name": "lit",
"bits": 1,
"default": 0
}
],
"components": {
"bworld:furnace": {}
}
+13 -1
View File
@@ -18,6 +18,18 @@
"bits": 1,
"default": 0
}
]
],
"variants": {
"watered=1": {
"textures": {
"side": "bworld:dirt",
"top": "bworld:hoed_watered_dirt",
"bottom": "bworld:dirt"
}
}
},
"components": {
"bworld:farmland": {}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
{
"format_version": 1,
"block": {
"id": "bworld:potatoes",
"textures": {
"crop": "bworld:potatoes_stage_0"
},
"model": "engine:crop",
"variants": {
"age=0": {
"textures": {
"crop": "bworld:potatoes_stage_0"
}
},
"age=1": {
"textures": {
"crop": "bworld:potatoes_stage_1"
}
},
"age=2": {
"textures": {
"crop": "bworld:potatoes_stage_2"
}
},
"age=3": {
"textures": {
"crop": "bworld:potatoes_stage_3"
}
}
},
"render_layer": "cutout",
"collision": false,
"mining": {
"toughness": 0
},
"item": false,
"place_on": [
"bworld:hoed_dirt"
],
"states": [
{
"name": "age",
"bits": 2,
"default": 0
}
],
"components": {
"bworld:crop": {
"days": 6,
"stages": 4,
"fertilizer": "bworld:bone_meal",
"drops": {
"young": "bworld:potato",
"mature": "bworld:potato",
"bonus": "bworld:potato"
}
}
}
}
}
+4 -1
View File
@@ -8,6 +8,9 @@
"alpha": 0.8,
"collision": false,
"item": false,
"replaceable": true
"replaceable": true,
"components": {
"bworld:water_source": {}
}
}
}
+10 -2
View File
@@ -53,8 +53,10 @@
"mining": {
"toughness": 0
},
"drops": "bworld:wheat_seeds",
"item": false,
"place_on": [
"bworld:hoed_dirt"
],
"states": [
{
"name": "age",
@@ -64,8 +66,14 @@
],
"components": {
"bworld:crop": {
"days": 7,
"stages": 8,
"fertilizer": "bworld:bone_meal",
"max_age": 7
"drops": {
"young": "bworld:wheat_seeds",
"mature": "bworld:wheat",
"bonus": "bworld:wheat_seeds"
}
}
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"format_version": 1,
"item": {
"id": "bworld:bowl",
"texture": "bworld:bowl"
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"item": {
"id": "bworld:carrot",
"texture": "bworld:carrot",
"food": {
"nutrition": 3,
"saturation_modifier": 0.6
},
"places": "bworld:carrots"
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"item": {
"id": "bworld:potato",
"texture": "bworld:potato",
"food": {
"nutrition": 1,
"saturation_modifier": 0.3
},
"places": "bworld:potatoes"
}
}
+17
View File
@@ -0,0 +1,17 @@
{
"format_version": 1,
"recipe": {
"type": "shaped",
"pattern": [
"P P",
" P "
],
"key": {
"P": "bworld:planks"
},
"result": {
"id": "bworld:bowl",
"count": 4
}
}
}
+221 -24
View File
@@ -1,13 +1,12 @@
// the base game's block and item behavior, written against the same api as any other mod
import type { BlockRef, Container, ScreenHandle, ServerContext } from "bworld/server";
import type { BlockRef, Container, Player, ScreenHandle, ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
register_hoeable(ctx);
register_storage(ctx);
register_furnace(ctx);
register_smithing_table(ctx);
register_crop(ctx);
register_watering_can(ctx);
register_farming(ctx);
}
// right clicking with a tool turns the block into another, like a hoe on grass
@@ -192,6 +191,12 @@ function register_furnace(ctx: ServerContext) {
}
}
// burning, so it heats what's on top, like farmer's delight's cooking pot
const lit = data.fuel > 0 ? 1 : 0;
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);
}
for (const screen of viewers.get(key(block)) ?? []) show(screen, data);
},
});
@@ -272,33 +277,225 @@ function register_smithing_table(ctx: ServerContext) {
});
}
// grows one stage each time it's right clicked with the fertilizer, like bone meal on wheat
function register_crop(ctx: ServerContext) {
ctx.components.register_block<{ fertilizer: string; max_age: number }>("bworld:crop", {
on_interact(block, params, player) {
const held = player.held_item;
if (held?.id !== params.fertilizer) {
return false;
}
const age = ctx.world.get_state(block.x, block.y, block.z, "age") ?? 0;
// fully grown, keep the fertilizer
if (age >= params.max_age) {
return false;
}
ctx.world.set_state(block.x, block.y, block.z, "age", age + 1);
held.count -= 1;
return true;
},
});
}
// farming: java's crop rules on stardew valley's clock. every morning at 06:00 a crop grows one stage if its farmland
// was watered the day before, then all farmland dries. crops only stand on farmland (their place_on), and pop off when
// it's dug up
const FARMLAND = "bworld:hoed_dirt";
const WATERING_CAN = "bworld:watering_can";
interface WateringCanData {
water: number;
max_water: number;
}
function register_watering_can(ctx: ServerContext) {
ctx.components.register_item<{ max_water: number }>("bworld:watering_can", {
// items as they appear in crop params: one id, or several
type Items = string | string[];
// what a crop drops when broken, like the loot tables of minecraft's and farmer's delight's crops
interface CropDrops {
// before it's fully grown, like wheat's seeds
young?: Items;
// fully grown, like wheat's wheat
mature?: Items;
// fully grown, 1 to 4 of this, like the seeds from wheat (minecraft's loot tables: 1 plus 3 tries at 57%)
bonus?: string;
}
// a crop, like a fabric CropBlock: its "age" state is its stage, and it grows one day every morning its farmland was
// watered the day before. see "Crops" in MODS.md
interface CropParams {
// watered mornings from planting to fully grown
days: number;
// how many stages it shows, ages 0 to stages - 1. its "age" state must fit them
stages: number;
drops?: CropDrops;
// grows back after it's harvested by right clicking, like tomatoes
regrow_days?: number;
harvest?: { item: string; count: [number, number] };
// grows it a day right away, like bone meal
fertilizer?: string;
// "farmland" (the default) needs watered farmland under it, "always" grows every morning, like rice in water
water?: "farmland" | "always";
// the last stages grow a second block on top, like rice's panicles. the crop stays at supporting_age meanwhile
upper?: { block: string; stages: number; supporting_age: number };
// what the spot becomes when it's broken, like water where rice was
leaves?: string;
}
// the top of a two block crop. it grows with the crop under it, and breaking it breaks the whole plant
interface CropTopParams {
stages: number;
drops?: CropDrops;
}
function register_farming(ctx: ServerContext) {
const is_watered = (x: number, y: number, z: number) =>
ctx.world.get_block(x, y, z) === FARMLAND && ctx.world.get_state(x, y, z, "watered") === 1;
// with the watering can the player holds. true when the click was about watering, so nothing gets placed
const water = (x: number, y: number, z: number, player: Player) => {
const can = player.held_item;
if (can?.id !== WATERING_CAN || ctx.world.get_block(x, y, z) !== FARMLAND) {
return false;
}
const data = can.data as WateringCanData;
if (is_watered(x, y, z)) {
return true;
}
if (data.water <= 0) {
player.send_message("The watering can is empty, fill it at some water");
return true;
}
can.data = { ...data, water: data.water - 1 };
ctx.world.set_state(x, y, z, "watered", 1);
return true;
};
ctx.components.register_block("bworld:farmland", {
// block data so on_new_day runs for it
on_create(block) {
block.data = {};
},
on_interact(block, _params, player) {
block.data ??= {};
return water(block.x, block.y, block.z, player);
},
on_new_day(block) {
if (!is_watered(block.x, block.y, block.z)) return;
// after every crop's on_new_day this morning, which look at it
ctx.system.run_timeout(() => {
if (ctx.world.get_block(block.x, block.y, block.z) === FARMLAND) {
ctx.world.set_state(block.x, block.y, block.z, "watered", 0);
}
}, 0);
},
});
const list = (items: Items | undefined) => items === undefined ? [] : typeof items === "string" ? [items] : items;
const drop = (x: number, y: number, z: number, drops: CropDrops | undefined, mature: boolean) => {
for (const id of list(mature ? drops?.mature : drops?.young)) ctx.world.drop_item(x, y, z, { id, count: 1 });
if (mature && drops?.bonus) {
let count = 1;
for (let i = 0; i < 3; i++) if (Math.random() < 0.5714) count++;
ctx.world.drop_item(x, y, z, { id: drops.bonus, count });
}
};
// the stage for how many days it has grown: evenly spread, fully grown on the last day
const stage_for = (params: CropParams, days: number) => {
const stages = params.stages + (params.upper?.stages ?? 0);
return Math.min(stages - 1, Math.floor(days * (stages - 1) / params.days));
};
// days grown, kept in the block's data. crops from before this start at the first day of the stage they show
const days_of = (block: BlockRef, params: CropParams) => {
if (typeof block.data?.days === "number") return block.data.days as number;
const age = ctx.world.get_state(block.x, block.y, block.z, "age") ?? 0;
let days = 0;
while (days < params.days && stage_for(params, days) < age) days++;
return days;
};
// shows the stage for days, growing or taking away the top block for two block crops
const set_days = (block: BlockRef, params: CropParams, days: number) => {
block.data = { ...block.data, days };
const stage = stage_for(params, days);
const upper = params.upper;
const above = ctx.world.get_block(block.x, block.y + 1, block.z);
if (!upper || stage < params.stages) {
ctx.world.set_state(block.x, block.y, block.z, "age", stage);
if (upper && above === upper.block) ctx.world.set_block(block.x, block.y + 1, block.z, "bworld:air");
return;
}
// the top needs room, like farmer's delight's rice
if (above !== upper.block && above !== "bworld:air") {
ctx.world.set_state(block.x, block.y, block.z, "age", params.stages - 1);
return;
}
ctx.world.set_state(block.x, block.y, block.z, "age", upper.supporting_age);
if (above !== upper.block) ctx.world.set_block(block.x, block.y + 1, block.z, upper.block);
ctx.world.set_state(block.x, block.y + 1, block.z, "age", stage - params.stages);
};
const is_grown = (block: BlockRef, params: CropParams) => days_of(block, params) >= params.days;
ctx.components.register_block<CropParams>("bworld:crop", {
// block data so on_new_day runs for it. placed at a later stage (by a script), it has grown that long
on_create(block, params) {
block.data = {};
block.data = { days: days_of(block, params) };
},
on_new_day(block, params) {
const days = days_of(block, params);
if (days >= params.days) return;
const watered = params.water === "always" || is_watered(block.x, block.y - 1, block.z);
if (watered) set_days(block, params, days + 1);
},
on_interact(block, params, player) {
const held = player.held_item;
// watering a crop waters the farmland under it
if (held?.id === WATERING_CAN) {
block.data ??= { days: days_of(block, params) };
return water(block.x, block.y - 1, block.z, player);
}
const days = days_of(block, params);
if (params.fertilizer && held?.id === params.fertilizer) {
// fully grown, keep the fertilizer
if (days >= params.days) return false;
set_days(block, params, days + 1);
held.count -= 1;
return true;
}
// regrowing crops are picked by hand and grow back, like farmer's delight's tomatoes
if (params.regrow_days && params.harvest && days >= params.days) {
const [min, max] = params.harvest.count;
const count = min + Math.floor(Math.random() * (max - min + 1));
ctx.world.drop_item(block.x, block.y, block.z, { id: params.harvest.item, count });
set_days(block, params, Math.max(0, params.days - params.regrow_days));
return true;
}
return false;
},
on_break(block, params) {
drop(block.x, block.y, block.z, params.drops, is_grown(block, params));
if (params.leaves) {
const { x, y, z } = block;
const leaves = params.leaves;
// after it's gone, it's still there while on_break runs
ctx.system.run_timeout(() => {
if (ctx.world.get_block(x, y, z) === "bworld:air") ctx.world.set_block(x, y, z, leaves);
}, 0);
}
},
});
ctx.components.register_block<CropTopParams>("bworld:crop_top", {
on_break(block, params) {
const age = ctx.world.get_state(block.x, block.y, block.z, "age") ?? 0;
drop(block.x, block.y, block.z, params.drops, age >= params.stages - 1);
// the plant under it goes too, once this is gone
const { x, y, z } = block;
const lower = ctx.world.get_block(x, y - 1, z);
ctx.system.run_timeout(() => {
if (lower && ctx.world.get_block(x, y - 1, z) === lower) ctx.world.break_block(x, y - 1, z);
}, 0);
},
});
// right clicking water with the watering can fills it
ctx.components.register_block("bworld:water_source", {
on_interact(_block, _params, player) {
const can = player.held_item;
if (can?.id !== WATERING_CAN) return false;
const data = can.data as WateringCanData;
can.data = { ...data, water: data.max_water };
return true;
},
});
ctx.components.register_item<{ max_water: number }>(WATERING_CAN, {
on_create(item, params) {
item.data = { water: 0, max_water: params.max_water } satisfies WateringCanData;
},
Binary file not shown.

After

Width:  |  Height:  |  Size: 178 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 212 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 150 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 B

+28
View File
@@ -0,0 +1,28 @@
# Farmer's Delight
A bworld port of [Farmer's Delight](https://github.com/vectorwing/FarmersDelight) by vectorwing. Its textures and game
design come from the original, version 1.3.4 for NeoForge 1.21.1, under the MIT license:
```
MIT License
Copyright (c) 2020 vectorwing
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+80
View File
@@ -0,0 +1,80 @@
{
"format_version": 1,
"block": {
"id": "farmersdelight:cabbages",
"textures": {
"cross": "farmersdelight:cabbages_stage0"
},
"model": "engine:cross",
"variants": {
"age=0": {
"textures": {
"cross": "farmersdelight:cabbages_stage0"
}
},
"age=1": {
"textures": {
"cross": "farmersdelight:cabbages_stage1"
}
},
"age=2": {
"textures": {
"cross": "farmersdelight:cabbages_stage2"
}
},
"age=3": {
"textures": {
"cross": "farmersdelight:cabbages_stage3"
}
},
"age=4": {
"textures": {
"cross": "farmersdelight:cabbages_stage4"
}
},
"age=5": {
"textures": {
"cross": "farmersdelight:cabbages_stage5"
}
},
"age=6": {
"textures": {
"cross": "farmersdelight:cabbages_stage6"
}
},
"age=7": {
"textures": {
"cross": "farmersdelight:cabbages_stage7"
}
}
},
"render_layer": "cutout",
"collision": false,
"mining": {
"toughness": 0
},
"item": false,
"place_on": [
"bworld:hoed_dirt"
],
"states": [
{
"name": "age",
"bits": 3,
"default": 0
}
],
"components": {
"bworld:crop": {
"days": 12,
"stages": 8,
"fertilizer": "bworld:bone_meal",
"drops": {
"young": "farmersdelight:cabbage_seeds",
"mature": "farmersdelight:cabbage",
"bonus": "farmersdelight:cabbage_seeds"
}
}
}
}
}
@@ -0,0 +1,24 @@
{
"format_version": 1,
"block": {
"id": "farmersdelight:cooking_pot",
"model": "farmersdelight:cooking_pot",
"textures": {
"side": "farmersdelight:cooking_pot_side",
"top": "farmersdelight:cooking_pot_top",
"bottom": "farmersdelight:cooking_pot_bottom",
"parts": "farmersdelight:cooking_pot_parts"
},
"render_layer": "cutout",
"mining": {
"toughness": 2,
"tool": "pickaxe"
},
"drops": "farmersdelight:cooking_pot",
"item": false,
"interactive": true,
"components": {
"farmersdelight:cooking_pot": {}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
{
"format_version": 1,
"block": {
"id": "farmersdelight:onions",
"textures": {
"crop": "farmersdelight:onions_stage0"
},
"model": "engine:crop",
"variants": {
"age=0": {
"textures": {
"crop": "farmersdelight:onions_stage0"
}
},
"age=1": {
"textures": {
"crop": "farmersdelight:onions_stage1"
}
},
"age=2": {
"textures": {
"crop": "farmersdelight:onions_stage2"
}
},
"age=3": {
"textures": {
"crop": "farmersdelight:onions_stage3"
}
}
},
"render_layer": "cutout",
"collision": false,
"mining": {
"toughness": 0
},
"item": false,
"place_on": [
"bworld:hoed_dirt"
],
"states": [
{
"name": "age",
"bits": 2,
"default": 0
}
],
"components": {
"bworld:crop": {
"days": 4,
"stages": 4,
"fertilizer": "bworld:bone_meal",
"drops": {
"young": "farmersdelight:onion",
"mature": "farmersdelight:onion",
"bonus": "farmersdelight:onion"
}
}
}
}
}
+76
View File
@@ -0,0 +1,76 @@
{
"format_version": 1,
"block": {
"id": "farmersdelight:rice",
"textures": {
"cross": "farmersdelight:rice_stage0"
},
"model": "engine:cross",
"variants": {
"age=0": {
"textures": {
"cross": "farmersdelight:rice_stage0"
}
},
"age=1": {
"textures": {
"cross": "farmersdelight:rice_stage1"
}
},
"age=2": {
"textures": {
"cross": "farmersdelight:rice_stage2"
}
},
"age=3": {
"textures": {
"cross": "farmersdelight:rice_stage3"
}
},
"age=4": {
"textures": {
"cross": "farmersdelight:rice_supporting"
}
}
},
"render_layer": "cutout",
"collision": false,
"mining": {
"toughness": 0
},
"item": false,
"place_on": [
"bworld:dirt",
"bworld:grass",
"bworld:hoed_dirt"
],
"states": [
{
"name": "age",
"bits": 3,
"default": 0
}
],
"place_in": [
"bworld:water"
],
"components": {
"bworld:crop": {
"days": 6,
"stages": 4,
"fertilizer": "bworld:bone_meal",
"water": "always",
"upper": {
"block": "farmersdelight:rice_panicles",
"stages": 4,
"supporting_age": 4
},
"leaves": "bworld:water",
"drops": {
"young": "farmersdelight:rice",
"mature": "farmersdelight:rice"
}
}
}
}
}
@@ -0,0 +1,56 @@
{
"format_version": 1,
"block": {
"id": "farmersdelight:rice_panicles",
"textures": {
"cross": "farmersdelight:rice_panicles_stage0"
},
"model": "engine:cross",
"variants": {
"age=0": {
"textures": {
"cross": "farmersdelight:rice_panicles_stage0"
}
},
"age=1": {
"textures": {
"cross": "farmersdelight:rice_panicles_stage1"
}
},
"age=2": {
"textures": {
"cross": "farmersdelight:rice_panicles_stage2"
}
},
"age=3": {
"textures": {
"cross": "farmersdelight:rice_panicles_stage3"
}
}
},
"render_layer": "cutout",
"collision": false,
"mining": {
"toughness": 0
},
"item": false,
"place_on": [
"farmersdelight:rice"
],
"states": [
{
"name": "age",
"bits": 2,
"default": 0
}
],
"components": {
"bworld:crop_top": {
"stages": 4,
"drops": {
"mature": "farmersdelight:rice_panicle"
}
}
}
}
}
+38
View File
@@ -0,0 +1,38 @@
{
"format_version": 1,
"block": {
"id": "farmersdelight:stove",
"textures": {
"top": "farmersdelight:stove_top",
"bottom": "farmersdelight:stove_bottom",
"front": "farmersdelight:stove_front",
"side": "farmersdelight:stove_side"
},
"variants": {
"lit=1": {
"textures": {
"top": "farmersdelight:stove_top_on",
"bottom": "farmersdelight:stove_bottom",
"front": "farmersdelight:stove_front_on",
"side": "farmersdelight:stove_side"
}
}
},
"mining": {
"toughness": 2,
"tool": "pickaxe",
"requires_tool": true
},
"drops": "farmersdelight:stove",
"states": [
{
"name": "lit",
"bits": 1,
"default": 1
}
],
"components": {
"farmersdelight:stove": {}
}
}
}
+90
View File
@@ -0,0 +1,90 @@
{
"format_version": 1,
"block": {
"id": "farmersdelight:tomatoes",
"textures": {
"cross": "farmersdelight:budding_tomatoes_stage0"
},
"model": "engine:cross",
"variants": {
"age=0": {
"textures": {
"cross": "farmersdelight:budding_tomatoes_stage0"
}
},
"age=1": {
"textures": {
"cross": "farmersdelight:budding_tomatoes_stage1"
}
},
"age=2": {
"textures": {
"cross": "farmersdelight:budding_tomatoes_stage2"
}
},
"age=3": {
"textures": {
"cross": "farmersdelight:budding_tomatoes_stage3"
}
},
"age=4": {
"textures": {
"cross": "farmersdelight:tomatoes_stage0"
}
},
"age=5": {
"textures": {
"cross": "farmersdelight:tomatoes_stage1"
}
},
"age=6": {
"textures": {
"cross": "farmersdelight:tomatoes_stage2"
}
},
"age=7": {
"textures": {
"cross": "farmersdelight:tomatoes_stage3"
}
}
},
"render_layer": "cutout",
"collision": false,
"mining": {
"toughness": 0
},
"item": false,
"place_on": [
"bworld:hoed_dirt"
],
"states": [
{
"name": "age",
"bits": 3,
"default": 0
}
],
"components": {
"bworld:crop": {
"days": 11,
"stages": 8,
"fertilizer": "bworld:bone_meal",
"regrow_days": 4,
"harvest": {
"item": "farmersdelight:tomato",
"count": [
1,
2
]
},
"drops": {
"young": "farmersdelight:tomato_seeds",
"mature": [
"farmersdelight:tomato",
"farmersdelight:tomato_seeds"
]
}
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:cabbage",
"texture": "farmersdelight:cabbage",
"food": {
"nutrition": 2,
"saturation_modifier": 0.4
}
}
}
@@ -0,0 +1,11 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:cabbage_rolls",
"texture": "farmersdelight:cabbage_rolls",
"food": {
"nutrition": 5,
"saturation_modifier": 0.5
}
}
}
@@ -0,0 +1,8 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:cabbage_seeds",
"texture": "farmersdelight:cabbage_seeds",
"places": "farmersdelight:cabbages"
}
}
@@ -0,0 +1,13 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:cooked_rice",
"texture": "farmersdelight:cooked_rice",
"max_stack": 16,
"food": {
"nutrition": 6,
"saturation_modifier": 0.4,
"returns": "bworld:bowl"
}
}
}
@@ -0,0 +1,9 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:cooking_pot",
"texture": "farmersdelight:cooking_pot",
"places": "farmersdelight:cooking_pot",
"max_stack": 1
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:onion",
"texture": "farmersdelight:onion",
"places": "farmersdelight:onions",
"food": {
"nutrition": 2,
"saturation_modifier": 0.4
}
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:rice",
"texture": "farmersdelight:rice",
"places": "farmersdelight:rice"
}
}
@@ -0,0 +1,7 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:rice_panicle",
"texture": "farmersdelight:rice_panicle"
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:tomato",
"texture": "farmersdelight:tomato",
"food": {
"nutrition": 1,
"saturation_modifier": 0.3
}
}
}
@@ -0,0 +1,12 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:tomato_sauce",
"texture": "farmersdelight:tomato_sauce",
"food": {
"nutrition": 4,
"saturation_modifier": 0.4,
"returns": "bworld:bowl"
}
}
}
@@ -0,0 +1,8 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:tomato_seeds",
"texture": "farmersdelight:tomato_seeds",
"places": "farmersdelight:tomatoes"
}
}
+22
View File
@@ -0,0 +1,22 @@
{
"format_version": 1,
"id": "farmersdelight",
"name": "Farmer's Delight",
"description": "A port of vectorwing's Farmer's Delight: its crops and the cooking pot.",
"version": "0.1.0",
"authors": [
"vectorwing (original)",
"paula (port)"
],
"game_version": ">=0.1.0",
"dependencies": [
{
"id": "bworld",
"version": "*"
}
],
"credits": "CREDITS.md",
"scripts": {
"server": "scripts/server.ts"
}
}
+134
View File
@@ -0,0 +1,134 @@
{
"format_version": 1,
"model": {
"id": "farmersdelight:cooking_pot",
"textures": {
"side": "farmersdelight:cooking_pot_side",
"top": "farmersdelight:cooking_pot_top",
"bottom": "farmersdelight:cooking_pot_bottom",
"parts": "farmersdelight:cooking_pot_parts"
},
"elements": [
{
"from": [2, 0, 2],
"to": [14, 10, 14],
"faces": {
"north": {
"texture": "#side",
"uv": [2, 6, 14, 16]
},
"east": {
"texture": "#side",
"uv": [2, 6, 14, 16]
},
"south": {
"texture": "#side",
"uv": [2, 6, 14, 16]
},
"west": {
"texture": "#side",
"uv": [2, 6, 14, 16]
},
"top": {
"texture": "#top",
"uv": [2, 2, 14, 14]
},
"bottom": {
"texture": "#bottom",
"uv": [2, 2, 14, 14],
"cullface": "bottom"
}
}
},
{
"from": [7, 3, 7],
"to": [9, 15, 9],
"rotation": {
"angle": -22.5,
"axis": "z",
"origin": [8, 3, 8]
},
"faces": {
"north": {
"texture": "#parts",
"uv": [2, 2, 0, 14]
},
"east": {
"texture": "#parts",
"uv": [0, 2, 2, 14]
},
"south": {
"texture": "#parts",
"uv": [2, 2, 0, 14]
},
"west": {
"texture": "#parts",
"uv": [0, 2, 2, 14]
},
"top": {
"texture": "#parts",
"uv": [0, 0, 2, 2]
}
}
},
{
"from": [14, 7, 5],
"to": [16, 9, 11],
"faces": {
"north": {
"texture": "#parts",
"uv": [10, 0, 12, 2]
},
"east": {
"texture": "#parts",
"uv": [4, 2, 10, 4],
"cullface": "east"
},
"south": {
"texture": "#parts",
"uv": [2, 0, 4, 2]
},
"top": {
"texture": "#parts",
"uv": [4, 0, 10, 2],
"rotation": 90
},
"bottom": {
"texture": "#parts",
"uv": [4, 2, 10, 4],
"rotation": 90
}
}
},
{
"from": [0, 7, 5],
"to": [2, 9, 11],
"faces": {
"north": {
"texture": "#parts",
"uv": [2, 0, 4, 2]
},
"south": {
"texture": "#parts",
"uv": [10, 0, 12, 2]
},
"west": {
"texture": "#parts",
"uv": [4, 2, 10, 4],
"cullface": "west"
},
"top": {
"texture": "#parts",
"uv": [4, 0, 10, 2],
"rotation": 270
},
"bottom": {
"texture": "#parts",
"uv": [4, 2, 10, 4],
"rotation": 270
}
}
}
]
}
}
@@ -0,0 +1,12 @@
{
"format_version": 1,
"recipe": {
"type": "farmersdelight:cooking",
"ingredients": [
"farmersdelight:cabbage",
["bworld:carrot", "bworld:potato", "farmersdelight:onion", "farmersdelight:tomato"]
],
"result": { "id": "farmersdelight:cabbage_rolls", "count": 1 },
"cook_time": 100
}
}
@@ -0,0 +1,10 @@
{
"format_version": 1,
"recipe": {
"type": "farmersdelight:cooking",
"ingredients": ["farmersdelight:rice"],
"result": { "id": "farmersdelight:cooked_rice", "count": 1 },
"container": "bworld:bowl",
"cook_time": 100
}
}
@@ -0,0 +1,10 @@
{
"format_version": 1,
"recipe": {
"type": "farmersdelight:cooking",
"ingredients": ["farmersdelight:tomato", "farmersdelight:tomato"],
"result": { "id": "farmersdelight:tomato_sauce", "count": 1 },
"container": "bworld:bowl",
"cook_time": 100
}
}
@@ -0,0 +1,9 @@
{
"format_version": 1,
"recipe": {
"type": "shaped",
"pattern": ["iSi", "i i", "iii"],
"key": { "i": "bworld:iron_ingot", "S": "bworld:stick" },
"result": { "id": "farmersdelight:cooking_pot", "count": 1 }
}
}
@@ -0,0 +1,9 @@
{
"format_version": 1,
"recipe": {
"type": "shaped",
"pattern": ["iii", "B B", "BCB"],
"key": { "i": "bworld:iron_ingot", "B": "bworld:stone", "C": "bworld:coal" },
"result": { "id": "farmersdelight:stove", "count": 1 }
}
}
+314
View File
@@ -0,0 +1,314 @@
// farmer's delight's kitchen. the stove is a heat source, like its StoveBlock. the cooking pot, like its
// 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
import type { BlockRef, Container, ScreenHandle, ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
register_stove(ctx);
register_cooking_pot(ctx);
}
// stove
// what lights an unlit stove, used up. the java mod's are flint and steel and fire charges, which bworld doesn't have
const STOVE_FUEL = "bworld:coal";
// what puts it out: any shovel, like the java mod (a water bucket too, once there are buckets)
const STOVE_EXTINGUISHER_TOOL = "shovel";
// standing on a lit stove hurts, like a magma block: 1 health every 10 ticks
const STOVE_BURN_DAMAGE = 1;
const STOVE_BURN_TICKS = 10;
function register_stove(ctx: ServerContext) {
const lit = (block: BlockRef) => ctx.world.get_state(block.x, block.y, block.z, "lit") === 1;
const set_lit = (block: BlockRef, value: boolean) =>
ctx.world.set_state(block.x, block.y, block.z, "lit", value ? 1 : 0);
ctx.components.register_block("farmersdelight:stove", {
// placed lit, like the java mod. block data so it ticks, to burn whoever stands on it
on_create(block) {
block.data ??= {};
},
on_interact(block, _params, player) {
const held = player.inventory.get(player.selected_slot);
if (!held) return false;
if (lit(block)) {
if (ctx.items.tool(held.id) !== STOVE_EXTINGUISHER_TOOL) return false;
set_lit(block, false);
return true;
}
if (held.id !== STOVE_FUEL) return false;
held.count -= 1;
set_lit(block, true);
return true;
},
on_tick(block) {
if (ctx.system.current_tick % STOVE_BURN_TICKS !== 0 || !lit(block)) return;
for (const player of ctx.players.all()) {
const { x, y, z } = player.position;
if (Math.floor(x) === block.x && Math.floor(z) === block.z && Math.abs(y - (block.y + 1)) < 0.01) {
player.damage(STOVE_BURN_DAMAGE, "hot_floor");
}
}
},
});
}
// cooking pot
// slots 0-5 are the ingredients, 6 the meal waiting to be served, 7 containers for it, 8 the served meal
const INGREDIENT_SLOTS = 6;
const MEAL_SLOT = 6;
const CONTAINER_SLOT = 7;
const OUTPUT_SLOT = 8;
const POT_SIZE = 9;
// ticks, for recipes that don't say
const DEFAULT_COOK_TIME = 200;
// what's under the pot that heats it, and the state that has to be 1 for it to, like minecraft's heat_sources tag
const HEAT_SOURCES: Record<string, string | undefined> = {
"bworld:furnace": "lit",
"farmersdelight:stove": "lit",
};
// a farmersdelight:cooking recipe: the ingredients in any slots, each an item id or a list of ids any of which will do
interface CookingRecipe {
ingredients: (string | string[])[];
result: { id: string; count: number };
// what the meal is served in, like a bowl. without it the meal comes out as soon as it's cooked
container?: string;
cook_time: number;
}
interface PotData {
container: string;
// ticks, counting up to cook_time_total
cook_time: number;
cook_time_total: number;
// what the meal in the meal slot is served in, "" for nothing
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",
},
];
// checked when the server starts, so a broken recipe is a load error naming it
function load_recipes(ctx: ServerContext): CookingRecipe[] {
return ctx.recipes.list("farmersdelight:cooking").map((json, i) => {
const where = `farmersdelight:cooking recipe ${i + 1} (${json.result?.id ?? "no result"})`;
const item = (id: unknown) => {
if (typeof id !== "string" || !ctx.items.exists(id)) throw new Error(`${where}: there's no item ${id}`);
return id;
};
const ingredients = json.ingredients;
if (!Array.isArray(ingredients) || ingredients.length < 1 || ingredients.length > INGREDIENT_SLOTS) {
throw new Error(`${where}: ingredients must be 1 to ${INGREDIENT_SLOTS} items`);
}
for (const ingredient of ingredients) {
if (Array.isArray(ingredient)) {
if (ingredient.length === 0) throw new Error(`${where}: an ingredient's list of items is empty`);
ingredient.forEach(item);
} else {
item(ingredient);
}
}
item(json.result?.id);
if (!Number.isInteger(json.result.count) || json.result.count < 1) {
throw new Error(`${where}: result.count must be a positive whole number`);
}
if (json.container !== undefined) item(json.container);
const cook_time = json.cook_time ?? DEFAULT_COOK_TIME;
if (!Number.isInteger(cook_time) || cook_time < 1) {
throw new Error(`${where}: cook_time must be positive ticks`);
}
return { ingredients, result: json.result, container: json.container, cook_time };
});
}
// the recipe whose ingredients are exactly what's in the ingredient slots, one item from each, in any order
function find_recipe(recipes: CookingRecipe[], container: Container): CookingRecipe | undefined {
const items: string[] = [];
for (let slot = 0; slot < INGREDIENT_SLOTS; slot++) {
const item = container.get(slot);
if (item) items.push(item.id);
}
if (items.length === 0) return undefined;
return recipes.find((recipe) => recipe.ingredients.length === items.length && matches(recipe.ingredients, items));
}
// pairs every ingredient with a different item, trying each way round, like a shapeless recipe
function matches(ingredients: (string | string[])[], items: string[], used = new Set<number>()): boolean {
if (ingredients.length === 0) return true;
const [first, ...rest] = ingredients;
const fits = (id: string) => Array.isArray(first) ? first.includes(id) : first === id;
for (let i = 0; i < items.length; i++) {
if (used.has(i) || !fits(items[i])) continue;
used.add(i);
if (matches(rest, items, used)) return true;
used.delete(i);
}
return false;
}
function register_cooking_pot(ctx: ServerContext) {
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 existing = block.data?.container && ctx.containers.get(block.data.container);
const container = existing || ctx.containers.create(POT_SIZE);
block.data = { cook_time: 0, cook_time_total: 0, meal_container: "", ...block.data, container: container.id };
return block.data;
};
const is_heated = (block: BlockRef) => {
const below = ctx.world.get_block(block.x, block.y - 1, block.z);
if (!below || !(below in HEAT_SOURCES)) return false;
const state = HEAT_SOURCES[below];
return state === undefined || ctx.world.get_state(block.x, block.y - 1, block.z, state) === 1;
};
const show = (screen: ScreenHandle, data: PotData, heated: boolean) => {
screen.set_property("progress", data.cook_time);
screen.set_property("progress_max", data.cook_time_total);
screen.set_property("heat", heated ? 1 : 0);
screen.set_property("heat_max", 1);
};
// there's room in the meal slot for what it makes
const can_cook = (container: Container, recipe: CookingRecipe) => {
const meal = container.get(MEAL_SLOT);
if (!meal) return true;
return meal.id === recipe.result.id && meal.count + recipe.result.count <= ctx.items.max_stack(meal.id);
};
const cook = (data: PotData, container: Container, recipe: CookingRecipe) => {
const meal = container.get(MEAL_SLOT);
if (meal) {
meal.count += recipe.result.count;
} else {
container.set(MEAL_SLOT, { ...recipe.result });
}
data.meal_container = recipe.container ?? "";
for (let slot = 0; slot < INGREDIENT_SLOTS; slot++) {
const item = container.get(slot);
if (item) item.count -= 1;
}
};
// the meal goes to the output, into its containers when it needs them, as much as fits
const serve = (data: PotData, container: Container) => {
const meal = container.get(MEAL_SLOT);
if (!meal) {
data.meal_container = "";
return;
}
const output = container.get(OUTPUT_SLOT);
if (output && output.id !== meal.id) return;
const room = ctx.items.max_stack(meal.id) - (output?.count ?? 0);
let count = Math.min(meal.count, room);
const bowls = container.get(CONTAINER_SLOT);
if (data.meal_container) {
count = bowls?.id === data.meal_container ? Math.min(count, bowls.count) : 0;
}
if (count <= 0) return;
if (data.meal_container) bowls!.count -= count;
if (output) {
output.count += count;
} else {
container.set(OUTPUT_SLOT, { id: meal.id, count });
}
meal.count -= count;
};
ctx.components.register_block("farmersdelight:cooking_pot", {
on_create(block) {
pot_data(block);
},
on_interact(block, _params, player) {
const data = pot_data(block);
const container = ctx.containers.get(data.container)!;
// holding what the meal is served in serves one straight into the hand, like the java mod
const meal = container.get(MEAL_SLOT);
const held = player.inventory.get(player.selected_slot);
if (meal && data.meal_container && held?.id === data.meal_container) {
held.count -= 1;
meal.count -= 1;
player.give_item(meal.id, 1);
return true;
}
const screen = ctx.ui.open_container(player, {
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;
},
on_break(block) {
const container = block.data?.container && ctx.containers.get(block.data.container);
if (!container) return;
for (let slot = 0; slot < container.size; slot++) {
const item = container.get(slot);
if (item) ctx.world.drop_item(block.x, block.y, block.z, item);
}
ctx.containers.delete(container.id);
},
on_tick(block) {
const data = pot_data(block);
const container = ctx.containers.get(data.container)!;
const heated = is_heated(block);
const recipe = heated ? find_recipe(recipes, container) : undefined;
if (recipe && can_cook(container, recipe)) {
data.cook_time_total = recipe.cook_time;
data.cook_time += 1;
if (data.cook_time >= recipe.cook_time) {
data.cook_time = 0;
cook(data, container, recipe);
}
} else {
// cools off, losing progress slowly
data.cook_time = Math.max(0, data.cook_time - 2);
}
serve(data, container);
for (const screen of viewers.get(key(block)) ?? []) show(screen, data, heated);
},
});
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 151 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 290 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 342 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 417 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 418 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 297 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 318 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 399 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 361 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 427 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 223 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 276 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 261 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 383 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 235 B

Some files were not shown because too many files have changed in this diff Show More