Client side chunk sections

This commit is contained in:
2026-11-07 10:39:16 -03:00
parent 8e14e9842a
commit 71cbf901a5
19 changed files with 162 additions and 116 deletions
+3 -2
View File
@@ -8,6 +8,7 @@
import { Alea } from "@paulaboks/rng";
import { AIR, CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { ChunkColumn } from "@/common/section.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { DEFAULT_MODEL } from "@/common/block_models.ts";
import { OctaveNoise2D, OctaveNoise3D, smoothstep } from "@/common/worldgen/noise.ts";
@@ -150,7 +151,7 @@ export class BenchTerrain {
return Math.min(TOP - 32, Math.round(height));
}
chunk(chunk_x: number, chunk_z: number): { blocks: Uint32Array; biomes: string[] } {
chunk(chunk_x: number, chunk_z: number): ChunkColumn {
const b = this.#blocks;
const blocks = new Uint32Array(LEVEL_SHAPE.volume);
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
@@ -193,7 +194,7 @@ export class BenchTerrain {
}
this.#trees(chunk_x, chunk_z, set);
this.#features(set);
return { blocks, biomes: new Array(CHUNK_AREA).fill(b.biome) };
return ChunkColumn.from_flat(chunk_x, chunk_z, LEVEL_SHAPE, blocks, new Array(CHUNK_AREA).fill(b.biome));
}
#in_zone(x: number, z: number, margin: number) {
+1 -2
View File
@@ -261,8 +261,7 @@ export class RenderBenchmark {
const start = performance.now();
while (built < chunks.length && performance.now() - start < BUILD_MS_PER_FRAME) {
const [x, z] = chunks[built++];
const { blocks, biomes } = terrain.chunk(x, z);
this.#level.set_chunk(x, z, blocks, biomes);
this.#level.set_chunk(terrain.chunk(x, z));
}
this.#build_ms += performance.now() - start;
this.status = `building the level, ${Math.floor(built / chunks.length * 100)}%`;
+30 -39
View File
@@ -23,9 +23,10 @@ import {
} from "@/common/everything_registry.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, section_index, type SectionData } from "@/common/section.ts";
import { AssetManager } from "../assets.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts";
import type { FaceGroup, FromChunkWorker } from "../workers/chunk_messages.ts";
import type { FaceGroup, FromChunkWorker, SectionLight } 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";
import { Camera } from "../camera.ts";
@@ -47,8 +48,8 @@ export { CHUNK_AREA, CHUNK_SIZE };
export interface Chunk {
x: number;
z: number;
// the dimension's whole height, y from its min_y then z then x
blocks: Uint32Array;
// its blocks and each column's biome, as the server sent them
column: ChunkColumn;
dirty: boolean;
// bumped on every mesh request so late results from older requests get ignored
mesh_version: number;
@@ -58,12 +59,10 @@ export interface Chunk {
max_y: number;
// only for translucent meshes that have to be sorted again as the camera moves
translucent_sort?: TranslucentSort;
// each column's biome id, x then z
biomes: string[];
// each column's biome grass color, x then z, then each column's foliage color, then water color
biome_colors: Uint32Array;
// from its last mesh, see get_light. undefined until it's been meshed
light?: Uint8Array;
// from its last mesh by section, see get_light. undefined until it's been meshed
light?: SectionLight[];
}
export interface ChunkMesh {
@@ -199,23 +198,22 @@ export class ClientLevel {
// 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(
const { x, z, sections, biomes } = decode_level_chunk(
data,
(value) => this.#to_local[value & ID_MASK] | (value & ~ID_MASK),
);
if (!this.#in_storage_range(x, z)) {
return;
}
if (blocks.length !== this.shape.volume) {
throw new Error(`Chunk ${x}, ${z} isn't as tall as the dimension`);
}
this.set_chunk(x, z, blocks, biomes);
// throws when it isn't as tall as the dimension
this.set_chunk(new ChunkColumn(x, z, this.shape, sections, biomes));
}
// a whole chunk, replacing it if it was already here. blocks are this client's numeric ids with their state bits
set_chunk(x: number, z: number, blocks: Uint32Array, biomes: string[]) {
// a whole chunk, replacing it if it was already here. its blocks are this client's numeric ids with their state bits
set_chunk(column: ChunkColumn) {
const { x, z } = column;
const biome_colors = new Uint32Array(CHUNK_AREA * 3);
biomes.forEach((biome, column) => {
column.biomes.forEach((biome, column) => {
biome_colors[column] = grass_color(biome);
biome_colors[CHUNK_AREA + column] = foliage_color(biome);
biome_colors[CHUNK_AREA * 2 + column] = water_color(biome);
@@ -224,16 +222,14 @@ export class ClientLevel {
const chunk = this.get_chunk(x, z);
if (chunk) {
// its old mesh stays up until the new one is ready
chunk.blocks = blocks;
chunk.biomes = biomes;
chunk.column = column;
chunk.biome_colors = biome_colors;
this.#mark_dirty(chunk);
} else {
const chunk: Chunk = {
x,
z,
blocks,
biomes,
column,
biome_colors,
dirty: true,
mesh_version: 0,
@@ -302,10 +298,10 @@ export class ClientLevel {
const lx = block.x - block_chunk_x * CHUNK_SIZE;
const lz = block.z - block_chunk_z * CHUNK_SIZE;
const index = this.#index(block.x, block.y, block.z, block_chunk_x, block_chunk_z);
const old_nid = chunk.blocks[index] & ID_MASK;
chunk.blocks[index] = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
const old_nid = chunk.column.get(block.x, block.y, block.z) & ID_MASK;
const value = state === undefined ? default_block_value(nid, info) : block_value(nid, state);
chunk.column.set(block.x, block.y, block.z, value);
this.#mark_dirty(chunk);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid);
}
@@ -321,7 +317,8 @@ export class ClientLevel {
const chunk_z = Math.floor(z / CHUNK_SIZE);
const light = this.get_chunk(chunk_x, chunk_z)?.light;
if (!light) return this.shape.open_light;
return light[this.#index(Math.floor(x), block_y, Math.floor(z), chunk_x, chunk_z)];
const section = light[(block_y - this.shape.min_y) >> 4];
return typeof section === "number" ? section : section[section_index(Math.floor(x), block_y, Math.floor(z))];
}
// the id with its state bits, VOID outside loaded chunks
@@ -332,7 +329,7 @@ export class ClientLevel {
if (!chunk) {
return VOID;
}
return this.shape.contains(y) ? chunk.blocks[this.#index(x, y, z, chunk_x, chunk_z)] : AIR;
return chunk.column.get(x, y, z);
}
get_block(x: number, y: number, z: number) {
@@ -344,13 +341,7 @@ export class ClientLevel {
if (!chunk) {
return VOID;
}
return this.shape.contains(y) ? chunk.blocks[this.#index(x, y, z, chunk_x, chunk_z)] & ID_MASK : AIR;
}
// a block's place in its chunk's blocks and light. y has to be in the shape
#index(x: number, y: number, z: number, chunk_x: number, chunk_z: number) {
return (y - this.shape.min_y) * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE +
(x - chunk_x * CHUNK_SIZE);
return chunk.column.get(x, y, z) & ID_MASK;
}
// whether entities bump into the block there. unloaded chunks count as solid, so nothing falls out of the world
@@ -374,7 +365,7 @@ export class ClientLevel {
const chunk_x = Math.floor(x / CHUNK_SIZE);
const chunk_z = Math.floor(z / CHUNK_SIZE);
return this.get_chunk(chunk_x, chunk_z)
?.biomes[(z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
?.column.biomes[(z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)];
}
// the biome's water color at a column as 0xRRGGBB, see "tint". plains' in unloaded chunks
@@ -414,15 +405,14 @@ export class ClientLevel {
const lx = x - block_chunk_x * CHUNK_SIZE;
const lz = z - block_chunk_z * CHUNK_SIZE;
const index = this.#index(x, y, z, block_chunk_x, block_chunk_z);
const old_value = chunk.blocks[index];
const old_value = chunk.column.get(x, y, z);
const old_nid = old_value & ID_MASK;
const old_block = this.#blocks[old_nid];
// a waterlogged block leaves its fluid, like the server's destroy_block
const fluid = is_waterlogged(old_value, old_block)
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
: AIR;
chunk.blocks[index] = fluid;
chunk.column.set(x, y, z, fluid);
this.#mark_dirty(chunk);
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, fluid);
}
@@ -619,13 +609,14 @@ export class ClientLevel {
chunk.dirty = false;
this.#dirty.delete(chunk);
chunk.mesh_version += 1;
// copies, the worker lights the whole 3x3 area
const chunks: (Uint32Array | null)[] = [];
// the worker lights the whole 3x3 area. posting copies the sections' blocks, only of the ones that aren't all
// one block
const chunks: (SectionData[] | null)[] = [];
const biome_colors: (Uint32Array | null)[] = [];
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
const neighbor = this.get_chunk(chunk.x + dx, chunk.z + dz);
chunks.push(neighbor?.blocks.slice() ?? null);
chunks.push(neighbor?.column.sections.map((section) => section.data) ?? null);
biome_colors.push(neighbor?.biome_colors ?? null);
}
}
@@ -638,7 +629,7 @@ export class ClientLevel {
chunks,
biome_colors,
camera: [camera.x, camera.y, camera.z],
}, chunks.filter((blocks) => blocks !== null).map((blocks) => blocks.buffer));
});
}
}
+12 -6
View File
@@ -5,6 +5,7 @@ import type { BlockRegistry } from "@/common/everything_registry.ts";
import type { SpriteRegion } from "@/common/constants.ts";
import type { ModelJson } from "@/common/block_models.ts";
import type { WorldShapeJson } from "@/common/world_shape.ts";
import type { SectionData } from "@/common/section.ts";
import type { SortType } from "./translucent_sort.ts";
// messages between the main thread and the chunk workers
@@ -47,8 +48,9 @@ export type ToChunkWorker =
chunk_x: number;
chunk_z: number;
version: number;
// copies of the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting
chunks: (Uint32Array | null)[];
// the blocks of the 3x3 chunks around it, going +x then +z from -x -z, for lighting. each one's sections from the
// bottom of the world up, null for a chunk that isn't loaded
chunks: (SectionData[] | null)[];
// the same chunks' biome colors (see Chunk.biome_colors in client_level.ts), blended across their edges
biome_colors: (Uint32Array | null)[];
// where the camera is, to sort the translucent quads
@@ -64,6 +66,10 @@ export type ToChunkWorker =
camera: number[];
};
// a section's light, a byte per block indexed like its blocks (see section_index): block light << 4 | sky light, like
// sodium's packed light data. one number when it's the same everywhere, like the open sky above the ground
export type SectionLight = number | Uint8Array<ArrayBuffer>;
// 4 vertices per quad, TERRAIN_VERTEX_BYTES each
export interface LayerMesh {
vertices: Uint8Array<ArrayBuffer>;
@@ -92,10 +98,10 @@ export type FromChunkWorker =
planes: [Float32Array, Float32Array, Float32Array];
};
camera: number[];
// the chunk's light, one byte per block indexed like its blocks (from the bottom of the world): block light << 4 | sky light, like sodium's
// packed light data. entities are lit from it
light: Uint8Array<ArrayBuffer>;
// the blocks in it with visuals, as pairs of the block's index in the chunk (like light's) and its value
// the chunk's light by section, from the bottom of the world up, see SectionLight. entities are lit from it
light: SectionLight[];
// the blocks in it with visuals, as pairs of the block's index in the chunk (y from the bottom of the world, then
// z, then x) and its value
visuals: Uint32Array<ArrayBuffer>;
}
| {
+38 -20
View File
@@ -15,11 +15,14 @@ import {
FACE_GROUPS,
type FaceGroup,
type FromChunkWorker,
type SectionLight,
TERRAIN_QUAD_BYTES,
TERRAIN_VERTEX_BYTES,
type ToChunkWorker,
UNALIGNED_GROUP,
} from "./chunk_messages.ts";
import { Section, section_index, SECTION_VOLUME } from "@/common/section.ts";
import { SECTION_HEIGHT } from "@/common/world_shape.ts";
import {
bake_block,
FACE_CORNERS,
@@ -145,13 +148,14 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
world_min_y = message.shape.min_y;
break;
case "mesh": {
region.fill(message.chunks);
const chunks = message.chunks.map((data) => data?.map((section) => new Section(section)) ?? null);
region.fill(chunks);
region.compute(light_tables);
blend_biome_colors(message.biome_colors);
const { solid, cutout, translucent, min_y, max_y, visuals } = make_chunk_mesh(
message.chunk_x,
message.chunk_z,
message.chunks,
chunks,
message.camera,
);
const light = chunk_light();
@@ -171,7 +175,7 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
visuals,
},
[
light.buffer,
...light.filter((section) => typeof section !== "number").map((section) => section.buffer),
visuals.buffer,
solid.vertices.buffer,
cutout.vertices.buffer,
@@ -199,19 +203,27 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
}
};
// the middle chunk of the light region, packed for the main thread, see "meshed"
function chunk_light() {
const light = new Uint8Array(CHUNK_AREA * region.height);
for (let y = 0; y < region.height; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const from = y * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
const to = y * CHUNK_AREA + z * CHUNK_SIZE;
for (let x = 0; x < CHUNK_SIZE; x++) {
light[to + x] = (region.block_light[from + x] << 4) | region.sky[from + x];
// the middle chunk of the light region, packed for the main thread by section, see "meshed"
const section_light = new Uint8Array(SECTION_VOLUME);
function chunk_light(): SectionLight[] {
const sections: SectionLight[] = [];
for (let bottom = 0; bottom < region.height; bottom += SECTION_HEIGHT) {
let same = true;
for (let y = 0; y < SECTION_HEIGHT; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const from = (bottom + y) * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + CHUNK_SIZE;
const to = (y << 8) | (z << 4);
for (let x = 0; x < CHUNK_SIZE; x++) {
const light = (region.block_light[from + x] << 4) | region.sky[from + x];
section_light[to + x] = light;
if (light !== section_light[0]) same = false;
}
}
}
sections.push(same ? section_light[0] : section_light.slice());
}
return light;
return sections;
}
function post(message: FromChunkWorker, transfer: Transferable[]) {
@@ -543,12 +555,12 @@ function hides_fluid(nid: number) {
// a cell's block with its states, from the 3x3 chunks the region was filled from. 0 (air) above the world and for
// chunks that aren't there
function region_value(chunks: (Uint32Array | null)[], index: number, y: number) {
function region_value(chunks: (Section[] | null)[], index: number, y: number) {
if (y < 0 || y >= region.height) return AIR;
const x = index % REGION_SIZE;
const z = Math.floor(index / REGION_SIZE) % REGION_SIZE;
const chunk = chunks[Math.floor(z / CHUNK_SIZE) * 3 + Math.floor(x / CHUNK_SIZE)];
return chunk ? chunk[y * CHUNK_AREA + (z % CHUNK_SIZE) * CHUNK_SIZE + (x % CHUNK_SIZE)] : AIR;
return chunk ? chunk[y >> 4].get(section_index(x, y, z)) : AIR;
}
// the surface of the fluid with this numeric id in a cell, if the cell is that fluid
@@ -563,7 +575,7 @@ const fluid_cells: FluidCell[] = Array.from(
);
// the numeric id of the fluid in a cell: the block, or what it's waterlogged with. 0 for none
function cell_fluid(chunks: (Uint32Array | null)[], index: number, y: number) {
function cell_fluid(chunks: (Section[] | null)[], index: number, y: number) {
const id = region_block(region, index, y);
if (fluid_range[id]) return id;
const fluid = waterlog_fluid[id];
@@ -572,7 +584,7 @@ function cell_fluid(chunks: (Uint32Array | null)[], index: number, y: number) {
}
// the 3x3 cells around the fluid at index and y, see FluidCell. a waterlogged block is a source of its fluid
function fill_fluid_cells(chunks: (Uint32Array | null)[], nid: number, index: number, y: number) {
function fill_fluid_cells(chunks: (Section[] | null)[], nid: number, index: number, y: number) {
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
const cell = fluid_cells[cell_index(dx, dz)];
@@ -640,8 +652,8 @@ function underside(top: MeshQuad): MeshQuad {
// region has to be filled and lit first
// chunks are the 3x3 chunks' blocks with their states, the middle one's for models that change with them and the
// ones around it for fluids, whose surface follows their neighbors'
function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array | null)[], camera: number[]) {
const values = chunks[4]!;
function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Section[] | null)[], camera: number[]) {
const middle = chunks[4]!;
// solid and cutout get a buffer per face group, translucent one for everything since it's sorted instead
const opaque = [SOLID, CUTOUT].map(() =>
Array.from({ length: FACE_GROUPS }, () => ({ buffer: new QuadBuffer(), min: Infinity, max: -Infinity }))
@@ -695,6 +707,12 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
};
for (let y = 0; y < region.height; y++) {
const section = middle[y >> 4];
// nothing to mesh in a section of air
if (section.blocks === null && section.value === AIR) {
y |= 15;
continue;
}
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
// the middle chunk of the region
@@ -738,7 +756,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
if (fluid_nid === block_nid) continue;
}
const value = values[y * CHUNK_AREA + z * CHUNK_SIZE + x];
const value = section.get(section_index(x, y, z));
if (block_visual[block_nid]) {
visuals.push(y * CHUNK_AREA + z * CHUNK_SIZE + x, value);
// with the block above and below, since a visual can reach past its block, like a large cog
+10 -7
View File
@@ -13,7 +13,8 @@
// y in a region counts from the bottom of the world, 0 is the dimension's min_y. in a dimension without sky light
// there's only block light
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import { AIR, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import type { Section } from "@/common/section.ts";
import type { WorldShapeJson } from "@/common/world_shape.ts";
export const REGION_SIZE = CHUNK_SIZE * 3;
@@ -50,21 +51,23 @@ export class LightRegion {
this.block_light = new Uint8Array(volume);
}
// the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z. missing ones are void
fill(chunks: (Uint32Array | null)[]) {
// the 3x3 chunks around the one being meshed, going +x then +z, starting at -x -z, by section. missing ones are
// void
fill(chunks: (Section[] | null)[]) {
for (let i = 0; i < 9; i++) {
const source = chunks[i];
const origin = Math.floor(i / 3) * CHUNK_SIZE * REGION_SIZE + (i % 3) * CHUNK_SIZE;
for (let y = 0; y < this.height; y++) {
const section = source?.[y >> 4];
for (let z = 0; z < CHUNK_SIZE; z++) {
const to = y * REGION_LAYER + origin + z * REGION_SIZE;
if (!source) {
this.blocks.fill(REGION_VOID, to, to + CHUNK_SIZE);
if (!section?.blocks) {
this.blocks.fill(section ? section.value & ID_MASK : REGION_VOID, to, to + CHUNK_SIZE);
continue;
}
const from = y * CHUNK_AREA + z * CHUNK_SIZE;
const from = ((y & 15) << 8) | (z << 4);
for (let x = 0; x < CHUNK_SIZE; x++) {
this.blocks[to + x] = source[from + x] & ID_MASK;
this.blocks[to + x] = section.blocks[from + x] & ID_MASK;
}
}
}