Proper cutting board

This commit is contained in:
2026-09-29 00:04:56 -03:00
parent a51adba46f
commit 445148e812
26 changed files with 549 additions and 16 deletions
+21
View File
@@ -19,6 +19,7 @@ import { crosses_planes } from "../workers/translucent_sort.ts";
import { Camera } from "../camera.ts";
import type { Entity } from "../entity/entity.ts";
import type { ModelJson } from "$/common/block_models.ts";
import type { ItemStack } from "$/common/inventory.ts";
export interface Block {
id: string;
@@ -106,6 +107,8 @@ export class ClientLevel {
// every entity this client knows about, the local player included, by id
entities = new Map<string, Entity>();
// what blocks with item_display show, by chunk_key then position_key "x,y,z"
block_items = new Map<number, Map<string, { x: number; y: number; z: number; item: ItemStack }>>();
// server_blocks is the server's block id for each of its numeric ids
constructor(server_blocks: string[], view_distance: number) {
@@ -390,6 +393,24 @@ export class ClientLevel {
}
this.delete_chunk_mesh(chunk);
this.chunks.delete(key);
this.block_items.delete(key);
}
// see set_block_item in common/protocol.ts
set_block_item(x: number, y: number, z: number, item: ItemStack | undefined) {
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
let items = this.block_items.get(key);
if (item) {
if (!this.chunks.has(key)) return;
if (!items) {
items = new Map();
this.block_items.set(key, items);
}
items.set(`${x},${y},${z}`, { x, y, z, item });
} else {
items?.delete(`${x},${y},${z}`);
if (items?.size === 0) this.block_items.delete(key);
}
}
// a chunk is only meshed once all its neighbors exist, otherwise its border faces and light would be
+8
View File
@@ -154,6 +154,14 @@ export class ClientPacketListener {
case "set_block":
level.apply_change(message.x, message.y, message.z, message.id, message.state);
break;
case "set_block_item":
level.set_block_item(
message.x,
message.y,
message.z,
message.item ? ItemStack.from_data(message.item) : undefined,
);
break;
case "chunk_batch_start":
this.#chunk_batch.on_batch_start();
break;
+92 -2
View File
@@ -5,9 +5,11 @@ 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, cube_face_tint } from "$/common/block_models.ts";
import { block_item_texture, block_variant, cube_face_texture, cube_face_tint } from "$/common/block_models.ts";
import { item_model } from "./item_model.ts";
import { item_texture } from "$/common/utils.ts";
import { get_state_value, item_texture } from "$/common/utils.ts";
import { ID_MASK, TEXTURE_SIZE } from "$/common/constants.ts";
import type { ClientLevel } from "$/client/level/client_level.ts";
// how big items on the ground are drawn, minecraft's ground transform
const BLOCK_SCALE = 0.25;
@@ -40,6 +42,13 @@ function copies(amount: number) {
return 1;
}
// items shown on blocks, like farmer's delight's CuttingBoardRenderer: items lie flat, blocks stand. the extra
// copies for bigger stacks are this far apart, and at most this far off the middle
const SHOWN_ITEM_SCALE = 0.6;
const SHOWN_BLOCK_SCALE = 0.4;
const SHOWN_COPY_GAP = 0.03;
const SHOWN_COPY_SPREAD = 0.075;
// 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];
@@ -69,6 +78,87 @@ export function render_item_entity(entity: ItemEntity, partial_tick: number) {
}
}
// every item blocks with item_display show on top of them, see BlockRegistry.item_display. the atlas has to be the
// current texture
export function render_block_items(level: ClientLevel) {
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
for (const items of level.block_items.values()) {
for (const { x, y, z, item } of items.values()) {
// gone already when this client predicted breaking it
const value = level.get_block_value(x, y, z);
const block = blocks[value & ID_MASK];
if (!block?.item_display) continue;
push_shown_item(atlas, block, value, item, x, y, z);
}
}
}
function push_shown_item(
atlas: Texture,
block: BlockRegistry,
value: number,
item: ItemStack,
x: number,
y: number,
z: number,
) {
const states: Record<string, number> = {};
for (const state of block.states ?? []) states[state.name] = get_state_value(value, block, state.name)!;
// the way the block's model is turned: towards the player who placed it, like the cutting board's facing
const turns = Math.round(block_variant(block, states).y / 90) % 4;
// to the right of whoever it faces, and away from them. unturned it faces north (-z)
let [rx, rz] = [-1, 0];
let [bx, bz] = [0, 1];
for (let t = 0; t < turns; t++) {
[rx, rz] = [-rz, rx];
[bx, bz] = [-bz, bx];
}
const is_block = item_block(item) !== undefined;
const scale = is_block ? SHOWN_BLOCK_SCALE : SHOWN_ITEM_SCALE;
const surface = y + block.item_display!.surface / TEXTURE_SIZE;
const random = seeded_random(item.type_id);
// one, then more the fuller the stack is, like the java mod
const count = item.amount > 1 ? 1 + Math.ceil((item.amount / item.max_amount) * 4) : 1;
for (let i = 0; i < count; i++) {
const ox = count > 1 ? (random() * 2 - 1) * SHOWN_COPY_SPREAD : 0;
const oz = count > 1 ? (random() * 2 - 1) * SHOWN_COPY_SPREAD : 0;
const cx = x + 0.5 + ox;
const cz = z + 0.5 + oz;
const bottom = surface + SHOWN_COPY_GAP * (i + 1);
if (is_block) {
// standing, its front towards whoever it faces
push_item(atlas, item, (lx, ly, lz) => [
cx + (rx * lx - bx * lz) * scale,
bottom + ly * scale,
cz + (rz * lx - bz * lz) * scale,
]);
} else {
// lying face up, its top away from whoever it faces so they read it the right way round
const half = scale / TEXTURE_SIZE / 2;
push_item(atlas, item, (lx, ly, lz) => [
cx + (rx * lx + bx * (ly - 0.5)) * scale,
bottom + half + lz * scale,
cz + (rz * lx + bz * (ly - 0.5)) * scale,
]);
}
}
}
// the same copies in the same places every frame, by item
function seeded_random(seed: string) {
let state = 0;
for (let i = 0; i < seed.length; i++) state = (Math.imul(state, 31) + seed.charCodeAt(i)) | 0;
return () => {
// mulberry32
state = (state + 0x6d2b79f5) | 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// 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);
+2 -1
View File
@@ -6,7 +6,7 @@ import type { MultiPlayerGameMode } from "$/client/game_mode.ts";
import type { Entity } from "$/client/entity/entity.ts";
import { RemotePlayer } from "$/client/entity/remote_player.ts";
import { ItemEntity } from "$/client/entity/item_entity.ts";
import { render_item_entity } from "./item_renderer.ts";
import { render_block_items, render_item_entity } from "./item_renderer.ts";
import { render_player } from "./player_renderer.ts";
import { render_mod_entity } from "./entity_renderer.ts";
import { RemoteEntity } from "$/client/entity/remote_entity.ts";
@@ -117,6 +117,7 @@ export class LevelRenderer {
render_mod_entity(entity, camera, partial_tick);
}
}
render_block_items(level);
flush_batch();
}
+3
View File
@@ -140,6 +140,9 @@ export interface BlockRegistry {
place_in?: string[];
// custom components from mods and their params, the server runs them
components?: Record<string, unknown>;
// draws the item a server script gives it (ServerWorld.set_block_item) on top of it, like farmer's delight's
// cutting board. surface is the height in pixels it lies on. turned with the variant's y
item_display?: { surface: number };
compiled_states?: CompiledStateDefinition[];
}
+7
View File
@@ -175,6 +175,11 @@ export interface ServerWorld {
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;
// the item a block with item_display shows on top of it, like a block entity renderer: saved with the block's data
// and synced to players. undefined shows nothing. it goes away with the block, without dropping
set_block_item(x: number, y: number, z: number, item: ItemStack | undefined): void;
// a copy
get_block_item(x: number, y: number, z: number): ItemStack | undefined;
// pops an item out of the block at x y z, like a broken block's drops
drop_item(x: number, y: number, z: number, item: ItemStack): void;
// an entity from entities/ with its feet at x y z. throws for kinds that don't exist
@@ -202,6 +207,8 @@ export interface Player {
readonly id: string;
readonly name: string;
readonly position: Readonly<Position>;
// where they look, in radians. 0 is north (-z), going up turning west
readonly yaw: number;
readonly inventory: Container; // 36 slots, hotbar is 0-8
readonly selected_slot: number;
readonly held_item: ItemStack | undefined;
+9
View File
@@ -55,6 +55,7 @@ export interface BlockJson {
place_in?: string[];
states?: BlockStateDefinition[];
components?: Record<string, unknown>;
item_display?: { surface: number };
}
export interface OreJson {
@@ -202,6 +203,7 @@ export function block_to_json(block: BlockRegistry, has_item: boolean): BlockJso
if (block.place_in) json.place_in = block.place_in;
if (block.states) json.states = block.states;
if (block.components) json.components = block.components;
if (block.item_display) json.item_display = block.item_display;
return json;
}
@@ -233,6 +235,7 @@ export function block_from_json(json: BlockJson): { block: BlockRegistry; has_it
if (json.place_in) block.place_in = json.place_in;
if (json.states) block.states = json.states;
if (json.components) block.components = json.components;
if (json.item_display) block.item_display = json.item_display;
return { block, has_item: json.item ?? true };
}
@@ -436,6 +439,12 @@ export function validate_block(json: unknown): Problems {
}
}
if (json.drops !== undefined) problems.push(...validate_id(json.drops, "drops"));
if (json.item_display !== undefined) {
const surface = is_object(json.item_display) ? json.item_display.surface : undefined;
if (typeof surface !== "number" || surface < 0 || surface > 16) {
problems.push("item_display.surface must be the height in pixels items lie on, from 0 to 16");
}
}
for (const key of ["place_on", "place_in"]) {
const list = json[key];
if (list === undefined) continue;
+3
View File
@@ -166,6 +166,9 @@ export type ServerMessage =
// to the players who have the chunk, including the one who caused it, which corrects anything their client
// predicted wrong
| { type: "set_block"; x: number; y: number; z: number; id: string; state?: number }
// the item a block shows, see BlockRegistry.item_display. to the players who have the chunk, after it and whenever
// it changes. null when it shows nothing any more
| { type: "set_block_item"; x: number; y: number; z: number; item: ItemData | null }
| { type: "chat"; from?: string; text: string }
| { type: "teleport"; x: number; y: number; z: number }
| { type: "container"; container: ContainerKey; items: (ItemData | null)[] }
+18 -1
View File
@@ -6,12 +6,29 @@
"textures": {
"main": "farmersdelight:cutting_board"
},
"variants": {
"facing=1": { "y": 90 },
"facing=2": { "y": 180 },
"facing=3": { "y": 270 }
},
"render_layer": "cutout",
"collision": false,
"mining": {
"toughness": 2,
"tool": "axe"
},
"drops": "farmersdelight:cutting_board"
"drops": "farmersdelight:cutting_board",
"interactive": true,
"item_display": { "surface": 1 },
"states": [
{
"name": "facing",
"bits": 2,
"default": 0
}
],
"components": {
"farmersdelight:cutting_board": {}
}
}
}
@@ -0,0 +1,11 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:cabbage_leaf",
"texture": "farmersdelight:cabbage_leaf",
"food": {
"nutrition": 1,
"saturation_modifier": 0.4
}
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:cod_slice",
"texture": "farmersdelight:cod_slice",
"food": {
"nutrition": 1,
"saturation_modifier": 0.1
}
}
}
@@ -0,0 +1,11 @@
{
"format_version": 1,
"item": {
"id": "farmersdelight:salmon_slice",
"texture": "farmersdelight:salmon_slice",
"food": {
"nutrition": 1,
"saturation_modifier": 0.1
}
}
}
@@ -0,0 +1,20 @@
{
"format_version": 1,
"recipe": {
"type": "shaped",
"pattern": ["SPP", "SPP"],
"key": {
"S": "bworld:stick",
"P": [
"bworld:planks",
"bworld:spruce_planks",
"bworld:birch_planks",
"bworld:jungle_planks",
"bworld:acacia_planks",
"bworld:dark_oak_planks",
"bworld:cherry_planks"
]
},
"result": { "id": "farmersdelight:cutting_board", "count": 1 }
}
}
@@ -0,0 +1,9 @@
{
"format_version": 1,
"recipe": {
"type": "farmersdelight:cutting",
"ingredients": ["farmersdelight:cabbage"],
"tool": "knife",
"result": [{ "id": "farmersdelight:cabbage_leaf", "count": 2 }]
}
}
@@ -0,0 +1,9 @@
{
"format_version": 1,
"recipe": {
"type": "farmersdelight:cutting",
"ingredients": ["bworld:cod"],
"tool": "knife",
"result": [{ "id": "farmersdelight:cod_slice", "count": 2 }, { "id": "bworld:bone_meal", "count": 1 }]
}
}
@@ -0,0 +1,9 @@
{
"format_version": 1,
"recipe": {
"type": "farmersdelight:cutting",
"ingredients": ["bworld:salmon"],
"tool": "knife",
"result": [{ "id": "farmersdelight:salmon_slice", "count": 2 }, { "id": "bworld:bone_meal", "count": 1 }]
}
}
+104 -2
View File
@@ -1,11 +1,13 @@
// 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";
// container the meal needs (a bowl), or straight out when it needs none. the cutting board, like its
// CuttingBoardBlockEntity, holds a stack of anything and cuts it one at a time with the right tool
import type { BlockRef, Container, ItemStack, ScreenHandle, ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) {
register_stove(ctx);
register_cooking_pot(ctx);
register_cutting_board(ctx);
}
// stove
@@ -312,3 +314,103 @@ function register_cooking_pot(ctx: ServerContext) {
},
});
}
// cutting board
// its facing state, the way its front points: north, east, south or west, like the java mod's HORIZONTAL_FACING
const FACINGS = 4;
// a farmersdelight:cutting recipe, like the java mod's: one ingredient (an item, or a list any of which will do), the
// tool type that cuts it, and everything one of it is cut into
interface CuttingRecipe {
ingredient: string[];
tool: string;
result: { id: string; count: number }[];
}
// checked when the server starts, like the cooking pot's
function load_cutting_recipes(ctx: ServerContext): CuttingRecipe[] {
return ctx.recipes.list("farmersdelight:cutting").map((json, i) => {
const where = `farmersdelight:cutting recipe ${i + 1} (${json.ingredients?.[0] ?? "no ingredient"})`;
const item = (id: unknown) => {
if (typeof id !== "string" || !ctx.items.exists(id)) throw new Error(`${where}: there's no item ${id}`);
return id;
};
if (!Array.isArray(json.ingredients) || json.ingredients.length !== 1) {
throw new Error(`${where}: ingredients must be one item, or one list of items any of which will do`);
}
const ingredient = [json.ingredients[0]].flat();
if (ingredient.length === 0) throw new Error(`${where}: the ingredient's list of items is empty`);
ingredient.forEach(item);
if (typeof json.tool !== "string") throw new Error(`${where}: tool must be a tool type, like "knife"`);
if (!Array.isArray(json.result) || json.result.length === 0) {
throw new Error(`${where}: result must be a list of { id, count }`);
}
for (const result of json.result) {
item(result?.id);
if (!Number.isInteger(result.count) || result.count < 1) {
throw new Error(`${where}: every result's count must be a positive whole number`);
}
}
return { ingredient, tool: json.tool, result: json.result };
});
}
// like the java mod's CuttingBoardBlock and CuttingBoardBlockEntity. what's on the board is the item it shows
// (set_block_item), so the client draws it, like its CuttingBoardRenderer
function register_cutting_board(ctx: ServerContext) {
const recipes = load_cutting_recipes(ctx);
const on_board = (block: BlockRef) => ctx.world.get_block_item(block.x, block.y, block.z);
const set_on_board = (block: BlockRef, item: ItemStack | undefined) =>
ctx.world.set_block_item(block.x, block.y, block.z, item);
// placed facing whoever placed it, like getStateForPlacement. they look along (-sin yaw, -cos yaw), so the way
// back to them is (sin yaw, cos yaw), and north (-z) is 0 going clockwise
ctx.events.after.block_place.subscribe(({ player, block }) => {
if (block.id !== "farmersdelight:cutting_board") return;
const quarter = Math.round((Math.PI - player.yaw) / (Math.PI / 2));
const facing = ((quarter % FACINGS) + FACINGS) % FACINGS;
ctx.world.set_state(block.x, block.y, block.z, "facing", facing);
});
ctx.components.register_block("farmersdelight:cutting_board", {
on_interact(block, _params, player) {
const held = player.inventory.get(player.selected_slot);
const item = on_board(block);
// an empty hand takes everything back
if (!held) {
if (!item) return false;
set_on_board(block, undefined);
player.give_item(item.id, item.count, item.data);
return true;
}
// anything goes on, as much of it as fits, like canAddItem and addItem. a knife on an empty board too
const room = !item
? ctx.items.max_stack(held.id)
: item.id === held.id && JSON.stringify(item.data) === JSON.stringify(held.data)
? ctx.items.max_stack(item.id) - item.count
: 0;
if (room > 0) {
const count = Math.min(room, held.count);
set_on_board(block, { id: held.id, count: (item?.count ?? 0) + count, data: held.data });
held.count -= count;
return true;
}
// anything else is a tool for cutting one of what's on it, like processStoredItemUsingTool
const recipe = item && recipes.find((recipe) => recipe.ingredient.includes(item.id));
if (item && recipe && ctx.items.tool(held.id) === recipe.tool) {
for (const result of recipe.result) ctx.world.drop_item(block.x, block.y, block.z, { ...result });
set_on_board(block, item.count > 1 ? { ...item, count: item.count - 1 } : undefined);
}
// like the java mod, the click is used up either way, nothing gets placed or eaten
return true;
},
on_break(block) {
const item = on_board(block);
if (item) ctx.world.drop_item(block.x, block.y, block.z, item);
},
});
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 386 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 311 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 B

+15 -6
View File
@@ -23,6 +23,7 @@ const CATALYSTS: Record<string, string> = {
fuel: "bworld:furnace",
smithing: "bworld:smithing_table",
"farmersdelight:cooking": "farmersdelight:cooking_pot",
"farmersdelight:cutting": "farmersdelight:cutting_board",
};
const CATEGORY_NAMES: Record<string, string> = {
shaped: "Crafting",
@@ -255,7 +256,7 @@ class RecipeViewer {
break;
default: {
// a mod's own type: the items in its lists in a grid, single items (like a bowl to serve in) under
// the arrow, then what it makes
// the arrow, then what it makes, one under the other
const { grid, extras } = mod_recipe_inputs(recipe);
grid.slice(0, 9).forEach((ingredient, i) =>
cell(ingredient, x + (i % 3) * CELL, top + Math.floor(i / 3) * CELL)
@@ -264,7 +265,10 @@ class RecipeViewer {
extras.slice(0, 1).forEach((ingredient) =>
cell(ingredient, x + 3.5 * CELL, top + CELL * 1.5, ["Served in"])
);
outputs(recipe).slice(0, 1).forEach((output) => cell(output, x + 5 * CELL, top + CELL / 2));
const made = outputs(recipe).slice(0, 3);
made.forEach((output, i) =>
cell(output, x + 5 * CELL, made.length > 1 ? top + i * CELL : top + CELL / 2)
);
if (typeof recipe.cook_time === "number") {
g.text(seconds(recipe.cook_time), x + 5 * CELL, top + CELL * 1.5 + (CELL - TEXT) / 2, {
color: LABEL_COLOR,
@@ -280,7 +284,9 @@ class RecipeViewer {
function card_height(recipe: Recipe): number {
let rows = 2;
if (recipe.type === "shaped") rows = 3;
else if (!(recipe.type in CATEGORY_NAMES)) rows = Math.max(2, Math.ceil(mod_recipe_inputs(recipe).grid.length / 3));
else if (!(recipe.type in CATEGORY_NAMES)) {
rows = Math.max(2, Math.ceil(mod_recipe_inputs(recipe).grid.length / 3), outputs(recipe).length);
}
return LINE + Math.min(rows, 3) * CELL + GAP;
}
@@ -317,10 +323,13 @@ export function outputs(recipe: Recipe): Ingredient[] {
case "smithing":
return [{ ids: [recipe.result], count: 1 }];
default: {
// one item or stack, or a list of them, like what a cutting board cuts something into
const output = recipe.result ?? recipe.output;
if (typeof output === "string") return [{ ids: [output], count: 1 }];
if (output && typeof output.id === "string") return [stack(output)];
return [];
return [output].flat().flatMap((output): Ingredient[] => {
if (typeof output === "string") return [{ ids: [output], count: 1 }];
if (output && typeof output.id === "string") return [stack(output)];
return [];
});
}
}
}
+24 -1
View File
@@ -123,6 +123,8 @@ interface SavedTile {
z: number;
// what BlockRef.data holds
mod_data?: unknown;
// what it shows, see ServerWorld.set_block_item in the mod api
item?: ItemData;
}
// the loaded mods, see load_mods.ts
@@ -197,7 +199,14 @@ export class GameServer {
this.containers.set(id, container);
}
for (const tile of saved?.tiles ?? []) {
this.world.add_tile({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: tile.mod_data });
this.world.add_tile({
id: tile.id,
x: tile.x,
y: tile.y,
z: tile.z,
mod_data: tile.mod_data,
item: tile.item,
});
}
this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []);
this.#saved_players = saved?.players ?? {};
@@ -218,6 +227,16 @@ export class GameServer {
}
}
};
this.world.on_tile_item_change = (x, y, z, item) => {
const data = JSON.stringify(
{ type: "set_block_item", x, y, z, item: item ?? null } satisfies ServerMessage,
);
for (const player of this.#players.values()) {
if (player.chunks.has_block(x, z)) {
this.#host.send(player.conn, data);
}
}
};
}
// connections
@@ -331,6 +350,7 @@ export class GameServer {
y: tile.y,
z: tile.z,
mod_data: tile.mod_data,
item: tile.item,
})),
containers: Object.fromEntries(
[...this.containers].map(([id, container]) => [id, container.to_data()]),
@@ -1458,6 +1478,9 @@ export class GameServer {
this.#send(player, { type: "chunk_batch_start" });
for (const [x, z] of batch) {
this.#host.send(player.conn, this.world.level_chunk(x, z));
for (const tile of this.world.item_tiles(x, z)) {
this.#send(player, { type: "set_block_item", x: tile.x, y: tile.y, z: tile.z, item: tile.item! });
}
}
this.#send(player, { type: "chunk_batch_finished", size: batch.length });
}
+16
View File
@@ -434,6 +434,19 @@ export class ModRuntime {
return true;
},
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
set_block_item: (x, y, z, item) => {
if (game().world.get_block_id(x, y, z) === AIR_ID) return;
if (!item || item.count <= 0) {
const tile = game().world.get_tile(x, y, z);
if (tile?.item) game().world.set_tile_item(tile, undefined);
return;
}
game().world.set_tile_item(game().get_or_create_tile(x, y, z), new_stack(item).to_data());
},
get_block_item: (x, y, z) => {
const item = game().world.get_tile(x, y, z)?.item;
return item && structuredClone(item);
},
drop_item: (x, y, z, item) => void game().pop_item(x, y, z, new_stack(item)),
spawn_entity: (id, x, y, z) => {
const entity = EverythingRegistry.get("entities", id)
@@ -750,6 +763,9 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
get position() {
return { x: player.x, y: player.y, z: player.z };
},
get yaw() {
return player.yaw;
},
inventory,
get selected_slot() {
return player.selected_slot;
+36 -1
View File
@@ -6,6 +6,7 @@ import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
import { LruMap } from "./lru.ts";
import { CYCLE_TICKS } from "$/common/time.ts";
import { encode_level_chunk } from "$/common/chunk_streaming.ts";
import type { ItemData } from "$/common/inventory.ts";
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, SavedChunk } from "./saves.ts";
// generation only, rebuilt when needed. 256 KB each
@@ -16,7 +17,7 @@ const SPAWN_SEARCH_CHUNKS = 32;
// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one
const FINGERPRINT_CHUNKS = [[0, 0], [7, -3], [-45, 18], [130, -80], [-310, 260], [1000, -1000]];
// a block with data the server keeps, like where a chest's items are. never sent to clients
// a block with data the server keeps, like where a chest's items are. never sent to clients, but for item
export interface Tile {
id: string;
x: number;
@@ -24,6 +25,8 @@ export interface Tile {
z: number;
// what BlockRef.data holds
mod_data?: unknown;
// the item it shows, sent to clients, see BlockRegistry.item_display. only set through set_tile_item
item?: ItemData;
}
export function position_key(x: number, y: number, z: number) {
@@ -47,6 +50,8 @@ export class ServerWorld {
// chunks changed since they were last saved, by chunk_key
#unsaved = new Map<number, [number, number]>();
tiles = new Map<string, Tile>();
// the tiles showing an item, by chunk_key, to send with their chunk
#item_tiles = new Map<number, Set<Tile>>();
// ticks since 06:00 of day 1, see common/time.ts
time = 0;
@@ -60,6 +65,7 @@ export class ServerWorld {
dirty = false;
on_block_change?: (x: number, y: number, z: number, id: string, state: number) => void;
on_tile_item_change?: (x: number, y: number, z: number, item: ItemData | undefined) => void;
constructor(seed: string, worldgen?: WorldgenSetup) {
this.seed = seed;
@@ -298,15 +304,44 @@ export class ServerWorld {
}
add_tile(tile: Tile) {
const item = tile.item;
delete tile.item;
this.tiles.set(position_key(tile.x, tile.y, tile.z), tile);
if (item) this.set_tile_item(tile, item);
this.dirty = true;
}
remove_tile(x: number, y: number, z: number) {
const tile = this.get_tile(x, y, z);
if (tile?.item) this.set_tile_item(tile, undefined);
this.tiles.delete(position_key(x, y, z));
this.dirty = true;
}
set_tile_item(tile: Tile, item: ItemData | undefined) {
const key = chunk_key(Math.floor(tile.x / CHUNK_SIZE), Math.floor(tile.z / CHUNK_SIZE));
let tiles = this.#item_tiles.get(key);
if (item) {
tile.item = item;
if (!tiles) {
tiles = new Set();
this.#item_tiles.set(key, tiles);
}
tiles.add(tile);
} else {
delete tile.item;
tiles?.delete(tile);
if (tiles?.size === 0) this.#item_tiles.delete(key);
}
this.dirty = true;
this.on_tile_item_change?.(tile.x, tile.y, tile.z, item);
}
// the tiles in a chunk that show an item
item_tiles(chunk_x: number, chunk_z: number): Iterable<Tile> {
return this.#item_tiles.get(chunk_key(chunk_x, chunk_z)) ?? [];
}
#record_change(x: number, y: number, z: number, id: string, state: number) {
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
let chunk_changes = this.#changes.get(key);
+108
View File
@@ -0,0 +1,108 @@
// farmer's delight's cutting board: holds a stack of anything, shows it on top, and a knife cuts it one at a time
import { assert, assertEquals } from "@std/assert";
import { get_state_value } from "$/common/utils.ts";
import { test_game } from "./helpers.ts";
const BOARD = [0, 100, 0] as const;
async function setup(yaw = 0) {
const t = await test_game("mods");
t.join(1, "alice");
for (let x = -3; x <= 3; x++) {
for (let z = -3; z <= 3; z++) t.game.set_block(x, 99, z, "bworld:stone");
}
t.send(1, { type: "move", x: 2.5, y: 100, z: 2.5, yaw, pitch: 0 });
t.send(1, { type: "chat", text: "/give farmersdelight:cutting_board" });
t.send(1, { type: "select_slot", slot: 0 });
t.send(1, { type: "use_block", x: BOARD[0], y: BOARD[1] - 1, z: BOARD[2], face: "top" });
assertEquals(t.game.world.get_block_id(...BOARD), "farmersdelight:cutting_board");
const use = (slot: number) => {
t.send(1, { type: "select_slot", slot });
t.send(1, { type: "use_block", x: BOARD[0], y: BOARD[1], z: BOARD[2], face: "top" });
};
const inventory = () => t.game.players()[0].inventory.to_data().filter((i) => i).map((i) => `${i!.id} ${i!.count}`);
const state = (name: string) =>
get_state_value(t.game.world.get_block_value(...BOARD), t.game.world.get_block_info(...BOARD)!, name);
const on_board = () => {
const item = t.game.world.get_tile(...BOARD)?.item;
return item ? `${item.id} ${item.count}` : "";
};
const dropped = () => t.game.item_entities().map((e) => `${e.item.type_id} ${e.item.amount}`).sort();
return { ...t, use, inventory, state, on_board, dropped };
}
Deno.test("the board faces whoever placed it", async () => {
// looking north it faces south, back at them
assertEquals((await setup(0)).state("facing"), 2);
// looking west it faces east
assertEquals((await setup(Math.PI / 2)).state("facing"), 1);
assertEquals((await setup(Math.PI)).state("facing"), 0);
assertEquals((await setup(-Math.PI / 2)).state("facing"), 3);
});
Deno.test("a stack goes on the board, and a knife cuts one at a time by its recipe", async () => {
const t = await setup();
t.send(1, { type: "chat", text: "/give bworld:cod 3" });
t.send(1, { type: "chat", text: "/give farmersdelight:iron_knife" });
t.use(0);
assertEquals(t.on_board(), "bworld:cod 3");
assertEquals(t.inventory(), ["farmersdelight:iron_knife 1"]);
t.use(1);
assertEquals(t.on_board(), "bworld:cod 2");
assertEquals(t.dropped(), ["bworld:bone_meal 1", "farmersdelight:cod_slice 2"]);
t.use(1);
t.use(1);
assertEquals(t.on_board(), "");
assertEquals(t.dropped().length, 6);
// on an empty board the knife goes on it, like the java mod, and cutting nothing does nothing
t.use(1);
assertEquals(t.on_board(), "farmersdelight:iron_knife 1");
t.send(1, { type: "chat", text: "/give farmersdelight:stone_knife" });
t.use(0);
assertEquals(t.on_board(), "farmersdelight:iron_knife 1");
assertEquals(t.inventory(), ["farmersdelight:stone_knife 1"]);
});
Deno.test("an empty hand takes it all back, and breaking the board drops it", async () => {
const t = await setup();
t.send(1, { type: "chat", text: "/give farmersdelight:cabbage 5" });
t.use(0);
assertEquals(t.on_board(), "farmersdelight:cabbage 5");
t.use(1);
assertEquals(t.on_board(), "");
assertEquals(t.inventory(), ["farmersdelight:cabbage 5"]);
t.use(0);
t.game.destroy_block(...BOARD);
assertEquals(t.dropped(), ["farmersdelight:cabbage 5", "farmersdelight:cutting_board 1"]);
assertEquals(t.game.world.get_tile(...BOARD), undefined);
});
Deno.test("what a block shows goes to players with its chunk and when it changes, and is saved", async () => {
const t = await setup();
t.send(1, { type: "chat", text: "/give bworld:salmon 2" });
// players only hear about blocks in chunks they have
for (let i = 0; i < 5; i++) t.game.tick();
t.take(1);
t.use(0);
const shown = (conn: number) =>
t.take(conn).filter((m) => m.type === "set_block_item").map((m) => m.item && `${m.item.id} ${m.item.count}`);
assertEquals(shown(1), ["bworld:salmon 2"]);
// someone joining gets it with the chunk
t.join(2, "bob");
for (let i = 0; i < 5; i++) t.game.tick();
assert(shown(2).includes("bworld:salmon 2"));
const loaded = await test_game("mods", t.game.save());
assertEquals(loaded.game.world.get_tile(...BOARD)?.item, { id: "bworld:salmon", count: 2 });
// breaking it takes it away for everyone
t.game.destroy_block(...BOARD);
assertEquals(shown(1), [null]);
assertEquals(shown(2), [null]);
});
+3 -2
View File
@@ -29,8 +29,9 @@ Deno.test("the base game loads from mods/bworld", async () => {
assertEquals(bworld(EverythingRegistry.entries("blocks")), 42);
// 38 items (20 of them tools) plus the item forms of the 37 blocks that have one
assertEquals(bworld(EverythingRegistry.entries("items")), 75);
// bworld's 16 (4 wood tools, 7 planks, the fishing rod), the cooking pot and stove are farmersdelight's
assertEquals(game.recipes.shaped.length, 18);
// bworld's 16 (4 wood tools, 7 planks, the fishing rod), the cooking pot, stove, cutting board and wood knife are
// farmersdelight's
assertEquals(game.recipes.shaped.length, 20);
// every log and fish smelts, every log burns
assertEquals(game.recipes.furnace.size, 14);
assertEquals(game.recipes.fuel.size, 8);