Files
bworld/server/game/worker.ts
T

107 lines
2.9 KiB
TypeScript

/// <reference lib="deno.worker" />
// 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 } from "./host_protocol.ts";
import { data_url, start_game } from "./load_mods.ts";
const SAVE_INTERVAL_MS = 30_000;
let game: GameServer | undefined;
let starting: Promise<void> | undefined;
// downloads waiting for the host, by id
const downloads = new Map<number, { resolve: (bytes: Uint8Array) => void; reject: (error: Error) => void }>();
let next_download = 1;
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);
}
self.onmessage = async (event: MessageEvent<HostToGame>) => {
const message = event.data;
if (message.type === "init") {
starting = init(message);
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<HostToGame, { type: "init" }>) {
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 });
}),
},
message.save,
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,
})),
);
} catch (e) {
post({ type: "failed", error: e instanceof Error ? e.message : String(e) });
return;
}
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 });
}