257 lines
10 KiB
TypeScript
257 lines
10 KiB
TypeScript
// 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. blocks hear of changes through a queue, once the change is done
|
|
import { assert, assertEquals } from "@std/assert";
|
|
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";
|
|
|
|
const SERVER_SCRIPT = `
|
|
import type { ServerContext } from "cubi/server";
|
|
export function server(ctx: ServerContext) {
|
|
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", {
|
|
on_neighbor_change(block, _params, neighbor) {
|
|
const seen = ctx.world.get_state(block.x, block.y, block.z, "seen");
|
|
log(["neighbor", at(block), neighbor.id, at(neighbor), seen]);
|
|
},
|
|
on_state_change(block, _params, before) {
|
|
const { x, y, z } = block;
|
|
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
|
|
ctx.components.register_block("testmod:lantern", {
|
|
on_neighbor_change(block) {
|
|
if (ctx.world.get_block(block.x, block.y + 1, block.z) === "cubi:air") {
|
|
ctx.world.break_block(block.x, block.y, block.z);
|
|
}
|
|
},
|
|
});
|
|
// 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", {
|
|
description: "", usage: "",
|
|
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 });
|
|
},
|
|
});
|
|
}
|
|
`;
|
|
|
|
const SHARED_SCRIPT = `
|
|
import type { SharedContext } from "cubi/shared";
|
|
export function shared(ctx: SharedContext) {
|
|
// marks the watcher once anything beside it changes
|
|
ctx.components.register_block("testmod:watcher", {
|
|
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);
|
|
},
|
|
});
|
|
}
|
|
`;
|
|
|
|
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: "*" }],
|
|
main: "scripts/main.ts",
|
|
});
|
|
const block = (name: string, states: unknown[] = []) =>
|
|
write(`blocks/${name}.json`, {
|
|
format_version: 1,
|
|
block: {
|
|
id: `testmod:${name}`,
|
|
textures: "bworld:stone",
|
|
mining: { toughness: 1 },
|
|
states,
|
|
components: { [`testmod:${name}`]: {} },
|
|
},
|
|
});
|
|
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/shared.ts`, SHARED_SCRIPT);
|
|
Deno.writeTextFileSync(
|
|
`${mod}/scripts/main.ts`,
|
|
`export { server } from "./server.ts";\nexport { shared } from "./shared.ts";\n`,
|
|
);
|
|
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 };
|
|
}
|
|
|
|
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 () => {
|
|
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", "0 100 0", { seen: 0, count: 0 }, { seen: 1, count: 0 }],
|
|
// the rule had marked it already
|
|
["neighbor", "0 100 0", "bworld:stone", "1 100 0", 1],
|
|
]);
|
|
game.set_block(1, 100, 0, AIR_ID);
|
|
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, 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", "0 100 0", { 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", "0 100 0", { 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();
|
|
});
|
|
|
|
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", "cubi: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();
|
|
});
|