Save all generated chunks instead of only chunks that were changed
This commit is contained in:
+17
-18
@@ -69,8 +69,8 @@ import { update_crafting_result } from "./crafting.ts";
|
||||
import type { Menu } from "./menu.ts";
|
||||
import { SavedPlayer, ServerPlayer } from "./player.ts";
|
||||
import { encode_skin, MAX_SKIN_BYTES, skin_problem } from "./skins.ts";
|
||||
import { FINGERPRINT_CHUNKS, ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
|
||||
import type { WorldSave } from "./saves.ts";
|
||||
import { ServerWorld, SPAWN_AREA_CHUNKS, Tile } from "./world.ts";
|
||||
import type { WorldSave, WorldSource } from "./saves.ts";
|
||||
import {
|
||||
BLOCK_DROP_PICKUP_DELAY,
|
||||
ITEM_ENTITY_TYPE,
|
||||
@@ -135,8 +135,6 @@ export interface GameHost {
|
||||
export interface SavedLevel {
|
||||
version: 5;
|
||||
seed: string;
|
||||
// see ServerWorld.worldgen_fingerprint
|
||||
worldgen: string;
|
||||
// world time in ticks
|
||||
time: number;
|
||||
tiles: SavedTile[];
|
||||
@@ -206,7 +204,7 @@ export class GameServer {
|
||||
// world.fallbacks each second for the last minute, for /tps
|
||||
#fallback_history: number[] = [];
|
||||
|
||||
constructor(host: GameHost, save: WorldSave | undefined, default_seed: string, mods: GameMods) {
|
||||
constructor(host: GameHost, save: WorldSource | undefined, default_seed: string, mods: GameMods) {
|
||||
this.#host = host;
|
||||
this.#mods = mods;
|
||||
this.mods = mods.runtime;
|
||||
@@ -265,9 +263,7 @@ export class GameServer {
|
||||
},
|
||||
});
|
||||
this.mods.storage = upgrade_mod_storage(saved?.mod_storage ?? {});
|
||||
if (saved) {
|
||||
this.world.load_chunks(save?.chunks ?? [], saved.worldgen);
|
||||
}
|
||||
if (save) this.world.use_saved_chunks(save.chunks);
|
||||
this.world.time = saved?.time ?? 0;
|
||||
this.#day = this.world.day;
|
||||
for (const [id, items] of Object.entries(saved?.containers ?? {})) {
|
||||
@@ -287,8 +283,8 @@ export class GameServer {
|
||||
}
|
||||
this.entities.load(saved?.version === 4 ? upgrade_v4_entities(saved.entities) : saved?.entities ?? []);
|
||||
this.#saved_players = saved?.players ?? {};
|
||||
// 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();
|
||||
// a new world is saved straight away
|
||||
this.world.dirty = !saved;
|
||||
this.#register_commands();
|
||||
|
||||
// players without the chunk get the block with it when they do, like minecraft
|
||||
@@ -430,7 +426,7 @@ export class GameServer {
|
||||
}
|
||||
}
|
||||
|
||||
// level.json and the chunks changed since the last save
|
||||
// level.json and the chunks generated or changed since the last save
|
||||
save(): Required<WorldSave> {
|
||||
for (const player of this.#players.values()) {
|
||||
this.#saved_players[player.name] = player.save_player();
|
||||
@@ -438,7 +434,6 @@ export class GameServer {
|
||||
const level: SavedLevel = {
|
||||
version: 5,
|
||||
seed: this.world.seed,
|
||||
worldgen: this.world.worldgen_fingerprint(),
|
||||
time: this.world.time,
|
||||
tiles: [...this.world.tiles.values()].map((tile) => ({
|
||||
id: tile.id,
|
||||
@@ -1965,16 +1960,20 @@ export class GameServer {
|
||||
}
|
||||
|
||||
// generates what's needed before players come with the pool, instead of on this thread when they do: the spawn
|
||||
// search's chunks and the worldgen fingerprint's
|
||||
// search's chunks
|
||||
async warm_up() {
|
||||
const pool = this.worldgen_pool;
|
||||
if (!pool) return;
|
||||
const reach = SPAWN_AREA_CHUNKS;
|
||||
const around_spawn: [number, number][] = [];
|
||||
for (let x = -reach; x <= reach; x++) for (let z = -reach; z <= reach; z++) around_spawn.push([x, z]);
|
||||
await pool.prefetch([...around_spawn, ...FINGERPRINT_CHUNKS as [number, number][]]);
|
||||
// what the chunks in it are built from, their neighbors' spills too. saved chunks need nothing
|
||||
const reach = SPAWN_AREA_CHUNKS - 1;
|
||||
const needed = new Map<string, [number, number]>();
|
||||
for (let x = -reach; x <= reach; x++) {
|
||||
for (let z = -reach; z <= reach; z++) {
|
||||
for (const [rx, rz] of this.world.raws_needed(x, z)) needed.set(`${rx},${rz}`, [rx, rz]);
|
||||
}
|
||||
}
|
||||
await pool.prefetch([...needed.values()]);
|
||||
this.world.spawn_point();
|
||||
this.world.worldgen_fingerprint();
|
||||
}
|
||||
|
||||
// asks the pool for the raw chunks the nearest chunks each player is waiting for are built from, nearest first.
|
||||
|
||||
@@ -3,10 +3,18 @@ import type { WorldSave } from "./saves.ts";
|
||||
|
||||
// messages between server/main.ts (the host) and the game server worker
|
||||
|
||||
// read_chunk's buffer: an i32 the game waits on while it's READ_WAITING, then an i32 the chunk's length, then the
|
||||
// chunk. a length of -1 is no chunk. READ_TOO_SMALL says the buffer is too small and the length is how big the chunk is
|
||||
export const READ_WAITING = 0;
|
||||
export const READ_DONE = 1;
|
||||
export const READ_TOO_SMALL = 2;
|
||||
export const READ_HEADER = 8;
|
||||
|
||||
export type HostToGame =
|
||||
| {
|
||||
type: "init";
|
||||
save: WorldSave;
|
||||
// level.json, and where the saved chunks are. the game reads them with read_chunk when it needs them
|
||||
save: { level?: string; chunks: [number, number][] };
|
||||
default_seed: string;
|
||||
// in load order, with the scripts' code since the worker can't read files
|
||||
mods: {
|
||||
@@ -36,7 +44,9 @@ export type GameToHost =
|
||||
// text is a json message, bytes a binary one
|
||||
| { type: "send"; conn: number; data: string | Uint8Array<ArrayBuffer> }
|
||||
| { type: "close"; conn: number }
|
||||
// level.json and the chunks that changed
|
||||
// level.json and the chunks generated or changed since the last save
|
||||
| { type: "save"; save: Required<WorldSave>; final: boolean }
|
||||
// the game waits on buffer for a saved chunk, see READ_WAITING
|
||||
| { type: "read_chunk"; x: number; z: number; buffer: SharedArrayBuffer }
|
||||
// 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 };
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { ModData, ModListing } from "$/common/mod_loader.ts";
|
||||
import { load_worldgen } from "$/common/worldgen_loader.ts";
|
||||
import { worldgen_bundle } from "$/common/worldgen_bundle.ts";
|
||||
import { GameHost, GameServer } from "./game_server.ts";
|
||||
import type { WorldSave } from "./saves.ts";
|
||||
import type { WorldSource } from "./saves.ts";
|
||||
import { ModRuntime } from "./mod_runtime.ts";
|
||||
import { register_entity_type } from "./entity/entity_types.ts";
|
||||
import { mod_entity_factory } from "./entity/mod_entity.ts";
|
||||
@@ -29,7 +29,7 @@ export interface ServerModSource {
|
||||
|
||||
export async function start_game(
|
||||
host: GameHost,
|
||||
save: WorldSave | undefined,
|
||||
save: WorldSource | undefined,
|
||||
default_seed: string,
|
||||
mods: ServerModSource[],
|
||||
): Promise<GameServer> {
|
||||
|
||||
+12
-2
@@ -3,9 +3,12 @@ export class LruMap<K, V> {
|
||||
#map = new Map<K, V>();
|
||||
#newest: K | undefined;
|
||||
readonly max_size: number;
|
||||
// called with what's forgotten for being the least recently used
|
||||
#on_evict?: (key: K, value: V) => void;
|
||||
|
||||
constructor(max_size: number) {
|
||||
constructor(max_size: number, on_evict?: (key: K, value: V) => void) {
|
||||
this.max_size = max_size;
|
||||
this.#on_evict = on_evict;
|
||||
}
|
||||
|
||||
get(key: K): V | undefined {
|
||||
@@ -26,7 +29,9 @@ export class LruMap<K, V> {
|
||||
this.#map.delete(key);
|
||||
this.#map.set(key, value);
|
||||
if (this.#map.size > this.max_size) {
|
||||
this.#map.delete(this.#map.keys().next().value!);
|
||||
const [oldest, value] = this.#map.entries().next().value!;
|
||||
this.#map.delete(oldest);
|
||||
this.#on_evict?.(oldest, value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +40,11 @@ export class LruMap<K, V> {
|
||||
return this.#map.has(key);
|
||||
}
|
||||
|
||||
// get without counting as a use
|
||||
peek(key: K): V | undefined {
|
||||
return this.#map.get(key);
|
||||
}
|
||||
|
||||
delete(key: K) {
|
||||
this.#map.delete(key);
|
||||
}
|
||||
|
||||
+67
-26
@@ -5,13 +5,17 @@
|
||||
// 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
|
||||
// u8 biome palette size, then each entry: u8 id length, the id as utf-8
|
||||
// the biome palette index of every column, u8 each, in the order of a layer's blocks
|
||||
//
|
||||
// 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
|
||||
// meaning other blocks. every chunk the game generates is saved whole, like minecraft's, so a change to world
|
||||
// generation only shows in chunks never generated before.
|
||||
// format 1 had no biomes, and a bit per block after the blocks for whether world generation made it, from when only
|
||||
// chunks players changed were saved. both are read
|
||||
import { CHUNK_AREA, CHUNK_HEIGHT } from "$/common/constants.ts";
|
||||
|
||||
export const CHUNK_FORMAT = 1;
|
||||
export const CHUNK_FORMAT = 2;
|
||||
export const CHUNK_VOLUME = CHUNK_AREA * CHUNK_HEIGHT;
|
||||
|
||||
export interface SavedChunk {
|
||||
@@ -20,32 +24,45 @@ export interface SavedChunk {
|
||||
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
|
||||
// a world as the game saves it: level.json's text and the chunks that changed since it last saved
|
||||
export interface WorldSave {
|
||||
// level.json, without it the world is new
|
||||
level?: string;
|
||||
chunks: SavedChunk[];
|
||||
}
|
||||
|
||||
// a world for the game to load. its chunks are read when they're needed, there can be far too many to keep
|
||||
export interface WorldSource {
|
||||
level?: string;
|
||||
chunks: SavedChunks;
|
||||
}
|
||||
|
||||
export interface SavedChunks {
|
||||
// where every saved chunk is
|
||||
list: [number, number][];
|
||||
// a saved chunk's bytes, see encode_chunk. undefined when it can't be read, which generates it again
|
||||
read(chunk_x: number, chunk_z: number): Uint8Array | undefined;
|
||||
}
|
||||
|
||||
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;
|
||||
// each column's, see ServerWorld.biome_at. format 1 chunks don't have them
|
||||
biomes?: string[];
|
||||
}
|
||||
|
||||
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> {
|
||||
export function encode_chunk(chunk: Required<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 biome_palette = [...new Set(chunk.biomes)];
|
||||
if (chunk.biomes.length !== CHUNK_AREA || biome_palette.length > 255) throw new Error("Bad biomes");
|
||||
const biome_ids = biome_palette.map((id) => new TextEncoder().encode(id));
|
||||
if (biome_ids.some((id) => id.length > 255)) throw new Error("A biome id is too long to save");
|
||||
const size = 1 + 4 + ids.reduce((sum, id) => sum + 1 + id.length + 2, 0) + CHUNK_VOLUME * (wide ? 2 : 1) +
|
||||
1 + biome_ids.reduce((sum, id) => sum + 1 + id.length, 0) + CHUNK_AREA;
|
||||
const bytes = new Uint8Array(size);
|
||||
const view = new DataView(bytes.buffer);
|
||||
let offset = 0;
|
||||
@@ -59,15 +76,22 @@ export function encode_chunk(chunk: ChunkBlocks): Uint8Array<ArrayBuffer> {
|
||||
view.setUint16(offset, state);
|
||||
offset += 2;
|
||||
});
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
if (wide) {
|
||||
if (wide) {
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
view.setUint16(offset, chunk.blocks[i]);
|
||||
offset += 2;
|
||||
} else {
|
||||
bytes[offset++] = chunk.blocks[i];
|
||||
}
|
||||
} else {
|
||||
bytes.set(chunk.blocks, offset);
|
||||
offset += CHUNK_VOLUME;
|
||||
}
|
||||
bytes.set(chunk.changed, offset);
|
||||
view.setUint8(offset++, biome_palette.length);
|
||||
for (const id of biome_ids) {
|
||||
view.setUint8(offset++, id.length);
|
||||
bytes.set(id, offset);
|
||||
offset += id.length;
|
||||
}
|
||||
for (const biome of chunk.biomes) bytes[offset++] = biome_palette.indexOf(biome);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
@@ -76,7 +100,7 @@ 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}`);
|
||||
if (format !== CHUNK_FORMAT && format !== 1) 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");
|
||||
@@ -89,19 +113,36 @@ export function decode_chunk(bytes: Uint8Array): ChunkBlocks {
|
||||
offset += 2;
|
||||
}
|
||||
const wide = palette_size > 256;
|
||||
if (bytes.length !== offset + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8) {
|
||||
if (format === 1 && bytes.length !== offset + CHUNK_VOLUME * (wide ? 2 : 1) + CHUNK_VOLUME / 8) {
|
||||
throw new Error("Wrong size");
|
||||
}
|
||||
if (bytes.length < offset + CHUNK_VOLUME * (wide ? 2 : 1)) throw new Error("Wrong size");
|
||||
const blocks = new Uint16Array(CHUNK_VOLUME);
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
if (wide) {
|
||||
if (wide) {
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
blocks[i] = view.getUint16(offset);
|
||||
offset += 2;
|
||||
} else {
|
||||
blocks[i] = bytes[offset++];
|
||||
}
|
||||
} else {
|
||||
blocks.set(bytes.subarray(offset, offset + CHUNK_VOLUME));
|
||||
offset += CHUNK_VOLUME;
|
||||
}
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
if (blocks[i] >= palette_size) throw new Error("Bad palette index");
|
||||
}
|
||||
const changed = bytes.slice(offset, offset + CHUNK_VOLUME / 8);
|
||||
return { palette, blocks, changed };
|
||||
if (format === 1) return { palette, blocks };
|
||||
|
||||
const biome_palette: string[] = [];
|
||||
const biome_palette_size = view.getUint8(offset++);
|
||||
for (let i = 0; i < biome_palette_size; i++) {
|
||||
const length = view.getUint8(offset++);
|
||||
biome_palette.push(new TextDecoder().decode(bytes.subarray(offset, offset + length)));
|
||||
offset += length;
|
||||
}
|
||||
if (bytes.length !== offset + CHUNK_AREA) throw new Error("Wrong size");
|
||||
const biomes = [...bytes.subarray(offset)].map((index) => {
|
||||
if (index >= biome_palette_size) throw new Error("Bad biome palette index");
|
||||
return biome_palette[index];
|
||||
});
|
||||
return { palette, blocks, biomes };
|
||||
}
|
||||
|
||||
+26
-2
@@ -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,
|
||||
|
||||
+145
-140
@@ -6,7 +6,7 @@ import {
|
||||
EverythingRegistry,
|
||||
} from "$/common/everything_registry.ts";
|
||||
import { generate_raw_chunk, RawChunk, WorldgenSetup } from "$/common/generation.ts";
|
||||
import { AIR_ID, BlockChange } from "$/common/protocol.ts";
|
||||
import { AIR_ID } from "$/common/protocol.ts";
|
||||
import { block_value, chunk_key } from "$/common/utils.ts";
|
||||
import { block_numbering } from "$/common/worldgen_bundle.ts";
|
||||
import { LruMap } from "./lru.ts";
|
||||
@@ -14,7 +14,7 @@ import { collision_shape_at, EMPTY_SHAPE, type Shape } from "$/common/block_shap
|
||||
import { farming_day } from "$/common/time.ts";
|
||||
import { encode_level_chunk } from "$/common/chunk_streaming.ts";
|
||||
import type { ItemData } from "$/common/inventory.ts";
|
||||
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, is_changed, SavedChunk } from "./saves.ts";
|
||||
import { CHUNK_VOLUME, ChunkBlocks, decode_chunk, encode_chunk, SavedChunk, SavedChunks } from "./saves.ts";
|
||||
|
||||
// generation only, rebuilt when needed. 256 KB each. with a worldgen pool, it holds what the pool made until the
|
||||
// chunks are built, a few dozen chunks ahead of what players are sent
|
||||
@@ -32,8 +32,6 @@ const LIGHT_BOX = LIGHT_REACH * 2 + 1;
|
||||
const SPAWN_SEARCH_CHUNKS = 32;
|
||||
// the chunks around the middle the spawn search usually finds land in, with their neighbors, worth generating ahead
|
||||
export const SPAWN_AREA_CHUNKS = 3;
|
||||
// generated for worldgen_fingerprint, spread out so most changes to world generation touch at least one
|
||||
export 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, but for item
|
||||
export interface Tile {
|
||||
@@ -47,11 +45,19 @@ export interface Tile {
|
||||
item?: ItemData;
|
||||
}
|
||||
|
||||
// a chunk as it is now, loaded from the save or generated
|
||||
interface LoadedChunk {
|
||||
blocks: Uint32Array;
|
||||
biomes: string[];
|
||||
// saved blocks of mods that are gone, by index in the chunk. air in blocks, and saved again until replaced
|
||||
unknown?: Map<number, [string, number]>;
|
||||
}
|
||||
|
||||
export function position_key(x: number, y: number, z: number) {
|
||||
return `${x},${y},${z}`;
|
||||
}
|
||||
|
||||
// the authoritative world: generated terrain plus everything players changed
|
||||
// the authoritative world: chunks from the save, and generated ones where there's nothing saved yet
|
||||
export class ServerWorld {
|
||||
readonly seed: string;
|
||||
readonly block_ids: Record<string, number> = {};
|
||||
@@ -62,9 +68,10 @@ export class ServerWorld {
|
||||
#opacity: Uint8Array;
|
||||
#emission: Uint8Array;
|
||||
|
||||
// what generation made, and the final blocks with neighbors' leaves and player changes applied
|
||||
// what generation made, and the chunks as they are, with neighbors' leaves and player changes. unsaved chunks
|
||||
// that are forgotten are kept in #evicted until they're saved
|
||||
#raw = new LruMap<number, RawChunk>(RAW_CACHE_SIZE);
|
||||
#chunks = new LruMap<number, Uint32Array>(CHUNK_CACHE_SIZE);
|
||||
#chunks = new LruMap<number, LoadedChunk>(CHUNK_CACHE_SIZE, (key, chunk) => this.#evict(key, chunk));
|
||||
// what generation decided each column's biome is, and what it put in neighbors, kept for longer than the rest
|
||||
#biomes = new LruMap<number, string[]>(SPILL_CACHE_SIZE);
|
||||
#spills = new LruMap<number, Int32Array>(SPILL_CACHE_SIZE);
|
||||
@@ -76,10 +83,13 @@ export class ServerWorld {
|
||||
// per column of a chunk, the highest block that isn't air, then the lowest y that sees the sky. see #columns_of
|
||||
#columns = new LruMap<number, Int16Array>(COLUMN_CACHE_SIZE);
|
||||
|
||||
// changes from generated terrain, per chunk. saved as whole chunks
|
||||
#changes = new Map<number, Map<string, BlockChange>>();
|
||||
// chunks changed since they were last saved, by chunk_key
|
||||
// where saved chunks are read from, and which there are, by chunk_key. chunks saved this session are added
|
||||
#saved_chunks: SavedChunks | undefined;
|
||||
#saved = new Set<number>();
|
||||
// chunks generated or changed since they were last saved, by chunk_key
|
||||
#unsaved = new Map<number, [number, number]>();
|
||||
// unsaved chunks #chunks forgot, ready to save, by chunk_key
|
||||
#evicted = new Map<number, SavedChunk>();
|
||||
tiles = new Map<string, Tile>();
|
||||
// the tiles showing an item, by chunk_key, to send with their chunk
|
||||
#item_tiles = new Map<number, Set<Tile>>();
|
||||
@@ -195,8 +205,17 @@ export class ServerWorld {
|
||||
biome_at(x: number, z: number): string {
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const biomes = this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes;
|
||||
return biomes[column_index(x, z)];
|
||||
return this.#chunk_biomes(chunk_x, chunk_z)[column_index(x, z)];
|
||||
}
|
||||
|
||||
// a saved chunk's are the ones saved with it, which loads it. other chunks' come from generation without building
|
||||
// them
|
||||
#chunk_biomes(chunk_x: number, chunk_z: number) {
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
const chunk = this.#chunks.get(key);
|
||||
if (chunk) return chunk.biomes;
|
||||
if (this.#is_saved(key)) return this.#get_loaded(chunk_x, chunk_z).biomes;
|
||||
return this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).biomes;
|
||||
}
|
||||
|
||||
// builds the chunk now if it isn't, generating what it needs on this thread
|
||||
@@ -217,7 +236,7 @@ export class ServerWorld {
|
||||
// where in a kept chunk (see has_chunk) the blocks are whose numeric id is set in wanted, as x, y, z. nothing when
|
||||
// the chunk isn't kept
|
||||
find_blocks(chunk_x: number, chunk_z: number, wanted: Uint8Array): [number, number, number][] {
|
||||
const blocks = this.#chunks.get(chunk_key(chunk_x, chunk_z));
|
||||
const blocks = this.#chunks.get(chunk_key(chunk_x, chunk_z))?.blocks;
|
||||
if (!blocks) return [];
|
||||
const found: [number, number, number][] = [];
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
@@ -356,14 +375,15 @@ export class ServerWorld {
|
||||
|
||||
const chunk_x = Math.floor(x / CHUNK_SIZE);
|
||||
const chunk_z = Math.floor(z / CHUNK_SIZE);
|
||||
const blocks = this.#get_chunk(chunk_x, chunk_z);
|
||||
blocks[index_in_chunk(x, y, z, chunk_x, chunk_z)] = value;
|
||||
const chunk = this.#get_loaded(chunk_x, chunk_z);
|
||||
const index = index_in_chunk(x, y, z, chunk_x, chunk_z);
|
||||
chunk.blocks[index] = value;
|
||||
chunk.unknown?.delete(index);
|
||||
|
||||
this.#columns.delete(chunk_key(chunk_x, chunk_z));
|
||||
this.#mark_unsaved(chunk_x, chunk_z);
|
||||
|
||||
const state_bits = value >>> 16;
|
||||
this.#record_change(x, y, z, id, state_bits);
|
||||
this.dirty = true;
|
||||
this.on_block_change?.(x, y, z, id, state_bits);
|
||||
}
|
||||
|
||||
@@ -372,8 +392,7 @@ export class ServerWorld {
|
||||
return encode_level_chunk({
|
||||
x: chunk_x,
|
||||
z: chunk_z,
|
||||
blocks: this.#get_chunk(chunk_x, chunk_z),
|
||||
biomes: this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes,
|
||||
...this.#get_loaded(chunk_x, chunk_z),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -387,86 +406,25 @@ export class ServerWorld {
|
||||
return table;
|
||||
}
|
||||
|
||||
#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;
|
||||
// where to read saved chunks from. they're read when they're needed
|
||||
use_saved_chunks(chunks: SavedChunks) {
|
||||
this.#saved_chunks = chunks;
|
||||
for (const [x, z] of chunks.list) this.#saved.add(chunk_key(x, z));
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
this.#columns.delete(chunk_key(chunk_x, chunk_z));
|
||||
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
|
||||
// every chunk generated or 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)),
|
||||
}));
|
||||
const saved = [...this.#unsaved].map(([key, [x, z]]) => {
|
||||
const chunk = this.#chunks.peek(key);
|
||||
this.#saved.add(key);
|
||||
return chunk ? { x, z, data: encode_chunk(this.#chunk_blocks(chunk)) } : this.#evicted.get(key)!;
|
||||
});
|
||||
this.#unsaved.clear();
|
||||
this.#evicted.clear();
|
||||
return saved;
|
||||
}
|
||||
|
||||
#chunk_blocks(chunk_x: number, chunk_z: number): ChunkBlocks {
|
||||
#chunk_blocks(chunk: LoadedChunk): Required<ChunkBlocks> {
|
||||
const palette: [string, number][] = [];
|
||||
const palette_index = new Map<string, number>();
|
||||
const index_of = (id: string, state: number) => {
|
||||
@@ -481,27 +439,28 @@ export class ServerWorld {
|
||||
|
||||
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);
|
||||
// runs of the same block are common, air above the ground and stone below
|
||||
let last_value = -1;
|
||||
let last_index = 0;
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
const value = chunk.blocks[i];
|
||||
if (value !== last_value) {
|
||||
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);
|
||||
}
|
||||
last_value = value;
|
||||
last_index = 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);
|
||||
blocks[i] = last_index;
|
||||
}
|
||||
return { palette, blocks, changed };
|
||||
for (const [i, [id, state]] of chunk.unknown ?? []) blocks[i] = index_of(id, state);
|
||||
return { palette, blocks, biomes: chunk.biomes };
|
||||
}
|
||||
|
||||
get_tile(x: number, y: number, z: number) {
|
||||
@@ -547,15 +506,14 @@ export class ServerWorld {
|
||||
return this.#item_tiles.get(chunk_key(chunk_x, chunk_z)) ?? [];
|
||||
}
|
||||
|
||||
#record_change(x: number, y: number, z: number, id: string, state: number) {
|
||||
const key = chunk_key(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
|
||||
let chunk_changes = this.#changes.get(key);
|
||||
if (!chunk_changes) {
|
||||
chunk_changes = new Map();
|
||||
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)]);
|
||||
#mark_unsaved(chunk_x: number, chunk_z: number) {
|
||||
this.#unsaved.set(chunk_key(chunk_x, chunk_z), [chunk_x, chunk_z]);
|
||||
this.dirty = true;
|
||||
}
|
||||
|
||||
// whether there's a saved chunk there, which the game's thread reads instead of generating anything
|
||||
#is_saved(key: number) {
|
||||
return this.#saved.has(key) || this.#evicted.has(key);
|
||||
}
|
||||
|
||||
#get_raw(chunk_x: number, chunk_z: number) {
|
||||
@@ -585,16 +543,17 @@ export class ServerWorld {
|
||||
if (!this.#raw.has(key)) this.#keep_raw(key, raw);
|
||||
}
|
||||
|
||||
// whether the chunk is built, or can be without generating anything: its own raw blocks and its neighbors' spills
|
||||
// are here
|
||||
// whether the chunk is built, or can be without generating anything: it's saved, or its own raw blocks and its
|
||||
// neighbors' spills are here
|
||||
can_build(chunk_x: number, chunk_z: number) {
|
||||
return this.raws_needed(chunk_x, chunk_z).length === 0;
|
||||
}
|
||||
|
||||
// the raw chunks building it would generate on this thread: its own, if it isn't built and its blocks aren't here,
|
||||
// and its neighbors' whose spills aren't
|
||||
// the raw chunks building it would generate on this thread: none if it's built or saved, otherwise its own if its
|
||||
// blocks aren't here, and its neighbors' whose spills aren't
|
||||
raws_needed(chunk_x: number, chunk_z: number): [number, number][] {
|
||||
if (this.#chunks.has(chunk_key(chunk_x, chunk_z))) return [];
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
if (this.#chunks.has(key) || this.#is_saved(key)) return [];
|
||||
const needed: [number, number][] = [];
|
||||
if (!this.#raw.has(chunk_key(chunk_x, chunk_z))) needed.push([chunk_x, chunk_z]);
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
@@ -612,25 +571,71 @@ export class ServerWorld {
|
||||
}
|
||||
|
||||
#get_chunk(chunk_x: number, chunk_z: number) {
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
let blocks = this.#chunks.get(key);
|
||||
if (!blocks) {
|
||||
blocks = this.#build_chunk(chunk_x, chunk_z);
|
||||
this.#chunks.set(key, blocks);
|
||||
}
|
||||
return blocks;
|
||||
return this.#get_loaded(chunk_x, chunk_z).blocks;
|
||||
}
|
||||
|
||||
// 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);
|
||||
#get_loaded(chunk_x: number, chunk_z: number) {
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
let chunk = this.#chunks.get(key);
|
||||
if (!chunk) {
|
||||
chunk = this.#load(chunk_x, chunk_z);
|
||||
this.#chunks.set(key, chunk);
|
||||
}
|
||||
return chunk;
|
||||
}
|
||||
|
||||
// the saved chunk, or a new one from generation, which is saved from then on like minecraft's
|
||||
#load(chunk_x: number, chunk_z: number): LoadedChunk {
|
||||
const key = chunk_key(chunk_x, chunk_z);
|
||||
if (this.#is_saved(key)) {
|
||||
const evicted = this.#evicted.get(key);
|
||||
this.#evicted.delete(key);
|
||||
const data = evicted?.data ?? this.#saved_chunks?.read(chunk_x, chunk_z);
|
||||
try {
|
||||
if (!data) throw new Error("it couldn't be read");
|
||||
return this.#from_saved(chunk_x, chunk_z, decode_chunk(data));
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`Couldn't load chunk ${chunk_x}, ${chunk_z}, generating it again: ${(e as Error).message}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return blocks;
|
||||
const blocks = this.#generate_chunk(chunk_x, chunk_z);
|
||||
this.#mark_unsaved(chunk_x, chunk_z);
|
||||
return { blocks, biomes: this.#biomes.get(key) ?? this.#get_raw(chunk_x, chunk_z).biomes };
|
||||
}
|
||||
|
||||
#from_saved(chunk_x: number, chunk_z: number, saved: ChunkBlocks): LoadedChunk {
|
||||
// ids of mods that are gone are air until they're back
|
||||
const values = saved.palette.map(([id, state]) => {
|
||||
const nid = id === AIR_ID ? AIR : this.block_ids[id];
|
||||
return nid === undefined ? undefined : block_value(nid, state);
|
||||
});
|
||||
const blocks = new Uint32Array(CHUNK_VOLUME);
|
||||
let unknown: Map<number, [string, number]> | undefined;
|
||||
for (let i = 0; i < CHUNK_VOLUME; i++) {
|
||||
const value = values[saved.blocks[i]];
|
||||
if (value === undefined) {
|
||||
(unknown ??= new Map()).set(i, saved.palette[saved.blocks[i]]);
|
||||
} else {
|
||||
blocks[i] = value;
|
||||
}
|
||||
}
|
||||
let biomes = saved.biomes;
|
||||
if (!biomes) {
|
||||
// saved before chunks had them. saved again with them
|
||||
biomes = this.#biomes.get(chunk_key(chunk_x, chunk_z)) ?? this.#get_raw(chunk_x, chunk_z).biomes;
|
||||
this.#mark_unsaved(chunk_x, chunk_z);
|
||||
}
|
||||
return { blocks, biomes, unknown };
|
||||
}
|
||||
|
||||
// an unsaved chunk is encoded to be saved, instead of being generated again or kept whole
|
||||
#evict(key: number, chunk: LoadedChunk) {
|
||||
const position = this.#unsaved.get(key);
|
||||
if (!position) return;
|
||||
const [x, z] = position;
|
||||
this.#evicted.set(key, { x, z, data: encode_chunk(this.#chunk_blocks(chunk)) });
|
||||
}
|
||||
|
||||
// own blocks, then neighbors' leaves only into air
|
||||
|
||||
Reference in New Issue
Block a user