Files
bworld/tests/mod_test.ts
T
2026-11-15 19:54:08 -03:00

467 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// .cubi files: packing mods, reading them back, and the server loading a folder of them
import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows } from "@std/assert";
import { zipSync } from "fflate";
import { ATLAS_BORDER, atlas_layout, extrude_borders } from "@/client/atlas.ts";
import { MAX_TEXTURE_SIZE } from "@/common/constants.ts";
import { type Mod, read_mod, write_mod } from "@/common/mod.ts";
import { load_and_check } from "@/tools/check_mods.ts";
import { pack_mod } from "@/tools/pack_mod.ts";
import { create_mod } from "@/tools/new_mod.ts";
import { load_mods } from "@/server/load_mods.ts";
import { start_host } from "@/server/host.ts";
import { copy_dir, ENGINE_TEXTURES } from "./helpers.ts";
import { PROTOCOL_VERSION } from "@/common/protocol.ts";
import { decode_level_chunk, type LevelChunk } from "@/common/chunk_streaming.ts";
import { decode_chunk, encode_chunk } from "@/server/game/saves.ts";
import { list_chunks, read_chunk, write_chunks } from "@/server/regions.ts";
import { section_index } from "@/common/section.ts";
import { encode_schematic, type Schematic } from "@/common/schematic.ts";
// a schematic the template mod gets
const POST: Schematic = {
size: [1, 2, 1],
palette: [{ id: "bworld:stone" }],
blocks: [{ i: 0, p: [0, 0, 0] }, { i: 0, p: [0, 1, 0] }],
entities: [],
};
// mods/bworld and one made from the template, with a schematic, packed into a folder of .cubi files
async function packed_mods() {
const sources = Deno.makeTempDirSync({ prefix: "bworld_mod_src_" });
copy_dir("mods/bworld", `${sources}/bworld`);
create_mod("copper_tools", "Copper Tools", sources);
Deno.mkdirSync(`${sources}/copper_tools/schematics`);
Deno.writeFileSync(`${sources}/copper_tools/schematics/post.cbsm`, encode_schematic(POST));
const mods = await load_and_check(sources);
for (const mod of mods) assertEquals(mod.report.errors, [], mod.id);
const folder = Deno.makeTempDirSync({ prefix: "bworld_mod_" });
for (const mod of mods) Deno.writeFileSync(`${folder}/${mod.id}.cubi`, await pack_mod(mod));
return { sources, folder, mods };
}
Deno.test("packing a mod keeps its data, script, textures, schematics and credits, and gives the same bytes every time", async () => {
const { sources, folder, mods } = await packed_mods();
const template = mods.find((mod) => mod.id === "copper_tools")!;
const bytes = Deno.readFileSync(`${folder}/copper_tools.cubi`);
assertEquals(await pack_mod(template), bytes);
const mod = read_mod(bytes, "copper_tools.cubi");
assertEquals(mod.manifest.id, "copper_tools");
assertEquals(mod.data.blocks.map((b) => b.id), template.blocks.map((b) => b.json.id));
assertEquals(mod.data.recipes, template.recipes.map((r) => r.json));
assertEquals([...mod.textures.keys()].sort(), [...template.textures].sort());
// named by their files
assertEquals(mod.data.schematics, [{ ...POST, id: "copper_tools:post" }]);
assertStringIncludes(mod.script!, "function server");
assert(mod.credits);
const bworld = read_mod(Deno.readFileSync(`${folder}/bworld.cubi`), "bworld.cubi");
assertEquals(bworld.data.blocks.length, [...Deno.readDirSync("mods/bworld/blocks")].length);
assert(bworld.script);
Deno.removeSync(sources, { recursive: true });
Deno.removeSync(folder, { recursive: true });
});
Deno.test("broken .cubi files are turned away, saying why", () => {
const text = (value: unknown) => new TextEncoder().encode(JSON.stringify(value));
const manifest = { format_version: 1, id: "broken", name: "Broken", version: "1.0.0" };
const zip = (files: Record<string, Uint8Array>) => zipSync(files);
assertThrows(() => read_mod(new TextEncoder().encode("not a zip"), "a.cubi"), Error, "isn't a readable .cubi");
assertThrows(() => read_mod(zip({ "data.json": text({}) }), "b.cubi"), Error, "manifest.json is missing");
assertThrows(
() =>
read_mod(
zip({
"manifest.json": text(manifest),
"data.json": text({ blocks: [{ id: "other:thing", textures: "broken:x" }, { id: "broken:y" }] }),
}),
"c.cubi",
),
Error,
"other:thing isn't in this mod's namespace",
);
assertThrows(
() =>
read_mod(
zip({
"manifest.json": text({ ...manifest, main: "script.js" }),
"data.json": text({}),
}),
"d.cubi",
),
Error,
"main script.js isn't in the file",
);
// a texture bigger than MAX_TEXTURE_SIZE. only its header is read
const big = new Uint8Array(24);
big.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
new DataView(big.buffer).setUint32(16, MAX_TEXTURE_SIZE * 2);
new DataView(big.buffer).setUint32(20, 16);
assertThrows(
() =>
read_mod(
zip({ "manifest.json": text(manifest), "data.json": text({}), "textures/big.png": big }),
"e.cubi",
),
Error,
`textures can be at most ${MAX_TEXTURE_SIZE}×${MAX_TEXTURE_SIZE}`,
);
// too much once unzipped, without unzipping it all
const huge = new Uint8Array(65 * 1024 * 1024);
assertThrows(
() => read_mod(zip({ "manifest.json": text(manifest), "data.json": text({}), "big.bin": huge }), "f.cubi"),
Error,
"unzips to more than",
);
});
Deno.test("the server loads every .cubi in its folder, dependencies first, and players get them without the terrain or schematics", async () => {
const { sources, folder } = await packed_mods();
const mods = await load_mods(folder, ENGINE_TEXTURES);
assertEquals(mods.map((mod) => mod.listing.id), ["bworld", "copper_tools"]);
for (const mod of mods) {
assertEquals(mod.listing.file, `mods/${mod.listing.sha256}.cubi`);
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", mod.client_bytes));
assertEquals([...digest].map((b) => b.toString(16).padStart(2, "0")).join(""), mod.listing.sha256);
const copy = read_mod(mod.client_bytes, mod.listing.file);
assertEquals(
copy.script,
mod.mod.script,
"players get the whole script, and only run its shared and client phases",
);
// the terrain's data and schematics stay on the server too, the rest is the same
const { noises, density_functions, noise_settings, biome_sources, dimensions, schematics: _, ...data } =
mod.mod.data;
const none = {
noises: [],
density_functions: [],
noise_settings: [],
biome_sources: [],
dimensions: [],
schematics: [],
};
assertEquals(copy.data, { ...data, ...none });
if (mod.listing.id === "copper_tools") assertEquals(mod.mod.data.schematics?.length, 1);
if (mod.listing.id === "bworld") {
const terrain = [noises, density_functions, noise_settings, biome_sources, dimensions];
assert(terrain.every((list) => list!.length > 0));
}
}
// the same mod twice, and a mod whose dependency isn't there
Deno.copyFileSync(`${folder}/copper_tools.cubi`, `${folder}/copper_tools_again.cubi`);
await assertRejects(() => load_mods(folder, ENGINE_TEXTURES), Error, 'are both the mod "copper_tools"');
Deno.removeSync(`${folder}/copper_tools_again.cubi`);
Deno.removeSync(`${folder}/bworld.cubi`);
await assertRejects(() => load_mods(folder, ENGINE_TEXTURES), Error, `depends on "bworld"`);
Deno.removeSync(sources, { recursive: true });
Deno.removeSync(folder, { recursive: true });
});
Deno.test("the host serves each mod's player copy by its hash, and a game made from .cubi files plays", async () => {
const { sources, folder } = await packed_mods();
const build = Deno.makeTempDirSync({ prefix: "bworld_build_" });
Deno.mkdirSync(`${build}/assets/textures`, { recursive: true });
Deno.writeTextFileSync(
`${build}/assets/textures/index.json`,
JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])),
);
const world = `${build}/world`;
const host = await start_host({
build_dir: build,
server_mods_dir: folder,
world_dir: world,
seed: "mod-seed",
on_fatal: (message) => {
throw new Error(message);
},
});
const listings = (await load_mods(folder, ENGINE_TEXTURES)).map((mod) => mod.listing);
for (const listing of listings) {
const response = await host.handle(new Request(`http://localhost/${listing.file}`));
assertEquals(response.status, 200);
assertEquals(response.headers.get("access-control-allow-origin"), "*");
const mod = read_mod(new Uint8Array(await response.arrayBuffer()), listing.file);
assertEquals(mod.manifest.id, listing.id);
}
assertEquals((await host.handle(new Request("http://localhost/mods/nope.cubi"))).status, 404);
// the game worker loaded both mods, including the template's server phase, and saves
await host.shutdown();
const saved = JSON.parse(Deno.readTextFileSync(`${world}/level.json`));
assertEquals(saved.seed, "mod-seed");
for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true });
});
Deno.test("a mod with its own deno.json is bundled with it", async () => {
const sources = Deno.makeTempDirSync({ prefix: "bworld_mod_project_" });
copy_dir("mods/bworld", `${sources}/bworld`);
const mod = `${sources}/project`;
Deno.mkdirSync(`${mod}/scripts/lib`, { recursive: true });
Deno.writeTextFileSync(
`${mod}/manifest.json`,
JSON.stringify({
format_version: 1,
id: "project",
name: "Project",
version: "1.0.0",
main: "scripts/server.ts",
}),
);
// only the mod's own import map knows "lib/"
Deno.writeTextFileSync(`${mod}/deno.json`, JSON.stringify({ imports: { "lib/": "./scripts/lib/" } }));
Deno.writeTextFileSync(`${mod}/scripts/lib/greeting.ts`, `export const GREETING = "hello from a deno project";\n`);
Deno.writeTextFileSync(
`${mod}/scripts/server.ts`,
`import { GREETING } from "lib/greeting.ts";\n// deno-lint-ignore no-explicit-any\nexport function server(ctx: any) {\n\tctx.log(GREETING);\n}\n`,
);
const project = (await load_and_check(sources)).find((m) => m.id === "project")!;
assertEquals(project.report.errors, []);
const packed = read_mod(await pack_mod(project), "project.cubi");
assertStringIncludes(packed.script!, "hello from a deno project");
Deno.removeSync(sources, { recursive: true });
});
const sizes = (entries: [string, number, number][]) =>
new Map(entries.map(([id, width, height]) => [id, { width, height }]));
Deno.test("the atlas lays out same sized textures by id, with the missing texture among them", () => {
const layout = atlas_layout(sizes([["b:two", 16, 16], ["a:one", 16, 16], ["cubi:break_0", 16, 16]]));
assertEquals(layout.size, 64);
// each inside a pixel of border
assertEquals(layout.regions, {
"a:one": { x: 1, y: 1, width: 16, height: 16 },
"b:two": { x: 19, y: 1, width: 16, height: 16 },
"cubi:break_0": { x: 37, y: 1, width: 16, height: 16 },
"cubi:missing": { x: 1, y: 19, width: 16, height: 16 },
});
const many = atlas_layout(sizes(Array.from({ length: 100 }, (_, i) => [`m:t${i}`, 16, 16])));
assertEquals(many.size, 256);
});
Deno.test("the atlas fits textures of any size, tallest first, without overlapping", () => {
const layout = atlas_layout(
sizes([["a:block", 16, 16], ["a:zombie", 64, 64], ["a:boat", 128, 32], ["a:x", 8, 24]]),
);
assertEquals(layout.size, 256);
assertEquals(layout.regions["a:zombie"], { x: 1, y: 1, width: 64, height: 64 });
assertEquals(layout.regions["a:boat"], { x: 67, y: 1, width: 128, height: 32 });
assertEquals(layout.regions["a:x"], { x: 197, y: 1, width: 8, height: 24 });
const big = atlas_layout(
sizes(Array.from({ length: 40 }, (_, i) => [`m:t${i}`, 16 + (i % 5) * 12, 8 + (i % 7) * 9])),
);
const regions = Object.values(big.regions);
// with their borders
const b = ATLAS_BORDER;
for (const [i, a] of regions.entries()) {
assert(a.x >= b && a.y >= b && a.x + a.width + b <= big.size && a.y + a.height + b <= big.size);
for (const c of regions.slice(i + 1)) {
const apart = a.x + a.width + 2 * b <= c.x || c.x + c.width + 2 * b <= a.x ||
a.y + a.height + 2 * b <= c.y || c.y + c.height + 2 * b <= a.y;
assert(apart, `${JSON.stringify(a)} overlaps ${JSON.stringify(c)}`);
}
}
});
Deno.test("each texture's border in the atlas repeats its edge, so lookups at the edge never reach the next one", () => {
// a 2×2 texture at 1 1 in a 4×4 atlas, pixels numbered 1 to 4 in the red channel
const pixels = new Uint8ClampedArray(4 * 4 * 4);
const red = (x: number, y: number) => pixels[(y * 4 + x) * 4];
[[1, 1, 1], [2, 1, 2], [1, 2, 3], [2, 2, 4]].forEach(([x, y, n]) => pixels[(y * 4 + x) * 4] = n);
extrude_borders(pixels, 4, { "a:t": { x: 1, y: 1, width: 2, height: 2 } });
const rows = [0, 1, 2, 3].map((y) => [0, 1, 2, 3].map((x) => red(x, y)));
assertEquals(rows, [
[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4],
]);
});
Deno.test({
name: "a player joining a real host gets chunks the worldgen workers made, and /tps says they're in use",
// the host's server and its workers outlive the sanitizers until they're shut down
sanitizeOps: false,
sanitizeResources: false,
fn: async () => {
const { sources, folder } = await packed_mods();
const build = Deno.makeTempDirSync({ prefix: "bworld_build_" });
Deno.mkdirSync(`${build}/assets/textures`, { recursive: true });
Deno.writeTextFileSync(
`${build}/assets/textures/index.json`,
JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])),
);
const host = await start_host({
build_dir: build,
server_mods_dir: folder,
world_dir: `${build}/world`,
seed: "workers-seed",
worldgen_workers: 2,
on_fatal: (message) => {
throw new Error(message);
},
});
const server = Deno.serve({ port: 0, onListen: () => {} }, host.handle);
try {
const socket = new WebSocket(`ws://localhost:${server.addr.port}/ws`);
socket.binaryType = "arraybuffer";
let chunks = 0;
const said: string[] = [];
const done = new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`only ${chunks} chunks came`)), 60_000);
socket.onmessage = (event) => {
if (typeof event.data !== "string") {
chunks++;
return;
}
const message = JSON.parse(event.data);
if (message.type === "welcome") socket.send(JSON.stringify({ type: "ready", view_distance: 4 }));
if (message.type === "chunk_batch_finished") {
socket.send(JSON.stringify({ type: "chunk_batch_received", chunks_per_tick: 64 }));
if (chunks >= 49) socket.send(JSON.stringify({ type: "chat", text: "/tps" }));
}
if (message.type === "chat") said.push(message.text);
if (said.some((text) => text.startsWith("Worldgen:"))) {
clearTimeout(timer);
resolve();
}
};
});
socket.onopen = () =>
socket.send(JSON.stringify({ type: "hello", name: "alice", protocol: PROTOCOL_VERSION }));
await done;
socket.close();
assert(chunks >= 49, `${chunks} chunks`);
assertStringIncludes(said.find((text) => text.startsWith("Worldgen:"))!, "Worldgen: 2 workers");
} finally {
await server.shutdown();
await host.shutdown();
for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true });
}
},
});
// joins a host as alice with view distance 4, until she has every chunk in view
async function join_host(port: number): Promise<LevelChunk[]> {
const socket = new WebSocket(`ws://localhost:${port}/ws`);
socket.binaryType = "arraybuffer";
const chunks: LevelChunk[] = [];
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`only ${chunks.length} chunks came`)), 60_000);
socket.onmessage = (event) => {
if (typeof event.data !== "string") {
chunks.push(decode_level_chunk(new Uint8Array(event.data)));
return;
}
const message = JSON.parse(event.data);
if (message.type === "welcome") socket.send(JSON.stringify({ type: "ready", view_distance: 4 }));
if (message.type === "chunk_batch_finished") {
socket.send(JSON.stringify({ type: "chunk_batch_received", chunks_per_tick: 64 }));
if (chunks.length >= 49) {
clearTimeout(timer);
resolve();
}
}
};
socket.onopen = () => socket.send(JSON.stringify({ type: "hello", name: "alice", protocol: PROTOCOL_VERSION }));
});
const closed = new Promise((resolve) => socket.onclose = resolve);
socket.close();
await closed;
return chunks;
}
Deno.test({
name: "a real host saves every chunk it generates, and players get them from the save after it starts again",
sanitizeOps: false,
sanitizeResources: false,
fn: async () => {
const { sources, folder } = await packed_mods();
const build = Deno.makeTempDirSync({ prefix: "bworld_build_" });
Deno.mkdirSync(`${build}/assets/textures`, { recursive: true });
Deno.writeTextFileSync(
`${build}/assets/textures/index.json`,
JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])),
);
const run = async () => {
const host = await start_host({
build_dir: build,
server_mods_dir: folder,
world_dir: `${build}/world`,
seed: "saving-seed",
worldgen_workers: 2,
on_fatal: (message) => {
throw new Error(message);
},
});
const server = Deno.serve({ port: 0, onListen: () => {} }, host.handle);
try {
return await join_host(server.addr.port);
} finally {
await server.shutdown();
await host.shutdown();
}
};
try {
const first = await run();
const region = `${build}/world/region`;
const saved = await list_chunks(region);
for (const chunk of first) assert(saved.some(([x, z]) => x === chunk.x && z === chunk.z));
// a block at the top of every saved chunk, which generation never puts there
await write_chunks(
region,
await Promise.all(saved.map(async ([x, z]) => {
const chunk = decode_chunk((await read_chunk(region, x, z))!);
chunk.sections.at(-1)!.set(section_index(0, 15, 0), chunk.palette.push(["bworld:stone", 0]) - 1);
return { x, z, data: encode_chunk(chunk as Required<typeof chunk>) };
})),
);
const second = await run();
assert(second.length >= 49);
for (const chunk of second) {
assert(
chunk.sections.at(-1)!.get(section_index(0, 15, 0)) !== 0,
`${chunk.x},${chunk.z} is from the save`,
);
}
} finally {
for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true });
}
},
});
// write_mod without anything optional still makes a file read_mod takes
Deno.test("a mod with only data packs and reads", () => {
const mod: Mod = {
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
data: {
blocks: [],
models: [],
items: [],
recipes: [],
ores: [],
spawns: [],
entities: [],
entity_models: [],
effects: [],
fluids: [],
tags: [],
},
textures: new Map(),
};
assertEquals(read_mod(write_mod(mod), "tiny.cubi").manifest.id, "tiny");
});