Save all generated chunks instead of only chunks that were changed

This commit is contained in:
2026-10-11 02:02:01 -03:00
parent 44a39bf8ec
commit 5a59a63862
17 changed files with 644 additions and 314 deletions
+26 -2
View File
@@ -3,19 +3,23 @@
// 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 { 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<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;
// 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
@@ -27,6 +31,26 @@ function post(message: GameToHost) {
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<HostToGame>) => {
const message = event.data;
@@ -86,7 +110,7 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
post({ type: "download", id, url, max_bytes });
}),
},
message.save,
{ level: message.save.level, chunks: { list: message.save.chunks, read: read_chunk } },
message.default_seed,
message.mods.map((mod) => ({
listing: mod.listing,