Meshing and lighting per section

This commit is contained in:
2026-11-07 11:41:21 -03:00
parent 71cbf901a5
commit b726ce9695
21 changed files with 736 additions and 544 deletions
+185 -162
View File
@@ -13,17 +13,16 @@ import { AIR_ID } from "@/common/protocol.ts";
import { decode_level_chunk } from "@/common/chunk_streaming.ts";
import { DEFAULT_WATER_COLOR, foliage_color, grass_color, water_color } from "@/common/worldgen/biome_colors.ts";
import {
block_light_emission,
block_light_opacity,
BlockRegistry,
EverythingRegistry,
is_fluid_block,
light_tables,
RENDER_LAYERS,
RenderLayer,
} 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 { SECTION_HEIGHT, type WorldShape } from "@/common/world_shape.ts";
import { ChunkColumn, column_heights, section_index, type SectionData } from "@/common/section.ts";
import { AssetManager } from "../assets.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts";
import type { FaceGroup, FromChunkWorker, SectionLight } from "../workers/chunk_messages.ts";
@@ -50,19 +49,29 @@ export interface Chunk {
z: number;
// its blocks and each column's biome, as the server sent them
column: ChunkColumn;
dirty: boolean;
// each column's lowest y that sees the sky, see column_heights in common/section.ts. kept up to date with its blocks
sky: Int16Array;
// one for each of its sections, from the bottom of the world up
sections: RenderSection[];
// each column's biome grass color, x then z, then each column's foliage color, then water color
biome_colors: Uint32Array;
}
// a chunk's section as it's drawn, like sodium's RenderSection. each is meshed and lit on its own
export interface RenderSection {
chunk: Chunk;
// in its chunk, from the bottom of the world up
index: number;
// bumped on every mesh request so late results from older requests get ignored
mesh_version: number;
meshes: Partial<Record<RenderLayer, ChunkMesh>>;
// the lowest and highest y of its meshes, for frustum culling
// the lowest and highest y of its quads and visuals, for frustum culling. Infinity and -Infinity when it has none
min_y: number;
max_y: number;
// only for translucent meshes that have to be sorted again as the camera moves
translucent_sort?: TranslucentSort;
// 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 by section, see get_light. undefined until it's been meshed
light?: SectionLight[];
// from its last mesh, see get_light. undefined until it's been meshed
light?: SectionLight;
}
export interface ChunkMesh {
@@ -107,9 +116,10 @@ export interface BlockData {
data: Record<string, unknown>;
}
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;
// light spreads diagonally too, so meshing and lighting need all 8 neighbors
const NEIGHBOR_OFFSETS = [[-1, 0], [1, 0], [0, -1], [0, 1], [-1, -1], [1, -1], [-1, 1], [1, 1]] as const;
// how far a change in light reaches, and one more for the faces at its edge, whose corners are lit from beyond them
const LIGHT_REACH = 16;
// 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;
@@ -119,9 +129,12 @@ const STORAGE_MARGIN = 3;
export class ClientLevel {
image: Texture = AssetManager.instance.get("cubi:textures");
chunks = new Map<number, Chunk>();
// the chunks request_meshes and update_translucent_sorting look at, so they don't go through every chunk each frame
#dirty = new Set<Chunk>();
#sorted = new Set<Chunk>();
// the sections request_meshes and update_translucent_sorting look at, so they don't go through every one each
// frame. dirty ones by chunk, since a chunk's go in one request
#dirty = new Map<Chunk, Set<RenderSection>>();
#sorted = new Set<RenderSection>();
// the sections with quads or visuals, the only ones there are to draw
drawn = new Set<RenderSection>();
second_timer = 0;
tick_timer = 0;
// world time in ticks, counted here between the server's updates. see common/time.ts
@@ -139,6 +152,7 @@ export class ClientLevel {
workers: ChunkWorkerPool;
#blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
#light = light_tables(this.#blocks);
// the server's numeric block ids to this client's
#to_local: Uint32Array;
@@ -219,34 +233,23 @@ export class ClientLevel {
biome_colors[CHUNK_AREA * 2 + column] = water_color(biome);
});
const sky = column_heights(column, this.#light.opacity).slice(CHUNK_AREA);
const chunk = this.get_chunk(x, z);
if (chunk) {
// its old mesh stays up until the new one is ready
// its old meshes stay up until the new ones are ready
chunk.column = column;
chunk.sky = sky;
chunk.biome_colors = biome_colors;
this.#mark_dirty(chunk);
} else {
const chunk: Chunk = {
x,
z,
column,
biome_colors,
dirty: true,
mesh_version: 0,
meshes: {},
min_y: 0,
max_y: 0,
};
this.chunks.set(chunk_key(x, z), chunk);
this.#dirty.add(chunk);
}
// 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) {
this.#mark_dirty(neighbor);
const chunk: Chunk = { x, z, column, sky, biome_colors, sections: [] };
for (let index = 0; index < column.sections.length; index++) {
chunk.sections.push({ chunk, index, mesh_version: 0, meshes: {}, min_y: Infinity, max_y: -Infinity });
}
this.chunks.set(chunk_key(x, z), chunk);
}
// and its neighbors, whose border faces and light depend on it
this.#mark_dirty_around(x, z, this.shape.min_y, this.shape.max_y);
}
// the server moved the player's view, chunks far outside it go even if the server didn't say
@@ -269,11 +272,12 @@ export class ClientLevel {
dispose() {
this.workers.terminate();
for (const chunk of this.chunks.values()) {
this.delete_chunk_mesh(chunk);
for (const section of chunk.sections) this.#delete_mesh(section);
}
this.visuals.dispose();
this.chunks.clear();
this.#dirty.clear();
this.drawn.clear();
}
get_chunk(x: number, z: number) {
@@ -296,29 +300,23 @@ export class ClientLevel {
const [nid, info] = EverythingRegistry.get_full<BlockRegistry>("blocks", block.id)!;
this.#retain(block.x, block.y, block.z);
const lx = block.x - block_chunk_x * CHUNK_SIZE;
const lz = block.z - block_chunk_z * CHUNK_SIZE;
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);
this.#block_changed(chunk, block.x, block.y, block.z, old_nid, nid);
}
// block light << 4 | sky light there, as of its chunk's last mesh. the shape's open light (full sky light, unless
// block light << 4 | sky light there, as of its section's last mesh. the shape's open light (full sky light, unless
// the dimension has none) above the world and where it isn't known yet, so entities don't go dark while their
// chunk loads
get_light(x: number, y: number, z: number): number {
const block_y = Math.floor(y);
if (block_y >= this.shape.max_y) return this.shape.open_light;
if (block_y < this.shape.min_y) return 0;
const chunk_x = Math.floor(x / CHUNK_SIZE);
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;
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))];
const chunk = this.get_chunk(Math.floor(x / CHUNK_SIZE), Math.floor(z / CHUNK_SIZE));
const light = chunk?.sections[(block_y - this.shape.min_y) >> 4].light;
if (light === undefined) return this.shape.open_light;
return typeof light === "number" ? light : light[section_index(Math.floor(x), block_y, Math.floor(z))];
}
// the id with its state bits, VOID outside loaded chunks
@@ -403,8 +401,6 @@ export class ClientLevel {
this.#retain(x, y, z);
const lx = x - block_chunk_x * CHUNK_SIZE;
const lz = z - block_chunk_z * CHUNK_SIZE;
const old_value = chunk.column.get(x, y, z);
const old_nid = old_value & ID_MASK;
const old_block = this.#blocks[old_nid];
@@ -413,56 +409,53 @@ export class ClientLevel {
? EverythingRegistry.get_id("blocks", old_block!.waterloggable!) ?? AIR
: AIR;
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);
this.#block_changed(chunk, x, y, z, old_nid, fluid);
}
// a block that lets through or gives off a different amount of light changes the light up to 15 blocks
// away, so in every neighbor. otherwise only a block on a chunk's edge matters, for its neighbor's faces
#mark_neighbors_dirty(
block_chunk_x: number,
block_chunk_z: number,
lx: number,
lz: number,
old_nid: number,
new_nid: number,
) {
const old_block = this.#blocks[old_nid];
const new_block = this.#blocks[new_nid];
if (
block_light_opacity(old_block) !== block_light_opacity(new_block) ||
block_light_emission(old_block) !== block_light_emission(new_block)
) {
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
const n = this.get_chunk(block_chunk_x + dx, block_chunk_z + dz);
if (n) {
this.#mark_dirty(n);
}
}
// what a block changing remeshes: its section, and the ones beside it when it's on their border. a block that lets
// through or gives off a different amount of light changes the light up to 15 blocks away, so in every section
// around it, and when it moves its column's sky height, from the old height to the new one in the columns around
#block_changed(chunk: Chunk, x: number, y: number, z: number, old_nid: number, new_nid: number) {
const { opacity, emission } = this.#light;
if (opacity[old_nid] !== opacity[new_nid] || emission[old_nid] !== emission[new_nid]) {
const column = (z & 15) * CHUNK_SIZE + (x & 15);
const old_sky = chunk.sky[column];
chunk.sky = column_heights(chunk.column, opacity).slice(CHUNK_AREA);
const new_sky = chunk.sky[column];
const changed = old_sky === new_sky ? [y] : [y, old_sky, new_sky];
this.#mark_dirty_around(
chunk.x,
chunk.z,
Math.min(...changed) - LIGHT_REACH,
Math.max(...changed) + LIGHT_REACH,
);
return;
}
if (lx === 0) {
const n = this.get_chunk(block_chunk_x - 1, block_chunk_z);
if (n) {
this.#mark_dirty(n);
}
} else if (lx === CHUNK_SIZE - 1) {
const n = this.get_chunk(block_chunk_x + 1, block_chunk_z);
if (n) {
this.#mark_dirty(n);
// the way to the neighbor on each axis whose faces it's next to, 0 for none
const side = (local: number) => local === 0 ? -1 : local === CHUNK_SIZE - 1 ? 1 : 0;
const sx = side(x & 15);
const sy = side((y - this.shape.min_y) & 15);
const sz = side(z & 15);
const index = (y - this.shape.min_y) >> 4;
for (const dx of new Set([0, sx])) {
for (const dz of new Set([0, sz])) {
const sections = this.get_chunk(chunk.x + dx, chunk.z + dz)?.sections;
for (const dy of new Set([0, sy])) {
const section = sections?.[index + dy];
if (section) this.#mark_dirty(section);
}
}
}
if (lz === 0) {
const n = this.get_chunk(block_chunk_x, block_chunk_z - 1);
if (n) {
this.#mark_dirty(n);
}
} else if (lz === CHUNK_SIZE - 1) {
const n = this.get_chunk(block_chunk_x, block_chunk_z + 1);
if (n) {
this.#mark_dirty(n);
}
}
// the sections from from_y to to_y of a chunk and the 8 around it
#mark_dirty_around(chunk_x: number, chunk_z: number, from_y: number, to_y: number) {
const lowest = Math.max(0, (from_y - this.shape.min_y) >> 4);
for (const [dx, dz] of [[0, 0], ...NEIGHBOR_OFFSETS]) {
const sections = this.get_chunk(chunk_x + dx, chunk_z + dz)?.sections ?? [];
const highest = Math.min(sections.length - 1, (to_y - this.shape.min_y) >> 4);
for (let i = lowest; i <= highest; i++) this.#mark_dirty(sections[i]);
}
}
@@ -520,9 +513,12 @@ export class ClientLevel {
if (!chunk) {
return;
}
this.delete_chunk_mesh(chunk);
this.chunks.delete(key);
for (const section of chunk.sections) {
this.#delete_mesh(section);
this.drawn.delete(section);
}
this.#dirty.delete(chunk);
this.chunks.delete(key);
this.block_data.delete(key);
this.visuals.unload(cx, cz);
for (const [position, { x, z }] of this.break_progress) {
@@ -566,10 +562,10 @@ export class ClientLevel {
return this.block_data.get(key)?.get(`${x},${y},${z}`)?.data;
}
// 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
// a chunk's sections are only meshed once all its neighbors exist, otherwise their border faces and light would be
// wrong and they would have to be meshed again as each neighbor loads
can_mesh(chunk: Chunk) {
for (const [dx, dz] of ALL_NEIGHBOR_OFFSETS) {
for (const [dx, dz] of NEIGHBOR_OFFSETS) {
if (!this.get_chunk(chunk.x + dx, chunk.z + dz)) {
return false;
}
@@ -577,46 +573,59 @@ export class ClientLevel {
return true;
}
// meshes asked of the workers that haven't come back, for the f3 performance window
// mesh requests sent to the workers that haven't come back, for the f3 performance window. each is some sections of
// a chunk
meshes_in_flight = 0;
// the rest wait for the next frame. chunks from the server come a few at a time, but the benchmark's level has every
// chunk at once, and each request copies its 3x3 chunks
// chunk at once, and each request copies the sections around the ones it's for
max_meshes_in_flight = Infinity;
// dirty chunks that can be meshed and the meshes the workers are on, 0 once every chunk that can be is meshed
// requests for chunks with dirty sections that can be meshed, and the ones the workers are on. 0 once every
// section that can be is meshed
get meshes_pending() {
let pending = this.meshes_in_flight;
for (const chunk of this.#dirty) {
for (const chunk of this.#dirty.keys()) {
if (this.can_mesh(chunk)) pending += 1;
}
return pending;
}
// meshes every chunk again, for the benchmark to time
// meshes every section again, for the benchmark to time
remesh_all() {
for (const chunk of this.chunks.values()) this.#mark_dirty(chunk);
for (const chunk of this.chunks.values()) {
for (const section of chunk.sections) this.#mark_dirty(section);
}
}
// sends every dirty chunk that can be meshed to the workers
// sends every dirty section that can be meshed to the workers, a request per chunk
request_meshes(camera: Camera) {
for (const chunk of this.#dirty) {
for (const [chunk, sections] of this.#dirty) {
if (this.meshes_in_flight >= this.max_meshes_in_flight) {
break;
}
if (!this.can_mesh(chunk)) {
continue;
}
chunk.dirty = false;
this.#dirty.delete(chunk);
chunk.mesh_version += 1;
// the worker lights the whole 3x3 area. posting copies the sections' blocks, only of the ones that aren't all
// one block
let lowest = Infinity;
let highest = -Infinity;
for (const section of sections) {
section.mesh_version += 1;
lowest = Math.min(lowest, section.index);
highest = Math.max(highest, section.index);
}
// they're lit with the 3x3 chunks' sections from the one below them to the one above. posting copies the
// blocks, of only the sections that aren't all one block
const first = Math.max(0, lowest - 1);
const end = Math.min(chunk.sections.length, highest + 2);
const chunks: (SectionData[] | null)[] = [];
const sky: (Int16Array | 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?.column.sections.map((section) => section.data) ?? null);
chunks.push(neighbor?.column.sections.slice(first, end).map((section) => section.data) ?? null);
sky.push(neighbor?.sky ?? null);
biome_colors.push(neighbor?.biome_colors ?? null);
}
}
@@ -625,20 +634,22 @@ export class ClientLevel {
type: "mesh",
chunk_x: chunk.x,
chunk_z: chunk.z,
version: chunk.mesh_version,
sections: [...sections].map((section) => ({ index: section.index, version: section.mesh_version })),
first,
chunks,
sky,
biome_colors,
camera: [camera.x, camera.y, camera.z],
});
}
}
// like sodium, a chunk's translucent quads only change order when the camera crosses one of the
// planes they lie on, so that's the only time they get sorted again
// like sodium, a section's translucent quads only change order when the camera crosses one of the planes they lie
// on, so that's the only time they get sorted again
update_translucent_sorting(camera: Camera) {
const position = [camera.x, camera.y, camera.z];
for (const chunk of this.#sorted) {
const sort = chunk.translucent_sort!;
for (const section of this.#sorted) {
const sort = section.translucent_sort!;
if (!crosses_planes(sort.planes, sort.camera, position)) {
continue;
}
@@ -646,8 +657,9 @@ export class ClientLevel {
sort.requested += 1;
this.workers.post({
type: "sort",
chunk_x: chunk.x,
chunk_z: chunk.z,
chunk_x: section.chunk.x,
chunk_z: section.chunk.z,
index: section.index,
version: sort.mesh_version,
sort_version: sort.requested,
centers: sort.centers,
@@ -667,47 +679,55 @@ export class ClientLevel {
#on_meshed(message: Extract<FromChunkWorker, { type: "meshed" }>) {
this.meshes_in_flight -= 1;
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
// unloaded, or remeshed again since this was requested
if (!chunk || chunk.mesh_version !== message.version) {
if (!chunk) {
return;
}
this.delete_chunk_mesh(chunk);
chunk.light = message.light;
chunk.min_y = message.min_y;
chunk.max_y = message.max_y;
this.visuals.meshed(chunk.x, chunk.z, this.shape.min_y, message.visuals);
for (const layer of RENDER_LAYERS) {
const { vertices, quad_count, groups } = message[layer];
if (quad_count === 0) {
for (const mesh of message.sections) {
const section = chunk.sections[mesh.index];
// remeshed again since this was requested
if (section.mesh_version !== mesh.version) {
continue;
}
chunk.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups };
}
this.#delete_mesh(section);
section.light = mesh.light;
section.min_y = mesh.min_y;
section.max_y = mesh.max_y;
// with no quads or visuals its bounds are empty
if (mesh.min_y <= mesh.max_y) this.drawn.add(section);
else this.drawn.delete(section);
this.visuals.meshed(chunk.x, chunk.z, this.shape.min_y + section.index * SECTION_HEIGHT, mesh.visuals);
const translucent = message.translucent;
if (translucent.quad_count === 0) {
return;
}
chunk.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices);
if (translucent.sort_type === "dynamic") {
this.#sorted.add(chunk);
chunk.translucent_sort = {
mesh_version: message.version,
centers: translucent.centers,
planes: translucent.planes,
camera: message.camera,
requested: 0,
applied: 0,
};
for (const layer of RENDER_LAYERS) {
const { vertices, quad_count, groups } = mesh[layer];
if (quad_count === 0) {
continue;
}
section.meshes[layer] = { vertex_buffer: create_vertex_buffer(vertices), quad_count, groups };
}
const translucent = mesh.translucent;
if (translucent.quad_count === 0) {
continue;
}
section.meshes.translucent!.index_buffer = create_index_buffer(translucent.indices);
if (translucent.sort_type === "dynamic") {
this.#sorted.add(section);
section.translucent_sort = {
mesh_version: mesh.version,
centers: translucent.centers,
planes: translucent.planes,
camera: message.camera,
requested: 0,
applied: 0,
};
}
}
}
#on_sorted(message: Extract<FromChunkWorker, { type: "sorted" }>) {
const chunk = this.get_chunk(message.chunk_x, message.chunk_z);
const sort = chunk?.translucent_sort;
const mesh = chunk?.meshes.translucent;
const section = this.get_chunk(message.chunk_x, message.chunk_z)?.sections[message.index];
const sort = section?.translucent_sort;
const mesh = section?.meshes.translucent;
// remeshed since, or a newer sort already came back
if (!sort || !mesh || sort.mesh_version !== message.version || message.sort_version <= sort.applied) {
return;
@@ -719,26 +739,29 @@ export class ClientLevel {
mesh.index_buffer = create_index_buffer(message.indices);
}
delete_chunk_mesh(chunk: Chunk) {
for (const mesh of Object.values(chunk.meshes)) {
#delete_mesh(section: RenderSection) {
for (const mesh of Object.values(section.meshes)) {
destroy_buffer(mesh.vertex_buffer);
if (mesh.index_buffer) {
destroy_buffer(mesh.index_buffer);
}
}
chunk.meshes = {};
chunk.translucent_sort = undefined;
this.#sorted.delete(chunk);
section.meshes = {};
section.translucent_sort = undefined;
this.#sorted.delete(section);
}
// chunks that need meshing, some waiting on their neighbors to load
// sections that need meshing, some waiting on their chunk's neighbors to load
get dirty_count() {
return this.#dirty.size;
let count = 0;
for (const sections of this.#dirty.values()) count += sections.size;
return count;
}
#mark_dirty(chunk: Chunk) {
chunk.dirty = true;
this.#dirty.add(chunk);
#mark_dirty(section: RenderSection) {
const sections = this.#dirty.get(section.chunk);
if (sections) sections.add(section);
else this.#dirty.set(section.chunk, new Set([section]));
}
// the closest entity whose box is along the view of something at x/y/z looking at yaw/pitch, within max_distance.