Region file format
This commit is contained in:
+67
-31
@@ -4,6 +4,8 @@ import { serveDir } from "@std/http/file-server";
|
||||
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 type { SavedChunk, WorldSave } from "./game/saves.ts";
|
||||
|
||||
const MAX_MESSAGE_SIZE = 4096;
|
||||
// in build/, see build.ts
|
||||
@@ -16,7 +18,8 @@ export interface HostOptions {
|
||||
build_dir: string;
|
||||
// the .bmod files to load
|
||||
server_mods_dir: string;
|
||||
world_file: string;
|
||||
// the world's folder: level.json, and the blocks in region/
|
||||
world_dir: string;
|
||||
seed?: string;
|
||||
// the game can't go on, like the worker crashing
|
||||
on_fatal(message: string): void;
|
||||
@@ -43,13 +46,17 @@ export async function start_host(options: HostOptions): Promise<Host> {
|
||||
|
||||
const sockets = new Map<number, WebSocket>();
|
||||
let next_conn = 1;
|
||||
let on_final_save: (() => void) | undefined;
|
||||
let on_final_save: ((error?: Error) => void) | undefined;
|
||||
// saves are written one after another, in order
|
||||
let saving = Promise.resolve();
|
||||
// chunks from saves that couldn't be written, tried again with the next one
|
||||
let unwritten = new Map<string, SavedChunk>();
|
||||
|
||||
game.onmessage = (event: MessageEvent<GameToHost>) => {
|
||||
const message = event.data;
|
||||
switch (message.type) {
|
||||
case "ready":
|
||||
console.log(`World ${options.world_file} ready, seed ${message.seed}`);
|
||||
console.log(`World ${options.world_dir} ready, seed ${message.seed}`);
|
||||
break;
|
||||
case "failed":
|
||||
options.on_fatal(`Couldn't start the game: ${message.error}`);
|
||||
@@ -64,13 +71,27 @@ export async function start_host(options: HostOptions): Promise<Host> {
|
||||
case "close":
|
||||
sockets.get(message.conn)?.close();
|
||||
break;
|
||||
case "save":
|
||||
write_world(options.world_file, message.data);
|
||||
if (message.final) {
|
||||
console.log("World saved");
|
||||
on_final_save?.();
|
||||
}
|
||||
case "save": {
|
||||
const { save, final } = message;
|
||||
saving = saving.then(async () => {
|
||||
const chunks = new Map(unwritten);
|
||||
for (const chunk of save.chunks) chunks.set(`${chunk.x},${chunk.z}`, chunk);
|
||||
try {
|
||||
await write_world(options.world_dir, { level: save.level, chunks: [...chunks.values()] });
|
||||
unwritten = new Map();
|
||||
} catch (e) {
|
||||
unwritten = chunks;
|
||||
console.error(`Couldn't save the world: ${(e as Error).message}`);
|
||||
if (final) on_final_save?.(e as Error);
|
||||
return;
|
||||
}
|
||||
if (final) {
|
||||
console.log("World saved");
|
||||
on_final_save?.();
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "download":
|
||||
download(message.url, message.max_bytes).then(
|
||||
(bytes) => post({ type: "downloaded", id: message.id, bytes }),
|
||||
@@ -85,17 +106,21 @@ export async function start_host(options: HostOptions): Promise<Host> {
|
||||
options.on_fatal(`Game server crashed: ${event.message}`);
|
||||
};
|
||||
|
||||
post({
|
||||
type: "init",
|
||||
save: read_world(options.world_file),
|
||||
default_seed: options.seed ?? crypto.randomUUID(),
|
||||
mods: mods.map(({ listing, bmod }) => ({
|
||||
listing,
|
||||
data: bmod.data,
|
||||
server_code: bmod.scripts.server,
|
||||
worldgen_code: bmod.scripts.worldgen,
|
||||
})),
|
||||
});
|
||||
const save = await read_world(options.world_dir);
|
||||
game.postMessage(
|
||||
{
|
||||
type: "init",
|
||||
save,
|
||||
default_seed: options.seed ?? crypto.randomUUID(),
|
||||
mods: mods.map(({ listing, bmod }) => ({
|
||||
listing,
|
||||
data: bmod.data,
|
||||
server_code: bmod.scripts.server,
|
||||
worldgen_code: bmod.scripts.worldgen,
|
||||
})),
|
||||
} satisfies HostToGame,
|
||||
save.chunks.map((chunk) => chunk.data.buffer),
|
||||
);
|
||||
|
||||
function handle_socket(socket: WebSocket) {
|
||||
const conn = next_conn++;
|
||||
@@ -154,10 +179,14 @@ export async function start_host(options: HostOptions): Promise<Host> {
|
||||
() => reject(new Error("Game server didn't save in time")),
|
||||
SHUTDOWN_TIMEOUT_MS,
|
||||
);
|
||||
on_final_save = () => {
|
||||
on_final_save = (error) => {
|
||||
clearTimeout(timeout);
|
||||
game.terminate();
|
||||
resolve();
|
||||
if (error) {
|
||||
reject(error);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
post({ type: "shutdown" });
|
||||
});
|
||||
@@ -219,21 +248,28 @@ async function download(url: string, max_bytes: number): Promise<Uint8Array> {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function read_world(file: string): string | undefined {
|
||||
const LEVEL_FILE = "level.json";
|
||||
const REGION_DIR = "region";
|
||||
|
||||
// a folder that isn't there is a new world
|
||||
async function read_world(dir: string): Promise<WorldSave> {
|
||||
let level: string | undefined;
|
||||
try {
|
||||
return Deno.readTextFileSync(file);
|
||||
level = Deno.readTextFileSync(join(dir, LEVEL_FILE));
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) {
|
||||
return undefined;
|
||||
}
|
||||
throw e;
|
||||
if (!(e instanceof Deno.errors.NotFound)) throw e;
|
||||
}
|
||||
return { level, chunks: level ? await read_regions(join(dir, REGION_DIR)) : [] };
|
||||
}
|
||||
|
||||
function write_world(file: string, data: string) {
|
||||
// the chunks first, level.json says which world generation they were saved with
|
||||
async function write_world(dir: string, save: Required<WorldSave>) {
|
||||
await write_chunks(join(dir, REGION_DIR), save.chunks);
|
||||
Deno.mkdirSync(dir, { recursive: true });
|
||||
// write then rename so a crash mid write doesnt eat the world
|
||||
Deno.writeTextFileSync(`${file}.tmp`, data);
|
||||
Deno.renameSync(`${file}.tmp`, file);
|
||||
const level = join(dir, LEVEL_FILE);
|
||||
Deno.writeTextFileSync(`${level}.tmp`, save.level);
|
||||
Deno.renameSync(`${level}.tmp`, level);
|
||||
}
|
||||
|
||||
// the engine's textures, listed by the build next to the client's assets. engine:missing is drawn by code
|
||||
|
||||
Reference in New Issue
Block a user