Workers for chunk generation !

This commit is contained in:
2026-10-11 01:15:14 -03:00
parent 3d2b235f64
commit cd3b39c3d7
24 changed files with 1119 additions and 91 deletions
+93 -6
View File
@@ -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<number, { x: number; z: number; priority: number }>();
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;
}
+5
View File
@@ -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 }
+12
View File
@@ -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;
+15 -2
View File
@@ -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]);
+29
View File
@@ -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<void> | undefined;
@@ -31,6 +34,12 @@ self.onmessage = async (event: MessageEvent<HostToGame>) => {
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<HostToGame, { type: "init" }>) {
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<typeof setTimeout> | 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();
+83 -14
View File
@@ -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<number, RawChunk>(RAW_CACHE_SIZE);
#chunks = new LruMap<number, Uint32Array>(CHUNK_CACHE_SIZE);
// what generation decided each column's biome is, kept for longer than the rest of it
#biomes = new LruMap<number, string[]>(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<number, string[]>(SPILL_CACHE_SIZE);
#spills = new LruMap<number, Int32Array>(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<string, number>;
// 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<number, Int16Array>(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<BlockRegistry>("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<BlockRegistry>("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);
}
+207
View File
@@ -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<WorkerToPool>) => 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<number, [number, number]>;
}
interface Queued {
x: number;
z: number;
// lower goes first
priority: number;
}
export class WorldgenPool {
#bundle: WorldgenBundle;
#slots: Slot[] = [];
#queue = new Map<number, Queued>();
// asked for by prefetch, kept when want() drops the rest
#kept = new Set<number>();
#waiters = new Map<number, (() => void)[]>();
#ready: Promise<void>;
#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<void> {
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<number, Queued>) {
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<void> {
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<void>((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 });
}
}
}
}
+41
View File
@@ -0,0 +1,41 @@
/// <reference lib="deno.worker" />
// 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<LoadedBundle> | undefined;
port.onmessage = async (event: MessageEvent<PoolToWorker>) => {
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) });
}
};
};