Send block data to clients

This commit is contained in:
2026-10-13 23:26:10 -03:00
parent a10b15a3fd
commit 55ad08266e
18 changed files with 283 additions and 90 deletions
+7 -7
View File
@@ -4,9 +4,8 @@ A plan for porting all of Create to bworld as a mod, `mods/create`: its kinetics
redstone, contraptions, trains, equipment, decoration and schematics. It aims to do this with as little hand work as
possible, and to stay fast on both the server and the client when a world has thousands of moving parts.
Built so far: the importer and Create's imported blocks and items, model `parent` and `x` turns, S0, and stonecutting
from S9. Facts about Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from
its source.
Built so far: the importer and Create's imported blocks and items, R1, R5, S0, S7, and stonecutting from S9. Facts about
Create come from reading `ports/create1.21.1` and `ports/create1.19.3`, and facts about bworld from its source.
## Sources
@@ -230,10 +229,11 @@ Everything here is general, and none of it mentions Create. Each line says which
### Rendering
**R1. Client-visible tile data** (P1). A component marks part of a block's tile data for clients, sent with the chunk
and again when it changes. Like NeoForge's `getUpdateTag`, but per field, so a fast-changing field doesn't resend the
rest. The display item (`set_block_item`, `ClientLevel.block_items`) moves onto it, so there's one way to sync block
data.
**R1. Client-visible tile data** (P1, built). `block.set_client_data(field, value)` keeps a field of a block's data that
clients see too, apart from its server-only `data`. Players get every field with the chunk, then each field again when
it's set to something else, like NeoForge's `getUpdateTag` but per field, so a fast-changing field doesn't resend the
rest. It's saved, goes with the block, and client scripts read it with `ctx.world.get_client_data`. The display item is
its `item` field now, so there's one way to sync block data. R2's visuals will be told when a field changes.
**R2. Block visuals** (P1). `ctx.render.register_visual(block_id, factory)` in client scripts. A visual is created when
its chunk is meshed, updated when the block's client data or states change, and deleted with the block or chunk, like
+2 -1
View File
@@ -36,7 +36,8 @@ deno task build && deno task server # packs the mods and starts a se
- [Blocks](docs/modding/blocks/index.md): looks, mining, drops and placement
- [Block States](docs/modding/blocks/states.md): state bits, variants and facing
- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from a server script
- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, and blocks that hold or show items
- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or
show items
- [Crops](docs/modding/blocks/crops.md): farming without writing code
**Items**
+34 -17
View File
@@ -31,7 +31,6 @@ import { Camera } from "../camera.ts";
import type { Entity } from "../entity/entity.ts";
import type { ModelJson } from "$/common/block_models.ts";
import { clip_shape, collision_shape_at, FULL_SHAPE, type Shape, shape_at } from "$/common/block_shapes.ts";
import type { ItemStack } from "$/common/inventory.ts";
import { BlockPredictions } from "./block_predictions.ts";
export interface Block {
@@ -98,6 +97,14 @@ export interface BlockHitResult {
hit: [number, number, number];
}
// a block's client data, see ClientLevel.block_data
export interface BlockData {
x: number;
y: number;
z: number;
data: Record<string, unknown>;
}
const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1]] as const;
// light spreads diagonally too, so meshing and lighting need all 8
const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
@@ -133,8 +140,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 }>>();
// the client data of blocks that have some, see BlockRef.set_client_data, by chunk_key then position_key "x,y,z"
block_data = new Map<number, Map<string, BlockData>>();
// server_blocks is the server's block id for each of its numeric ids
constructor(server_blocks: string[], view_distance: number) {
@@ -517,24 +524,34 @@ export class ClientLevel {
this.delete_chunk_mesh(chunk);
this.chunks.delete(key);
this.#dirty.delete(chunk);
this.block_items.delete(key);
this.block_data.delete(key);
}
// see set_block_item in common/protocol.ts
set_block_item(x: number, y: number, z: number, item: ItemStack | undefined) {
// see block_data in common/protocol.ts
set_block_data(x: number, y: number, z: number, changed: Record<string, unknown>) {
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);
if (!this.chunks.has(key)) return;
let blocks = this.block_data.get(key);
const position = `${x},${y},${z}`;
const data = { ...blocks?.get(position)?.data };
for (const [field, value] of Object.entries(changed)) {
if (value === null) delete data[field];
else data[field] = value;
}
if (Object.keys(data).length > 0) {
if (!blocks) {
blocks = new Map();
this.block_data.set(key, blocks);
}
blocks.set(position, { x, y, z, data });
} else if (blocks?.delete(position) && blocks.size === 0) {
this.block_data.delete(key);
}
}
get_block_data(x: number, y: number, z: number): Readonly<Record<string, unknown>> | undefined {
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
return this.block_data.get(key)?.get(`${x},${y},${z}`)?.data;
}
// a chunk is only meshed once all its neighbors exist, otherwise its border faces and light would be
+2
View File
@@ -294,6 +294,8 @@ function client_context(listing: ModListing): ClientContext {
if (nid === AIR) return AIR_ID;
return EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id;
},
get_client_data: (x, y, z, field) =>
structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never,
biome_at: (x, z) => rules_world.biome_at(x, z),
season_at: (x, z) => rules_world.season_at(x, z),
get time() {
+2 -7
View File
@@ -186,13 +186,8 @@ export class ClientPacketListener {
case "block_ack":
level.ack_predictions(message.seq);
break;
case "set_block_item":
level.set_block_item(
message.x,
message.y,
message.z,
message.item ? ItemStack.from_data(message.item) : undefined,
);
case "block_data":
level.set_block_data(message.x, message.y, message.z, message.data);
break;
case "chunk_batch_start":
this.#chunk_batch.on_batch_start();
+15 -5
View File
@@ -7,7 +7,7 @@ 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 { type ItemData, ItemStack } from "$/common/inventory.ts";
import { light_color, push_vertex, Texture } from "$/client/renderer/mod.ts";
import {
bake_model,
@@ -105,17 +105,27 @@ 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
// the stacks shown items are drawn as, by their "item" client data, which is replaced whenever it changes
const shown_stacks = new WeakMap<ItemData, ItemStack>();
// every item blocks with item_display show on top of them, their "item" client data, 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()) {
for (const in_chunk of level.block_data.values()) {
for (const { x, y, z, data } of in_chunk.values()) {
const shown = data.item as ItemData | undefined;
if (!shown) continue;
// 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;
let item = shown_stacks.get(shown);
if (!item) {
item = ItemStack.from_data(shown);
shown_stacks.set(shown, item);
}
// the block's own light, or the one above for blocks light doesn't get into, since the items sit on top
const here = level.get_light(x, y, z);
const above = level.get_light(x, y + 1, z);
+3
View File
@@ -29,6 +29,9 @@ export interface ClientContext {
// read only, what this client sees
world: {
get_block(x: number, y: number, z: number): Id | undefined;
// a field of the block's client data, what server scripts set with BlockRef.set_client_data, a copy.
// undefined when it isn't set or the chunk isn't loaded
get_client_data<T>(x: number, y: number, z: number, field: string): T | undefined;
// the column's biome and its season, undefined when the chunk isn't loaded
biome_at(x: number, z: number): Id | undefined;
season_at(x: number, z: number): Season | undefined;
+8 -2
View File
@@ -44,6 +44,12 @@ export interface BlockRef {
// tile data, any json value. saved with the world, never sent to clients
// deno-lint-ignore no-explicit-any
data: any;
// the part of its data clients see too, like how fast a shaft turns, by field. each is any json value, saved with
// the world, sent to players with the block's chunk and again when it's set to something else, so a field that
// changes often doesn't resend the rest. undefined removes a field, and they all go with the block. "item" is the
// item a block with item_display shows, see set_block_item. get returns a copy
get_client_data<T>(field: string): T | undefined;
set_client_data(field: string, value: unknown): void;
// turns on_tick and on_second off for this block, or back on, like a machine with nothing to do. it stays off until
// it's turned on again, saved with the world, and goes with the block
set_ticking(ticking: boolean): void;
@@ -234,8 +240,8 @@ export interface ServerWorld {
get_block_data<T>(x: number, y: number, z: number): T | undefined;
// BlockRef.set_ticking for a block, for waking one from somewhere else, like a machine getting something to work on
set_block_ticking(x: number, y: number, z: number, ticking: boolean): void;
// 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
// the item a block with item_display shows on top of it, like a block entity renderer: its "item" client data, see
// BlockRef.set_client_data. 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;
+4 -4
View File
@@ -10,7 +10,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 = 21;
export const PROTOCOL_VERSION = 22;
export interface PlayerInfo {
id: string;
@@ -221,9 +221,9 @@ export type ServerMessage =
// the break_block or use_block with this seq is handled, and so is every one before it. the set_blocks it caused
// came first, and what they said about blocks this client guessed shows now
| { type: "block_ack"; seq: 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 }
// fields of a block's client data, see BlockRef.set_client_data. to the players who have the chunk: every field
// right after it, then each field when it changes. null when a field is gone, and every field when the block is
| { type: "block_data"; x: number; y: number; z: number; data: Record<string, unknown> }
| { type: "chat"; from?: string; text: string }
// the player is here now. with motion, they're moving that fast (blocks per second) too: the server is moving them,
// like when knocked back, and the client keeps going that way until the next one. id counts up, see move
+3 -2
View File
@@ -69,8 +69,9 @@ component.
| `on_second(block, params, dt)` | Every second, near a player. | |
| `on_new_day(block, params, day)` | Every morning at 06:00. See [Ticking](#ticking) for where. | |
`block` is `{ id, x, y, z, biome, season, data, set_ticking }`, where `data` is the block's [tile data](tiledata.md),
`biome` and `season` are its column's (see [Seasons](../worldgen/biomes.md#seasons)) and `set_ticking` turns its
`block` is `{ id, x, y, z, biome, season, data, get_client_data, set_client_data, set_ticking }`, where `data` is the
block's [tile data](tiledata.md) and the client data functions its [part clients see](tiledata.md#client-data), `biome`
and `season` are its column's (see [Seasons](../worldgen/biomes.md#seasons)) and `set_ticking` turns its
[ticking](#ticking) off and on. `params` is what the block's JSON lists for this component, and `dt` is in seconds.
## Rules
+32 -5
View File
@@ -2,7 +2,7 @@
Tile data is extra data kept for one block in the world, like what a chest holds or how far along a furnace is. It's
bworld's version of Minecraft's block entities: a [block state](states.md) is a few bits every client knows, while tile
data is any JSON value that only the server knows.
data is any JSON value that only the server knows, apart from the fields it [shares with clients](#client-data).
## Reading and Writing
@@ -25,8 +25,8 @@ ctx.components.register_block("copper_tools:counter", {
Outside a handler, `ctx.world.get_block_data<T>(x, y, z)` reads it.
- Tile data is saved with the world, and goes away when the block is broken or replaced.
- It's **never sent to clients**. To show it to a player, open a [menu](../inventories/menus.md), or change a block
state that the block's `variants` show.
- It's **never sent to clients**. To show it to a player, give it [client data](#client-data), open a
[menu](../inventories/menus.md), or change a block state that the block's `variants` show.
- Only blocks with tile data run `on_tick` and `on_second`, unless they turned it off. `on_new_day` runs for blocks
without it too, but only near players, see [Ticking](components.md#ticking).
@@ -54,6 +54,33 @@ ctx.components.register_block("copper_tools:crate", {
The base game's `bworld:storage` does exactly this, see `mods/bworld/scripts/server.ts`.
## Client Data
Client data is the part of a block's data its clients see too, like how fast a shaft turns. It's kept by field, each any
JSON value, and set apart from `block.data`:
```ts
ctx.components.register_block("copper_tools:shaft", {
on_create(block) {
block.set_client_data("speed", 0);
block.set_client_data("axis", "y");
},
on_interact(block) {
block.set_client_data("speed", block.get_client_data<number>("speed")! + 16);
return true;
},
});
```
- Players get every field with the block's chunk, then each field again when it's set to something else. A field that
changes often doesn't resend the others, and setting a field to what it already is sends nothing.
- `undefined` removes a field. All of them go when the block is broken or replaced.
- It's saved with the world. `get_client_data` and `set_client_data` copy the value, so change it by setting it again.
- Client scripts read it with `ctx.world.get_client_data<T>(x, y, z, field)`, see [GUI](../gui/index.md).
Like NeoForge's `getUpdateTag`, but per field. Keep it to what clients need to draw the block: everything in it is sent
to every player near it.
## Showing an Item
A block with `item_display` draws one item lying on top of it, like the food on Farmer's Delight's cutting board:
@@ -70,5 +97,5 @@ const shown = ctx.world.get_block_item(x, y, z); // a copy, or undefined
ctx.world.set_block_item(x, y, z, undefined); // shows nothing
```
Unlike the rest of tile data, the displayed item is synced to players. It's saved with the block, turns with the block's
`y` variant, and disappears with the block without dropping, so drop it in `on_break` if it should.
The item is the block's `item` [client data](#client-data), so it's synced and saved the same way. It turns with the
block's `y` variant, and disappears with the block without dropping, so drop it in `on_break` if it should.
+2 -1
View File
@@ -14,7 +14,8 @@ the server. A mod's own logic has to do the same:
[command](../misc/commands.md).
- Never use a value from a client as an item id, a count or a position without checking it.
Server script code and tile data are never sent to clients, so a mod can keep anti-cheat logic or secrets there.
Server script code and tile data are never sent to clients, so a mod can keep anti-cheat logic or secrets there. Only
the fields a script sets as [client data](../blocks/tiledata.md#client-data) are.
## Server Scripts
+1
View File
@@ -155,6 +155,7 @@ ctx.player.position; // { x, y, z }
ctx.player.is_swimming(); // see ../entities/players.md#swimming
ctx.player.biome; // and ctx.player.season, see ../worldgen/biomes.md#seasons
ctx.world.get_block(x, y, z); // a block id, what this client sees
ctx.world.get_client_data<number>(x, y, z, "speed"); // see ../blocks/tiledata.md#client-data, a copy
ctx.world.biome_at(x, z); // and ctx.world.season_at(x, z), undefined where nothing's loaded
ctx.world.time; // see Time
ctx.items.ids(); // every item, in load order
+19 -6
View File
@@ -279,10 +279,8 @@ 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,
);
this.world.on_client_data_change = (x, y, z, changed) => {
const data = JSON.stringify({ type: "block_data", x, y, z, data: changed } satisfies ServerMessage);
for (const player of this.#players.values()) {
if (player.chunks.has_block(x, z)) {
this.#host.send(player.conn, data);
@@ -688,6 +686,15 @@ export class GameServer {
this.world.dirty = true;
}
// BlockRef.set_client_data. a block without a tile only gets one when a field is set, not removed
set_tile_client_data(x: number, y: number, z: number, field: string, value: unknown) {
if (this.world.get_block_id(x, y, z) === AIR_ID) {
return;
}
const tile = value === undefined ? this.world.get_tile(x, y, z) : this.get_or_create_tile(x, y, z);
if (tile) this.world.set_tile_client_data(tile, field, value);
}
// a component turning ticking off for one block, or back on, see BlockRef.set_ticking. it stays off when saved
set_tile_ticking(x: number, y: number, z: number, ticking: boolean) {
if (this.world.get_block_id(x, y, z) === AIR_ID) {
@@ -2108,8 +2115,14 @@ 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! });
for (const tile of this.world.client_tiles(x, z)) {
this.#send(player, {
type: "block_data",
x: tile.x,
y: tile.y,
z: tile.z,
data: tile.client_data!,
});
}
}
this.#send(player, { type: "chunk_batch_finished", size: batch.length });
+9 -11
View File
@@ -549,6 +549,11 @@ export class ModRuntime {
set data(value) {
game.set_tile_data(x, y, z, value);
},
get_client_data: (field) => structuredClone(game.world.get_tile(x, y, z)?.client_data?.[field]) as never,
set_client_data(field, value) {
if (typeof field !== "string" || field === "") throw new Error("a client data field needs a name");
game.set_tile_client_data(x, y, z, field, structuredClone(value));
},
set_ticking(ticking) {
game.set_tile_ticking(x, y, z, ticking);
},
@@ -691,18 +696,11 @@ export class ModRuntime {
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
set_block_ticking: (x, y, z, ticking) => game().set_tile_ticking(x, y, z, ticking),
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);
const shown = item && item.count > 0 ? new_stack(item).to_data() : undefined;
game().set_tile_client_data(x, y, z, "item", shown);
},
get_block_item: (x, y, z) =>
structuredClone(game().world.get_tile(x, y, z)?.client_data?.item as ItemStack),
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)
+28 -19
View File
@@ -16,7 +16,6 @@ import { LruMap } from "./lru.ts";
import { collision_shape_at, EMPTY_SHAPE, type Shape } from "$/common/block_shapes.ts";
import { farming_day } 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, SavedChunk, SavedChunks } from "./saves.ts";
// generation only, rebuilt when needed. 256 KB each. with a worldgen pool, it holds what the pool made until the
@@ -36,7 +35,7 @@ const SPAWN_SEARCH_CHUNKS = 32;
// the chunks around the middle the spawn search usually finds land in, with their neighbors, worth generating ahead
export const SPAWN_AREA_CHUNKS = 3;
// a block with data the server keeps, like where a chest's items are. never sent to clients, but for item
// a block with data the server keeps, like where a chest's items are. only client_data is sent to clients
export interface Tile {
id: string;
x: number;
@@ -44,8 +43,9 @@ 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;
// the fields clients see, see BlockRef.set_client_data. only set through set_tile_client_data, which replaces the
// object, so a saved copy of the tile never changes under the save
client_data?: Record<string, unknown>;
// false when its components turned ticking off for it, see GameServer.set_tile_ticking
ticking?: false;
}
@@ -132,8 +132,8 @@ export class ServerWorld {
// unsaved chunks #chunks forgot, ready to save, by chunk_key
#evicted = new Map<number, SavedChunk>();
tiles = new Map<string, Tile>();
// the tiles showing an item, to send with their chunk
#item_tiles = new ChunkTiles();
// the tiles with client data, to send with their chunk
#client_tiles = new ChunkTiles();
// the tiles that tick, which the game decides, see GameServer.set_tile_ticking
#ticking_tiles = new ChunkTiles();
@@ -149,7 +149,8 @@ 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;
// the fields that changed, null for the ones that are gone
on_client_data_change?: (x: number, y: number, z: number, changed: Record<string, unknown>) => void;
constructor(seed: string, worldgen: WorldgenSetup) {
this.seed = seed;
@@ -511,33 +512,41 @@ 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.#client_tiles.set(tile, tile.client_data !== undefined);
this.dirty = true;
}
// clients drop its client data with it
remove_tile(x: number, y: number, z: number) {
const tile = this.get_tile(x, y, z);
if (!tile) return;
if (tile.item) this.set_tile_item(tile, undefined);
if (tile.client_data) {
this.#client_tiles.set(tile, false);
const gone = Object.fromEntries(Object.keys(tile.client_data).map((field) => [field, null]));
this.on_client_data_change?.(x, y, z, gone);
}
this.#ticking_tiles.set(tile, false);
this.tiles.delete(position_key(x, y, z));
this.dirty = true;
}
set_tile_item(tile: Tile, item: ItemData | undefined) {
if (item) tile.item = item;
else delete tile.item;
this.#item_tiles.set(tile, item !== undefined);
// one field of what clients see of it, any json value. undefined removes it. setting what it already is sends
// nothing
set_tile_client_data(tile: Tile, field: string, value: unknown) {
if (JSON.stringify(tile.client_data?.[field]) === JSON.stringify(value)) return;
const { [field]: _, ...data } = tile.client_data ?? {};
if (value !== undefined) data[field] = value;
if (Object.keys(data).length > 0) tile.client_data = data;
else delete tile.client_data;
this.#client_tiles.set(tile, tile.client_data !== undefined);
this.dirty = true;
this.on_tile_item_change?.(tile.x, tile.y, tile.z, item);
this.on_client_data_change?.(tile.x, tile.y, tile.z, { [field]: value ?? null });
}
// the tiles in a chunk that show an item
item_tiles(chunk_x: number, chunk_z: number): Iterable<Tile> {
return this.#item_tiles.in_chunk(chunk_x, chunk_z);
// the tiles in a chunk that have client data
client_tiles(chunk_x: number, chunk_z: number): Iterable<Tile> {
return this.#client_tiles.in_chunk(chunk_x, chunk_z);
}
// whether it runs its components' on_tick and on_second near players
+107
View File
@@ -0,0 +1,107 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the part of a block's tile data clients see: sent with its chunk, then field by field as it changes, saved, and gone
// with the block
import { assertEquals } from "@std/assert";
import { chunk_key, ClientLevel } from "$/client/level/client_level.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SHAFT = [1, 99, 1] as const;
async function setup() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_client_data_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const t = await test_game(dir);
Deno.removeSync(dir, { recursive: true });
t.join(1, "alice");
stone_floor(t.game);
t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
for (let i = 0; i < 5; i++) t.game.tick();
t.take(1);
const block = t.game.mods.block_ref(...SHAFT, "bworld:stone");
// what conn was told about the block since last asked
const sent = (conn: number) =>
t.take(conn).filter((m) => m.type === "block_data" && m.x === SHAFT[0] && m.y === SHAFT[1] && m.z === SHAFT[2])
.map((m) => m.data);
return { ...t, block, sent };
}
Deno.test("a block's client data goes to players field by field, only when a field changes", async () => {
const { block, sent } = await setup();
block.set_client_data("speed", 16);
block.set_client_data("axis", "x");
assertEquals(sent(1), [{ speed: 16 }, { axis: "x" }]);
// the same again sends nothing, and a change sends only that field
block.set_client_data("speed", 16);
block.set_client_data("speed", 32);
assertEquals(sent(1), [{ speed: 32 }]);
assertEquals(block.get_client_data("speed"), 32);
// removed, it's null
block.set_client_data("axis", undefined);
assertEquals(sent(1), [{ axis: null }]);
assertEquals(block.get_client_data("axis"), undefined);
});
Deno.test("client data is copied in and out, so changing a value after setting it doesn't change what's sent", async () => {
const { block, sent } = await setup();
const value = { rpm: 16 };
block.set_client_data("speed", value);
value.rpm = 64;
block.get_client_data<{ rpm: number }>("speed")!.rpm = 128;
assertEquals(block.get_client_data("speed"), { rpm: 16 });
assertEquals(sent(1), [{ speed: { rpm: 16 } }]);
});
Deno.test("a player getting the chunk gets every field with it, and it's saved", async () => {
const { game, block, join, sent } = await setup();
block.set_client_data("speed", 16);
block.set_client_data("axis", "x");
join(2, "bob");
for (let i = 0; i < 5; i++) game.tick();
assertEquals(sent(2), [{ speed: 16, axis: "x" }]);
const loaded = await test_game("mods", game.save());
assertEquals(loaded.game.world.get_tile(...SHAFT)?.client_data, { speed: 16, axis: "x" });
});
Deno.test("breaking the block takes every field away from everyone", async () => {
const { game, block, sent } = await setup();
block.set_client_data("speed", 16);
block.set_client_data("axis", "x");
sent(1);
game.set_block(...SHAFT, AIR_ID);
assertEquals(sent(1), [{ speed: null, axis: null }]);
assertEquals(game.world.get_tile(...SHAFT), undefined);
// air keeps none, and removing a field doesn't make a tile for it
game.mods.block_ref(...SHAFT, AIR_ID).set_client_data("speed", 16);
game.mods.block_ref(2, 99, 2, "bworld:stone").set_client_data("speed", undefined);
assertEquals(sent(1), []);
assertEquals(game.world.get_tile(...SHAFT), undefined);
assertEquals(game.world.get_tile(2, 99, 2), undefined);
});
Deno.test("the client keeps the fields it's sent for each block until they're removed", () => {
// only the parts of a level the client data needs, without its chunk workers
const level = Object.assign(Object.create(ClientLevel.prototype), {
chunks: new Map([[chunk_key(0, 0), {}]]),
block_data: new Map(),
}) as ClientLevel;
level.set_block_data(1, 99, 1, { speed: 16, axis: "x" });
level.set_block_data(1, 99, 1, { speed: 32 });
assertEquals(level.get_block_data(1, 99, 1), { speed: 32, axis: "x" });
level.set_block_data(1, 99, 1, { speed: null });
assertEquals(level.get_block_data(1, 99, 1), { axis: "x" });
level.set_block_data(1, 99, 1, { axis: null });
assertEquals(level.get_block_data(1, 99, 1), undefined);
assertEquals(level.block_data.size, 0);
// not for chunks it doesn't have
level.set_block_data(40, 99, 1, { speed: 16 });
assertEquals(level.get_block_data(40, 99, 1), undefined);
});
+5 -3
View File
@@ -4,6 +4,7 @@
// 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 type { ItemData } from "$/common/inventory.ts";
import { stone_floor, test_game } from "./helpers.ts";
const BOARD = [0, 100, 0] as const;
@@ -26,7 +27,7 @@ async function setup(yaw = 0) {
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;
const item = t.game.world.get_tile(...BOARD)?.client_data?.item as ItemData | undefined;
return item ? `${item.id} ${item.count}` : "";
};
const dropped = () => t.game.item_entities().map((e) => `${e.item.type_id} ${e.item.amount}`).sort();
@@ -103,7 +104,8 @@ Deno.test("what a block shows goes to players with its chunk and when it changes
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}`);
t.take(conn).filter((m) => m.type === "block_data" && "item" in m.data)
.map((m) => m.data.item && `${m.data.item.id} ${m.data.item.count}`);
assertEquals(shown(1), ["bworld:salmon 2"]);
// someone joining gets it with the chunk
@@ -112,7 +114,7 @@ Deno.test("what a block shows goes to players with its chunk and when it changes
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 });
assertEquals(loaded.game.world.get_tile(...BOARD)?.client_data?.item, { id: "bworld:salmon", count: 2 });
// breaking it takes it away for everyone
t.game.destroy_block(...BOARD);