Send chunks to players connected to server

This commit is contained in:
2026-09-28 11:14:40 -03:00
parent 677ad8115a
commit ded9a7e5d0
26 changed files with 920 additions and 357 deletions
+87 -207
View File
@@ -1,5 +1,7 @@
import { block_value, chunk_key, default_block_value } from "$/common/utils.ts";
import { AIR_ID, BlockChange } from "$/common/protocol.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { decode_level_chunk } from "$/common/chunk_streaming.ts";
import { foliage_color, grass_color } from "$/common/worldgen/biome_colors.ts";
import {
block_light_emission,
block_light_opacity,
@@ -11,7 +13,6 @@ import {
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import { AssetManager } from "../assets.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts";
import { worldgen_mods } from "../mods.ts";
import type { FaceGroup, FromChunkWorker } from "../workers/chunk_messages.ts";
import { create_index_buffer, create_vertex_buffer, destroy_buffer, Texture } from "../renderer/mod.ts";
import { crosses_planes } from "../workers/translucent_sort.ts";
@@ -32,7 +33,6 @@ export interface Chunk {
x: number;
z: number;
blocks: Uint32Array;
generated: boolean;
dirty: boolean;
// bumped on every mesh request so late results from older requests get ignored
mesh_version: number;
@@ -42,11 +42,8 @@ export interface Chunk {
max_y: number;
// only for translucent meshes that have to be sorted again as the camera moves
translucent_sort?: TranslucentSort;
// blocks its generation put in neighboring chunks (leaves), as x, y, z, numeric id. kept so a neighbor that
// generates later, or unloads and comes back, still gets them
spills?: Int32Array;
// each column's biome grass then foliage color, once it's generated
biome_colors?: Uint32Array;
// each column's biome grass color, x then z, then each column's foliage color
biome_colors: Uint32Array;
}
export interface ChunkMesh {
@@ -84,46 +81,54 @@ export interface BlockHitResult {
const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1]] as const;
// light spreads diagonally too, so meshing and lighting need all 8
const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
// how far past the view distance chunks are kept, like minecraft's ClientChunkCache. the server tells the client
// which ones to forget, this only catches the ones it didn't
const STORAGE_MARGIN = 3;
// what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it
// what minecraft calls the ClientLevel: this client's copy of the world, its chunks and the entities in it. the
// chunks are what the server sent, see common/chunk_streaming.ts
export class ClientLevel {
image: Texture = AssetManager.instance.get("bworld:textures");
chunks = new Map<number, Chunk>();
second_timer = 0;
tick_timer = 0;
seed: string;
// world time in ticks, counted here between the server's updates. see common/time.ts
time = 0;
// blocks players changed from the generated terrain, per chunk, so they survive reloading chunks
changes = new Map<string, Map<string, BlockChange>>();
// in chunks, what the server was asked to send
view_distance: number;
// the chunk the server says the player is in
center: { x: number; z: number } | undefined;
workers: ChunkWorkerPool;
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
// chunks being generated by a worker, by chunk key
pending_generation = new Map<number, { x: number; z: number }>();
// the server's numeric block ids to this client's
#to_local: Uint32Array;
// every entity this client knows about, the local player included, by id
entities = new Map<string, Entity>();
constructor(seed = "seed") {
this.seed = seed;
// server_blocks is the server's block id for each of its numeric ids
constructor(server_blocks: string[], view_distance: number) {
this.view_distance = view_distance;
this.#to_local = new Uint32Array(server_blocks.length);
server_blocks.forEach((id, nid) => {
if (!id) return;
const local = id === AIR_ID ? AIR : EverythingRegistry.get_id("blocks", id);
if (local === undefined) {
console.warn(`The server has a block this client doesn't: ${id}`);
}
this.#to_local[nid] = local ?? AIR;
});
this.workers = new ChunkWorkerPool((message) => this.#on_worker_message(message));
const blocks_registry = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const block_ids: Record<string, number> = {};
blocks_registry.forEach((block, nid) => block_ids[block.id] = nid);
// sent once instead of with every mesh request
this.workers.broadcast({
type: "init",
blocks_registry: strip_functions(blocks_registry),
block_ids,
blocks_registry: strip_functions(EverythingRegistry.get_registry<BlockRegistry>("blocks")),
models: Object.fromEntries(EverythingRegistry.entries<ModelJson>("models")),
textures_info: AssetManager.instance.get("bworld:textures_info"),
image: { width: this.image.width, height: this.image.height },
worldgen_scripts: worldgen_mods.scripts,
ores: worldgen_mods.ores,
});
}
@@ -143,72 +148,72 @@ export class ClientLevel {
}
}
// generates the chunks around a position and forgets the ones too far away. one extra ring past the render
// distance gets generated so the edge has neighbors to mesh against
update_loaded_chunks(x: number, z: number, render_distance: number) {
const center_x = Math.floor(x / CHUNK_SIZE);
const center_z = Math.floor(z / CHUNK_SIZE);
const load_distance = render_distance + 1;
const out_of_range = (cx: number, cz: number) =>
Math.max(Math.abs(cx - center_x), Math.abs(cz - center_z)) > load_distance;
// collect first, deleting from the map while iterating it skips entries
const to_unload = [...this.chunks.values()].filter((chunk) => out_of_range(chunk.x, chunk.z));
for (const chunk of to_unload) {
this.unload_chunk(chunk.x, chunk.z);
}
for (const pending of [...this.pending_generation.values()]) {
if (out_of_range(pending.x, pending.z)) {
this.cancel_chunk_request(pending.x, pending.z);
}
}
// dont queue up the whole area at once, so walking somewhere new gets the close chunks first
const max_in_flight = this.workers.size * 2;
if (this.pending_generation.size >= max_in_flight) {
// a level_chunk from the server: the whole chunk, replacing it if it was already here
load_chunk(data: Uint8Array) {
const { x, z, blocks, biomes } = decode_level_chunk(
data,
(value) => this.#to_local[value & ID_MASK] | (value & ~ID_MASK),
);
if (!this.#in_storage_range(x, z)) {
return;
}
const biome_colors = new Uint32Array(CHUNK_AREA * 2);
biomes.forEach((biome, column) => {
biome_colors[column] = grass_color(biome);
biome_colors[CHUNK_AREA + column] = foliage_color(biome);
});
const missing: { x: number; z: number; distance: number }[] = [];
for (let cx = center_x - load_distance; cx <= center_x + load_distance; cx += 1) {
for (let cz = center_z - load_distance; cz <= center_z + load_distance; cz += 1) {
if (!this.is_generated(cx, cz) && !this.is_generating(cx, cz)) {
const dx = cx - center_x;
const dz = cz - center_z;
missing.push({ x: cx, z: cz, distance: dx * dx + dz * dz });
}
const chunk = this.get_chunk(x, z);
if (chunk) {
// its old mesh stays up until the new one is ready
chunk.blocks = blocks;
chunk.biome_colors = biome_colors;
chunk.dirty = true;
} else {
this.chunks.set(chunk_key(x, z), {
x,
z,
blocks,
biome_colors,
dirty: true,
mesh_version: 0,
meshes: {},
min_y: 0,
max_y: 0,
});
}
// their border faces and light depend on this one
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
const neighbor = this.get_chunk(x + dx, z + dz);
if (neighbor) {
neighbor.dirty = true;
}
}
missing.sort((a, b) => a.distance - b.distance);
}
for (const chunk of missing.slice(0, max_in_flight - this.pending_generation.size)) {
this.request_chunk(chunk.x, chunk.z);
// the server moved the player's view, chunks far outside it go even if the server didn't say
set_center(x: number, z: number) {
this.center = { x, z };
const far = [...this.chunks.values()].filter((chunk) => !this.#in_storage_range(chunk.x, chunk.z));
for (const chunk of far) {
this.unload_chunk(chunk.x, chunk.z);
}
}
#in_storage_range(x: number, z: number) {
if (!this.center) {
return true;
}
const range = Math.max(2, this.view_distance) + STORAGE_MARGIN;
return Math.max(Math.abs(x - this.center.x), Math.abs(z - this.center.z)) <= range;
}
dispose() {
this.workers.terminate();
for (const chunk of this.chunks.values()) {
this.delete_chunk_mesh(chunk);
}
this.chunks.clear();
this.pending_generation.clear();
}
add_chunk(x: number, z: number, blocks: Uint32Array = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT)) {
const chunk: Chunk = {
x,
z,
blocks,
dirty: true,
generated: false,
mesh_version: 0,
meshes: {},
min_y: 0,
max_y: 0,
};
this.chunks.set(chunk_key(x, z), chunk);
return chunk;
}
get_chunk(x: number, z: number) {
@@ -219,9 +224,9 @@ export class ClientLevel {
add_block(block: Block, state?: number) {
const block_chunk_x = Math.floor(block.x / CHUNK_SIZE);
const block_chunk_z = Math.floor(block.z / CHUNK_SIZE);
let chunk = this.get_chunk(block_chunk_x, block_chunk_z);
const chunk = this.get_chunk(block_chunk_x, block_chunk_z);
if (!chunk) {
chunk = this.add_chunk(block_chunk_x, block_chunk_z);
return;
}
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
@@ -354,20 +359,10 @@ export class ClientLevel {
return [x, y, z];
}
record_change(x: number, y: number, z: number, id: string, state = 0) {
const chunk_key = `${Math.floor(x / CHUNK_SIZE)},${Math.floor(z / CHUNK_SIZE)}`;
let chunk_changes = this.changes.get(chunk_key);
if (!chunk_changes) {
chunk_changes = new Map();
this.changes.set(chunk_key, chunk_changes);
}
chunk_changes.set(`${x},${y},${z}`, [x, y, z, id, state]);
}
// set a block the server told us about
// set a block the server told us about. the server only sends them for chunks this client has
apply_change(x: number, y: number, z: number, id: string, state = 0) {
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
if (!chunk || !chunk.generated) {
if (!chunk) {
return;
}
@@ -386,34 +381,7 @@ export class ClientLevel {
this.add_block({ x, y, z, id }, state);
}
apply_chunk_changes(cx: number, cz: number) {
for (const [x, y, z, id, state] of this.changes.get(`${cx},${cz}`)?.values() ?? []) {
this.apply_change(x, y, z, id, state);
}
}
is_generated(cx: number, cz: number) {
return this.get_chunk(cx, cz)?.generated ?? false;
}
is_generating(cx: number, cz: number) {
return this.pending_generation.has(chunk_key(cx, cz));
}
// generation happens in a worker, the chunk shows up in #on_generated
request_chunk(cx: number, cz: number) {
const key = chunk_key(cx, cz);
if (this.pending_generation.has(key) || this.chunks.get(key)?.generated) {
return;
}
this.pending_generation.set(key, { x: cx, z: cz });
this.workers.post({ type: "generate", chunk_x: cx, chunk_z: cz, seed: this.seed });
}
cancel_chunk_request(cx: number, cz: number) {
this.pending_generation.delete(chunk_key(cx, cz));
}
// also what forget_level_chunk does
unload_chunk(cx: number, cz: number) {
const key = chunk_key(cx, cz);
const chunk = this.chunks.get(key);
@@ -427,11 +395,8 @@ export class ClientLevel {
// a chunk is only meshed once all its neighbors exist, otherwise its border faces and light would be
// wrong and it would have to be meshed again as each neighbor loads
can_mesh(chunk: Chunk) {
if (!chunk.generated) {
return false;
}
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
if (!this.is_generated(chunk.x + dx, chunk.z + dz)) {
if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) {
return false;
}
}
@@ -492,66 +457,13 @@ export class ClientLevel {
}
#on_worker_message(message: FromChunkWorker) {
if (message.type === "generated") {
this.#on_generated(message.chunk_x, message.chunk_z, message.blocks, message.spills, message.biome_colors);
} else if (message.type === "meshed") {
if (message.type === "meshed") {
this.#on_meshed(message);
} else {
this.#on_sorted(message);
}
}
#on_generated(cx: number, cz: number, blocks: Uint32Array, spills: Int32Array, biome_colors: Uint32Array) {
const key = chunk_key(cx, cz);
// unloaded or cancelled while the worker was busy
if (!this.pending_generation.delete(key)) {
return;
}
let chunk = this.chunks.get(key);
if (chunk) {
// blocks placed here before it generated, keep them where generation left air
const existing = chunk.blocks;
for (let i = 0; i < blocks.length; i++) {
if (blocks[i] !== AIR) {
existing[i] = blocks[i];
}
}
} else {
chunk = this.add_chunk(cx, cz, blocks);
}
chunk.generated = true;
chunk.dirty = true;
chunk.spills = spills;
chunk.biome_colors = biome_colors;
// the same rules as the server (server/game/world.ts): a chunk's own blocks, then what its neighbors'
// features put in it, only where it has air. both ways, since the neighbors may have generated first
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
const neighbor_spills = this.get_chunk(cx + dx, cz + dz)?.spills;
if (neighbor_spills) {
this.#apply_spills(neighbor_spills, chunk);
}
}
for (let i = 0; i < spills.length; i += 4) {
this.#set_block_raw(spills[i], spills[i + 1], spills[i + 2], spills[i + 3]);
}
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
const neighbor = this.get_chunk(cx + dx, cz + dz);
if (neighbor && neighbor.generated) {
neighbor.dirty = true;
}
}
// features spill into neighboring chunks, so their changes need reapplying too
for (let dx = -1; dx <= 1; dx++) {
for (let dz = -1; dz <= 1; dz++) {
this.apply_chunk_changes(cx + dx, cz + dz);
}
}
}
#on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) {
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
// unloaded, or remeshed again since this was requested
@@ -603,38 +515,6 @@ export class ClientLevel {
mesh.index_buffer = create_index_buffer(message.indices);
}
// blocks a neighbor's features put here, only fill air so the result doesn't depend on which chunk loaded first.
// the server builds chunks the same way (server/game/world.ts)
#set_block_raw(x: number, y: number, z: number, nid: number) {
if (y < 0 || y >= CHUNK_HEIGHT) {
return;
}
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
const chunk = this.get_chunk(chunk_x, chunk_z);
// a chunk that isn't generated yet takes it from our spills when it is
if (!chunk?.generated) {
return;
}
const lx = x - chunk_x * CHUNK_SIZE;
const lz = z - chunk_z * CHUNK_SIZE;
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
if (chunk.blocks[index] === AIR) {
chunk.blocks[index] = nid;
chunk.dirty = true;
this.#mark_neighbors_dirty(chunk_x, chunk_z, lx, lz, AIR, nid & ID_MASK);
}
}
// the spills that land in chunk
#apply_spills(spills: Int32Array, chunk: Chunk) {
for (let i = 0; i < spills.length; i += 4) {
if (Math.floor(spills[i] / CHUNK_SIZE) === chunk.x && Math.floor(spills[i + 2] / CHUNK_SIZE) === chunk.z) {
this.#set_block_raw(spills[i], spills[i + 1], spills[i + 2], spills[i + 3]);
}
}
}
delete_chunk_mesh(chunk: Chunk) {
for (const mesh of Object.values(chunk.meshes)) {
destroy_buffer(mesh.vertex_buffer);