Neighbor Updates as a Queue

This commit is contained in:
2026-10-20 13:40:44 -03:00
parent 0af35d1e17
commit 77cd327f94
9 changed files with 348 additions and 138 deletions
+19 -19
View File
@@ -50,23 +50,6 @@ export function receive_mod_message(channel: string, data: unknown) {
} }
} }
// what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts
export let block_rules = new BlockRules(run_mod);
// whether shared scripts are being set up, the only time they can register rules
let rules_setup = false;
// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told
// which blocks have them when the level starts
let client_setup = false;
function run_mod<T>(mod: string, what: string, fn: () => T): T | undefined {
try {
return fn();
} catch (e) {
console.error(`[${mod}] ${what} threw:`, e);
return undefined;
}
}
// the world shared rules see on this client: what it shows. what they change is a guess the server corrects // the world shared rules see on this client: what it shows. what they change is a guess the server corrects
const rules_world: SharedWorld = { const rules_world: SharedWorld = {
get_block(x, y, z) { get_block(x, y, z) {
@@ -105,10 +88,27 @@ const rules_world: SharedWorld = {
}, },
}; };
// what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts
export let block_rules = new BlockRules(run_mod, rules_world.get_block);
// whether shared scripts are being set up, the only time they can register rules
let rules_setup = false;
// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told
// which blocks have them when the level starts
let client_setup = false;
function run_mod<T>(mod: string, what: string, fn: () => T): T | undefined {
try {
return fn();
} catch (e) {
console.error(`[${mod}] ${what} threw:`, e);
return undefined;
}
}
// this client changed the block at x y z ahead of the server, the blocks beside it change with it the way they will // this client changed the block at x y z ahead of the server, the blocks beside it change with it the way they will
// on the server // on the server
export function predict_neighbors(x: number, y: number, z: number) { export function predict_neighbors(x: number, y: number, z: number) {
block_rules.notify_neighbors(rules_world.get_block, x, y, z); block_rules.notify_neighbors(x, y, z);
} }
// the loaded mods' recipes, and their names by id // the loaded mods' recipes, and their names by id
@@ -162,7 +162,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
loading_mod(bmod.manifest.id, bmod.manifest.engine_access ?? false, fn); loading_mod(bmod.manifest.id, bmod.manifest.engine_access ?? false, fn);
// every mod's shared rules first, so client scripts can count on any mod's being there // every mod's shared rules first, so client scripts can count on any mod's being there
block_rules = new BlockRules(run_mod); block_rules = new BlockRules(run_mod, rules_world.get_block);
rules_setup = true; rules_setup = true;
for (const [i, bmod] of bmods.entries()) { for (const [i, bmod] of bmods.entries()) {
const code = bmod.scripts.shared; const code = bmod.scripts.shared;
+79 -24
View File
@@ -9,6 +9,7 @@ import type {
BlockPlacement, BlockPlacement,
BlockRules as Rules, BlockRules as Rules,
Face, Face,
Position,
SharedBlock, SharedBlock,
SharedWorld, SharedWorld,
} from "./mod_api/shared.ts"; } from "./mod_api/shared.ts";
@@ -49,11 +50,25 @@ export function default_placement_value(block: BlockRegistry, yaw: number): numb
return set_state_value(value, block, "facing", toward)!; return set_state_value(value, block, "facing", toward)!;
} }
// the most blocks one change can tell of changes, counting the ones those set off, before the rest are dropped. a
// loop between two rules would otherwise never stop
export const MAX_NEIGHBOR_UPDATES = 65536;
export class BlockRules { export class BlockRules {
#rules = new Map<string, { mod: string; rules: Rules }>(); #rules = new Map<string, { mod: string; rules: Rules }>();
// blocks waiting to hear of a change, 6 numbers each: where the block is, then where the change was
#queue: number[] = [];
// changes going on. the queue waits until they're all done, see change
#changing = 0;
// runs a mod's code, reporting what it throws instead of letting it take the game down // run runs a mod's code, reporting what it throws instead of letting it take the game down. get_block reads the
constructor(readonly run: <T>(mod: string, what: string, fn: () => T) => T | undefined) {} // side's world. told runs for each block told of a change once its rules have, where the server runs its
// components' on_neighbor_change
constructor(
readonly run: <T>(mod: string, what: string, fn: () => T) => T | undefined,
readonly get_block: SharedWorld["get_block"],
readonly told?: (x: number, y: number, z: number, from: Position) => void,
) {}
register(mod: string, id: string, rules: Rules) { register(mod: string, id: string, rules: Rules) {
if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of ${id} are registered twice`); if (this.#rules.has(id)) throw new Error(`[${mod}] the rules of ${id} are registered twice`);
@@ -130,28 +145,68 @@ export class BlockRules {
return handled; return handled;
} }
// tells the blocks beside x y z it changed, so they can change with it like a fence joining it: their rules' // tells the blocks beside x y z it changed, so they can change with it like a fence joining it. the world's
// on_neighbor_change, then after for each, which the server runs its components' on_neighbor_change in. the // set_state calls this again for what they change, until nothing changes. see neighbor_changed
// world's set_state calls this again for what they change, until nothing changes notify_neighbors(x: number, y: number, z: number) {
notify_neighbors( for (const [dx, dy, dz] of NEIGHBORS) this.#queue.push(x + dx, y + dy, z + dz, x, y, z);
get_block: SharedWorld["get_block"], this.#settle();
x: number, }
y: number,
z: number, // tells the block at x y z the one at from changed: its rules' on_neighbor_change, then told. blocks hear in the
after?: (x: number, y: number, z: number, neighbor: SharedBlock) => void, // order they were told, the same on every side, once the change that told them is done. a queue instead of
) { // calling them right away, so a long chain of changes doesn't grow the stack
const neighbor = { x, y, z, id: get_block(x, y, z) ?? "bworld:air" }; neighbor_changed(x: number, y: number, z: number, from: Position) {
for (const [dx, dy, dz] of NEIGHBORS) { this.#queue.push(x, y, z, from.x, from.y, from.z);
const [nx, ny, nz] = [x + dx, y + dy, z + dz]; this.#settle();
const id = get_block(nx, ny, nz); }
const block = id && EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) continue; // runs a change to the world, holding back the blocks it tells until it's done, so they hear of all of it: one
for (const { mod, id: rules_id, rules, params } of this.#of(block)) { // told in a block's on_break hears once it's gone. the outermost change tells them all before it returns, so its
if (!rules.on_neighbor_change) continue; // caller sees a settled world
const at = { x: nx, y: ny, z: nz, id }; change<T>(fn: () => T): T {
this.run(mod, `${rules_id} on_neighbor_change`, () => rules.on_neighbor_change!(at, params, neighbor)); this.#changing++;
} try {
after?.(nx, ny, nz, neighbor); return fn();
} finally {
this.#changing--;
this.#settle();
} }
} }
// tells the blocks waiting, and the ones they set off, unless a change is still going on
#settle() {
if (this.#changing > 0) return;
this.#changing++;
const queue = this.#queue;
try {
for (let i = 0; i < queue.length; i += 6) {
if (i === MAX_NEIGHBOR_UPDATES * 6) {
console.warn(
`one change told blocks of changes ${MAX_NEIGHBOR_UPDATES} times and was stopped, last the ` +
`block at ${queue[i - 6]} ${queue[i - 5]} ${queue[i - 4]}`,
);
break;
}
this.#tell(queue[i], queue[i + 1], queue[i + 2], { x: queue[i + 3], y: queue[i + 4], z: queue[i + 5] });
}
} finally {
queue.length = 0;
this.#changing--;
}
}
#tell(x: number, y: number, z: number, from: Position) {
const id = this.get_block(x, y, z);
const block = id && EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) return;
// what's there now, read only for rules that want it
let neighbor: SharedBlock | undefined;
for (const { mod, id: rules_id, rules, params } of this.#of(block)) {
if (!rules.on_neighbor_change) continue;
const changed = neighbor ??= { ...from, id: this.get_block(from.x, from.y, from.z) ?? "bworld:air" };
const at = { x, y, z, id };
this.run(mod, `${rules_id} on_neighbor_change`, () => rules.on_neighbor_change!(at, params, changed));
}
this.told?.(x, y, z, from);
}
} }
+12 -1
View File
@@ -248,7 +248,13 @@ export interface ServerWorld {
// destroyBlockProgress: a drill getting through it. undefined takes them off, and so does the block changing // destroyBlockProgress: a drill getting through it. undefined takes them off, and so does the block changing
set_break_progress(x: number, y: number, z: number, progress: number | undefined): void; set_break_progress(x: number, y: number, z: number, progress: number | undefined): void;
get_state(x: number, y: number, z: number, name: string): number | undefined; 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; // update_neighbors false changes the state without telling the blocks around it, for a script that tells them
// itself, like a wire telling each block beside its whole length once. on_state_change still runs
set_state(x: number, y: number, z: number, name: string, value: number, options?: SetStateOptions): boolean;
// tells the block at x y z that the one at from changed, running its rules' and components' on_neighbor_change,
// like neoforge's neighborChanged. for a block whose effect on others changed without it changing, or for blocks
// it reaches that aren't beside it. it hears once the change going on is done, like the blocks beside one do
neighbor_changed(x: number, y: number, z: number, from: Position): void;
// whether the block's side is a full square things can attach to, like minecraft's isFaceSturdy: its collision // whether the block's side is a full square things can attach to, like minecraft's isFaceSturdy: its collision
// shape covers the whole face. false for air, plants, water and the sides of a slab // shape covers the whole face. false for air, plants, water and the sides of a slab
is_face_sturdy(x: number, y: number, z: number, face: Face): boolean; is_face_sturdy(x: number, y: number, z: number, face: Face): boolean;
@@ -301,6 +307,11 @@ export interface ServerWorld {
set_time(time: number): void; set_time(time: number): void;
} }
export interface SetStateOptions {
// true when not given
update_neighbors?: boolean;
}
// how a machine breaks a block, see ServerWorld.break_block // how a machine breaks a block, see ServerWorld.break_block
export interface BreakOptions { export interface BreakOptions {
// it drops what it would for the right tool, though nothing holds one, like create's drills and saws // it drops what it would for the right tool, though nothing holds one, like create's drills and saws
+19
View File
@@ -99,6 +99,23 @@ ctx.components.register_block("copper_tools:bell", {
}); });
``` ```
The blocks beside one that changed don't hear of it while the change is going on. They wait in a queue and hear in the
order they were told, once the change is done, along with the ones they set off. The world is settled again by the time
the outermost change returns, so a script that places a fence in `on_tick` sees it joined right after. One that places
it in `on_neighbor_change`, which runs while another change is settling, sees it joined once that's done. Blocks a
handler tells while its block is being broken, in `on_break`, hear once it's gone. A change can tell blocks 65,536 times
before it's stopped and the server logs where, so blocks that keep setting each other off can't hang the server.
Two more things in `ctx.world` are for blocks that tell others themselves:
- `ctx.world.neighbor_changed(x, y, z, from)` tells the block at `x y z` that the one at `from` changed, running its
rules' and components' `on_neighbor_change`, like NeoForge's `neighborChanged`. It's for a block whose effect on
others changed without it changing, or for blocks it reaches that aren't beside it, like the far end of something it's
joined to.
- `ctx.world.set_state(x, y, z, name, value, { update_neighbors: false })` changes a state without telling the blocks
around it, for a script that tells them itself, so a long line of blocks changing together tells each block beside it
once instead of once per block. `on_state_change` still runs.
## Rules ## Rules
A component's rules decide a block's states from where it's placed, what's around it and being right clicked. They're A component's rules decide a block's states from where it's placed, what's around it and being right clicked. They're
@@ -135,6 +152,8 @@ the axle of the block it's placed against.
`on_neighbor_change` is how a block keeps up with what's around it, like Minecraft's `updateShape`: `neighbor` is `on_neighbor_change` is how a block keeps up with what's around it, like Minecraft's `updateShape`: `neighbor` is
`{ x, y, z, id }` of the block that changed. A fence sets its `north`, `east`, `south` and `west` states from it. `{ x, y, z, id }` of the block that changed. A fence sets its `north`, `east`, `south` and `west` states from it.
Setting a state to what it already is changes nothing and tells no one, so blocks answering each other this way settle. Setting a state to what it already is changes nothing and tells no one, so blocks answering each other this way settle.
The blocks a change tells hear of it one after another, in the same order on the server and on clients, once the change
is done (see [Changes](#changes)).
`ctx.world.is_face_sturdy(x, y, z, face)` says whether a block's side is something to attach to, like Minecraft's `ctx.world.is_face_sturdy(x, y, z, face)` says whether a block's side is something to attach to, like Minecraft's
`isFaceSturdy`: its [collision shape](../resources/models.md#collision-shapes) covers the whole side. Stone's sides are, `isFaceSturdy`: its [collision shape](../resources/models.md#collision-shapes) covers the whole side. Stone's sides are,
+2 -1
View File
@@ -31,7 +31,8 @@ ctx.world.set_state(x, y, z, "age", age + 1);
`get_state` is `undefined` where there's no block, and `set_state` does nothing there and returns `false`. Both throw `get_state` is `undefined` where there's no block, and `set_state` does nothing there and returns `false`. Both throw
for a state the block doesn't have, and `set_state` for a value that doesn't fit its bits. Changes are synced to for a state the block doesn't have, and `set_state` for a value that doesn't fit its bits. Changes are synced to
everyone who can see the block. Unlike `set_block`, it doesn't run `on_break` or `on_create`, and the block keeps its everyone who can see the block. Unlike `set_block`, it doesn't run `on_break` or `on_create`, and the block keeps its
tile data. It runs the block's [`on_state_change`](components.md#changes) instead. tile data. It runs the block's [`on_state_change`](components.md#changes) instead, and tells the blocks beside it,
unless it's given `{ update_neighbors: false }`.
## Variants ## Variants
+47 -62
View File
@@ -582,87 +582,72 @@ export class GameServer {
} }
// changes a block's state bits without replacing it, see ServerWorld.get_block_value: its on_state_change, then the // changes a block's state bits without replacing it, see ServerWorld.get_block_value: its on_state_change, then the
// blocks beside it hear of it // blocks beside it hear of it, unless update_neighbors is false
set_block_state(x: number, y: number, z: number, state: number) { set_block_state(x: number, y: number, z: number, state: number, update_neighbors = true) {
const id = this.world.get_block_id(x, y, z); const id = this.world.get_block_id(x, y, z);
const value = this.world.get_block_value(x, y, z); const value = this.world.get_block_value(x, y, z);
if (id === AIR_ID || value >>> 16 === state) return; if (id === AIR_ID || value >>> 16 === state) return;
const components = this.mods.components_with(id, "on_state_change"); this.mods.rules.change(() => {
// only worked out for blocks that want it, states change often const components = this.mods.components_with(id, "on_state_change");
const before = components.length > 0 ? block_states(value, this.world.get_block_info(x, y, z)!) : undefined; // only worked out for blocks that want it, states change often
this.world.set_block(x, y, z, id, state); const before = components.length > 0 ? block_states(value, this.world.get_block_info(x, y, z)!) : undefined;
if (before) { this.world.set_block(x, y, z, id, state);
const block = this.mods.block_ref(x, y, z, id); if (before) {
for (const { mod, id: component_id, component, params } of components) { const block = this.mods.block_ref(x, y, z, id);
run_guarded(
mod,
`${component_id} on_state_change`,
() => component.on_state_change!(block, params, before),
);
}
}
this.#notify_neighbors(x, y, z);
}
// tells the blocks around one that changed, so they can change with it like a fence joining it: their rules (see
// BlockRules), then their components' on_neighbor_change
#notify_neighbors(x: number, y: number, z: number) {
this.mods.rules.notify_neighbors(
(bx, by, bz) => this.world.get_block_id(bx, by, bz),
x,
y,
z,
(nx, ny, nz, neighbor) => {
// read again, a rule's state change can have had a component replace it
const id = this.world.get_block_id(nx, ny, nz);
const components = this.mods.components_with(id, "on_neighbor_change");
if (components.length === 0) return;
const block = this.mods.block_ref(nx, ny, nz, id);
for (const { mod, id: component_id, component, params } of components) { for (const { mod, id: component_id, component, params } of components) {
run_guarded( run_guarded(
mod, mod,
`${component_id} on_neighbor_change`, `${component_id} on_state_change`,
() => component.on_neighbor_change!(block, params, neighbor), () => component.on_state_change!(block, params, before),
); );
} }
}, }
); if (update_neighbors) this.mods.rules.notify_neighbors(x, y, z);
});
} }
// replaces a block: the old one's on_break, then the new one's on_create, then the blocks beside it hear of it
set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) { set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) {
const old_id = this.world.get_block_id(x, y, z); this.mods.rules.change(() => {
if (this.#break_stages.size > 0) this.set_break_progress(x, y, z, undefined); const old_id = this.world.get_block_id(x, y, z);
if (old_id !== AIR_ID) { if (this.#break_stages.size > 0) this.set_break_progress(x, y, z, undefined);
const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break); if (old_id !== AIR_ID) {
if (components.length > 0) { const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break);
const block = this.mods.block_ref(x, y, z, old_id); if (components.length > 0) {
const player_api = player && this.mods.player(player); const block = this.mods.block_ref(x, y, z, old_id);
for (const { mod, id: component_id, component, params } of components) { const player_api = player && this.mods.player(player);
run_guarded(mod, `${component_id} on_break`, () => component.on_break!(block, params, player_api)); for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_break`,
() => component.on_break!(block, params, player_api),
);
}
} }
} }
}
this.world.remove_tile(x, y, z); this.world.remove_tile(x, y, z);
this.world.set_block(x, y, z, id, state); this.world.set_block(x, y, z, id, state);
if (id !== AIR_ID) { if (id !== AIR_ID) {
const block = this.mods.block_ref(x, y, z, id); const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of this.mods.components_of(id)) { for (const { mod, id: component_id, component, params } of this.mods.components_of(id)) {
if (component.on_create) { if (component.on_create) {
run_guarded(mod, `${component_id} on_create`, () => component.on_create!(block, params)); run_guarded(mod, `${component_id} on_create`, () => component.on_create!(block, params));
}
} }
} }
} this.mods.rules.notify_neighbors(x, y, z);
this.#notify_neighbors(x, y, z);
// a block standing on this one that can't stand on what it is now breaks, like a crop on farmland that was dug // a block standing on this one that can't stand on what it is now breaks, like a crop on farmland that was
if (y + 1 < CHUNK_HEIGHT) { // dug
const above = this.world.get_block_info(x, y + 1, z); if (y + 1 < CHUNK_HEIGHT) {
if (above && !can_stand_on(above, id)) { const above = this.world.get_block_info(x, y + 1, z);
this.destroy_block(x, y + 1, z, player); if (above && !can_stand_on(above, id)) {
this.destroy_block(x, y + 1, z, player);
}
} }
} });
} }
// the cracks machines are making on blocks, as the stage clients draw, by position. see set_break_progress // the cracks machines are making on blocks, as the stage clients draw, by position. see set_break_progress
+30 -4
View File
@@ -34,6 +34,7 @@ import type {
MenuType, MenuType,
Player, Player,
PlayerMenuBuilder, PlayerMenuBuilder,
Position,
ServerAfterEvents, ServerAfterEvents,
ServerBeforeEvents, ServerBeforeEvents,
ServerContext, ServerContext,
@@ -143,8 +144,12 @@ interface Timer {
export class ModRuntime { export class ModRuntime {
block_components = new Map<string, { mod: string; component: BlockComponent }>(); block_components = new Map<string, { mod: string; component: BlockComponent }>();
// what shared scripts registered, see common/block_rules.ts // what shared scripts registered, see common/block_rules.ts, running on the game's world
rules = new BlockRules(run_guarded); rules = new BlockRules(
run_guarded,
(x, y, z) => this.game.world.get_block_id(x, y, z),
(x, y, z, from) => this.#neighbor_changed(x, y, z, from),
);
item_components = new Map<string, { mod: string; component: ItemComponent }>(); item_components = new Map<string, { mod: string; component: ItemComponent }>();
effect_components = new Map<string, { mod: string; component: EffectComponent }>(); effect_components = new Map<string, { mod: string; component: EffectComponent }>();
// every command, the engine's and mods', see common/commands.ts // every command, the engine's and mods', see common/commands.ts
@@ -492,6 +497,25 @@ export class ModRuntime {
} }
#components_with = new Map<keyof BlockComponent, Map<string, BlockComponentOf[]>>(); #components_with = new Map<keyof BlockComponent, Map<string, BlockComponentOf[]>>();
// the block at x y z was told the one at from changed, and its rules have had their say: its components'
// on_neighbor_change
#neighbor_changed(x: number, y: number, z: number, from: Position) {
const world = this.game.world;
// read again, a rule's state change can have had a component replace it
const id = world.get_block_id(x, y, z);
const components = this.components_with(id, "on_neighbor_change");
if (components.length === 0) return;
const block = this.block_ref(x, y, z, id);
const neighbor = { ...from, id: world.get_block_id(from.x, from.y, from.z) };
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_neighbor_change`,
() => component.on_neighbor_change!(block, params, neighbor),
);
}
}
// components on an item, with their params from its json // components on an item, with their params from its json
item_components_of(item_id: string): { mod: string; id: string; component: ItemComponent; params: unknown }[] { item_components_of(item_id: string): { mod: string; id: string; component: ItemComponent; params: unknown }[] {
const item = EverythingRegistry.get<ItemRegistry>("items", item_id); const item = EverythingRegistry.get<ItemRegistry>("items", item_id);
@@ -708,7 +732,7 @@ export class ModRuntime {
const info = state_owner(id, name); const info = state_owner(id, name);
return get_state_value(game().world.get_block_value(x, y, z), info, name); return get_state_value(game().world.get_block_value(x, y, z), info, name);
}, },
set_state: (x, y, z, name, value) => { set_state: (x, y, z, name, value, options) => {
const id = game().world.get_block_id(x, y, z); const id = game().world.get_block_id(x, y, z);
if (id === AIR_ID) return false; if (id === AIR_ID) return false;
const info = state_owner(id, name); const info = state_owner(id, name);
@@ -717,9 +741,11 @@ export class ModRuntime {
throw new Error(`${id} state "${name}" has ${bits} bits, ${value} doesn't fit`); throw new Error(`${id} state "${name}" has ${bits} bits, ${value} doesn't fit`);
} }
const new_value = set_state_value(game().world.get_block_value(x, y, z), info, name, value)!; const new_value = set_state_value(game().world.get_block_value(x, y, z), info, name, value)!;
game().set_block_state(x, y, z, new_value >>> 16); game().set_block_state(x, y, z, new_value >>> 16, options?.update_neighbors !== false);
return true; return true;
}, },
neighbor_changed: (x, y, z, from) =>
this.rules.neighbor_changed(x, y, z, { x: from.x, y: from.y, z: from.z }),
is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face), is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face),
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never, get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
get_block_ref: (x, y, z) => { get_block_ref: (x, y, z) => {
+136 -23
View File
@@ -2,23 +2,28 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// the server's side of a block hearing about changes: its components' on_neighbor_change, after the shared rules, and // the server's side of a block hearing about changes: its components' on_neighbor_change, after the shared rules, and
// on_state_change when its own states change // on_state_change when its own states change. blocks hear of changes through a queue, once the change is done
import { assertEquals } from "@std/assert"; import { assert, assertEquals } from "@std/assert";
import { AIR_ID } from "$/common/protocol.ts"; import { AIR_ID } from "$/common/protocol.ts";
import { MAX_NEIGHBOR_UPDATES } from "$/common/block_rules.ts";
import { get_state_value } from "$/common/utils.ts";
import type { GameServer } from "$/server/game/game_server.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts"; import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SERVER_SCRIPT = ` const SERVER_SCRIPT = `
import type { ServerContext } from "bworld/server"; import type { ServerContext } from "bworld/server";
export function setup(ctx: ServerContext) { export function setup(ctx: ServerContext) {
const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get<unknown[]>("log") ?? [], event]); const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get<unknown[]>("log") ?? [], event]);
const at = ({ x, y, z }: { x: number; y: number; z: number }) => x + " " + y + " " + z;
ctx.components.register_block("testmod:watcher", { ctx.components.register_block("testmod:watcher", {
on_neighbor_change(block, _params, neighbor) { on_neighbor_change(block, _params, neighbor) {
const seen = ctx.world.get_state(block.x, block.y, block.z, "seen"); const seen = ctx.world.get_state(block.x, block.y, block.z, "seen");
log(["neighbor", neighbor.id, neighbor.x, neighbor.y, neighbor.z, seen]); log(["neighbor", at(block), neighbor.id, at(neighbor), seen]);
}, },
on_state_change(block, _params, before) { on_state_change(block, _params, before) {
const { x, y, z } = block; const { x, y, z } = block;
log(["state", before, { seen: ctx.world.get_state(x, y, z, "seen"), count: ctx.world.get_state(x, y, z, "count") }]); const now = { seen: ctx.world.get_state(x, y, z, "seen"), count: ctx.world.get_state(x, y, z, "count") };
log(["state", at(block), before, now]);
}, },
}); });
// hangs from the block above and falls when it's gone, which only a server handler can do // hangs from the block above and falls when it's gone, which only a server handler can do
@@ -29,20 +34,50 @@ export function setup(ctx: ServerContext) {
} }
}, },
}); });
// tells the block two to the east when it's broken, which isn't beside it
ctx.components.register_block("testmod:tether", {
on_break(block) { ctx.world.neighbor_changed(block.x + 2, block.y, block.z, block); },
});
ctx.commands.register("state", { ctx.commands.register("state", {
description: "", usage: "", description: "", usage: "",
run([x, y, z, name, value]) { ctx.world.set_state(Number(x), Number(y), Number(z), name, Number(value)); }, run([x, y, z, name, value, quiet]) {
const options = quiet === "quiet" ? { update_neighbors: false } : undefined;
ctx.world.set_state(Number(x), Number(y), Number(z), name, Number(value), options);
},
});
ctx.commands.register("tell", {
description: "", usage: "",
run(args) {
const [x, y, z, fx, fy, fz] = args.map(Number);
ctx.world.neighbor_changed(x, y, z, { x: fx, y: fy, z: fz });
},
}); });
} }
`; `;
// marks the watcher once anything beside it changes
const SHARED_SCRIPT = ` const SHARED_SCRIPT = `
import type { SharedContext } from "bworld/shared"; import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) { export function setup(ctx: SharedContext) {
// marks the watcher once anything beside it changes
ctx.components.register_block("testmod:watcher", { ctx.components.register_block("testmod:watcher", {
on_neighbor_change(block) { ctx.world.set_state(block.x, block.y, block.z, "seen", 1); }, on_neighbor_change(block) { ctx.world.set_state(block.x, block.y, block.z, "seen", 1); },
}); });
// passes a count back and forth with a relay beside it, one higher each time, up to 10000
ctx.components.register_block("testmod:relay", {
on_neighbor_change(block, _params, neighbor) {
if (neighbor.id !== "testmod:relay") return;
const theirs = ctx.world.get_state(neighbor.x, neighbor.y, neighbor.z, "count")!;
const mine = ctx.world.get_state(block.x, block.y, block.z, "count")!;
if (theirs >= mine && theirs < 10000) ctx.world.set_state(block.x, block.y, block.z, "count", theirs + 1);
},
});
// flips whenever anything beside it changes, so two side by side never stop
ctx.components.register_block("testmod:flipper", {
on_neighbor_change(block) {
const on = ctx.world.get_state(block.x, block.y, block.z, "on")!;
ctx.world.set_state(block.x, block.y, block.z, "on", 1 - on);
},
});
} }
`; `;
@@ -60,18 +95,22 @@ function test_mods() {
dependencies: [{ id: "bworld", version: "*" }], dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" }, scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" },
}); });
const block = (id: string, extra: Record<string, unknown>) => ({ const block = (name: string, states: unknown[] = []) =>
format_version: 1, write(`blocks/${name}.json`, {
block: { id, textures: "bworld:stone", mining: { toughness: 1 }, ...extra }, format_version: 1,
}); block: {
write( id: `testmod:${name}`,
"blocks/watcher.json", textures: "bworld:stone",
block("testmod:watcher", { mining: { toughness: 1 },
states: [{ name: "seen", bits: 1, default: 0 }, { name: "count", bits: 4, default: 0 }], states,
components: { "testmod:watcher": {} }, components: { [`testmod:${name}`]: {} },
}), },
); });
write("blocks/lantern.json", block("testmod:lantern", { components: { "testmod:lantern": {} } })); block("watcher", [{ name: "seen", bits: 1, default: 0 }, { name: "count", bits: 4, default: 0 }]);
block("lantern");
block("tether");
block("relay", [{ name: "count", bits: 14, default: 0 }]);
block("flipper", [{ name: "on", bits: 1, default: 0 }]);
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT); Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT); Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT);
return dir; return dir;
@@ -94,6 +133,10 @@ async function setup() {
return { game, log, command, cleanup }; return { game, log, command, cleanup };
} }
function state(game: GameServer, x: number, y: number, z: number, name: string) {
return get_state_value(game.world.get_block_value(x, y, z), game.world.get_block_info(x, y, z)!, name);
}
Deno.test("a component's on_neighbor_change runs after the block's rules, and can change the world", async () => { Deno.test("a component's on_neighbor_change runs after the block's rules, and can change the world", async () => {
const { game, log, cleanup } = await setup(); const { game, log, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:watcher"); game.set_block(0, 100, 0, "testmod:watcher");
@@ -101,12 +144,12 @@ Deno.test("a component's on_neighbor_change runs after the block's rules, and ca
game.set_block(1, 100, 0, "bworld:stone"); game.set_block(1, 100, 0, "bworld:stone");
assertEquals(log(), [ assertEquals(log(), [
["state", { seen: 0, count: 0 }, { seen: 1, count: 0 }], ["state", "0 100 0", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
// the rule had marked it already // the rule had marked it already
["neighbor", "bworld:stone", 1, 100, 0, 1], ["neighbor", "0 100 0", "bworld:stone", "1 100 0", 1],
]); ]);
game.set_block(1, 100, 0, AIR_ID); game.set_block(1, 100, 0, AIR_ID);
assertEquals(log(), [["neighbor", AIR_ID, 1, 100, 0, 1]], "the block that changed is what's there now"); assertEquals(log(), [["neighbor", "0 100 0", AIR_ID, "1 100 0", 1]], "the block that changed is what's there now");
game.set_block(3, 101, 0, "bworld:stone"); game.set_block(3, 101, 0, "bworld:stone");
game.set_block(3, 100, 0, "testmod:lantern"); game.set_block(3, 100, 0, "testmod:lantern");
@@ -123,13 +166,13 @@ Deno.test("on_state_change gets the states from before, when a script or a rule
log(); log();
command("/state 0 100 0 count 3"); command("/state 0 100 0 count 3");
assertEquals(log(), [["state", { seen: 0, count: 0 }, { seen: 0, count: 3 }]]); assertEquals(log(), [["state", "0 100 0", { seen: 0, count: 0 }, { seen: 0, count: 3 }]]);
command("/state 0 100 0 count 3"); command("/state 0 100 0 count 3");
assertEquals(log(), [], "setting a state to what it is changes nothing"); assertEquals(log(), [], "setting a state to what it is changes nothing");
// a rule // a rule
game.set_block(0, 101, 0, "bworld:stone"); game.set_block(0, 101, 0, "bworld:stone");
assertEquals(log()[0], ["state", { seen: 0, count: 3 }, { seen: 1, count: 3 }]); assertEquals(log()[0], ["state", "0 100 0", { seen: 0, count: 3 }, { seen: 1, count: 3 }]);
// replacing it is a new block, not a state change // replacing it is a new block, not a state change
game.set_block(0, 100, 0, "testmod:watcher"); game.set_block(0, 100, 0, "testmod:watcher");
@@ -137,3 +180,73 @@ Deno.test("on_state_change gets the states from before, when a script or a rule
assertEquals(game.world.get_block_value(0, 100, 0) >>> 16, 0); assertEquals(game.world.get_block_value(0, 100, 0) >>> 16, 0);
cleanup(); cleanup();
}); });
Deno.test("a script can tell any block of a change, and one told in on_break hears once the block is gone", async () => {
const { game, log, command, cleanup } = await setup();
game.set_block(2, 100, 0, "testmod:watcher");
game.set_block(0, 100, 0, "testmod:tether");
log();
game.set_block(0, 100, 0, AIR_ID);
assertEquals(log(), [
// its rule and its component heard
["state", "2 100 0", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
["neighbor", "2 100 0", AIR_ID, "0 100 0", 1],
]);
// right away, when nothing else is changing
command("/tell 2 100 0 2 100 5");
assertEquals(log(), [["neighbor", "2 100 0", "bworld:air", "2 100 5", 1]]);
cleanup();
});
Deno.test("update_neighbors false changes a state without telling anyone, but on_state_change runs", async () => {
const { game, log, command, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:watcher");
game.set_block(1, 100, 0, "testmod:watcher");
log();
command("/state 0 100 0 count 5 quiet");
assertEquals(log(), [["state", "0 100 0", { seen: 1, count: 0 }, { seen: 1, count: 5 }]]);
command("/state 0 100 0 count 6");
assert(
log().some((event) =>
JSON.stringify(event) === JSON.stringify(["neighbor", "1 100 0", "testmod:watcher", "0 100 0", 1])
),
);
cleanup();
});
Deno.test("a chain of 10000 changes, each setting off the next, runs to the end", async () => {
const { game, cleanup } = await setup();
game.set_block(0, 100, 0, "testmod:relay");
game.set_block(1, 100, 0, "testmod:relay");
const counts = [state(game, 0, 100, 0, "count")!, state(game, 1, 100, 0, "count")!];
assertEquals(Math.max(...counts), 10000);
assertEquals(Math.min(...counts), 9999);
cleanup();
});
Deno.test("blocks that keep setting each other off are stopped, and the server says where", async () => {
const { game, log, cleanup } = await setup();
const warn = console.warn;
const warnings: string[] = [];
console.warn = (...args: unknown[]) => warnings.push(args.join(" "));
try {
game.set_block(0, 100, 0, "testmod:flipper");
game.set_block(1, 100, 0, "testmod:flipper");
} finally {
console.warn = warn;
}
assertEquals(warnings.length, 1);
assert(warnings[0].includes(String(MAX_NEIGHBOR_UPDATES)), warnings[0]);
const [x, y, z] = warnings[0].match(/at (-?\d+) (-?\d+) (-?\d+)/)!.slice(1).map(Number);
assert(Math.abs(x - 0.5) <= 1.5 && Math.abs(y - 100) <= 1 && Math.abs(z) <= 1, "beside the flippers");
// the next change goes as usual
game.set_block(0, 100, 3, "testmod:watcher");
log();
game.set_block(1, 100, 3, "bworld:stone");
assertEquals(log().length, 2);
cleanup();
});
+4 -4
View File
@@ -46,7 +46,7 @@ function client_of(t: Game) {
const at = (x: number, y: number, z: number) => copy.get(`${x} ${y} ${z}`); const at = (x: number, y: number, z: number) => copy.get(`${x} ${y} ${z}`);
const info = (id: string) => EverythingRegistry.get<BlockRegistry>("blocks", id); const info = (id: string) => EverythingRegistry.get<BlockRegistry>("blocks", id);
const rules = new BlockRules((_mod, _what, fn) => fn()); const rules = new BlockRules((_mod, _what, fn) => fn(), (x, y, z) => at(x, y, z)?.[0]);
const world: SharedWorld = { const world: SharedWorld = {
get_block: (x, y, z) => at(x, y, z)?.[0], get_block: (x, y, z) => at(x, y, z)?.[0],
get_state(x, y, z, name) { get_state(x, y, z, name) {
@@ -61,7 +61,7 @@ function client_of(t: Game) {
const changed = set_state_value(state << 16, block, name, value)! >>> 16; const changed = set_state_value(state << 16, block, name, value)! >>> 16;
if (changed !== state) { if (changed !== state) {
copy.set(`${x} ${y} ${z}`, [id, changed]); copy.set(`${x} ${y} ${z}`, [id, changed]);
rules.notify_neighbors(world.get_block, x, y, z); rules.notify_neighbors(x, y, z);
} }
return true; return true;
}, },
@@ -90,7 +90,7 @@ function client_of(t: Game) {
place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) { place(id: string, x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
const value = rules.placement_value(info(id)!, yaw, 0, { x, y, z, face, hit, sneaking: false }); const value = rules.placement_value(info(id)!, yaw, 0, { x, y, z, face, hit, sneaking: false });
copy.set(`${x} ${y} ${z}`, [id, value! >>> 16]); copy.set(`${x} ${y} ${z}`, [id, value! >>> 16]);
rules.notify_neighbors(world.get_block, x, y, z); rules.notify_neighbors(x, y, z);
}, },
// what game_mode does when this client right clicks face of x y z, at hit. whether the rules did something // what game_mode does when this client right clicks face of x y z, at hit. whether the rules did something
interact(x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) { interact(x: number, y: number, z: number, yaw: number, face: Face, hit: [number, number, number]) {
@@ -98,7 +98,7 @@ function client_of(t: Game) {
}, },
break(x: number, y: number, z: number) { break(x: number, y: number, z: number) {
copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]); copy.set(`${x} ${y} ${z}`, [AIR_ID, 0]);
rules.notify_neighbors(world.get_block, x, y, z); rules.notify_neighbors(x, y, z);
}, },
blocks: () => blocks_in((x, y, z) => at(x, y, z)!), blocks: () => blocks_in((x, y, z) => at(x, y, z)!),
}; };