New hooks
This commit is contained in:
+18
-3
@@ -4,7 +4,14 @@
|
||||
// the block rules shared scripts register (see BlockRules in mod_api/shared.ts), run the same way on the server and on
|
||||
// clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own
|
||||
// BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with
|
||||
import type { BlockInteraction, BlockPlacement, BlockRules as Rules, Face, SharedWorld } from "./mod_api/shared.ts";
|
||||
import type {
|
||||
BlockInteraction,
|
||||
BlockPlacement,
|
||||
BlockRules as Rules,
|
||||
Face,
|
||||
SharedBlock,
|
||||
SharedWorld,
|
||||
} from "./mod_api/shared.ts";
|
||||
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
|
||||
import { default_block_value, set_state_value } from "./utils.ts";
|
||||
|
||||
@@ -124,8 +131,15 @@ export class BlockRules {
|
||||
}
|
||||
|
||||
// tells the blocks beside x y z it changed, so they can change with it like a fence joining it: their rules'
|
||||
// on_neighbor_change. the world's set_state calls this again for what they change, until nothing changes
|
||||
notify_neighbors(get_block: SharedWorld["get_block"], x: number, y: number, z: number) {
|
||||
// on_neighbor_change, then after for each, which the server runs its components' on_neighbor_change in. the
|
||||
// world's set_state calls this again for what they change, until nothing changes
|
||||
notify_neighbors(
|
||||
get_block: SharedWorld["get_block"],
|
||||
x: number,
|
||||
y: number,
|
||||
z: number,
|
||||
after?: (x: number, y: number, z: number, neighbor: SharedBlock) => void,
|
||||
) {
|
||||
const neighbor = { x, y, z, id: get_block(x, y, z) ?? "bworld:air" };
|
||||
for (const [dx, dy, dz] of NEIGHBORS) {
|
||||
const [nx, ny, nz] = [x + dx, y + dy, z + dz];
|
||||
@@ -137,6 +151,7 @@ export class BlockRules {
|
||||
const at = { x: nx, y: ny, z: nz, id };
|
||||
this.run(mod, `${rules_id} on_neighbor_change`, () => rules.on_neighbor_change!(at, params, neighbor));
|
||||
}
|
||||
after?.(nx, ny, nz, neighbor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +71,13 @@ export interface BlockComponent<P = any> {
|
||||
on_second?(block: BlockRef, params: P, dt: number): void;
|
||||
// every morning at 06:00, for every block with data in the world, near a player or not. day is ServerWorld.day
|
||||
on_new_day?(block: BlockRef, params: P, day: number): void;
|
||||
// a block on one of its 6 sides was placed, broken or changed its states, like neoforge's neighborChanged. after
|
||||
// the shared rules' on_neighbor_change, so it sees what they changed, and can do what rules can't: read tile data,
|
||||
// change other blocks. neighbor is where, and what's there now
|
||||
on_neighbor_change?(block: BlockRef, params: P, neighbor: { readonly id: Id } & Position): void;
|
||||
// its own states changed without it being replaced, by set_state or a rule, like a clutch another mod powers.
|
||||
// before is what they were. it runs right away, before the blocks beside it hear of the change
|
||||
on_state_change?(block: BlockRef, params: P, before: Readonly<Record<string, number>>): void;
|
||||
// placing and neighbor rules are in shared scripts, see BlockRules in bworld/shared
|
||||
}
|
||||
|
||||
|
||||
@@ -59,21 +59,46 @@ component.
|
||||
|
||||
## Handlers
|
||||
|
||||
| Handler | Called when | Returns |
|
||||
| ------------------------------------ | ----------------------------------------------------------------- | -------------------------- |
|
||||
| `on_create(block, params)` | The block is placed or set, by a player or a script. | |
|
||||
| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | |
|
||||
| `on_click(block, params, player)` | A player starts hitting it. | |
|
||||
| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something |
|
||||
| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | |
|
||||
| `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. | |
|
||||
| Handler | Called when | Returns |
|
||||
| --------------------------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------- |
|
||||
| `on_create(block, params)` | The block is placed or set, by a player or a script. | |
|
||||
| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | |
|
||||
| `on_click(block, params, player)` | A player starts hitting it. | |
|
||||
| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something |
|
||||
| `on_tick(block, params, dt)` | Every tick, 20 times a second, near a player. | |
|
||||
| `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. | |
|
||||
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. See [Changes](#changes). | |
|
||||
| `on_state_change(block, params, before)` | Its own states change without it being replaced, by `set_state` or a rule. See [Changes](#changes). | |
|
||||
|
||||
`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.
|
||||
|
||||
### Changes
|
||||
|
||||
`on_neighbor_change` is the server's side of the [rule](#neighbors) with the same name, like NeoForge's
|
||||
`neighborChanged`: `neighbor` is `{ x, y, z, id }` of the block that changed. It runs after the block's rules have had
|
||||
their say, so it sees the states they set, and it can do what rules can't, like reading tile data or breaking the block
|
||||
when what it hangs from is gone. A block whose states follow from its neighbors, like a fence, uses the rule instead, so
|
||||
clients see it change right away.
|
||||
|
||||
`on_state_change` runs when the block's states change and it stays the same block: a script's `ctx.world.set_state`, a
|
||||
rule, a liquid's level. `before` is every state as it was, by name, and `ctx.world.get_state` gives what they are now.
|
||||
It's how a block reacts to a state something else sets on it, like a machine another mod's script turns off. It runs
|
||||
right away, before the blocks beside it are told, like `on_create`. Replacing the block with `set_block` runs `on_break`
|
||||
and `on_create` instead, and setting a state to what it already is runs nothing.
|
||||
|
||||
```ts
|
||||
ctx.components.register_block("copper_tools:bell", {
|
||||
on_state_change(block, _params, before) {
|
||||
const rung = ctx.world.get_state(block.x, block.y, block.z, "rung");
|
||||
if (rung === 1 && before.rung === 0) ring(block);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## 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
|
||||
|
||||
@@ -31,7 +31,7 @@ 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
|
||||
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
|
||||
tile data.
|
||||
tile data. It runs the block's [`on_state_change`](components.md#changes) instead.
|
||||
|
||||
## Variants
|
||||
|
||||
|
||||
@@ -581,18 +581,52 @@ export class GameServer {
|
||||
this.world.dirty = true;
|
||||
}
|
||||
|
||||
// changes a block's state bits without anything else happening, see ServerWorld.get_block_value
|
||||
// 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
|
||||
set_block_state(x: number, y: number, z: number, state: number) {
|
||||
const id = this.world.get_block_id(x, y, z);
|
||||
if (id !== AIR_ID && this.world.get_block_value(x, y, z) >>> 16 !== state) {
|
||||
this.world.set_block(x, y, z, id, state);
|
||||
this.#notify_neighbors(x, y, z);
|
||||
const value = this.world.get_block_value(x, y, z);
|
||||
if (id === AIR_ID || value >>> 16 === state) return;
|
||||
const components = this.mods.components_with(id, "on_state_change");
|
||||
// only worked out for blocks that want it, states change often
|
||||
const before = components.length > 0 ? block_states(value, this.world.get_block_info(x, y, z)!) : undefined;
|
||||
this.world.set_block(x, y, z, id, state);
|
||||
if (before) {
|
||||
const block = this.mods.block_ref(x, y, z, id);
|
||||
for (const { mod, id: component_id, component, params } of components) {
|
||||
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, see BlockRules
|
||||
// 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);
|
||||
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) {
|
||||
run_guarded(
|
||||
mod,
|
||||
`${component_id} on_neighbor_change`,
|
||||
() => component.on_neighbor_change!(block, params, neighbor),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) {
|
||||
|
||||
@@ -479,6 +479,19 @@ export class ModRuntime {
|
||||
}
|
||||
#ticking_components_of = new Map<string, BlockComponentOf[]>();
|
||||
|
||||
// the ones with a handler, for handlers that run often, like on_neighbor_change. cached like components_of
|
||||
components_with(block_id: string, handler: keyof BlockComponent): readonly BlockComponentOf[] {
|
||||
let of_handler = this.#components_with.get(handler);
|
||||
if (!of_handler) this.#components_with.set(handler, of_handler = new Map());
|
||||
let components = of_handler.get(block_id);
|
||||
if (!components) {
|
||||
components = this.components_of(block_id).filter(({ component }) => component[handler]);
|
||||
of_handler.set(block_id, components);
|
||||
}
|
||||
return components;
|
||||
}
|
||||
#components_with = new Map<keyof BlockComponent, Map<string, BlockComponentOf[]>>();
|
||||
|
||||
// components on an item, with their params from its json
|
||||
item_components_of(item_id: string): { mod: string; id: string; component: ItemComponent; params: unknown }[] {
|
||||
const item = EverythingRegistry.get<ItemRegistry>("items", item_id);
|
||||
@@ -604,6 +617,7 @@ export class ModRuntime {
|
||||
this.block_components.set(id, { mod, component: component as BlockComponent });
|
||||
this.#components_of.clear();
|
||||
this.#ticking_components_of.clear();
|
||||
this.#components_with.clear();
|
||||
},
|
||||
register_item: (id, component) => {
|
||||
setup_only("components");
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// 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
|
||||
// on_state_change when its own states change
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
|
||||
|
||||
const SERVER_SCRIPT = `
|
||||
import type { ServerContext } from "bworld/server";
|
||||
export function setup(ctx: ServerContext) {
|
||||
const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get<unknown[]>("log") ?? [], event]);
|
||||
ctx.components.register_block("testmod:watcher", {
|
||||
on_neighbor_change(block, _params, neighbor) {
|
||||
const seen = ctx.world.get_state(block.x, block.y, block.z, "seen");
|
||||
log(["neighbor", neighbor.id, neighbor.x, neighbor.y, neighbor.z, seen]);
|
||||
},
|
||||
on_state_change(block, _params, before) {
|
||||
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") }]);
|
||||
},
|
||||
});
|
||||
// hangs from the block above and falls when it's gone, which only a server handler can do
|
||||
ctx.components.register_block("testmod:lantern", {
|
||||
on_neighbor_change(block) {
|
||||
if (ctx.world.get_block(block.x, block.y + 1, block.z) === "bworld:air") {
|
||||
ctx.world.break_block(block.x, block.y, block.z);
|
||||
}
|
||||
},
|
||||
});
|
||||
ctx.commands.register("state", {
|
||||
description: "", usage: "",
|
||||
run([x, y, z, name, value]) { ctx.world.set_state(Number(x), Number(y), Number(z), name, Number(value)); },
|
||||
});
|
||||
}
|
||||
`;
|
||||
|
||||
// marks the watcher once anything beside it changes
|
||||
const SHARED_SCRIPT = `
|
||||
import type { SharedContext } from "bworld/shared";
|
||||
export function setup(ctx: SharedContext) {
|
||||
ctx.components.register_block("testmod:watcher", {
|
||||
on_neighbor_change(block) { ctx.world.set_state(block.x, block.y, block.z, "seen", 1); },
|
||||
});
|
||||
}
|
||||
`;
|
||||
|
||||
function test_mods() {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_neighbors_" });
|
||||
copy_dir("mods/bworld", `${dir}/bworld`);
|
||||
const mod = `${dir}/testmod`;
|
||||
for (const folder of ["blocks", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true });
|
||||
const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json));
|
||||
write("manifest.json", {
|
||||
format_version: 1,
|
||||
id: "testmod",
|
||||
name: "Test",
|
||||
version: "1.0.0",
|
||||
dependencies: [{ id: "bworld", version: "*" }],
|
||||
scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" },
|
||||
});
|
||||
const block = (id: string, extra: Record<string, unknown>) => ({
|
||||
format_version: 1,
|
||||
block: { id, textures: "bworld:stone", mining: { toughness: 1 }, ...extra },
|
||||
});
|
||||
write(
|
||||
"blocks/watcher.json",
|
||||
block("testmod:watcher", {
|
||||
states: [{ name: "seen", bits: 1, default: 0 }, { name: "count", bits: 4, default: 0 }],
|
||||
components: { "testmod:watcher": {} },
|
||||
}),
|
||||
);
|
||||
write("blocks/lantern.json", block("testmod:lantern", { components: { "testmod:lantern": {} } }));
|
||||
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
|
||||
Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT);
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function setup() {
|
||||
const dir = test_mods();
|
||||
const { game, send, join } = await test_game(dir);
|
||||
join(1, "alice");
|
||||
stone_floor(game);
|
||||
send(1, { type: "move", x: 0.5, y: 100, z: 3.5, yaw: 0, pitch: 0 });
|
||||
// what happened since it was last called
|
||||
const log = () => {
|
||||
const events = (game.mods.storage.testmod?.log ?? []) as unknown[];
|
||||
delete game.mods.storage.testmod?.log;
|
||||
return events;
|
||||
};
|
||||
const command = (text: string) => send(1, { type: "chat", text });
|
||||
const cleanup = () => Deno.removeSync(dir, { recursive: true });
|
||||
return { game, log, command, cleanup };
|
||||
}
|
||||
|
||||
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();
|
||||
game.set_block(0, 100, 0, "testmod:watcher");
|
||||
log();
|
||||
|
||||
game.set_block(1, 100, 0, "bworld:stone");
|
||||
assertEquals(log(), [
|
||||
["state", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
|
||||
// the rule had marked it already
|
||||
["neighbor", "bworld:stone", 1, 100, 0, 1],
|
||||
]);
|
||||
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");
|
||||
|
||||
game.set_block(3, 101, 0, "bworld:stone");
|
||||
game.set_block(3, 100, 0, "testmod:lantern");
|
||||
game.set_block(4, 100, 0, "bworld:stone");
|
||||
assertEquals(game.world.get_block_id(3, 100, 0), "testmod:lantern");
|
||||
game.set_block(3, 101, 0, AIR_ID);
|
||||
assertEquals(game.world.get_block_id(3, 100, 0), AIR_ID, "it fell once what it hung from was gone");
|
||||
cleanup();
|
||||
});
|
||||
|
||||
Deno.test("on_state_change gets the states from before, when a script or a rule changes them", async () => {
|
||||
const { game, log, command, cleanup } = await setup();
|
||||
game.set_block(0, 100, 0, "testmod:watcher");
|
||||
log();
|
||||
|
||||
command("/state 0 100 0 count 3");
|
||||
assertEquals(log(), [["state", { seen: 0, count: 0 }, { seen: 0, count: 3 }]]);
|
||||
command("/state 0 100 0 count 3");
|
||||
assertEquals(log(), [], "setting a state to what it is changes nothing");
|
||||
|
||||
// a rule
|
||||
game.set_block(0, 101, 0, "bworld:stone");
|
||||
assertEquals(log()[0], ["state", { seen: 0, count: 3 }, { seen: 1, count: 3 }]);
|
||||
|
||||
// replacing it is a new block, not a state change
|
||||
game.set_block(0, 100, 0, "testmod:watcher");
|
||||
assertEquals(log(), []);
|
||||
assertEquals(game.world.get_block_value(0, 100, 0) >>> 16, 0);
|
||||
cleanup();
|
||||
});
|
||||
Reference in New Issue
Block a user