211 lines
6.5 KiB
TypeScript
211 lines
6.5 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// 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
|
|
// server/worldgen_workers.ts). 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 });
|
|
}
|
|
}
|
|
}
|
|
}
|