Files
bworld/tests/world_save_test.ts
T
2026-11-15 20:31:10 -03:00

263 lines
12 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { assert, assertEquals } from "@std/assert";
import { AIR_ID } from "@/common/protocol.ts";
import { CHUNK_AREA } from "@/common/constants.ts";
import { ChunkBlocks, 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";
import { DEFAULT_SHAPE, WorldShape } from "@/common/world_shape.ts";
import { biome_in, ChunkColumn, column_biomes, section_index, to_flat } from "@/common/section.ts";
import { Writer } from "@/common/bytes.ts";
// a chunk 0 to 256 high, or of another shape
function chunk_data(seed: number, palette_size = 3, shape = DEFAULT_SHAPE): Required<ChunkBlocks> {
const palette: [string, number][] = [];
for (let i = 0; i < palette_size; i++) palette.push([`test:block_${i}`, i % 5]);
const blocks = new Uint32Array(shape.volume).map((_, i) => (i * seed) % palette_size);
const biomes = Array.from({ length: CHUNK_AREA }, (_, i) => `test:biome_${(i * seed) % 4}`);
const { sections, biomes: column_biomes } = ChunkColumn.from_flat(0, 0, shape, blocks, biomes);
return { palette, min_y: shape.min_y, sections, biomes: column_biomes };
}
// the palette entry of a saved chunk's block
function saved_block(chunk: ChunkBlocks, x: number, y: number, z: number) {
return chunk.palette[chunk.sections[(y - chunk.min_y) >> 4].get(section_index(x, y, z))];
}
function set_saved_block(chunk: ChunkBlocks, x: number, y: number, z: number, index: number) {
chunk.sections[(y - chunk.min_y) >> 4].set(section_index(x, y, z), index);
}
// a chunk's part from 0 to 256 as formats 1 and 2 saved it, big-endian. format 1 had no biomes, and a bit per block
// after the blocks instead, for whether world generation made it
function old_format(format: 1 | 2, chunk: ChunkBlocks) {
const bottom = -chunk.min_y >> 4;
const flat = to_flat(chunk.sections.slice(bottom, bottom + 16));
const wide = chunk.palette.length > 256;
const bytes: number[] = [format, ...u32(chunk.palette.length)];
for (const [id, state] of chunk.palette) bytes.push(...string(id), state >> 8, state & 255);
for (const index of flat) bytes.push(...wide ? [index >> 8, index & 255] : [index]);
if (format === 1) {
bytes.push(...new Uint8Array(flat.length / 8));
} else {
// each column's biome at the bottom
const columns = Array.from(
{ length: CHUNK_AREA },
(_, i) => biome_in(chunk.biomes!, shape_of(chunk), i, 0, i >> 4),
);
const biome_palette = [...new Set(columns)];
bytes.push(biome_palette.length, ...biome_palette.flatMap(string));
bytes.push(...columns.map((biome) => biome_palette.indexOf(biome)));
}
return Uint8Array.from(bytes);
}
const shape_of = (chunk: ChunkBlocks) =>
new WorldShape({ min_y: chunk.min_y, max_y: chunk.min_y + chunk.sections.length * 16, sky_light: true });
const u32 = (value: number) => [value >>> 24, (value >> 16) & 255, (value >> 8) & 255, value & 255];
const string = (text: string) => [text.length, ...new TextEncoder().encode(text)];
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.min_y, chunk.min_y);
assertEquals(to_flat(decoded.sections), to_flat(chunk.sections));
assertEquals(decoded.biomes, chunk.biomes);
}
// a section that's all one block takes a few bytes
const uniform = chunk_data(0, 1);
assert(encode_chunk(uniform).length < 16 * 8 + 1024);
// a taller dimension's, from below 0
const tall = chunk_data(5, 40, new WorldShape({ min_y: -64, max_y: 320, sky_light: true }));
const decoded = decode_chunk(encode_chunk(tall));
assertEquals([decoded.min_y, decoded.sections.length], [-64, 24]);
assertEquals(to_flat(decoded.sections), to_flat(tall.sections));
// formats 1 and 2 still load, 1 without biomes
for (const format of [1, 2] as const) {
const chunk = chunk_data(3, 300);
const old = decode_chunk(old_format(format, chunk));
assertEquals([old.min_y, old.palette], [0, chunk.palette]);
assertEquals(to_flat(old.sections), to_flat(chunk.sections));
assertEquals(old.biomes, format === 1 ? undefined : chunk.biomes);
}
// and format 3, from before biomes had heights: each column's biome, which goes all the way up
const columns = Array.from({ length: CHUNK_AREA }, (_, i) => i < 10 ? "test:a" : "test:b");
const writer = new Writer();
writer.u8(3);
writer.i16(0);
writer.u32(1);
writer.string("test:block_0");
writer.u16(0);
writer.u16(2);
writer.string("test:a");
writer.string("test:b");
for (const biome of columns) writer.u8(biome === "test:a" ? 0 : 1);
writer.u16(16);
// sections all of the one block
for (let i = 0; i < 16; i++) {
writer.u8(0);
writer.u32(0);
}
const three = decode_chunk(writer.bytes());
assertEquals(three.sections.map((section) => section.value), new Array(16).fill(0));
assertEquals(three.biomes, column_biomes(columns, 16));
});
Deno.test("region files keep chunks, including negative ones, and saving one again doesn't touch the others", async () => {
const dir = Deno.makeTempDirSync();
const chunk = (x: number, z: number, seed: number): SavedChunk => ({
x,
z,
data: encode_chunk(chunk_data(seed)),
});
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))!).sections[0].get(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((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)}`;
await write_chunks(dir, [chunk(0, 0, 2)]);
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(await by_position(), { "0,0": 1, "31,31": 1, "-1,-1": 0, "-33,40": 2 });
assertEquals(await list_chunks(`${dir}/nothing`), []);
Deno.removeSync(dir, { recursive: true });
});
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();
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`);
// every block, and each column's biome
const chunk = decode_chunk(saved.chunks.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(saved_block(chunk, 3, 120, 5), ["bworld:stone", 0]);
assert(saved_block(chunk, 3, 10, 5)[0] !== AIR_ID);
assertEquals(biome_in(chunk.biomes!, game.world.shape, 3, 120, 5), game.world.biome_at(3, 120, 5));
const untouched = decode_chunk(saved.chunks.find((c) => c.x === 5 && c.z === 5)!.data);
assertEquals(
Uint32Array.from(to_flat(untouched.sections), (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).to_flat(),
);
assertEquals(game.save().chunks, []);
game.set_block(4, 120, 5, "bworld:stone");
assertEquals(game.save().chunks.map((c) => [c.x, c.z]), [[0, 0]]);
const loaded = await test_game("mods", saved);
assertEquals(loaded.game.world.get_block_id(3, 120, 5), "bworld:stone");
assertEquals(loaded.game.world.get_block_id(-20, 120, 40), "bworld:oak_planks");
assertEquals(loaded.game.world.get_block_value(-20, 121, 40) >>> 16, 1);
// players get the whole chunks, with what was saved in them
const join = loaded.join(1, "alice");
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]);
// 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 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 at_0_0 = saved.chunks.find((c) => c.x === 0 && c.z === 0)!;
const chunk = decode_chunk(at_0_0.data);
assertEquals(saved_block(chunk, 3, 121, 5)[0], AIR_ID);
set_saved_block(chunk, 3, 121, 5, chunk.palette.indexOf(saved_block(chunk, 3, 120, 5)));
at_0_0.data = encode_chunk(chunk as Required<typeof chunk>);
return { saved, at_0_0 };
}
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), "bworld:stone");
assertEquals(game.world.generated_blocks(0, 0).get(3, 121, 5), 0);
assertEquals(game.save().chunks.filter((c) => c.x === 0 && c.z === 0), []);
});
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 = old_format(1, decode_chunk(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, 120, 5), biome_in(biomes, game.world.shape, 3, 120, 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.palette.indexOf(saved_block(chunk, 3, 120, 5))] = ["gone:thing", 2];
at_0_0.data = encode_chunk(chunk as Required<typeof chunk>);
const { game } = await test_game("mods", saved);
// 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.find((c) => c.x === 0 && c.z === 0)!.data);
assertEquals(saved_block(again, 3, 120, 5), ["gone:thing", 2]);
assertEquals(saved_block(again, 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(saved_block(replaced, 3, 120, 5), ["bworld:oak_planks", 0]);
assertEquals(saved_block(replaced, 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");
});