diff --git a/common/worldgen_bundle.ts b/common/worldgen_bundle.ts new file mode 100644 index 0000000..752cb04 --- /dev/null +++ b/common/worldgen_bundle.ts @@ -0,0 +1,112 @@ +// everything generating a chunk reads, as one plain object a worker can be sent: the seed, the generator, and each +// mod's data generation needs with its worldgen script's url. loading it registers the data in this realm and loads +// the scripts, which gives the same numeric block ids and the same generator as the game, so chunks come out the same +// block for block. see GENERATION.md +import type { ModData } from "./mod_loader.ts"; +import { register_mod_data } from "./mod_loader.ts"; +import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts"; +import { default_block_value } from "./utils.ts"; +import { generate_raw_chunk, type RawChunk, type WorldgenSetup } from "./generation.ts"; +import { load_worldgen } from "./worldgen_loader.ts"; + +// the parts of a mod's data generation reads. tags only the block ones +export type WorldgenModData = Pick< + ModData, + | "blocks" + | "models" + | "tags" + | "ores" + | "biomes" + | "noises" + | "density_functions" + | "noise_settings" + | "biome_sources" + | "features" +>; + +export interface WorldgenBundle { + seed: string; + // the noise settings the world uses + generator: string; + // in load order + mods: { id: string; data: WorldgenModData; worldgen_url?: string; engine_access?: boolean }[]; +} + +export function worldgen_bundle( + seed: string, + generator: string, + mods: { id: string; data: ModData; worldgen_url?: string; engine_access?: boolean }[], +): WorldgenBundle { + return { + seed, + generator, + mods: mods.map(({ id, data, worldgen_url, engine_access }) => ({ + id, + data: { + blocks: data.blocks, + models: data.models, + tags: data.tags.filter((tag) => tag.registry === "blocks"), + ores: data.ores, + biomes: data.biomes ?? [], + noises: data.noises ?? [], + density_functions: data.density_functions ?? [], + noise_settings: data.noise_settings ?? [], + biome_sources: data.biome_sources ?? [], + features: data.features ?? [], + }, + ...(worldgen_url ? { worldgen_url } : {}), + ...(engine_access ? { engine_access } : {}), + })), + }; +} + +// numeric block ids by id, and each one's value with its default states, the way ServerWorld numbers them +export function block_numbering(): { block_ids: Record; default_values: number[] } { + const block_ids: Record = {}; + const default_values: number[] = []; + EverythingRegistry.get_registry("blocks").forEach((block, nid) => { + block_ids[block.id] = nid; + default_values[nid] = default_block_value(nid, block); + }); + return { block_ids, default_values }; +} + +export interface LoadedBundle { + setup: WorldgenSetup; + block_ids: Record; + default_values: number[]; + generate(chunk_x: number, chunk_z: number): RawChunk; +} + +// sets up generation in this realm from a bundle. the registry has to be empty, like a worker's +export async function load_bundle(bundle: WorldgenBundle): Promise { + const recipes = register_mod_data(bundle.mods.map(({ id, data }) => ({ + id, + data: { + ...data, + items: [], + recipes: [], + spawns: [], + entities: [], + entity_models: [], + effects: [], + loot_tables: [], + }, + }))); + const setup = await load_worldgen({ + mods: bundle.mods.map((mod) => mod.id), + scripts: bundle.mods.flatMap((mod) => + mod.worldgen_url ? [{ mod: mod.id, url: mod.worldgen_url, engine_access: mod.engine_access }] : [] + ), + ores: recipes.ores, + generator: bundle.generator, + }); + const { block_ids, default_values } = block_numbering(); + return { + setup, + block_ids, + default_values, + generate: (chunk_x, chunk_z) => + generate_raw_chunk(chunk_x, chunk_z, bundle.seed, block_ids, setup, default_values), + }; +} diff --git a/deno.json b/deno.json index f2d21f2..38353ed 100644 --- a/deno.json +++ b/deno.json @@ -8,7 +8,7 @@ "pack-mod": "deno run --allow-read --allow-write --allow-run --allow-env tools/pack_mod.ts", "test": "deno test --allow-read --allow-write --allow-run tests/", "bench": "deno bench --allow-read --allow-write --allow-run tests/", - "desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-ffi --allow-env=BWORLD_SERVER,BWORLD_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME,DEBUG --include build --include server_mods --include server/game/worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld", + "desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-ffi --allow-env=BWORLD_SERVER,BWORLD_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME,DEBUG --include build --include server_mods --include server/game/worker.ts --include server/game/worldgen_worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld", "desktop-all": "deno run -A tools/desktop_all.ts" }, "compilerOptions": { diff --git a/docs/modding/misc/engine.md b/docs/modding/misc/engine.md index 1eea567..329c9af 100644 --- a/docs/modding/misc/engine.md +++ b/docs/modding/misc/engine.md @@ -67,8 +67,9 @@ types are the engine's own source, so `check-mods` typechecks against exactly th through: `engine.common.physics.move_body` is how every entity moves, on the server and on clients. - `#private` members can't be hooked. They're kept for things with rules that must hold, like a container's slots. - Hooks reach one JavaScript realm. Chunk workers run their own copy of the engine, so a client hook doesn't change - meshing. Worldgen scripts run on the server, next to the server script, so hooking `engine.common.OverworldTerrain` - from either changes the terrain. + meshing. The server generates chunks in worldgen workers, and each loads the worldgen scripts into its own copy, so + hooks on the terrain (`engine.common.OverworldTerrain`) go in the worldgen script. A server script's hooks there only + reach the few chunks the game generates itself, so the world would come out different in places. ## Performance diff --git a/docs/modding/worldgen/index.md b/docs/modding/worldgen/index.md index 9327296..4c07314 100644 --- a/docs/modding/worldgen/index.md +++ b/docs/modding/worldgen/index.md @@ -11,7 +11,8 @@ and their builds end up half buried. - **Never use `Math.random`, `Date`, `performance.now` or anything else that changes between runs.** Use the chunk's `rng` and noise helpers, which are seeded from the world's seed. -- Don't keep state between chunks. Chunks generate in any order. +- Don't keep state between chunks. Chunks generate in any order, and in several worldgen workers at once, each with its + own copy of the worldgen scripts (and the game generates a few itself). - Adding or removing a mod's features is safe for chunks that haven't been generated yet, but changes existing worlds' untouched terrain the next time it loads. diff --git a/server/game/game_server.ts b/server/game/game_server.ts index b6275cf..f4d3a73 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -22,6 +22,8 @@ import { } from "$/common/protocol.ts"; import type { ModListing, RecipeBook } from "$/common/mod_loader.ts"; import type { WorldgenSetup } from "$/common/generation.ts"; +import type { WorldgenBundle } from "$/common/worldgen_bundle.ts"; +import type { WorldgenPool } from "./worldgen_pool.ts"; import { MAX_VIEW_DISTANCE, MIN_VIEW_DISTANCE } from "$/common/chunk_streaming.ts"; import { CYCLE_TICKS, format_clock, time_of_day, TIMES_OF_DAY } from "$/common/time.ts"; import { @@ -67,7 +69,7 @@ import { update_crafting_result } from "./crafting.ts"; import type { Menu } from "./menu.ts"; import { SavedPlayer, ServerPlayer } from "./player.ts"; import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts"; -import { ServerWorld, Tile } from "./world.ts"; +import { FINGERPRINT_CHUNKS, ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts"; import type { WorldSave } from "./saves.ts"; import { BLOCK_DROP_PICKUP_DELAY, @@ -116,6 +118,9 @@ const READY_TIMEOUT_TICKS = 60 * TICKS_PER_SECOND; const SERVER_VIEW_DISTANCE = 16; // how long a tick can spend building chunks for players, the rest go out on the next ticks const CHUNK_SEND_BUDGET_MS = 20; +// with a worldgen pool, how many of the chunks each player is waiting for it's asked for at once, nearest first. a +// few ticks of sending ahead, without filling the world's raw chunk cache with ones that won't be sent for a while +const WORLDGEN_REQUEST_WINDOW = 64; // everything the game server needs from whatever runs it export interface GameHost { @@ -194,6 +199,12 @@ export class GameServer { view_distance = SERVER_VIEW_DISTANCE; // how long a tick can spend building chunks for players. tests lift it so what gets sent doesn't depend on speed chunk_send_budget_ms = CHUNK_SEND_BUDGET_MS; + // what a worldgen worker needs to generate the same chunks as this game, see start_game + worldgen_bundle?: WorldgenBundle; + // generates chunks off the game's thread, see use_worldgen_pool. without it, they're generated when needed + worldgen_pool?: WorldgenPool; + // world.fallbacks each second for the last minute, for /tps + #fallback_history: number[] = []; constructor(host: GameHost, save: WorldSave | undefined, default_seed: string, mods: GameMods) { this.#host = host; @@ -411,7 +422,12 @@ export class GameServer { this.#sync_worn(player); this.#sync(player); } + this.#request_chunks(); this.#send_chunks(); + if (second) { + this.#fallback_history.push(this.world.fallbacks); + if (this.#fallback_history.length > 60) this.#fallback_history.shift(); + } } // level.json and the chunks changed since the last save @@ -1491,6 +1507,14 @@ export class GameServer { `${tps} ticks per second (aiming for ${TICKS_PER_SECOND}), ${mspt.toFixed(1)} ms per tick, ` + `${skipped} skipped since starting`, ); + const pool = this.worldgen_pool; + const last_minute = this.world.fallbacks - (this.#fallback_history[0] ?? 0); + context.source.send_message( + pool + ? `Worldgen: ${pool.workers} workers, ${pool.queued} chunks waiting, ${pool.generated} generated. ` + + `${last_minute} chunks generated on the game thread in the last minute` + : `Worldgen: on the game thread, ${last_minute} chunks in the last minute`, + ); }), ); @@ -1662,9 +1686,10 @@ export class GameServer { #tick_vitals() { for (const player of this.#players.values()) { - // burning, effects, falling out of the world, and being knocked back + // burning, effects, falling out of the world, and being knocked back. like entities, not while the chunk + // they're in is still being generated, see #tick_entities const knocked_back = player.knockback_ticks !== undefined; - player.tick(); + if (this.#generated_at(player.x, player.z)) player.tick(); if (knocked_back && player.alive) { // the last one hands what's left of the slide to their client this.#place(player, [player.vx, player.vy, player.vz]); @@ -1769,10 +1794,26 @@ export class GameServer { // entities, see entity/ - // like minecraft: entities only move near players, and players pick up items by walking into them + // whether the chunks within a block of x, z (what an entity there touches) can be built without generating anything + // here. always without a worldgen pool, which is what anything ticking there would otherwise wait for + #generated_at(x: number, z: number) { + if (!this.worldgen_pool) return true; + for (let cx = Math.floor((x - 1) / CHUNK_SIZE); cx <= Math.floor((x + 1) / CHUNK_SIZE); cx++) { + for (let cz = Math.floor((z - 1) / CHUNK_SIZE); cz <= Math.floor((z + 1) / CHUNK_SIZE); cz++) { + if (!this.world.can_build(cx, cz)) return false; + } + } + return true; + } + + // like minecraft: entities only move near players, and players pick up items by walking into them. with a worldgen + // pool, only where the chunk is generated too, like minecraft's entities in chunks that aren't loaded: one that + // just got somewhere new, like a teleported player, waits for the pool instead of the game generating it here #tick_entities() { if (this.do_mob_spawning) this.spawner.tick(this, SIMULATION_DISTANCE); - this.entities.tick((entity) => this.#near_any_player(entity.x, entity.z)); + this.entities.tick((entity) => + this.#near_any_player(entity.x, entity.z) && this.#generated_at(entity.x, entity.z) + ); const items = this.item_entities(); for (const player of this.#players.values()) { for (const entity of items) { @@ -1916,6 +1957,47 @@ export class GameServer { } } + // generates chunks in a pool's workers from now on: what players need goes to it, and only chunks it has made the + // parts of are sent (see #request_chunks). undefined goes back to generating on this thread + use_worldgen_pool(pool: WorldgenPool | undefined) { + this.worldgen_pool = pool; + if (pool) pool.on_chunk = (x, z, raw) => this.world.add_raw(x, z, raw); + } + + // generates what's needed before players come with the pool, instead of on this thread when they do: the spawn + // search's chunks and the worldgen fingerprint's + async warm_up() { + const pool = this.worldgen_pool; + if (!pool) return; + const reach = SPAWN_AREA_CHUNKS; + const around_spawn: [number, number][] = []; + for (let x = -reach; x <= reach; x++) for (let z = -reach; z <= reach; z++) around_spawn.push([x, z]); + await pool.prefetch([...around_spawn, ...FINGERPRINT_CHUNKS as [number, number][]]); + this.world.spawn_point(); + this.world.worldgen_fingerprint(); + } + + // asks the pool for the raw chunks the nearest chunks each player is waiting for are built from, nearest first. + // what nobody is waiting for any more is dropped from its queue + #request_chunks() { + const pool = this.worldgen_pool; + if (!pool) return; + const wanted = new Map(); + for (const player of this.#players.values()) { + const center = player.chunks.center; + if (!center) continue; + for (const [cx, cz] of player.chunks.nearest_pending(WORLDGEN_REQUEST_WINDOW)) { + const priority = (cx - center.x) ** 2 + (cz - center.z) ** 2; + for (const [x, z] of this.world.raws_needed(cx, cz)) { + const key = chunk_key(x, z); + const known = wanted.get(key); + if (!known || priority < known.priority) wanted.set(key, { x, z, priority }); + } + } + } + pool.want(wanted); + } + // every player's next batch, like minecraft's PlayerChunkSender. building chunks is the slow part, so they share // a time budget and whoever didn't get theirs goes first next tick #send_chunks() { @@ -1925,6 +2007,11 @@ export class GameServer { } const start = performance.now(); const can_send = () => performance.now() - start < this.chunk_send_budget_ms; + // with a pool, only chunks it has made the parts of, the rest wait for it instead of being generated here. + // without one, each is built as it's picked, so the time it takes counts against the budget for the next + const ready = this.worldgen_pool + ? (x: number, z: number) => this.world.can_build(x, z) + : (x: number, z: number) => (this.world.build(x, z), true); const first = this.#next_chunk_player % players.length; for (let i = 0; i < players.length; i++) { const player = players[(first + i) % players.length]; @@ -1932,7 +2019,7 @@ export class GameServer { this.#next_chunk_player = first + i; return; } - const batch = player.chunks.next_batch(can_send); + const batch = player.chunks.next_batch(can_send, ready); if (batch.length === 0) { continue; } diff --git a/server/game/host_protocol.ts b/server/game/host_protocol.ts index 3380b36..33c7cfc 100644 --- a/server/game/host_protocol.ts +++ b/server/game/host_protocol.ts @@ -16,7 +16,12 @@ export type HostToGame = worldgen_code?: string; shared_code?: string; }[]; + // the game's ends of channels to the worldgen workers the host started, see worldgen_pool.ts. none means + // generating on the game's thread + worldgen_ports: MessagePort[]; } + // a worldgen worker crashed and the host started it again, this is the new one's port + | { type: "worldgen_port"; index: number; port: MessagePort } | { type: "connect"; conn: number } | { type: "message"; conn: number; data: string } | { type: "disconnect"; conn: number } diff --git a/server/game/load_mods.ts b/server/game/load_mods.ts index ab9e030..e018972 100644 --- a/server/game/load_mods.ts +++ b/server/game/load_mods.ts @@ -3,6 +3,7 @@ import { register_mod_data } from "$/common/mod_loader.ts"; import type { ModData, ModListing } from "$/common/mod_loader.ts"; import { load_worldgen } from "$/common/worldgen_loader.ts"; +import { worldgen_bundle } from "$/common/worldgen_bundle.ts"; import { GameHost, GameServer } from "./game_server.ts"; import type { WorldSave } from "./saves.ts"; import { ModRuntime } from "./mod_runtime.ts"; @@ -73,6 +74,17 @@ export async function start_game( mods.flatMap((mod) => mod.server_url ? [{ ...script_of(mod), url: mod.server_url }] : []), ); runtime.finish_setup(); + // what a worldgen worker needs to generate the same chunks, see worldgen_pool.ts + game.worldgen_bundle = worldgen_bundle( + game.world.seed, + GENERATOR, + mods.map((mod) => ({ + id: mod.listing.id, + data: mod.data, + worldgen_url: mod.worldgen_url, + engine_access: mod.listing.engine_access, + })), + ); runtime.after.server_start.emit({}); return game; diff --git a/server/game/player_chunks.ts b/server/game/player_chunks.ts index 9a12458..e6622c4 100644 --- a/server/game/player_chunks.ts +++ b/server/game/player_chunks.ts @@ -74,9 +74,21 @@ export class PlayerChunks { return { moved: true, forget }; } + // the count chunks in view the client doesn't have yet that are nearest the player + nearest_pending(count: number): [number, number][] { + if (!this.center) return []; + const { x, z } = this.center; + return [...this.#pending.values()] + .map(([cx, cz]) => ({ cx, cz, distance: (cx - x) ** 2 + (cz - z) ** 2 })) + .sort((a, b) => a.distance - b.distance) + .slice(0, count) + .map(({ cx, cz }): [number, number] => [cx, cz]); + } + // the chunks to send this tick, nearest the player first, and counts them as sent. empty when the client is - // still busy with earlier batches. can_send says whether there's time left to build one more - next_batch(can_send: () => boolean = () => true): [number, number][] { + // still busy with earlier batches. can_send says whether there's time left to build one more, ready whether a + // chunk can be built yet (with a worldgen pool, whether what it's built from has been generated) + next_batch(can_send: () => boolean = () => true, ready?: (x: number, z: number) => boolean): [number, number][] { if (this.#unacknowledged_batches >= this.#max_unacknowledged_batches || !this.center) { return []; } @@ -95,6 +107,7 @@ export class PlayerChunks { const batch: [number, number][] = []; for (const { key, cx, cz } of nearest) { if (batch.length >= Math.floor(this.#batch_quota) || !can_send()) break; + if (ready && !ready(cx, cz)) continue; this.#pending.delete(key); this.#sent.set(key, [cx, cz]); batch.push([cx, cz]); diff --git a/server/game/worker.ts b/server/game/worker.ts index c1ac95d..2f50e89 100644 --- a/server/game/worker.ts +++ b/server/game/worker.ts @@ -5,8 +5,11 @@ import type { GameServer } from "./game_server.ts"; import { GameLoop } from "./game_loop.ts"; import { GameToHost, HostToGame } from "./host_protocol.ts"; import { data_url, start_game } from "./load_mods.ts"; +import { type WorkerPort, WorldgenPool } from "./worldgen_pool.ts"; const SAVE_INTERVAL_MS = 30_000; +// how long the worldgen workers get to load the mods before the game starts without them +const WORLDGEN_START_TIMEOUT_MS = 60_000; let game: GameServer | undefined; let starting: Promise | undefined; @@ -31,6 +34,12 @@ self.onmessage = async (event: MessageEvent) => { starting = init(message); return; } + if (message.type === "worldgen_port") { + // the worker it replaces crashed. the pool resends what it was working on + await starting; + game?.worldgen_pool?.replace(message.index, message.port as unknown as WorkerPort); + return; + } if (message.type === "downloaded") { const pending = downloads.get(message.id); downloads.delete(message.id); @@ -93,6 +102,26 @@ async function init(message: Extract) { return; } + // chunks are generated in the worldgen workers, except what can't wait for them + if (message.worldgen_ports.length > 0) { + const pool = new WorldgenPool(message.worldgen_ports as unknown as WorkerPort[], game.worldgen_bundle!); + game.use_worldgen_pool(pool); + try { + let timer: ReturnType | undefined; + await Promise.race([ + pool.ready(), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("they took too long")), WORLDGEN_START_TIMEOUT_MS); + }), + ]).finally(() => clearTimeout(timer)); + await game.warm_up(); + } catch (e) { + console.error(`The worldgen workers didn't start, generating on the game thread: ${(e as Error).message}`); + game.use_worldgen_pool(undefined); + pool.close(); + } + } + const loop = new GameLoop(() => game!.tick()); game.loop = loop; loop.start(); diff --git a/server/game/world.ts b/server/game/world.ts index 64045c3..d9513bb 100644 --- a/server/game/world.ts +++ b/server/game/world.ts @@ -7,7 +7,8 @@ import { } from "$/common/everything_registry.ts"; import { generate_raw_chunk, RawChunk, WorldgenSetup } from "$/common/generation.ts"; import { AIR_ID, BlockChange } from "$/common/protocol.ts"; -import { block_value, chunk_key, default_block_value } from "$/common/utils.ts"; +import { block_value, chunk_key } from "$/common/utils.ts"; +import { block_numbering } from "$/common/worldgen_bundle.ts"; import { LruMap } from "./lru.ts"; import { collision_shape_at, EMPTY_SHAPE, type Shape } from "$/common/block_shapes.ts"; import { farming_day } from "$/common/time.ts"; @@ -15,9 +16,13 @@ import { encode_level_chunk } from "$/common/chunk_streaming.ts"; import type { ItemData } from "$/common/inventory.ts"; import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, SavedChunk } from "./saves.ts"; -// generation only, rebuilt when needed. 256 KB each -const RAW_CACHE_SIZE = 128; +// generation only, rebuilt when needed. 256 KB each. with a worldgen pool, it holds what the pool made until the +// chunks are built, a few dozen chunks ahead of what players are sent +const RAW_CACHE_SIZE = 256; const CHUNK_CACHE_SIZE = 256; +// a raw chunk's spills and biomes, a few KB each, kept longer than its blocks: building a chunk needs its own raw +// blocks and only its neighbors' spills +const SPILL_CACHE_SIZE = 4096; // surface and sky heights, 1 KB each const COLUMN_CACHE_SIZE = 1024; // light reaches at most this far, see light_at @@ -25,8 +30,10 @@ const LIGHT_REACH = 15; const LIGHT_BOX = LIGHT_REACH * 2 + 1; // how far from the middle of the world to look for dry land to spawn on, in chunks const SPAWN_SEARCH_CHUNKS = 32; +// the chunks around the middle the spawn search usually finds land in, with their neighbors, worth generating ahead +export const SPAWN_AREA_CHUNKS = 3; // generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one -const FINGERPRINT_CHUNKS = [[0, 0], [7, -3], [-45, 18], [130, -80], [-310, 260], [1000, -1000]]; +export const FINGERPRINT_CHUNKS = [[0, 0], [7, -3], [-45, 18], [130, -80], [-310, 260], [1000, -1000]]; // a block with data the server keeps, like where a chest's items are. never sent to clients, but for item export interface Tile { @@ -58,8 +65,14 @@ export class ServerWorld { // what generation made, and the final blocks with neighbors' leaves and player changes applied #raw = new LruMap(RAW_CACHE_SIZE); #chunks = new LruMap(CHUNK_CACHE_SIZE); - // what generation decided each column's biome is, kept for longer than the rest of it - #biomes = new LruMap(COLUMN_CACHE_SIZE); + // what generation decided each column's biome is, and what it put in neighbors, kept for longer than the rest + #biomes = new LruMap(SPILL_CACHE_SIZE); + #spills = new LruMap(SPILL_CACHE_SIZE); + // raw chunks generated on this thread because nothing had made them yet: with a worldgen pool, what still waits + // on generation. see GameServer's /tps + fallbacks = 0; + // what called for them, by the caller's place in the code, when set. for finding what to move off the fallback + fallback_callers?: Map; // per column of a chunk, the highest block that isn't air, then the lowest y that sees the sky. see #columns_of #columns = new LruMap(COLUMN_CACHE_SIZE); @@ -88,12 +101,13 @@ export class ServerWorld { constructor(seed: string, worldgen: WorldgenSetup) { this.seed = seed; this.worldgen = worldgen; - const blocks = EverythingRegistry.get_registry("blocks"); + // numbered the same way as generation in a worker numbers them, see common/worldgen_bundle.ts + const { block_ids, default_values } = block_numbering(); + Object.assign(this.block_ids, block_ids); + this.default_values.push(...default_values); this.#opacity = new Uint8Array(ID_MASK + 1); this.#emission = new Uint8Array(ID_MASK + 1); - blocks.forEach((block, nid) => { - this.block_ids[block.id] = nid; - this.default_values[nid] = default_block_value(nid, block); + EverythingRegistry.get_registry("blocks").forEach((block, nid) => { this.#opacity[nid] = block_light_opacity(block); this.#emission[nid] = block_light_emission(block); }); @@ -185,6 +199,11 @@ export class ServerWorld { return biomes[column_index(x, z)]; } + // builds the chunk now if it isn't, generating what it needs on this thread + build(chunk_x: number, chunk_z: number) { + this.#get_chunk(chunk_x, chunk_z); + } + // whether the chunk is built and kept, like a loaded chunk in minecraft. nothing builds one by asking has_chunk(chunk_x: number, chunk_z: number) { return this.#chunks.has(chunk_key(chunk_x, chunk_z)); @@ -354,7 +373,7 @@ export class ServerWorld { x: chunk_x, z: chunk_z, blocks: this.#get_chunk(chunk_x, chunk_z), - biomes: this.#get_raw(chunk_x, chunk_z).biomes, + biomes: this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes, }); } @@ -543,13 +562,55 @@ export class ServerWorld { const key = chunk_key(chunk_x, chunk_z); let raw = this.#raw.get(key); if (!raw) { + this.fallbacks += 1; + if (this.fallback_callers) { + const caller = fallback_caller(new Error().stack ?? ""); + this.fallback_callers.set(caller, (this.fallback_callers.get(caller) ?? 0) + 1); + } raw = generate_raw_chunk(chunk_x, chunk_z, this.seed, this.block_ids, this.worldgen, this.default_values); - this.#raw.set(key, raw); - this.#biomes.set(key, raw.biomes); + this.#keep_raw(key, raw); } return raw; } + #keep_raw(key: number, raw: RawChunk) { + this.#raw.set(key, raw); + this.#biomes.set(key, raw.biomes); + this.#spills.set(key, raw.spills); + } + + // a raw chunk a worldgen worker made. generation is the same everywhere, so one made here first is kept + add_raw(chunk_x: number, chunk_z: number, raw: RawChunk) { + const key = chunk_key(chunk_x, chunk_z); + if (!this.#raw.has(key)) this.#keep_raw(key, raw); + } + + // whether the chunk is built, or can be without generating anything: its own raw blocks and its neighbors' spills + // are here + can_build(chunk_x: number, chunk_z: number) { + return this.raws_needed(chunk_x, chunk_z).length === 0; + } + + // the raw chunks building it would generate on this thread: its own, if it isn't built and its blocks aren't here, + // and its neighbors' whose spills aren't + raws_needed(chunk_x: number, chunk_z: number): [number, number][] { + if (this.#chunks.has(chunk_key(chunk_x, chunk_z))) return []; + const needed: [number, number][] = []; + if (!this.#raw.has(chunk_key(chunk_x, chunk_z))) needed.push([chunk_x, chunk_z]); + for (let dx = -1; dx <= 1; dx++) { + for (let dz = -1; dz <= 1; dz++) { + if ((dx !== 0 || dz !== 0) && !this.#spills.has(chunk_key(chunk_x + dx, chunk_z + dz))) { + needed.push([chunk_x + dx, chunk_z + dz]); + } + } + } + return needed; + } + + #spills_of(chunk_x: number, chunk_z: number) { + return this.#spills.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).spills; + } + #get_chunk(chunk_x: number, chunk_z: number) { const key = chunk_key(chunk_x, chunk_z); let blocks = this.#chunks.get(key); @@ -581,7 +642,7 @@ export class ServerWorld { if (dx === 0 && dz === 0) { continue; } - const spills = this.#get_raw(chunk_x + dx, chunk_z + dz).spills; + const spills = this.#spills_of(chunk_x + dx, chunk_z + dz); for (let i = 0; i < spills.length; i += 4) { const [x, y, z, nid] = [spills[i], spills[i + 1], spills[i + 2], spills[i + 3]]; if (Math.floor(x / CHUNK_SIZE) !== chunk_x || Math.floor(z / CHUNK_SIZE) !== chunk_z) { @@ -598,6 +659,14 @@ export class ServerWorld { } } +// where in the code a fallback came from: the first caller outside this file, as file:line +function fallback_caller(stack: string) { + const frames = stack.split("\n").slice(1).map((line) => line.trim()); + const outside = frames.find((frame) => !frame.includes("/world.ts")) ?? frames[0] ?? "unknown"; + const match = outside.match(/at (?:(\S+) )?\(?.*\/([^/]+:\d+):\d+\)?$/); + return match ? `${match[1] ?? "?"} ${match[2]}` : outside; +} + function index_in_chunk(x: number, y: number, z: number, chunk_x: number, chunk_z: number) { return y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE); } diff --git a/server/game/worldgen_pool.ts b/server/game/worldgen_pool.ts new file mode 100644 index 0000000..0a9ffe0 --- /dev/null +++ b/server/game/worldgen_pool.ts @@ -0,0 +1,207 @@ +// generates chunks in worldgen workers (worldgen_worker.ts) instead of on the game's thread. the host starts the +// workers and gives the game a port to each, since the game has no permissions to start them itself (see +// GENERATION.md). requests go nearest first, a worker has a couple at a time so priorities stay fresh, and what the +// game stops wanting is dropped before it starts +import type { RawChunk } from "$/common/generation.ts"; +import type { WorldgenBundle } from "$/common/worldgen_bundle.ts"; +import { chunk_key } from "$/common/utils.ts"; + +export type PoolToWorker = + | { type: "init"; bundle: WorldgenBundle } + | { type: "generate"; x: number; z: number }; + +export type WorkerToPool = + | { type: "ready" } + | { type: "failed"; error: string } + | { type: "chunk"; x: number; z: number; blocks: Uint32Array; spills: Int32Array; biomes: string[] } + | { type: "error"; x: number; z: number; error: string }; + +// the game's end of a channel to a worker +export interface WorkerPort { + postMessage(message: PoolToWorker): void; + onmessage: ((event: MessageEvent) => void) | null; + close?(): void; +} + +// chunks a worker works on at once: one generating, one waiting so it never sits idle between messages +const IN_FLIGHT_PER_WORKER = 2; + +interface Slot { + port: WorkerPort; + ready: boolean; + dead: boolean; + in_flight: Map; +} + +interface Queued { + x: number; + z: number; + // lower goes first + priority: number; +} + +export class WorldgenPool { + #bundle: WorldgenBundle; + #slots: Slot[] = []; + #queue = new Map(); + // asked for by prefetch, kept when want() drops the rest + #kept = new Set(); + #waiters = new Map void)[]>(); + #ready: Promise; + #settle_ready!: { resolve: () => void; reject: (error: Error) => void }; + #reported = false; + // where finished chunks go + on_chunk: (x: number, z: number, raw: RawChunk) => void = () => {}; + // chunks generated since the pool started + generated = 0; + + constructor(ports: WorkerPort[], bundle: WorldgenBundle) { + this.#bundle = bundle; + this.#ready = new Promise((resolve, reject) => this.#settle_ready = { resolve, reject }); + ports.forEach((port, index) => this.#attach(index, port)); + if (ports.length === 0) this.#settle_ready.resolve(); + } + + // every worker has loaded the bundle. rejects when none could + ready(): Promise { + return this.#ready; + } + + get workers() { + return this.#slots.filter((slot) => !slot.dead).length; + } + + get queued() { + return this.#queue.size; + } + + get in_flight() { + return this.#slots.reduce((sum, slot) => sum + slot.in_flight.size, 0); + } + + // queued or being generated + pending(x: number, z: number) { + const key = chunk_key(x, z); + return this.#queue.has(key) || this.#slots.some((slot) => slot.in_flight.has(key)); + } + + // what the game wants generated now, by chunk_key: these are queued with their priorities, the rest of the queue + // is dropped, except what prefetch asked for. chunks being generated finish either way + want(wanted: Map) { + for (const key of this.#queue.keys()) { + if (!wanted.has(key) && !this.#kept.has(key)) this.#queue.delete(key); + } + for (const [key, request] of wanted) { + if (this.#slots.some((slot) => slot.in_flight.has(key))) continue; + const queued = this.#queue.get(key); + if (!queued || request.priority < queued.priority) this.#queue.set(key, request); + } + this.#pump(); + } + + // generates these first, and resolves once they're all through on_chunk (or failed) + prefetch(chunks: [number, number][]): Promise { + const done = Promise.all(chunks.map(([x, z]) => { + const key = chunk_key(x, z); + this.#kept.add(key); + if (!this.pending(x, z)) this.#queue.set(key, { x, z, priority: -Infinity }); + return new Promise((resolve) => { + const waiting = this.#waiters.get(key) ?? []; + waiting.push(resolve); + this.#waiters.set(key, waiting); + }); + })); + this.#pump(); + return done.then(() => {}); + } + + // a worker that crashed was started again: its chunks are sent to the new one + replace(index: number, port: WorkerPort) { + const old = this.#slots[index]; + if (old) { + for (const [key, [x, z]] of old.in_flight) this.#queue.set(key, { x, z, priority: -Infinity }); + old.port.onmessage = null; + } + this.#attach(index, port); + } + + close() { + for (const slot of this.#slots) { + slot.port.onmessage = null; + slot.port.close?.(); + } + this.#slots = []; + } + + #attach(index: number, port: WorkerPort) { + const slot: Slot = { port, ready: false, dead: false, in_flight: new Map() }; + this.#slots[index] = slot; + port.onmessage = (event) => this.#on_message(slot, event.data); + port.postMessage({ type: "init", bundle: this.#bundle }); + } + + #on_message(slot: Slot, message: WorkerToPool) { + switch (message.type) { + case "ready": + slot.ready = true; + this.#settle_ready.resolve(); + break; + case "failed": + slot.dead = true; + console.error( + `A worldgen worker couldn't start, chunks it would have made are made on the game thread: ${message.error}`, + ); + if (this.workers === 0) this.#settle_ready.reject(new Error(message.error)); + break; + case "chunk": { + const key = chunk_key(message.x, message.z); + slot.in_flight.delete(key); + this.generated++; + this.on_chunk(message.x, message.z, { + blocks: message.blocks, + spills: message.spills, + biomes: message.biomes, + }); + this.#done(key); + break; + } + case "error": { + // the game generates it itself when it needs it, and runs into the same error there + const key = chunk_key(message.x, message.z); + slot.in_flight.delete(key); + if (!this.#reported) { + this.#reported = true; + console.error( + `A worldgen worker couldn't generate chunk ${message.x}, ${message.z}: ${message.error}`, + ); + } + this.#done(key); + break; + } + } + this.#pump(); + } + + #done(key: number) { + this.#kept.delete(key); + for (const resolve of this.#waiters.get(key) ?? []) resolve(); + this.#waiters.delete(key); + } + + // gives free workers the queue's most urgent chunks + #pump() { + for (const slot of this.#slots) { + if (!slot.ready || slot.dead) continue; + while (slot.in_flight.size < IN_FLIGHT_PER_WORKER && this.#queue.size > 0) { + let best: [number, Queued] | undefined; + for (const entry of this.#queue) { + if (!best || entry[1].priority < best[1].priority) best = entry; + } + const [key, { x, z }] = best!; + this.#queue.delete(key); + slot.in_flight.set(key, [x, z]); + slot.port.postMessage({ type: "generate", x, z }); + } + } + } +} diff --git a/server/game/worldgen_worker.ts b/server/game/worldgen_worker.ts new file mode 100644 index 0000000..ab291b5 --- /dev/null +++ b/server/game/worldgen_worker.ts @@ -0,0 +1,41 @@ +/// + +// generates chunks for the game, off its thread. the host starts it without permissions, like the game, and hands it +// a port the game talks to it through (see server/worldgen_workers.ts and worldgen_pool.ts). the game sends the +// worldgen bundle once, then chunks to generate, and gets their blocks back moved, not copied +import { load_bundle, type LoadedBundle } from "$/common/worldgen_bundle.ts"; +import { expose_engine } from "$/common/hooks.ts"; +import { common_engine } from "$/common/engine_modules.ts"; +import type { PoolToWorker, WorkerToPool } from "./worldgen_pool.ts"; + +self.onmessage = (event: MessageEvent<{ port: MessagePort }>) => { + const port = event.data.port; + const send = (message: WorkerToPool, transfer: Transferable[] = []) => port.postMessage(message, transfer); + let loaded: Promise | undefined; + + port.onmessage = async (event: MessageEvent) => { + const message = event.data; + if (message.type === "init") { + // worldgen scripts with engine access hook engine.common here, in this worker's own copy of the engine + expose_engine({ common: common_engine() }); + loaded = load_bundle(message.bundle); + try { + await loaded; + send({ type: "ready" }); + } catch (e) { + send({ type: "failed", error: e instanceof Error ? e.message : String(e) }); + } + return; + } + const { x, z } = message; + try { + const raw = (await loaded!).generate(x, z); + send({ type: "chunk", x, z, blocks: raw.blocks, spills: raw.spills, biomes: raw.biomes }, [ + raw.blocks.buffer, + raw.spills.buffer, + ]); + } catch (e) { + send({ type: "error", x, z, error: e instanceof Error ? e.message : String(e) }); + } + }; +}; diff --git a/server/host.ts b/server/host.ts index b70bdc2..7c609e1 100644 --- a/server/host.ts +++ b/server/host.ts @@ -5,6 +5,7 @@ import { join } from "@std/path"; import { GameToHost, HostToGame } from "./game/host_protocol.ts"; import { load_bmods } from "./load_bmods.ts"; import { read_regions, write_chunks } from "./regions.ts"; +import { default_worldgen_workers, start_worldgen_workers } from "./worldgen_workers.ts"; import type { SavedChunk, WorldSave } from "./game/saves.ts"; const MAX_MESSAGE_SIZE = 4096; @@ -25,6 +26,9 @@ export interface HostOptions { // the world's folder: level.json, and the blocks in region/ world_dir: string; seed?: string; + // how many workers generate chunks, besides the game. 0 generates on the game's thread. a few by default, see + // default_worldgen_workers + worldgen_workers?: number; // the game can't go on, like the worker crashing on_fatal(message: string): void; } @@ -46,7 +50,12 @@ export async function start_host(options: HostOptions): Promise { type: "module", deno: { permissions: "none" }, } as WorkerOptions); - const post = (message: HostToGame) => game.postMessage(message); + const post = (message: HostToGame, transfer: Transferable[] = []) => game.postMessage(message, transfer); + // without permissions like the game, which can't start them itself + const worldgen = start_worldgen_workers(options.worldgen_workers ?? default_worldgen_workers(), { + permissions: "none", + on_restart: (index, port) => post({ type: "worldgen_port", index, port }, [port]), + }); const sockets = new Map(); let next_conn = 1; @@ -123,8 +132,9 @@ export async function start_host(options: HostOptions): Promise { worldgen_code: bmod.scripts.worldgen, shared_code: bmod.scripts.shared, })), + worldgen_ports: worldgen.ports, } satisfies HostToGame, - save.chunks.map((chunk) => chunk.data.buffer), + [...save.chunks.map((chunk) => chunk.data.buffer), ...worldgen.ports], ); function handle_socket(socket: WebSocket) { @@ -191,6 +201,7 @@ export async function start_host(options: HostOptions): Promise { on_final_save = (error) => { clearTimeout(timeout); game.terminate(); + worldgen.terminate(); if (error) { reject(error); } else { diff --git a/server/main.ts b/server/main.ts index 650037e..92d8eaa 100644 --- a/server/main.ts +++ b/server/main.ts @@ -11,6 +11,8 @@ try { dist_dir: Deno.env.get("DIST_DIR") ?? "dist", world_dir: Deno.env.get("WORLD_DIR") ?? "world", seed: Deno.env.get("SEED"), + // leave it out for a few, 0 to generate on the game's thread + worldgen_workers: Deno.env.get("WORLDGEN_WORKERS") ? Number(Deno.env.get("WORLDGEN_WORKERS")) : undefined, on_fatal(message) { console.error(message); Deno.exit(1); diff --git a/server/worldgen_workers.ts b/server/worldgen_workers.ts new file mode 100644 index 0000000..6678eee --- /dev/null +++ b/server/worldgen_workers.ts @@ -0,0 +1,62 @@ +// the worldgen workers (game/worldgen_worker.ts), started by the host because the game worker has no permissions to +// start workers itself: Deno checks a new worker's code against its parent's permissions. each gets one end of a +// channel and the game the other, so the game talks to them directly. a worker that crashes is started again and the +// game is given its new port. see GENERATION.md +const WORKER_URL = new URL("./game/worldgen_worker.ts", import.meta.url); +// a worker that keeps crashing isn't started again after this many times, the game generates without it +const MAX_RESTARTS = 5; + +// leaves a core for the game and one for everything else, and more than 4 doesn't help much +export function default_worldgen_workers(): number { + return Math.min(4, Math.max(1, (navigator.hardwareConcurrency ?? 2) - 2)); +} + +export interface WorldgenWorkers { + // the game's ends, in order + ports: MessagePort[]; + terminate(): void; +} + +export function start_worldgen_workers( + count: number, + options: { + // "none" like the game, for the host. tests load worldgen scripts from files, which needs "inherit" + permissions: "none" | "inherit"; + // a worker crashed and was started again: the game's end of its new channel + on_restart(index: number, port: MessagePort): void; + }, +): WorldgenWorkers { + const workers: Worker[] = []; + const restarts: number[] = Array(count).fill(0); + let stopped = false; + const start = (index: number): MessagePort => { + const worker = new Worker(WORKER_URL, { + type: "module", + deno: { permissions: options.permissions }, + } as WorkerOptions); + const channel = new MessageChannel(); + worker.postMessage({ port: channel.port1 }, [channel.port1]); + worker.onerror = (event) => { + event.preventDefault(); + worker.terminate(); + if (stopped) return; + if (++restarts[index] > MAX_RESTARTS) { + console.error(`Worldgen worker ${index} crashed again, leaving it: ${event.message}`); + return; + } + console.error(`Worldgen worker ${index} crashed, starting it again: ${event.message}`); + options.on_restart(index, start(index)); + }; + workers[index] = worker; + return channel.port2; + }; + const ports = Array.from({ length: count }, (_, index) => start(index)); + return { + ports, + terminate() { + stopped = true; + for (const worker of workers) worker.terminate(); + for (const port of ports) port.close(); + }, + }; +} diff --git a/tests/bmod_test.ts b/tests/bmod_test.ts index 357bb05..13e36c3 100644 --- a/tests/bmod_test.ts +++ b/tests/bmod_test.ts @@ -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((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 = { diff --git a/tests/chunk_loading.ts b/tests/chunk_loading.ts new file mode 100644 index 0000000..02c41c8 --- /dev/null +++ b/tests/chunk_loading.ts @@ -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>, + 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(); + 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 }; +} diff --git a/tests/chunk_loading_test.ts b/tests/chunk_loading_test.ts new file mode 100644 index 0000000..eed0b49 --- /dev/null +++ b/tests/chunk_loading_test.ts @@ -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(); + } + }, +}); diff --git a/tests/engine_access_test.ts b/tests/engine_access_test.ts index 0b9d6ad..6dac635 100644 --- a/tests/engine_access_test.ts +++ b/tests/engine_access_test.ts @@ -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", { diff --git a/tests/golden.ts b/tests/golden.ts new file mode 100644 index 0000000..9ebe223 --- /dev/null +++ b/tests/golden.ts @@ -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>; + +// 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): (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 { + 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 { + 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(); + 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; +} diff --git a/tests/worldgen_bundle_test.ts b/tests/worldgen_bundle_test.ts new file mode 100644 index 0000000..d00bb30 --- /dev/null +++ b/tests/worldgen_bundle_test.ts @@ -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}`, + ); + } + } +}); diff --git a/tests/worldgen_golden_test.ts b/tests/worldgen_golden_test.ts index a4c939e..11cc5ae 100644 --- a/tests/worldgen_golden_test.ts +++ b/tests/worldgen_golden_test.ts @@ -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>; +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(); - 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; -} diff --git a/tests/worldgen_pool_test.ts b/tests/worldgen_pool_test.ts new file mode 100644 index 0000000..b9809cf --- /dev/null +++ b/tests/worldgen_pool_test.ts @@ -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(); + 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(); + } + }, +}); diff --git a/tools/chunk_loading_bench.ts b/tools/chunk_loading_bench.ts new file mode 100644 index 0000000..c6994e8 --- /dev/null +++ b/tools/chunk_loading_bench.ts @@ -0,0 +1,33 @@ +// how fast a player arriving somewhere new gets the chunks around them, with worldgen workers and without, and the +// longest tick while they come in. ticks are paced like the game loop's, 50 ms apart. +// deno run -A tools/chunk_loading_bench.ts [workers=4] [view distance=16] +import { game_with_pool, load_view } from "../tests/chunk_loading.ts"; + +const workers = Number(Deno.args[0] ?? 4); +const distance = Number(Deno.args[1] ?? 16); + +for (const count of [0, workers]) { + const t = await game_with_pool(count, "bench-seed"); + // like the real server: a tick only builds chunks for 20 ms, and monsters spawn + t.game.chunk_send_budget_ms = 20; + t.game.do_mob_spawning = true; + t.game.view_distance = distance; + t.join(1, "alice"); + t.send(1, { type: "view_distance", distance }); + const player = t.game.players()[0]; + // what's around spawn first, so the teleport is all that's measured + await load_view(t, 1, 50); + const fallbacks = t.game.world.fallbacks; + t.game.world.fallback_callers = new Map(); + t.game.teleport(player, 10_000.5, 150, 3_000.5); + const { chunks, longest_tick, ms } = await load_view(t, 1, 50); + console.log( + `${count === 0 ? "game thread" : `${count} workers`}: ${chunks.size} chunks in ${(ms / 1000).toFixed(1)} s, ` + + `longest tick ${longest_tick.toFixed(0)} ms, ${ + t.game.world.fallbacks - fallbacks + } generated on the game thread`, + Object.fromEntries(t.game.world.fallback_callers), + ); + t.close(); +} +Deno.exit(0);