Region file format

This commit is contained in:
2026-09-27 23:45:07 -03:00
parent a6869eeb59
commit 677ad8115a
18 changed files with 666 additions and 567 deletions
+28 -37
View File
@@ -14,7 +14,6 @@ import { BlockRegistry, EverythingRegistry, ItemRegistry } from "$/common/everyt
import { can_take_output, click_slot, Container, ItemData, ItemStack, take_output } from "$/common/inventory.ts";
import {
AIR_ID,
BlockChange,
ClientMessage,
ContainerKey,
CRAFTING_RESULT_SLOT,
@@ -45,6 +44,7 @@ import { consume_recipe_items, update_crafting_result } from "./crafting.ts";
import { OpenScreen, SavedPlayer, ServerPlayer } from "./player.ts";
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
import { ServerWorld, Tile } from "./world.ts";
import type { WorldSave } from "./saves.ts";
import {
BLOCK_DROP_PICKUP_DELAY,
DESPAWN_TICKS,
@@ -91,20 +91,22 @@ export interface GameHost {
download(url: string, max_bytes: number): Promise<Uint8Array>;
}
export interface SavedWorld {
version: 3;
// level.json, everything saved but the blocks, which are in region files (see saves.ts)
export interface SavedLevel {
version: 4;
seed: string;
// world time in ticks, 0 in saves from before the day and night cycle
time?: number;
changes: BlockChange[];
// see ServerWorld.worldgen_fingerprint
worldgen: string;
// world time in ticks
time: number;
tiles: SavedTile[];
// every ctx.containers container, by id
containers?: Record<string, (ItemData | null)[]>;
containers: Record<string, (ItemData | null)[]>;
players: Record<string, SavedPlayer>;
// items on the ground
entities?: SavedItemEntity[];
entities: SavedItemEntity[];
// ctx.storage of every mod, by mod id
mod_storage?: Record<string, Record<string, unknown>>;
mod_storage: Record<string, Record<string, unknown>>;
}
interface SavedTile {
@@ -114,9 +116,6 @@ interface SavedTile {
z: number;
// what BlockRef.data holds
mod_data?: unknown;
// version 2, when chests and furnaces were engine code: their fields and their items
data?: Record<string, unknown>;
containers?: Record<string, (ItemData | null)[]>;
}
// the loaded mods, see load_mods.ts
@@ -148,17 +147,21 @@ export class GameServer {
// what runs tick(), for /tps. tests call tick() themselves
loop?: GameLoop;
constructor(host: GameHost, save: string | undefined, default_seed: string, mods: GameMods) {
constructor(host: GameHost, save: WorldSave | undefined, default_seed: string, mods: GameMods) {
this.#host = host;
this.#mods = mods;
this.mods = mods.runtime;
this.recipes = mods.recipes;
// version 1 saves only had the seed and block changes
const saved: Partial<SavedWorld> | undefined = save ? JSON.parse(save) : undefined;
const saved: SavedLevel | undefined = save?.level ? JSON.parse(save.level) : undefined;
if (saved && saved.version !== 4) {
throw new Error(`The world was saved in format ${saved.version}, this server only loads format 4`);
}
this.world = new ServerWorld(saved?.seed ?? default_seed, mods.worldgen);
this.mods.storage = saved?.mod_storage ?? {};
this.world.load_changes(saved?.changes ?? []);
if (saved) {
this.world.load_chunks(save?.chunks ?? [], saved.worldgen);
}
this.world.time = saved?.time ?? 0;
this.#day = this.world.day;
for (const [id, items] of Object.entries(saved?.containers ?? {})) {
@@ -167,14 +170,15 @@ export class GameServer {
this.containers.set(id, container);
}
for (const tile of saved?.tiles ?? []) {
this.world.add_tile({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: this.#upgrade_tile(tile) });
this.world.add_tile({ id: tile.id, x: tile.x, y: tile.y, z: tile.z, mod_data: tile.mod_data });
}
for (const entity of saved?.entities ?? []) {
const item = ItemEntity.load(this.#new_entity_id(), entity);
this.#entities.set(item.id, item);
}
this.#saved_players = saved?.players ?? {};
this.world.dirty = saved?.version !== 3;
// a new world is saved straight away, and a loaded one when load_chunks had to save chunks again
this.world.dirty = !saved || this.world.has_unsaved_chunks();
this.#register_commands();
this.world.on_block_change = (x, y, z, id, state) =>
@@ -273,15 +277,16 @@ export class GameServer {
}
}
save(): string {
// level.json and the chunks changed since the last save
save(): Required<WorldSave> {
for (const player of this.#players.values()) {
this.#saved_players[player.name] = player.save();
}
const saved: SavedWorld = {
version: 3,
const level: SavedLevel = {
version: 4,
seed: this.world.seed,
worldgen: this.world.worldgen_fingerprint(),
time: this.world.time,
changes: this.world.all_changes(),
tiles: [...this.world.tiles.values()].map((tile) => ({
id: tile.id,
x: tile.x,
@@ -297,7 +302,7 @@ export class GameServer {
mod_storage: this.mods.storage,
};
this.world.dirty = false;
return JSON.stringify(saved);
return { level: JSON.stringify(level), chunks: this.world.save_chunks() };
}
// used by block behaviors and mods
@@ -540,20 +545,6 @@ export class GameServer {
// version 2 saves had chests and furnaces in the engine, with their fields in data and their items in
// containers.main. the components keep those fields and put the items in a ctx.containers container
#upgrade_tile(tile: SavedTile): unknown {
if (tile.mod_data !== undefined || (!tile.data && !tile.containers)) {
return tile.mod_data;
}
const data: Record<string, unknown> = { ...tile.data };
const items = tile.containers?.main;
if (items) {
const { id, container } = this.create_container(items.length);
container.load(items);
data.container = id;
}
return data;
}
// messages
// hello -> welcome, then ready -> join. see "Delivery to clients" in MODS.md
+4 -2
View File
@@ -1,11 +1,12 @@
import type { ModData, ModListing } from "$/common/mod_loader.ts";
import type { WorldSave } from "./saves.ts";
// messages between server/main.ts (the host) and the game server worker
export type HostToGame =
| {
type: "init";
save: string | undefined;
save: WorldSave;
default_seed: string;
// in load order, with the scripts' code since the worker can't read files
mods: { listing: ModListing; data: ModData; server_code?: string; worldgen_code?: string }[];
@@ -23,6 +24,7 @@ export type GameToHost =
| { type: "failed"; error: string }
| { type: "send"; conn: number; data: string }
| { type: "close"; conn: number }
| { type: "save"; data: string; final: boolean }
// level.json and the chunks that changed
| { type: "save"; save: Required<WorldSave>; final: boolean }
// the worker can't use the network, so the host fetches urls for it, like skins
| { type: "download"; id: number; url: string; max_bytes: number };
+2 -1
View File
@@ -4,6 +4,7 @@ import { register_mod_data } from "$/common/mod_loader.ts";
import type { ModData, ModListing } from "$/common/mod_loader.ts";
import { load_worldgen } from "$/common/worldgen_loader.ts";
import { GameHost, GameServer } from "./game_server.ts";
import type { WorldSave } from "./saves.ts";
import { ModRuntime } from "./mod_runtime.ts";
export interface ServerModSource {
@@ -16,7 +17,7 @@ export interface ServerModSource {
export async function start_game(
host: GameHost,
save: string | undefined,
save: WorldSave | undefined,
default_seed: string,
mods: ServerModSource[],
): Promise<GameServer> {
+107
View File
@@ -0,0 +1,107 @@
// what a world is saved as, apart from the files: level.json's text and each chunk's blocks. server/regions.ts puts
// the chunks into region files, this is what's inside one chunk's entry before it's compressed:
//
// u8 format, CHUNK_FORMAT
// u32 palette size, then each entry: u8 id length, the id as utf-8, u16 state bits
// the palette index of every block, in ServerWorld's order (y, then z, then x): u8 each for up to 256 entries,
// u16 each for more
// a bit per block, set where it isn't what world generation makes there, like a block a player placed
//
// numbers are big-endian. blocks are saved by their string ids, so mods can come and go without a save's numbers
// meaning other blocks
import { CHUNK_AREA, CHUNK_HEIGHT } from "$/common/constants.ts";
export const CHUNK_FORMAT = 1;
export const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT;
export interface SavedChunk {
x: number;
z: number;
data: Uint8Array<ArrayBuffer>;
}
// a world as the host reads it and the game saves it. the game only saves the chunks that changed since it last did
export interface WorldSave {
// level.json, without it the world is new
level?: string;
chunks: SavedChunk[];
}
export interface ChunkBlocks {
// an id and its state bits
palette: [string, number][];
// the palette index of each block
blocks: Uint16Array;
// CHUNK_VOLUME bits, see is_changed
changed: Uint8Array;
}
export function is_changed(chunk: ChunkBlocks, index: number) {
return (chunk.changed[index >> 3] & (1 << (index & 7))) !== 0;
}
export function encode_chunk(chunk: ChunkBlocks): Uint8Array<ArrayBuffer> {
const ids = chunk.palette.map(([id]) => new TextEncoder().encode(id));
if (ids.some((id) => id.length > 255)) throw new Error("A block id is too long to save");
const wide = chunk.palette.length > 256;
const size = 1 + 4 + ids.reduce((sum, id) => sum + 1 + id.length + 2, 0) +
CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8;
const bytes = new Uint8Array(size);
const view = new DataView(bytes.buffer);
let offset = 0;
view.setUint8(offset++, CHUNK_FORMAT);
view.setUint32(offset, chunk.palette.length);
offset += 4;
chunk.palette.forEach(([, state], i) => {
view.setUint8(offset++, ids[i].length);
bytes.set(ids[i], offset);
offset += ids[i].length;
view.setUint16(offset, state);
offset += 2;
});
for (let i = 0; i < CHUNK_VOLUME; i++) {
if (wide) {
view.setUint16(offset, chunk.blocks[i]);
offset += 2;
} else {
bytes[offset++] = chunk.blocks[i];
}
}
bytes.set(chunk.changed, offset);
return bytes;
}
// throws when the bytes aren't a chunk this can read
export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
let offset = 0;
const format = view.getUint8(offset++);
if (format !== CHUNK_FORMAT) throw new Error(`Unknown chunk format ${format}`);
const palette_size = view.getUint32(offset);
offset += 4;
if (palette_size > CHUNK_VOLUME) throw new Error("Bad palette");
const palette: [string, number][] = [];
for (let i = 0; i < palette_size; i++) {
const length = view.getUint8(offset++);
const id = new TextDecoder().decode(bytes.subarray(offset, offset + length));
offset += length;
palette.push([id, view.getUint16(offset)]);
offset += 2;
}
const wide = palette_size > 256;
if (bytes.length !== offset + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8) {
throw new Error("Wrong size");
}
const blocks = new Uint16Array(CHUNK_VOLUME);
for (let i = 0; i < CHUNK_VOLUME; i++) {
if (wide) {
blocks[i] = view.getUint16(offset);
offset += 2;
} else {
blocks[i] = bytes[offset++];
}
if (blocks[i] >= palette_size) throw new Error("Bad palette index");
}
const changed = bytes.slice(offset, offset + CHUNK_VOLUME / 8);
return { palette, blocks, changed };
}
+5 -3
View File
@@ -15,7 +15,9 @@ const downloads = new Map<number, { resolve: (bytes: Uint8Array) => void; reject
let next_download = 1;
function post(message: GameToHost) {
self.postMessage(message);
// the chunks are moved to the host, not copied
const transfer = message.type === "save" ? message.save.chunks.map((chunk) => chunk.data.buffer) : [];
self.postMessage(message, transfer);
}
self.onmessage = async (event: MessageEvent<HostToGame>) => {
@@ -53,7 +55,7 @@ self.onmessage = async (event: MessageEvent<HostToGame>) => {
game.on_disconnect(message.conn);
break;
case "shutdown":
post({ type: "save", data: game.save(), final: true });
post({ type: "save", save: game.save(), final: true });
break;
}
};
@@ -92,7 +94,7 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
setInterval(() => {
if (game!.world.dirty) {
post({ type: "save", data: game!.save(), final: false });
post({ type: "save", save: game!.save(), final: false });
}
}, SAVE_INTERVAL_MS);
+133 -13
View File
@@ -5,12 +5,15 @@ import { AIR_ID, BlockChange } from "$/common/protocol.ts";
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
import { LruMap } from "./lru.ts";
import { CYCLE_TICKS } from "$/common/time.ts";
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, SavedChunk } from "./saves.ts";
// generation only, rebuilt when needed. 256 KB each
const RAW_CACHE_SIZE = 128;
const CHUNK_CACHE_SIZE = 256;
// how far from the middle of the world to look for dry land to spawn on, in chunks
const SPAWN_SEARCH_CHUNKS = 32;
// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one
const FINGERPRINT_CHUNKS = [[0, 0], [7, -3], [-45, 18], [130, -80], [-310, 260], [1000, -1000]];
// a block with data the server keeps, like where a chest's items are. never sent to clients
export interface Tile {
@@ -38,8 +41,10 @@ export class ServerWorld {
#raw = new LruMap<number, RawChunk>(RAW_CACHE_SIZE);
#chunks = new LruMap<number, Uint32Array>(CHUNK_CACHE_SIZE);
// changes from generated terrain, per chunk. these and the tiles are what gets saved
// changes from generated terrain, per chunk, which is also what clients get sent. saved as whole chunks
#changes = new Map<number, Map<string, BlockChange>>();
// chunks changed since they were last saved, by chunk_key
#unsaved = new Map<number, [number, number]>();
tiles = new Map<string, Tile>();
// ticks since 06:00 of day 1, see common/time.ts
@@ -159,10 +164,120 @@ export class ServerWorld {
return all;
}
load_changes(changes: BlockChange[]) {
for (const [x, y, z, id, state] of changes) {
this.#record_change(x, y, z, id, state ?? 0);
#fingerprint: string | undefined;
// a hash of some generated chunks, saved with the world: when it's different world generation changed, like a mod
// update, and saved chunks can't be trusted to say which of their blocks generation made
worldgen_fingerprint(): string {
if (this.#fingerprint === undefined) {
// fnv-1a
let hash = 0x811c9dc5;
const add = (values: ArrayLike<number>) => {
for (let i = 0; i < values.length; i++) {
hash = Math.imul(hash ^ values[i], 0x01000193) >>> 0;
}
};
for (const [x, z] of FINGERPRINT_CHUNKS) {
const raw = this.#get_raw(x, z);
add(raw.blocks);
add(raw.spills);
}
this.#fingerprint = hash.toString(16).padStart(8, "0");
}
return this.#fingerprint;
}
// chunks from a save. with a different fingerprint every block is compared with what generation makes now, so the
// saved terrain stays as it was and only chunks never saved get the new generation, like minecraft
load_chunks(chunks: SavedChunk[], fingerprint: string | undefined) {
const regenerate = chunks.length > 0 && fingerprint !== this.worldgen_fingerprint();
if (regenerate) {
console.log(`World generation changed, comparing ${chunks.length} saved chunks with it`);
}
for (const { x: chunk_x, z: chunk_z, data } of chunks) {
let chunk: ChunkBlocks;
try {
chunk = decode_chunk(data);
} catch (e) {
console.error(`Couldn't load chunk ${chunk_x}, ${chunk_z}: ${(e as Error).message}`);
continue;
}
const generated = regenerate ? this.#generate_chunk(chunk_x, chunk_z) : undefined;
// unknown ids, from mods that are gone, stay as changes so they come back with the mod
const values = chunk.palette.map(([id, state]) => {
const nid = id === AIR_ID ? AIR : this.block_ids[id];
return nid === undefined ? -1 : block_value(nid, state);
});
for (let i = 0; i < CHUNK_VOLUME; i++) {
const block = chunk.blocks[i];
if (generated ? generated[i] === values[block] : !is_changed(chunk, i)) {
continue;
}
const [id, state] = chunk.palette[block];
const x = chunk_x * CHUNK_SIZE + (i % CHUNK_SIZE);
const z = chunk_z * CHUNK_SIZE + Math.floor(i / CHUNK_SIZE) % CHUNK_SIZE;
this.#record_change(x, Math.floor(i / CHUNK_AREA), z, id, state);
}
if (regenerate) {
this.#unsaved.set(chunk_key(chunk_x, chunk_z), [chunk_x, chunk_z]);
this.dirty = true;
} else {
this.#unsaved.delete(chunk_key(chunk_x, chunk_z));
}
}
}
has_unsaved_chunks() {
return this.#unsaved.size > 0;
}
// every chunk changed since the last call, as saved chunks
save_chunks(): SavedChunk[] {
const saved = [...this.#unsaved.values()].map(([x, z]) => ({
x,
z,
data: encode_chunk(this.#chunk_blocks(x, z)),
}));
this.#unsaved.clear();
return saved;
}
#chunk_blocks(chunk_x: number, chunk_z: number): ChunkBlocks {
const palette: [string, number][] = [];
const palette_index = new Map<string, number>();
const index_of = (id: string, state: number) => {
const key = `${id} ${state}`;
let index = palette_index.get(key);
if (index === undefined) {
index = palette.push([id, state]) - 1;
palette_index.set(key, index);
}
return index;
};
const blocks = new Uint16Array(CHUNK_VOLUME);
const by_value = new Map<number, number>();
this.#get_chunk(chunk_x, chunk_z).forEach((value, i) => {
let index = by_value.get(value);
if (index === undefined) {
const nid = value & ID_MASK;
const id = nid === AIR
? AIR_ID
: EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id ?? AIR_ID;
index = index_of(id, value >>> 16);
by_value.set(value, index);
}
blocks[i] = index;
});
// the changes, which also keeps blocks of mods that are gone
const changed = new Uint8Array(CHUNK_VOLUME / 8);
for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) {
const i = index_in_chunk(x, y, z, chunk_x, chunk_z);
blocks[i] = index_of(id, state ?? 0);
changed[i >> 3] |= 1 << (i & 7);
}
return { palette, blocks, changed };
}
get_tile(x: number, y: number, z: number) {
@@ -187,6 +302,7 @@ export class ServerWorld {
this.#changes.set(key, chunk_changes);
}
chunk_changes.set(position_key(x, y, z), state ? [x, y, z, id, state] : [x, y, z, id]);
this.#unsaved.set(key, [Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE)]);
}
#get_raw(chunk_x: number, chunk_z: number) {
@@ -209,8 +325,20 @@ export class ServerWorld {
return blocks;
}
// same rules as the client: own blocks, then neighbors' leaves only into air, then player changes
// same rules as the client: what generation makes, then player changes
#build_chunk(chunk_x: number, chunk_z: number) {
const blocks = this.#generate_chunk(chunk_x, chunk_z);
for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) {
const nid = id === AIR_ID ? AIR : this.block_ids[id];
if (nid !== undefined) {
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = block_value(nid, state ?? 0);
}
}
return blocks;
}
// own blocks, then neighbors' leaves only into air
#generate_chunk(chunk_x: number, chunk_z: number) {
const blocks = this.#get_raw(chunk_x, chunk_z).blocks.slice();
for (let dx = -1; dx <= 1; dx++) {
@@ -231,14 +359,6 @@ export class ServerWorld {
}
}
}
for (const [x, y, z, id, state] of this.#changes.get(chunk_key(chunk_x, chunk_z))?.values() ?? []) {
const nid = id === AIR_ID ? AIR : this.block_ids[id];
if (nid !== undefined) {
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = block_value(nid, state ?? 0);
}
}
return blocks;
}
}
+67 -31
View File
@@ -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
+1 -1
View File
@@ -8,7 +8,7 @@ try {
host = await start_host({
build_dir: Deno.env.get("BUILD_DIR") ?? "build",
server_mods_dir: Deno.env.get("SERVER_MODS_DIR") ?? "server_mods",
world_file: Deno.env.get("WORLD_FILE") ?? "world.json",
world_dir: Deno.env.get("WORLD_DIR") ?? "world",
seed: Deno.env.get("SEED"),
on_fatal(message) {
console.error(message);
+171
View File
@@ -0,0 +1,171 @@
// region files, laid out like minecraft's since mcregion (a mod, part of the game from beta 1.3): the chunks of a
// 32 by 32 chunk square in one file, so saving writes only the chunks that changed. the file is 4 KiB sectors, the
// first two are the header:
//
// 1024 locations, one per chunk: u24 first sector, u8 how many sectors. 0 and 0 where there's no chunk
// 1024 timestamps: u32 seconds, when the chunk was last written
//
// a chunk's place in those is (x & 31) + (z & 31) * 32. its sectors start with u32 the length of what follows, u8
// the compression (2, zlib like minecraft's default), then the compressed chunk from server/game/saves.ts.
// big-endian. a chunk saved again goes into sectors nothing uses and the header is written last, so a crash while
// saving leaves the chunks as they were instead of half written
import { join } from "@std/path";
import type { SavedChunk } from "./game/saves.ts";
const SECTOR = 4096;
const REGION_CHUNKS = 32;
const CHUNKS_PER_REGION = REGION_CHUNKS * REGION_CHUNKS;
const HEADER_SECTORS = 2;
const HEADER_SIZE = HEADER_SECTORS * SECTOR;
const ZLIB = 2;
// what fits in a location's sector count, 1 MB
const MAX_CHUNK_SECTORS = 255;
const REGION_FILE = /^r\.(-?\d+)\.(-?\d+)\.bwr$/;
export function region_file(region_x: number, region_z: number) {
return `r.${region_x}.${region_z}.bwr`;
}
// every chunk in the folder's region files, uncompressed. chunks that can't be read are skipped, saying so
export async function read_regions(dir: string): Promise<SavedChunk[]> {
let entries: Deno.DirEntry[];
try {
entries = [...Deno.readDirSync(dir)];
} catch (e) {
if (e instanceof Deno.errors.NotFound) return [];
throw e;
}
const chunks: SavedChunk[] = [];
for (const entry of entries) {
const match = entry.isFile && REGION_FILE.exec(entry.name);
if (!match) continue;
const [region_x, region_z] = [Number(match[1]), Number(match[2])];
const bytes = await Deno.readFile(join(dir, entry.name));
if (bytes.length < HEADER_SIZE) {
console.error(`${entry.name} is too short to be a region file`);
continue;
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
for (let i = 0; i < CHUNKS_PER_REGION; i++) {
const location = view.getUint32(i * 4);
if (location === 0) continue;
const x = region_x * REGION_CHUNKS + (i % REGION_CHUNKS);
const z = region_z * REGION_CHUNKS + Math.floor(i / REGION_CHUNKS);
try {
const start = (location >>> 8) * SECTOR;
const length = view.getUint32(start);
const compression = view.getUint8(start + 4);
if (compression !== ZLIB) throw new Error(`unknown compression ${compression}`);
if (length < 1 || start + 4 + length > bytes.length) {
throw new Error("it goes past the end of the file");
}
chunks.push({ x, z, data: await inflate(bytes.subarray(start + 5, start + 4 + length)) });
} catch (e) {
console.error(`Couldn't read chunk ${x}, ${z} from ${entry.name}: ${(e as Error).message}`);
}
}
}
return chunks;
}
// saves the chunks into their region files, making them and the folder when needed
export async function write_chunks(dir: string, chunks: SavedChunk[]) {
const regions = new Map<string, SavedChunk[]>();
for (const chunk of chunks) {
const name = region_file(Math.floor(chunk.x / REGION_CHUNKS), Math.floor(chunk.z / REGION_CHUNKS));
regions.set(name, [...regions.get(name) ?? [], chunk]);
}
if (regions.size) Deno.mkdirSync(dir, { recursive: true });
for (const [name, region_chunks] of regions) {
await write_region(join(dir, name), region_chunks);
}
}
async function write_region(path: string, chunks: SavedChunk[]) {
const compressed = await Promise.all(chunks.map((chunk) => deflate(chunk.data)));
using file = await Deno.open(path, { read: true, write: true, create: true });
const header = new Uint8Array(HEADER_SIZE);
await read_at(file, 0, header);
const view = new DataView(header.buffer);
// the sectors the header points at now, which stay untouched until the new header is written
const used: boolean[] = [];
for (let i = 0; i < HEADER_SECTORS; i++) used[i] = true;
for (let i = 0; i < CHUNKS_PER_REGION; i++) {
const location = view.getUint32(i * 4);
const [first, count] = [location >>> 8, location & 0xFF];
for (let sector = first; sector < first + count; sector++) used[sector] = true;
}
const now = Math.floor(Date.now() / 1000);
for (const [i, chunk] of chunks.entries()) {
const data = compressed[i];
const sectors = Math.ceil((5 + data.length) / SECTOR);
if (sectors > MAX_CHUNK_SECTORS) {
throw new Error(`Chunk ${chunk.x}, ${chunk.z} is too big to save (${data.length} bytes)`);
}
const first = free_sectors(used, sectors);
for (let sector = first; sector < first + sectors; sector++) used[sector] = true;
const bytes = new Uint8Array(sectors * SECTOR);
const chunk_view = new DataView(bytes.buffer);
chunk_view.setUint32(0, data.length + 1);
chunk_view.setUint8(4, ZLIB);
bytes.set(data, 5);
await write_at(file, first * SECTOR, bytes);
const index = (chunk.x & (REGION_CHUNKS - 1)) + (chunk.z & (REGION_CHUNKS - 1)) * REGION_CHUNKS;
view.setUint32(index * 4, (first << 8) | sectors);
view.setUint32(SECTOR + index * 4, now);
}
// the chunks are on disk before the header points at them
await file.syncData();
await write_at(file, 0, header);
}
// the first of the first run of that many sectors nothing uses, which can be past the end of the file
function free_sectors(used: boolean[], count: number) {
let start = HEADER_SECTORS;
for (let sector = HEADER_SECTORS; sector < used.length; sector++) {
if (used[sector]) {
start = sector + 1;
} else if (sector - start + 1 === count) {
return start;
}
}
return start;
}
// reads as much of bytes as the file has there, a new file reads as zeros
async function read_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) {
await file.seek(offset, Deno.SeekMode.Start);
let read = 0;
while (read < bytes.length) {
const n = await file.read(bytes.subarray(read));
if (n === null) break;
read += n;
}
}
async function write_at(file: Deno.FsFile, offset: number, bytes: Uint8Array) {
await file.seek(offset, Deno.SeekMode.Start);
let written = 0;
while (written < bytes.length) {
written += await file.write(bytes.subarray(written));
}
}
// "deflate" is zlib's format, what minecraft calls compression 2
function deflate(bytes: Uint8Array<ArrayBuffer>) {
return transform(bytes, new CompressionStream("deflate"));
}
function inflate(bytes: Uint8Array<ArrayBuffer>) {
return transform(bytes, new DecompressionStream("deflate"));
}
async function transform(bytes: Uint8Array<ArrayBuffer>, stream: CompressionStream | DecompressionStream) {
return new Uint8Array(await new Response(new Blob([bytes]).stream().pipeThrough(stream)).arrayBuffer());
}