/// // runs the game in a worker without any permissions, the host does files and networking import type { GameServer } from "./game_server.ts"; import { GameLoop } from "./game_loop.ts"; import { GameToHost, HostToGame, READ_DONE, READ_HEADER, READ_TOO_SMALL, READ_WAITING } 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; // a host that takes longer to read a chunk is stuck, and the game can't go on without it const CHUNK_READ_TIMEOUT_MS = 30_000; let game: GameServer | undefined; let starting: Promise | undefined; // downloads waiting for the host, by id const downloads = new Map void; reject: (error: Error) => void }>(); let next_download = 1; // where the host puts saved chunks, grown when one doesn't fit let chunk_buffer = new SharedArrayBuffer(READ_HEADER + 256 * 1024); function post(message: GameToHost) { // the chunks are moved to the host, not copied const transfer = message.type === "save" ? message.save.chunks.map((chunk) => chunk.data.buffer) : message.type === "send" && typeof message.data !== "string" ? [message.data.buffer] : []; self.postMessage(message, transfer); } // a saved chunk from the host. the game waits for it, like minecraft's server waits for a chunk it needs right away, // which takes much less than generating it function read_chunk(x: number, z: number): Uint8Array | undefined { for (;;) { const header = new Int32Array(chunk_buffer, 0, 2); Atomics.store(header, 0, READ_WAITING); post({ type: "read_chunk", x, z, buffer: chunk_buffer }); if (Atomics.wait(header, 0, READ_WAITING, CHUNK_READ_TIMEOUT_MS) === "timed-out") { throw new Error(`The host didn't read chunk ${x}, ${z}`); } const length = header[1]; if (Atomics.load(header, 0) === READ_TOO_SMALL) { chunk_buffer = new SharedArrayBuffer(READ_HEADER + length); continue; } if (Atomics.load(header, 0) !== READ_DONE) throw new Error(`Bad answer reading chunk ${x}, ${z}`); return length < 0 ? undefined : new Uint8Array(chunk_buffer, READ_HEADER, length).slice(); } } self.onmessage = async (event: MessageEvent) => { const message = event.data; if (message.type === "init") { 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); if (message.bytes) { pending?.resolve(message.bytes); } else { pending?.reject(new Error(message.error ?? "Couldn't download it")); } return; } // players can connect while mods are still loading await starting; if (!game) { return; } switch (message.type) { case "connect": game.on_connect(message.conn); break; case "message": game.on_message(message.conn, message.data); break; case "disconnect": game.on_disconnect(message.conn); break; case "shutdown": post({ type: "save", save: game.save(), final: true }); break; } }; async function init(message: Extract) { try { game = await start_game( { send: (conn, data) => post({ type: "send", conn, data }), close: (conn) => post({ type: "close", conn }), download: (url, max_bytes) => new Promise((resolve, reject) => { const id = next_download++; downloads.set(id, { resolve, reject }); post({ type: "download", id, url, max_bytes }); }), }, { level: message.save.level, chunks: { list: message.save.chunks, read: read_chunk } }, message.default_seed, message.mods.map((mod) => ({ listing: mod.listing, data: mod.data, // the worker has no file access, so the host sends the code and it's imported from memory server_url: mod.server_code ? data_url(mod.server_code) : undefined, worldgen_url: mod.worldgen_code ? data_url(mod.worldgen_code) : undefined, shared_url: mod.shared_code ? data_url(mod.shared_code) : undefined, })), ); } catch (e) { post({ type: "failed", error: e instanceof Error ? e.message : String(e) }); 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(); setInterval(() => { if (game!.world.dirty) { post({ type: "save", save: game!.save(), final: false }); } }, SAVE_INTERVAL_MS); post({ type: "ready", seed: game.world.seed }); }