Workers for chunk generation !
This commit is contained in:
@@ -10,6 +10,7 @@ import { create_mod } from "$/tools/new_mod.ts";
|
||||
import { load_bmods } from "$/server/load_bmods.ts";
|
||||
import { start_host } from "$/server/host.ts";
|
||||
import { copy_dir } from "./helpers.ts";
|
||||
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
|
||||
|
||||
const ENGINE_TEXTURES = ["engine:missing", ...Array.from({ length: 9 }, (_, i) => `engine:break_${i}`)];
|
||||
|
||||
@@ -260,6 +261,69 @@ Deno.test("each texture's border in the atlas repeats its edge, so lookups at th
|
||||
]);
|
||||
});
|
||||
|
||||
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 });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// write_bmod without anything optional still makes a file read_bmod takes
|
||||
Deno.test("a mod with only data packs and reads", () => {
|
||||
const bmod = {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// a game with a worldgen pool, and ticking it like a client loads chunks, for tests/chunk_loading_test.ts and
|
||||
// tools/chunk_loading_bench.ts
|
||||
import { type WorkerPort, WorldgenPool } from "$/server/game/worldgen_pool.ts";
|
||||
import { start_worldgen_workers } from "$/server/worldgen_workers.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
// a game whose chunks come from a pool of workers
|
||||
// warm_up generates the spawn area and finds the spawn, which in a world without land searches a long way
|
||||
export async function game_with_pool(workers: number, seed?: string, mods_dir = "mods", warm_up = true) {
|
||||
if (workers === 0) return { ...(await test_game(mods_dir, undefined, seed)), pool: undefined, close: () => {} };
|
||||
const t = await test_game(mods_dir, undefined, seed);
|
||||
const started = start_worldgen_workers(workers, { permissions: "inherit", on_restart: () => {} });
|
||||
const pool: WorldgenPool | undefined = new WorldgenPool(
|
||||
started.ports as unknown as WorkerPort[],
|
||||
t.game.worldgen_bundle!,
|
||||
);
|
||||
t.game.use_worldgen_pool(pool);
|
||||
await pool.ready();
|
||||
if (warm_up) await t.game.warm_up();
|
||||
return { ...t, pool, close: () => (pool.close(), started.terminate()) };
|
||||
}
|
||||
|
||||
// ticks, answering chunk batches like a client, until the player has every chunk in view. the chunks they got, by
|
||||
// "x,z", and how long the longest tick took
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export async function load_view(
|
||||
t: Awaited<ReturnType<typeof test_game>>,
|
||||
conn: number,
|
||||
// how far apart ticks start, 50 like the game loop for timing, less for tests
|
||||
tick_ms = 5,
|
||||
timeout_ms = 120_000,
|
||||
) {
|
||||
const player = t.game.players().find((p) => p.conn === conn)!;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const chunks = new Map<string, any>();
|
||||
let longest_tick = 0;
|
||||
const start = performance.now();
|
||||
while (player.chunks.pending_count > 0) {
|
||||
if (performance.now() - start > timeout_ms) throw new Error(`${player.chunks.pending_count} chunks never came`);
|
||||
const tick_start = performance.now();
|
||||
t.game.tick();
|
||||
longest_tick = Math.max(longest_tick, performance.now() - tick_start);
|
||||
for (const message of t.take(conn)) {
|
||||
if (message.type === "level_chunk") chunks.set(`${message.x},${message.z}`, message);
|
||||
if (message.type === "chunk_batch_finished") {
|
||||
t.send(conn, { type: "chunk_batch_received", chunks_per_tick: 64 });
|
||||
}
|
||||
}
|
||||
// the rest of the tick, when the workers' chunks come in
|
||||
await new Promise((resolve) => setTimeout(resolve, Math.max(1, tick_ms - (performance.now() - tick_start))));
|
||||
}
|
||||
return { chunks, longest_tick, ms: performance.now() - start };
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// with a worldgen pool, chunks players are sent are generated in its workers: a player that teleports somewhere new
|
||||
// gets every chunk around them, the same as the game would make them, without the game generating them itself. see
|
||||
// GameServer.use_worldgen_pool and GENERATION.md
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { is_within_view } from "$/common/chunk_streaming.ts";
|
||||
import { game_with_pool, load_view } from "./chunk_loading.ts";
|
||||
|
||||
// the workers and their ports live until the test closes them
|
||||
const options = { sanitizeOps: false, sanitizeResources: false };
|
||||
|
||||
Deno.test({
|
||||
name: "a player teleported somewhere new gets every chunk in view from the pool, as the game would make them",
|
||||
...options,
|
||||
fn: async () => {
|
||||
const t = await game_with_pool(2);
|
||||
try {
|
||||
t.join(1, "alice");
|
||||
t.send(1, { type: "view_distance", distance: 5 });
|
||||
const player = t.game.players()[0];
|
||||
t.game.world.fallback_callers = new Map();
|
||||
const fallbacks = t.game.world.fallbacks;
|
||||
t.game.teleport(player, 10_000.5, 150, 3_000.5);
|
||||
const generated = t.pool!.generated;
|
||||
const { chunks } = await load_view(t, 1);
|
||||
|
||||
const [cx, cz] = [Math.floor(10_000 / 16), Math.floor(3_000 / 16)];
|
||||
for (let x = cx - 6; x <= cx + 6; x++) {
|
||||
for (let z = cz - 6; z <= cz + 6; z++) {
|
||||
if (!is_within_view(cx, cz, player.chunks.view_distance, x, z)) continue;
|
||||
const chunk = chunks.get(`${x},${z}`);
|
||||
assert(chunk, `chunk ${x},${z} wasn't sent`);
|
||||
assertEquals(chunk.blocks, t.game.world.generated_blocks(x, z), `chunk ${x},${z}`);
|
||||
}
|
||||
}
|
||||
assert(t.pool!.generated - generated > chunks.size, "the pool made them, and their neighbors");
|
||||
const on_thread = t.game.world.fallbacks - fallbacks;
|
||||
console.log(
|
||||
`generated on the game thread: ${on_thread}`,
|
||||
Object.fromEntries(t.game.world.fallback_callers),
|
||||
);
|
||||
assert(on_thread < chunks.size / 4, `${on_thread} chunks generated on the game thread`);
|
||||
} finally {
|
||||
t.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -14,6 +14,7 @@ import { Options } from "$/client/options.ts";
|
||||
import type { Client } from "$/client/client.ts";
|
||||
import type { ModListing } from "$/common/mod_loader.ts";
|
||||
import { copy_dir, test_game } from "./helpers.ts";
|
||||
import { game_with_pool } from "./chunk_loading.ts";
|
||||
|
||||
const [MAJOR, MINOR] = GAME_VERSION.split(".");
|
||||
const THIS_MINOR = `~${MAJOR}.${MINOR}.0`;
|
||||
@@ -121,6 +122,38 @@ Deno.test("a worldgen mod hooks the terrain in engine.common", async () => {
|
||||
assert(plain.world.get_block_id(8, 10, 8) !== "bworld:water");
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "a worldgen mod's hook reaches the worldgen workers too, since each loads the worldgen scripts",
|
||||
sanitizeOps: false,
|
||||
sanitizeResources: false,
|
||||
fn: async () => {
|
||||
const dir = mods_dir((dir) =>
|
||||
write_mod(dir, "flat_sea", {
|
||||
worldgen: [
|
||||
"worldgen.ts",
|
||||
`import { engine, hook } from "bworld/engine";
|
||||
export function setup() {
|
||||
hook(engine.common.OverworldTerrain.prototype, "density", { replace: () => -1 });
|
||||
}`,
|
||||
],
|
||||
})
|
||||
);
|
||||
// it's all sea, so no spawn search
|
||||
const t = await game_with_pool(1, "engine-access-flat-sea-pool", dir, false);
|
||||
try {
|
||||
const around: [number, number][] = [];
|
||||
for (let x = -1; x <= 1; x++) for (let z = -1; z <= 1; z++) around.push([x, z]);
|
||||
await t.pool!.prefetch(around);
|
||||
const fallbacks = t.game.world.fallbacks;
|
||||
assertEquals(t.game.world.get_block_id(8, 10, 8), "bworld:water");
|
||||
assertEquals(t.game.world.fallbacks, fallbacks, "the worker made it, not the game");
|
||||
} finally {
|
||||
t.close();
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test("a client mod hooks LocalPlayer from its .bmod", async () => {
|
||||
const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" });
|
||||
write_mod(dir, "floaty", {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// the golden fixture's hashes, shared by the tests that check generation against it: worldgen_golden_test.ts,
|
||||
// worldgen_bundle_test.ts and worldgen_pool_test.ts. hashed by name, since numeric ids move whenever a block is added
|
||||
import { AIR, ID_MASK } from "$/common/constants.ts";
|
||||
import type { RawChunk } from "$/common/generation.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
|
||||
export const FIXTURE = new URL("./fixtures/worldgen_golden.json", import.meta.url);
|
||||
export const SEEDS = ["golden-1", "golden-2", "golden-3"];
|
||||
// 4 by 4 chunks around each of these, 64 a seed. far apart so they land in different terrain, and in squares so
|
||||
// neighbors' spills are shared
|
||||
export const CLUSTERS = [[0, 0], [40, -25], [-120, 85], [300, 300]];
|
||||
|
||||
export type Hashes = Record<string, Record<string, { raw: string; final: string }>>;
|
||||
|
||||
// every chunk the fixture has, as x, z
|
||||
export function golden_chunks(): [number, number][] {
|
||||
return CLUSTERS.flatMap(([x0, z0]) =>
|
||||
[0, 1, 2, 3].flatMap((dx) => [0, 1, 2, 3].map((dz): [number, number] => [x0 + dx, z0 + dz]))
|
||||
);
|
||||
}
|
||||
|
||||
export function recorded(): Hashes {
|
||||
return JSON.parse(Deno.readTextFileSync(FIXTURE));
|
||||
}
|
||||
|
||||
// a block value's name and states, from numeric ids by id
|
||||
export function namer(block_ids: Record<string, number>): (value: number) => string {
|
||||
const names: string[] = [];
|
||||
for (const [id, nid] of Object.entries(block_ids)) names[nid] = id;
|
||||
names[AIR] = AIR_ID;
|
||||
return (value) => `${names[value & ID_MASK]}[${value >>> 16}]`;
|
||||
}
|
||||
|
||||
// what the fixture's "raw" is: the chunk's own blocks, its spills and its biomes
|
||||
export function raw_hash(raw: RawChunk, name: (value: number) => string): Promise<string> {
|
||||
const spills: (string | number)[] = [];
|
||||
for (let i = 0; i < raw.spills.length; i += 4) {
|
||||
spills.push(raw.spills[i], raw.spills[i + 1], raw.spills[i + 2], name(raw.spills[i + 3]));
|
||||
}
|
||||
return sha256(blocks_text(raw.blocks, name), JSON.stringify(spills), raw.biomes.join(","));
|
||||
}
|
||||
|
||||
// what the fixture's "final" is: the chunk with its neighbors' spills
|
||||
export function final_hash(blocks: Uint32Array, name: (value: number) => string): Promise<string> {
|
||||
return sha256(blocks_text(blocks, name));
|
||||
}
|
||||
|
||||
// the blocks as a palette of names in the order they first appear, then each block's place in it
|
||||
function blocks_text(blocks: Uint32Array, name: (value: number) => string): (string | Uint8Array)[] {
|
||||
const palette = new Map<number, number>();
|
||||
const indices = new Uint16Array(blocks.length);
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
let index = palette.get(blocks[i]);
|
||||
if (index === undefined) {
|
||||
index = palette.size;
|
||||
palette.set(blocks[i], index);
|
||||
}
|
||||
indices[i] = index;
|
||||
}
|
||||
return [JSON.stringify([...palette.keys()].map(name)), new Uint8Array(indices.buffer)];
|
||||
}
|
||||
|
||||
async function sha256(...parts: (string | Uint8Array | (string | Uint8Array)[])[]) {
|
||||
const bytes = parts.flat().map((part) => typeof part === "string" ? new TextEncoder().encode(part + "\n") : part);
|
||||
const all = new Uint8Array(bytes.reduce((sum, part) => sum + part.length, 0));
|
||||
let offset = 0;
|
||||
for (const part of bytes) {
|
||||
all.set(part, offset);
|
||||
offset += part.length;
|
||||
}
|
||||
let hex = "";
|
||||
for (const byte of new Uint8Array(await crypto.subtle.digest("SHA-256", all))) {
|
||||
hex += byte.toString(16).padStart(2, "0");
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// the bundle is everything generation reads, so a worker sent it generates what the game does. see
|
||||
// common/worldgen_bundle.ts and GENERATION.md
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import { load_bundle } from "$/common/worldgen_bundle.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
import { golden_chunks, namer, raw_hash, recorded, SEEDS } from "./golden.ts";
|
||||
|
||||
Deno.test("a bundle, cloned like a message to a worker and loaded into an empty registry, generates the golden chunks", async () => {
|
||||
const fixture = recorded();
|
||||
for (const seed of SEEDS) {
|
||||
const { game } = await test_game("mods", undefined, seed);
|
||||
const bundle = structuredClone(game.worldgen_bundle!);
|
||||
const game_ids = { ...game.world.block_ids };
|
||||
|
||||
// nothing left from the game, like a fresh worker
|
||||
EverythingRegistry.clear();
|
||||
const loaded = await load_bundle(bundle);
|
||||
assertEquals(loaded.block_ids, game_ids, "blocks are numbered like the game numbers them");
|
||||
assert(loaded.setup.features.some((f) => f.id === "bworld:trees"), "bworld's worldgen script was loaded");
|
||||
|
||||
const name = namer(loaded.block_ids);
|
||||
for (const [x, z] of golden_chunks()) {
|
||||
assertEquals(
|
||||
await raw_hash(loaded.generate(x, z), name),
|
||||
fixture[seed][`${x},${z}`].raw,
|
||||
`${seed} ${x},${z}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -4,46 +4,23 @@
|
||||
// after a change that's meant to change generation, record it again:
|
||||
// deno test -A tests/worldgen_golden_test.ts -- --update
|
||||
import { assertEquals } from "@std/assert";
|
||||
import { AIR, ID_MASK } from "$/common/constants.ts";
|
||||
import { generate_raw_chunk } from "$/common/generation.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
const FIXTURE = new URL("./fixtures/worldgen_golden.json", import.meta.url);
|
||||
const SEEDS = ["golden-1", "golden-2", "golden-3"];
|
||||
// 4 by 4 chunks around each of these, 64 a seed. far apart so they land in different terrain, and in squares so
|
||||
// neighbors' spills are shared
|
||||
const CLUSTERS = [[0, 0], [40, -25], [-120, 85], [300, 300]];
|
||||
|
||||
type Hashes = Record<string, Record<string, { raw: string; final: string }>>;
|
||||
import { final_hash, FIXTURE, golden_chunks, type Hashes, namer, raw_hash, recorded, SEEDS } from "./golden.ts";
|
||||
|
||||
Deno.test("world generation makes the same chunks as recorded", async () => {
|
||||
const hashes: Hashes = {};
|
||||
for (const seed of SEEDS) {
|
||||
const { game } = await test_game("mods", undefined, seed);
|
||||
const world = game.world;
|
||||
// by name, since numeric ids move whenever a block is added
|
||||
const names: string[] = [];
|
||||
for (const [id, nid] of Object.entries(world.block_ids)) names[nid] = id;
|
||||
names[AIR] = AIR_ID;
|
||||
const name = (value: number) => `${names[value & ID_MASK]}[${value >>> 16}]`;
|
||||
|
||||
const name = namer(world.block_ids);
|
||||
hashes[seed] = {};
|
||||
for (const [x0, z0] of CLUSTERS) {
|
||||
for (let dx = 0; dx < 4; dx++) {
|
||||
for (let dz = 0; dz < 4; dz++) {
|
||||
const [x, z] = [x0 + dx, z0 + dz];
|
||||
const raw = generate_raw_chunk(x, z, seed, world.block_ids, world.worldgen, world.default_values);
|
||||
const spills: (string | number)[] = [];
|
||||
for (let i = 0; i < raw.spills.length; i += 4) {
|
||||
spills.push(raw.spills[i], raw.spills[i + 1], raw.spills[i + 2], name(raw.spills[i + 3]));
|
||||
}
|
||||
hashes[seed][`${x},${z}`] = {
|
||||
raw: await sha256(blocks_text(raw.blocks, name), JSON.stringify(spills), raw.biomes.join(",")),
|
||||
final: await sha256(blocks_text(world.generated_blocks(x, z), name)),
|
||||
};
|
||||
}
|
||||
}
|
||||
for (const [x, z] of golden_chunks()) {
|
||||
const raw = generate_raw_chunk(x, z, seed, world.block_ids, world.worldgen, world.default_values);
|
||||
hashes[seed][`${x},${z}`] = {
|
||||
raw: await raw_hash(raw, name),
|
||||
final: await final_hash(world.generated_blocks(x, z), name),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,40 +28,10 @@ Deno.test("world generation makes the same chunks as recorded", async () => {
|
||||
Deno.writeTextFileSync(FIXTURE, JSON.stringify(hashes, null, "\t") + "\n");
|
||||
return;
|
||||
}
|
||||
const recorded: Hashes = JSON.parse(Deno.readTextFileSync(FIXTURE));
|
||||
const fixture = recorded();
|
||||
for (const seed of SEEDS) {
|
||||
for (const [chunk, hash] of Object.entries(hashes[seed])) {
|
||||
assertEquals(hash, recorded[seed]?.[chunk], `seed ${seed}, chunk ${chunk} isn't what was recorded`);
|
||||
assertEquals(hash, fixture[seed]?.[chunk], `seed ${seed}, chunk ${chunk} isn't what was recorded`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// the blocks as a palette of names in the order they first appear, then each block's place in it
|
||||
function blocks_text(blocks: Uint32Array, name: (value: number) => string): (string | Uint8Array)[] {
|
||||
const palette = new Map<number, number>();
|
||||
const indices = new Uint16Array(blocks.length);
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
let index = palette.get(blocks[i]);
|
||||
if (index === undefined) {
|
||||
index = palette.size;
|
||||
palette.set(blocks[i], index);
|
||||
}
|
||||
indices[i] = index;
|
||||
}
|
||||
return [JSON.stringify([...palette.keys()].map(name)), new Uint8Array(indices.buffer)];
|
||||
}
|
||||
|
||||
async function sha256(...parts: (string | Uint8Array | (string | Uint8Array)[])[]) {
|
||||
const bytes = parts.flat().map((part) => typeof part === "string" ? new TextEncoder().encode(part + "\n") : part);
|
||||
const all = new Uint8Array(bytes.reduce((sum, part) => sum + part.length, 0));
|
||||
let offset = 0;
|
||||
for (const part of bytes) {
|
||||
all.set(part, offset);
|
||||
offset += part.length;
|
||||
}
|
||||
let hex = "";
|
||||
for (const byte of new Uint8Array(await crypto.subtle.digest("SHA-256", all))) {
|
||||
hex += byte.toString(16).padStart(2, "0");
|
||||
}
|
||||
return hex;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
// chunks generated in worldgen workers are the ones the game would generate, in any order and with any number of
|
||||
// workers. see server/game/worldgen_pool.ts
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { chunk_key } from "$/common/utils.ts";
|
||||
import type { RawChunk } from "$/common/generation.ts";
|
||||
import { type WorkerPort, WorldgenPool } from "$/server/game/worldgen_pool.ts";
|
||||
import { start_worldgen_workers } from "$/server/worldgen_workers.ts";
|
||||
import { test_game } from "./helpers.ts";
|
||||
import { golden_chunks, namer, raw_hash, recorded } from "./golden.ts";
|
||||
|
||||
// workers and their ports outlive a test's sanitizers until they're closed
|
||||
const options = { sanitizeOps: false, sanitizeResources: false };
|
||||
|
||||
async function pool_for(seed: string, workers: number) {
|
||||
const { game } = await test_game("mods", undefined, seed);
|
||||
// tests load worldgen scripts from files, so the workers need to read them
|
||||
const started = start_worldgen_workers(workers, { permissions: "inherit", on_restart: () => {} });
|
||||
const pool = new WorldgenPool(started.ports as unknown as WorkerPort[], game.worldgen_bundle!);
|
||||
const chunks = new Map<number, RawChunk>();
|
||||
const order: [number, number][] = [];
|
||||
pool.on_chunk = (x, z, raw) => {
|
||||
chunks.set(chunk_key(x, z), raw);
|
||||
order.push([x, z]);
|
||||
};
|
||||
await pool.ready();
|
||||
return { game, pool, started, chunks, order };
|
||||
}
|
||||
|
||||
// waits until there's nothing queued or being generated
|
||||
async function drained(pool: WorldgenPool) {
|
||||
while (pool.queued > 0 || pool.in_flight > 0) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
}
|
||||
|
||||
Deno.test({
|
||||
name: "the pool generates the golden chunks, asked for in any order, with any number of workers",
|
||||
...options,
|
||||
fn: async () => {
|
||||
const fixture = recorded();
|
||||
for (const workers of [1, 3]) {
|
||||
const { game, pool, started, chunks } = await pool_for("golden-2", workers);
|
||||
try {
|
||||
// a different order each time, and priorities that don't follow it
|
||||
const asked = golden_chunks().sort(() => Math.random() - 0.5);
|
||||
pool.want(new Map(asked.map(([x, z], i) => [chunk_key(x, z), { x, z, priority: (i * 7) % 11 }])));
|
||||
await drained(pool);
|
||||
assertEquals(chunks.size, asked.length);
|
||||
const name = namer(game.world.block_ids);
|
||||
for (const [x, z] of asked) {
|
||||
const raw = chunks.get(chunk_key(x, z))!;
|
||||
assertEquals(await raw_hash(raw, name), fixture["golden-2"][`${x},${z}`].raw, `${x},${z}`);
|
||||
}
|
||||
} finally {
|
||||
pool.close();
|
||||
started.terminate();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "the nearest go first, what's no longer wanted is dropped, and a replaced worker's chunks are sent again",
|
||||
...options,
|
||||
fn: async () => {
|
||||
const { pool, started, chunks, order } = await pool_for("pool-seed", 1);
|
||||
try {
|
||||
// priority is the distance: the worker takes two straight away, then the rest nearest first
|
||||
const wanted = new Map([5, 1, 4, 2, 3, 0].map((d) => [chunk_key(d, 0), { x: d, z: 0, priority: d }]));
|
||||
pool.want(wanted);
|
||||
await drained(pool);
|
||||
assertEquals(order.map(([x]) => x), [0, 1, 2, 3, 4, 5]);
|
||||
|
||||
// the player moved away before these started
|
||||
order.length = 0;
|
||||
pool.want(new Map([10, 11, 12, 13].map((d) => [chunk_key(d, 0), { x: d, z: 0, priority: d }])));
|
||||
pool.want(new Map());
|
||||
await drained(pool);
|
||||
assertEquals(order.map(([x]) => x), [10, 11], "the two being generated finish, the rest never start");
|
||||
|
||||
// a worker that crashed and was started again gets what the old one was working on
|
||||
order.length = 0;
|
||||
pool.want(new Map([20, 21].map((d) => [chunk_key(d, 0), { x: d, z: 0, priority: d }])));
|
||||
const fresh = start_worldgen_workers(1, { permissions: "inherit", on_restart: () => {} });
|
||||
pool.replace(0, fresh.ports[0] as unknown as WorkerPort);
|
||||
await pool.prefetch([[30, 0]]);
|
||||
await drained(pool);
|
||||
assert(chunks.has(chunk_key(20, 0)) && chunks.has(chunk_key(21, 0)) && chunks.has(chunk_key(30, 0)));
|
||||
fresh.terminate();
|
||||
} finally {
|
||||
pool.close();
|
||||
started.terminate();
|
||||
}
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user