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
+88
View File
@@ -11,6 +11,9 @@ import { load_bmods } from "$/server/load_bmods.ts";
import { start_host } from "$/server/host.ts";
import { copy_dir } from "./helpers.ts";
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
import { decode_level_chunk, type LevelChunk } from "$/common/chunk_streaming.ts";
import { decode_chunk, encode_chunk } from "$/server/game/saves.ts";
import { list_chunks, read_chunk, write_chunks } from "$/server/regions.ts";
const ENGINE_TEXTURES = ["engine:missing", ...Array.from({ length: 9 }, (_, i) => `engine:break_${i}`)];
@@ -324,6 +327,91 @@ Deno.test({
},
});
// joins a host as alice with view distance 4, until she has every chunk in view
async function join_host(port: number): Promise<LevelChunk[]> {
const socket = new WebSocket(`ws://localhost:${port}/ws`);
socket.binaryType = "arraybuffer";
const chunks: LevelChunk[] = [];
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`only ${chunks.length} chunks came`)), 60_000);
socket.onmessage = (event) => {
if (typeof event.data !== "string") {
chunks.push(decode_level_chunk(new Uint8Array(event.data)));
return;
}
const message = JSON.parse(event.data);
if (message.type === "welcome") socket.send(JSON.stringify({ type: "ready", view_distance: 4 }));
if (message.type === "chunk_batch_finished") {
socket.send(JSON.stringify({ type: "chunk_batch_received", chunks_per_tick: 64 }));
if (chunks.length >= 49) {
clearTimeout(timer);
resolve();
}
}
};
socket.onopen = () => socket.send(JSON.stringify({ type: "hello", name: "alice", protocol: PROTOCOL_VERSION }));
});
const closed = new Promise((resolve) => socket.onclose = resolve);
socket.close();
await closed;
return chunks;
}
Deno.test({
name: "a real host saves every chunk it generates, and players get them from the save after it starts again",
sanitizeOps: false,
sanitizeResources: false,
fn: async () => {
const { sources, folder } = await packed_mods();
const build = Deno.makeTempDirSync({ prefix: "bworld_build_" });
Deno.mkdirSync(`${build}/assets/textures`, { recursive: true });
Deno.writeTextFileSync(
`${build}/assets/textures/index.json`,
JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])),
);
const run = async () => {
const host = await start_host({
build_dir: build,
server_mods_dir: folder,
world_dir: `${build}/world`,
seed: "saving-seed",
worldgen_workers: 2,
on_fatal: (message) => {
throw new Error(message);
},
});
const server = Deno.serve({ port: 0, onListen: () => {} }, host.handle);
try {
return await join_host(server.addr.port);
} finally {
await server.shutdown();
await host.shutdown();
}
};
try {
const first = await run();
const region = `${build}/world/region`;
const saved = await list_chunks(region);
for (const chunk of first) assert(saved.some(([x, z]) => x === chunk.x && z === chunk.z));
// a block at the top of every saved chunk, which generation never puts there
await write_chunks(
region,
await Promise.all(saved.map(async ([x, z]) => {
const chunk = decode_chunk((await read_chunk(region, x, z))!);
chunk.blocks[255 * 256] = chunk.palette.push(["bworld:stone", 0]) - 1;
return { x, z, data: encode_chunk(chunk as Required<typeof chunk>) };
})),
);
const second = await run();
assert(second.length >= 49);
for (const chunk of second) assert(chunk.blocks[255 * 256] !== 0, `${chunk.x},${chunk.z} is from the save`);
} finally {
for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true });
}
},
});
// write_bmod without anything optional still makes a file read_bmod takes
Deno.test("a mod with only data packs and reads", () => {
const bmod = {
-1
View File
@@ -22,7 +22,6 @@ export async function game_with_pool(workers: number, seed?: string, mods_dir =
// ticks, answering chunk batches like a client, until the player has every chunk in view. the chunks they got, by
// "x,z", and how long the longest tick took
// deno-lint-ignore no-explicit-any
export async function load_view(
t: Awaited<ReturnType<typeof test_game>>,
conn: number,
+33 -2
View File
@@ -7,7 +7,7 @@ import { start_game } from "$/server/game/load_mods.ts";
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts";
import type { WorldSave } from "$/server/game/saves.ts";
import type { SavedChunk, SavedChunks, WorldSave } from "$/server/game/saves.ts";
// mods straight from their source folders, skipping the build: scripts are imported as typescript
export function mod_sources(mods_dir: string): ServerModSource[] {
@@ -53,6 +53,23 @@ export function mod_sources(mods_dir: string): ServerModSource[] {
});
}
// saved chunks kept in memory, the last saved where a chunk is saved more than once
class MemoryChunks implements SavedChunks {
#chunks = new Map<string, SavedChunk>();
get list(): [number, number][] {
return [...this.#chunks.values()].map(({ x, z }) => [x, z]);
}
read(x: number, z: number) {
return this.#chunks.get(`${x},${z}`)?.data;
}
add(chunks: SavedChunk[]) {
for (const chunk of chunks) this.#chunks.set(`${chunk.x},${chunk.z}`, chunk);
}
}
// a game with an in memory host that remembers what it sent to each connection. the seed has low, dry land around
// 0, 0, where players spawn and where tests build things
export async function test_game(mods_dir: string, save?: WorldSave, seed = "test-seed-90") {
@@ -77,7 +94,21 @@ export async function test_game(mods_dir: string, save?: WorldSave, seed = "test
return bytes ? Promise.resolve(bytes) : Promise.reject(new Error("Couldn't download it"));
},
};
const game: GameServer = await start_game(host, save, seed, mod_sources(mods_dir));
const chunks = new MemoryChunks();
if (save) chunks.add(save.chunks);
const game: GameServer = await start_game(
host,
{ level: save?.level, chunks },
seed,
mod_sources(mods_dir),
);
// what it saves is read back from memory, like a host's region files
const save_game = game.save.bind(game);
game.save = () => {
const saved = save_game();
chunks.add(saved.chunks);
return saved;
};
game.chunk_send_budget_ms = Infinity;
// tests that want natural spawning turn it back on
game.do_mob_spawning = false;
+116 -55
View File
@@ -1,27 +1,48 @@
import { assert, assertEquals, assertNotEquals } from "@std/assert";
import { assert, assertEquals } from "@std/assert";
import { AIR_ID } from "$/common/protocol.ts";
import { CHUNK_VOLUME, decode_chunk, encode_chunk, is_changed, SavedChunk } from "$/server/game/saves.ts";
import { read_regions, region_file, write_chunks } from "$/server/regions.ts";
import { CHUNK_AREA } from "$/common/constants.ts";
import { CHUNK_VOLUME, decode_chunk, encode_chunk, SavedChunk } from "$/server/game/saves.ts";
import { list_chunks, read_chunk, region_file, write_chunks } from "$/server/regions.ts";
import { sent_block, test_game } from "./helpers.ts";
function chunk_data(seed: number, palette_size = 3) {
const palette: [string, number][] = [];
for (let i = 0; i < palette_size; i++) palette.push([`test:block_${i}`, i % 5]);
const blocks = new Uint16Array(CHUNK_VOLUME).map((_, i) => (i * seed) % palette_size);
const changed = new Uint8Array(CHUNK_VOLUME / 8).map((_, i) => (i * seed) & 0xFF);
return { palette, blocks, changed };
const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => `test:biome_${(i * seed) % 4}`);
return { palette, blocks, biomes };
}
Deno.test("a chunk's blocks come back as they were saved, with more than 256 kinds too", () => {
const index = (x: number, y: number, z: number) => y * CHUNK_AREA + z * 16 + x;
// what a chunk was saved as before chunks had biomes: a bit per block after the blocks instead, for whether world
// generation made it
function format_1(data: Uint8Array<ArrayBuffer>) {
const chunk = decode_chunk(data);
const biomes = 1 +
[...new Set(chunk.biomes)].reduce((sum, id) => sum + 1 + new TextEncoder().encode(id).length, 0) +
CHUNK_AREA;
const old = new Uint8Array(data.length - biomes + CHUNK_VOLUME / 8);
old.set(data.subarray(0, data.length - biomes));
old[0] = 1;
return old;
}
Deno.test("a chunk's blocks and biomes come back as they were saved, with more than 256 kinds too", () => {
for (const palette_size of [1, 3, 256, 300]) {
const chunk = chunk_data(7, palette_size);
const decoded = decode_chunk(encode_chunk(chunk));
assertEquals(decoded.palette, chunk.palette);
assertEquals(decoded.blocks, chunk.blocks);
assertEquals(decoded.changed, chunk.changed);
assertEquals(decoded.biomes, chunk.biomes);
}
// a byte a block when that's enough
assert(encode_chunk(chunk_data(7, 256)).length < encode_chunk(chunk_data(7, 257)).length - CHUNK_VOLUME / 2);
// format 1 chunks still load, without biomes
const old = decode_chunk(format_1(encode_chunk(chunk_data(3, 300))));
assertEquals(old.blocks, chunk_data(3, 300).blocks);
assertEquals(old.biomes, undefined);
});
Deno.test("region files keep chunks, including negative ones, and saving one again doesn't touch the others", async () => {
@@ -31,15 +52,24 @@ Deno.test("region files keep chunks, including negative ones, and saving one aga
z,
data: encode_chunk(chunk_data(seed)),
});
const by_position = (chunks: SavedChunk[]) =>
Object.fromEntries(chunks.map((c) => [`${c.x},${c.z}`, decode_chunk(c.data).blocks[5]]));
const positions = [[0, 0], [31, 31], [-1, -1], [-33, 40]];
const by_position = async () =>
Object.fromEntries(
await Promise.all(
positions.map(async ([x, z]) => [`${x},${z}`, decode_chunk((await read_chunk(dir, x, z))!).blocks[5]]),
),
);
await write_chunks(dir, [chunk(0, 0, 1), chunk(31, 31, 2), chunk(-1, -1, 3), chunk(-33, 40, 4)]);
assertEquals(
[...Deno.readDirSync(dir)].map((e) => e.name).sort(),
[region_file(-1, -1), region_file(-2, 1), region_file(0, 0)].sort(),
);
assertEquals(by_position(await read_regions(dir)), { "0,0": 2, "31,31": 1, "-1,-1": 0, "-33,40": 2 });
assertEquals((await list_chunks(dir)).sort(), positions.toSorted());
assertEquals(await by_position(), { "0,0": 2, "31,31": 1, "-1,-1": 0, "-33,40": 2 });
// one that isn't saved, in a region that is and one that isn't
assertEquals(await read_chunk(dir, 1, 0), undefined);
assertEquals(await read_chunk(dir, 100, 100), undefined);
// saved again, over and over: the file doesn't keep growing, sectors let go of get used again
const path = `${dir}/${region_file(0, 0)}`;
@@ -47,27 +77,35 @@ Deno.test("region files keep chunks, including negative ones, and saving one aga
const size = Deno.statSync(path).size;
for (let i = 0; i < 5; i++) await write_chunks(dir, [chunk(0, 0, 2 + (i % 2))]);
assert(Deno.statSync(path).size <= size + 4096 * 2);
assertEquals(by_position(await read_regions(dir)), { "0,0": 1, "31,31": 1, "-1,-1": 0, "-33,40": 2 });
assertEquals(await by_position(), { "0,0": 1, "31,31": 1, "-1,-1": 0, "-33,40": 2 });
assertEquals(await read_regions(`${dir}/nothing`), []);
assertEquals(await list_chunks(`${dir}/nothing`), []);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("changed blocks are saved as whole chunks, and only chunks that changed are saved again", async () => {
Deno.test("every chunk generated is saved whole, and saved again only when it changes", async () => {
const { game } = await test_game("mods");
game.world.build(5, 5);
game.set_block(3, 120, 5, "bworld:stone");
game.set_block(-20, 120, 40, "bworld:oak_planks");
game.world.set_block(-20, 121, 40, "bworld:furnace", 1);
const saved = game.save();
assertEquals(saved.chunks.map((c) => [c.x, c.z]).sort(), [[-2, 2], [0, 0]]);
const positions = saved.chunks.map((c) => `${c.x},${c.z}`);
for (const chunk of ["0,0", "-2,2", "5,5"]) assert(positions.includes(chunk), `${chunk} is saved`);
// the chunk has every block, and marks the ones generation didn't make
const chunk = decode_chunk(saved.chunks.find((c) => c.x === 0)!.data);
const index = 120 * 256 + 5 * 16 + 3;
assertEquals(chunk.palette[chunk.blocks[index]], ["bworld:stone", 0]);
assert(is_changed(chunk, index));
assert(chunk.palette.some(([id]) => id === "bworld:bedrock" || id === "bworld:stone"));
assertEquals(chunk.changed.reduce((sum, byte) => sum + byte.toString(2).split("1").length - 1, 0), 1);
// every block, and each column's biome
const chunk = decode_chunk(saved.chunks.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(chunk.palette[chunk.blocks[index(3, 120, 5)]], ["bworld:stone", 0]);
assert(chunk.palette[chunk.blocks[index(3, 10, 5)]][0] !== AIR_ID);
assertEquals(chunk.biomes![index(3, 0, 5)], game.world.biome_at(3, 5));
const untouched = decode_chunk(saved.chunks.find((c) => c.x === 5 && c.z === 5)!.data);
assertEquals(
Uint32Array.from(untouched.blocks, (block) => {
const [id, state] = untouched.palette[block];
return id === AIR_ID ? 0 : game.world.block_ids[id] | (state << 16);
}),
game.world.generated_blocks(5, 5),
);
assertEquals(game.save().chunks, []);
game.set_block(4, 120, 5, "bworld:stone");
@@ -82,54 +120,77 @@ Deno.test("changed blocks are saved as whole chunks, and only chunks that change
loaded.send(1, { type: "move", x: 3.5, y: 130, z: 5.5, yaw: 0, pitch: 0 });
loaded.game.tick();
assertEquals(sent_block(loaded.take(1), join, 3, 120, 5), ["bworld:stone", 0]);
// nothing to save again after loading
assertEquals(loaded.game.save().chunks, []);
// what was loaded isn't saved again, only what's new
const again = loaded.game.save().chunks.map((c) => `${c.x},${c.z}`);
for (const chunk of positions) assert(!again.includes(chunk), `${chunk} is saved again`);
});
// a saved chunk with a block that isn't marked changed and isn't what generation makes: what's saved from a world
// generation that's since changed
// a world saved with a block in chunk 0, 0 that generation doesn't make there, like one generation made before it
// changed
async function saved_with_old_terrain() {
const { game } = await test_game("mods");
game.set_block(3, 120, 5, "bworld:stone");
const saved = game.save();
const chunk = decode_chunk(saved.chunks[0].data);
const index = 121 * 256 + 5 * 16 + 3;
assertEquals(chunk.palette[chunk.blocks[index]][0], AIR_ID);
chunk.blocks[index] = chunk.blocks[120 * 256 + 5 * 16 + 3];
saved.chunks[0].data = encode_chunk(chunk);
return { saved, level: JSON.parse(saved.level) };
const at_0_0 = saved.chunks.find((c) => c.x === 0 && c.z === 0)!;
const chunk = decode_chunk(at_0_0.data);
assertEquals(chunk.palette[chunk.blocks[index(3, 121, 5)]][0], AIR_ID);
chunk.blocks[index(3, 121, 5)] = chunk.blocks[index(3, 120, 5)];
at_0_0.data = encode_chunk(chunk as Required<typeof chunk>);
return { saved, at_0_0 };
}
Deno.test("when world generation is the same, blocks it made come from it", async () => {
Deno.test("saved chunks stay as they were saved, whatever generation makes there now", async () => {
const { saved } = await saved_with_old_terrain();
const { game } = await test_game("mods", saved);
assertEquals(game.world.get_block_id(3, 121, 5), AIR_ID);
assertEquals(game.save().chunks, []);
});
Deno.test("when world generation changed, saved chunks keep their terrain and are saved again", async () => {
const { saved, level } = await saved_with_old_terrain();
saved.level = JSON.stringify({ ...level, worldgen: "older" });
const { game } = await test_game("mods", saved);
assertEquals(game.world.get_block_id(3, 121, 5), "bworld:stone");
assertEquals(game.world.get_block_id(3, 120, 5), "bworld:stone");
const again = game.save();
assertNotEquals(JSON.parse(again.level).worldgen, "older");
const chunk = decode_chunk(again.chunks[0].data);
assert(is_changed(chunk, 121 * 256 + 5 * 16 + 3));
assertEquals(game.world.generated_blocks(0, 0)[index(3, 121, 5)], 0);
assertEquals(game.save().chunks.filter((c) => c.x === 0 && c.z === 0), []);
});
Deno.test("blocks of a mod that's gone are kept in the save", async () => {
const { saved } = await saved_with_old_terrain();
const chunk = decode_chunk(saved.chunks[0].data);
chunk.palette[chunk.blocks[120 * 256 + 5 * 16 + 3]] = ["gone:thing", 2];
saved.chunks[0].data = encode_chunk(chunk);
Deno.test("chunks saved before they had biomes get them from generation, and are saved again with them", async () => {
const { saved, at_0_0 } = await saved_with_old_terrain();
const biomes = decode_chunk(at_0_0.data).biomes!;
at_0_0.data = format_1(at_0_0.data);
const { game } = await test_game("mods", saved);
assertEquals(game.world.get_block_id(3, 121, 5), "bworld:stone");
assertEquals(game.world.biome_at(3, 5), biomes[index(3, 0, 5)]);
const again = game.save().chunks.find((c) => c.x === 0 && c.z === 0)!;
assertEquals(decode_chunk(again.data).biomes, biomes);
});
Deno.test("blocks of a mod that's gone are kept in the save until something replaces them", async () => {
const { saved, at_0_0 } = await saved_with_old_terrain();
const chunk = decode_chunk(at_0_0.data);
chunk.palette[chunk.blocks[index(3, 120, 5)]] = ["gone:thing", 2];
at_0_0.data = encode_chunk(chunk as Required<typeof chunk>);
const { game } = await test_game("mods", saved);
// generation's block stands in for it
assertNotEquals(game.world.get_block_id(3, 120, 5), "gone:thing");
// air stands in for it
assertEquals(game.world.get_block_id(3, 120, 5), AIR_ID);
game.set_block(0, 120, 0, "bworld:stone");
const again = decode_chunk(game.save().chunks[0].data);
assertEquals(again.palette[again.blocks[120 * 256 + 5 * 16 + 3]], ["gone:thing", 2]);
const again = decode_chunk(game.save().chunks.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(again.palette[again.blocks[index(3, 120, 5)]], ["gone:thing", 2]);
assertEquals(again.palette[again.blocks[index(3, 121, 5)]], ["gone:thing", 2]);
game.set_block(3, 120, 5, "bworld:oak_planks");
const replaced = decode_chunk(game.save().chunks.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(replaced.palette[replaced.blocks[index(3, 120, 5)]], ["bworld:oak_planks", 0]);
assertEquals(replaced.palette[replaced.blocks[index(3, 121, 5)]], ["gone:thing", 2]);
});
Deno.test("chunks forgotten before they're saved are still saved, and load from the save after", async () => {
const { game } = await test_game("mods");
game.set_block(100 * 16 + 3, 120, 5, "bworld:oak_planks");
game.set_block(100 * 16 + 3, 120, 16 + 5, "bworld:oak_planks");
// more than the world keeps built
for (let x = 101; x < 101 + 17; x++) for (let z = 0; z < 16; z++) game.world.build(x, z);
assert(!game.world.has_chunk(100, 0) && !game.world.has_chunk(100, 1));
assertEquals(game.world.get_block_id(100 * 16 + 3, 120, 16 + 5), "bworld:oak_planks");
const positions = game.save().chunks.map((c) => `${c.x},${c.z}`);
assert(positions.includes("100,0") && positions.includes("100,1"));
for (let x = 101; x < 101 + 17; x++) {
for (let z = 0; z < 16; z++) assert(positions.includes(`${x},${z}`), `${x},${z} is saved`);
}
assertEquals(game.world.get_block_id(100 * 16 + 3, 120, 5), "bworld:oak_planks");
});