Files
bworld/client/workers/chunk_worker.ts
T
2026-11-06 22:49:43 -03:00

820 lines
29 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
/// <reference lib="webworker" />
import {
block_light_emission,
block_light_opacity,
type BlockRegistry,
type RenderLayer,
} from "@/common/everything_registry.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK, type SpriteRegion, TEXTURE_SIZE } from "@/common/constants.ts";
import type { Texture } from "../renderer/types.ts";
import {
FACE_GROUPS,
type FaceGroup,
type FromChunkWorker,
TERRAIN_QUAD_BYTES,
TERRAIN_VERTEX_BYTES,
type ToChunkWorker,
UNALIGNED_GROUP,
} from "./chunk_messages.ts";
import {
bake_block,
FACE_CORNERS,
is_full_cube,
is_tinted,
looks_by_state,
type ModelJson,
} from "@/common/block_models.ts";
import {
choose_sort_type,
FACE_AXIS,
FACE_NORMALS,
quad_indices,
quad_planes,
sort_by_distance,
sort_quads,
} from "./translucent_sort.ts";
import {
LightRegion,
type LightTables,
region_block,
region_block_light,
REGION_LAYER,
REGION_SIZE,
region_sky,
REGION_VOID,
} from "./lighting.ts";
import { cell_index, fluid_quads, type FluidCell } from "./fluid_mesh.ts";
import { fluid_height, fluid_textures } from "@/common/everything_registry.ts";
type TexturesInfo = Record<string, SpriteRegion>;
// same order as FACE_NORMALS in translucent_sort.ts, and FACE_CORNERS and CORNER_UVS in block_models.ts
// minecraft's shading by direction, so faces stay apart even in flat light
const FACE_SHADE = [1.0, 0.5, 0.8, 0.8, 0.6, 0.6];
// for each face corner, the two cells beside the cell in front of the face that touch that corner,
// as [index offset, y offset] for each. the cell touching both is at the sum of them
const CORNER_SIDES = FACE_CORNERS.map((corners, face) =>
corners.map((corner) => {
const sides: number[] = [];
for (let axis = 0; axis < 3; axis++) {
if (FACE_NORMALS[face][axis] !== 0) continue;
const d = corner[axis] * 2 - 1;
sides.push(axis === 0 ? d : axis === 1 ? d * REGION_LAYER : d * REGION_SIZE, axis === 1 ? d : 0);
}
return sides;
})
);
const SOLID = 0;
const CUTOUT = 1;
const TRANSLUCENT = 2;
const LAYER_IDS: Record<RenderLayer, number> = { solid: SOLID, cutout: CUTOUT, translucent: TRANSLUCENT };
let blocks_registry: BlockRegistry[] = [];
// by numeric id, looked up for every face. like sodium's light data cache, everything the mesher asks about a
// block is worked out once instead of per face
const TABLE_SIZE = ID_MASK + 1;
const block_layers = new Uint8Array(TABLE_SIZE);
const block_cull_same = new Uint8Array(TABLE_SIZE);
// darkens the corners it touches (minecraft's ambient occlusion), full cubes with collision do
const block_occludes = new Uint8Array(TABLE_SIZE);
// light can come around a corner past it
const block_lets_light_by = new Uint8Array(TABLE_SIZE);
const light_tables: LightTables = { opacity: new Uint8Array(TABLE_SIZE), emission: new Uint8Array(TABLE_SIZE) };
// fluids: their range, 0 for blocks that aren't one, and where their level state is in the state bits
const fluid_range = new Uint8Array(TABLE_SIZE);
const fluid_level_shift = new Uint8Array(TABLE_SIZE);
// waterloggable blocks: the numeric id of the fluid they hold, 0 for other blocks, and where their waterlogged state is
const waterlog_fluid = new Uint16Array(TABLE_SIZE);
const waterlogged_shift = new Uint8Array(TABLE_SIZE);
// blocks with visuals: HAS_VISUAL, or REPLACED_MODEL when the visual draws all of it, see ctx.render.register_visual
const block_visual = new Uint8Array(TABLE_SIZE);
const HAS_VISUAL = 1;
const REPLACED_MODEL = 2;
// the 3x3 chunks being meshed, made for the dimension's height by "init". its y, like the mesher's, counts from the
// bottom of the world
let region: LightRegion;
// the dimension's min_y, which quads are moved up by to be where they are in the world
let world_min_y = 0;
// a model's quad ready for the mesher: uvs in the atlas, and for each corner how much of each of the face's
// four corner lights it gets, so faces smaller than the block are lit like minecraft's
interface MeshQuad {
positions: number[];
uvs: number[];
face: number;
cull: number;
flush: boolean;
// the face group it goes in, see FACE_GROUPS
group: number;
shade: number;
sprite: SpriteRegion;
// 4 weights per corner
light_weights: number[];
// 0xRRGGBB it's drawn in, GRASS, FOLIAGE or WATER for the biome's (see "tint"), or white
tint: number;
}
let models: Record<string, ModelJson> = {};
// by block value, or by numeric id for blocks without variants
const baked = new Map<number, MeshQuad[]>();
let textures_info: TexturesInfo = {};
let image: Texture;
self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
const message = event.data;
switch (message.type) {
case "init":
blocks_registry = message.blocks_registry;
models = message.models;
baked.clear();
build_block_tables();
block_visual.fill(0);
for (const [nid, replaces_model] of message.visuals) {
block_visual[nid] = replaces_model ? REPLACED_MODEL : HAS_VISUAL;
}
textures_info = message.textures_info;
image = message.image as Texture;
region = new LightRegion(message.shape);
world_min_y = message.shape.min_y;
break;
case "mesh": {
region.fill(message.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,
message.camera,
);
const light = chunk_light();
post(
{
type: "meshed",
chunk_x: message.chunk_x,
chunk_z: message.chunk_z,
version: message.version,
min_y,
max_y,
solid,
cutout,
translucent,
camera: message.camera,
light,
visuals,
},
[
light.buffer,
visuals.buffer,
solid.vertices.buffer,
cutout.vertices.buffer,
translucent.vertices.buffer,
translucent.indices.buffer,
translucent.centers.buffer,
...translucent.planes.map((planes) => planes.buffer),
],
);
break;
}
case "sort": {
const [x, y, z] = message.camera;
const indices = quad_indices(sort_by_distance(message.centers, message.centers.length / 3, x, y, z));
post({
type: "sorted",
chunk_x: message.chunk_x,
chunk_z: message.chunk_z,
version: message.version,
sort_version: message.sort_version,
indices,
}, [indices.buffer]);
break;
}
}
};
// 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];
}
}
}
return light;
}
function post(message: FromChunkWorker, transfer: Transferable[]) {
self.postMessage(message, transfer);
}
// like minecraft's biome blend at its default radius: each column's grass, foliage and water color is the average of the 5x5
// columns around it, so biome edges fade instead of being a line. neighbors that aren't there are left out
const BLEND_RADIUS = 2;
// the middle chunk's blended colors, x then z, grass then foliage then water
const blended = new Uint32Array(CHUNK_AREA * 3);
// what MeshQuad.tint is for the biome's colors, they aren't colors since those only go up to 0xffffff
const GRASS = -1;
const FOLIAGE = -2;
const WATER = -3;
function blend_biome_colors(colors: (Uint32Array | null)[]) {
for (const offset of [0, CHUNK_AREA, CHUNK_AREA * 2]) {
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
let r = 0;
let g = 0;
let b = 0;
let count = 0;
for (let dz = -BLEND_RADIUS; dz <= BLEND_RADIUS; dz++) {
for (let dx = -BLEND_RADIUS; dx <= BLEND_RADIUS; dx++) {
// which of the 3x3 chunks, and where in it
const sx = x + dx + CHUNK_SIZE;
const sz = z + dz + CHUNK_SIZE;
const chunk = colors[Math.floor(sz / CHUNK_SIZE) * 3 + Math.floor(sx / CHUNK_SIZE)];
if (!chunk) continue;
const color = chunk[offset + (sz % CHUNK_SIZE) * CHUNK_SIZE + (sx % CHUNK_SIZE)];
r += color >> 16;
g += (color >> 8) & 0xff;
b += color & 0xff;
count++;
}
}
const color = count === 0
? 0xffffff
: (Math.round(r / count) << 16) | (Math.round(g / count) << 8) | Math.round(b / count);
blended[offset + z * CHUNK_SIZE + x] = color;
}
}
}
}
// a quad's MeshQuad.tint from its block's "tint"
function quad_tint(block: BlockRegistry, variables: string[]) {
if (!is_tinted(block, variables)) return 0xffffff;
const color = block.tint!.color;
if (color === "grass") return GRASS;
if (color === "foliage") return FOLIAGE;
if (color === "water") return WATER;
return parseInt(color.slice(1), 16);
}
function build_block_tables() {
// the registry has gaps, which forEach skips
const nids = new Map<string, number>();
blocks_registry.forEach((block, nid) => block && nids.set(block.id, nid));
waterlog_fluid.fill(0);
blocks_registry.forEach((block, nid) => {
if (!block || nid === AIR) return;
const layer = LAYER_IDS[block.render_layer ?? "solid"];
const opacity = block_light_opacity(block);
block_layers[nid] = layer;
block_cull_same[nid] = (block.cull_same ?? layer === TRANSLUCENT) ? 1 : 0;
block_occludes[nid] = block.has_collision && layer !== TRANSLUCENT && is_full_cube(block) ? 1 : 0;
block_lets_light_by[nid] = layer !== SOLID || opacity === 0 ? 1 : 0;
light_tables.opacity[nid] = opacity;
light_tables.emission[nid] = block_light_emission(block);
fluid_range[nid] = block.fluid?.range ?? 0;
if (block.fluid) {
// the level state is the last one, see block_from_json
fluid_level_shift[nid] = (block.states ?? []).slice(0, -1).reduce((bits, state) => bits + state.bits, 0);
}
if (block.waterloggable) {
waterlog_fluid[nid] = nids.get(block.waterloggable) ?? 0;
// the waterlogged state is the last one, see block_from_json
waterlogged_shift[nid] = (block.states ?? []).slice(0, -1).reduce((bits, state) => bits + state.bits, 0);
}
});
block_lets_light_by[AIR] = 1;
block_layers[REGION_VOID] = SOLID;
block_occludes[REGION_VOID] = 1;
light_tables.opacity[REGION_VOID] = 15;
}
// the rule vanilla minecraft (and so sodium) uses: solid neighbors hide a face, and some blocks
// hide faces between two of themselves
function show_face(block: number, neighbor: number) {
if (neighbor === AIR) return true;
if (block_layers[neighbor] === SOLID) return false;
return !(neighbor === block && block_cull_same[block]);
}
// per corner of the face being built
const corner_sky = new Float32Array(4);
const corner_block = new Float32Array(4);
const corner_ao = new Float32Array(4);
// minecraft's smooth lighting: each corner averages the light of the cell in front of the face and the three
// cells around it that touch the corner, and gets darker for each of those that's a full block
function light_face_corners(face: number, front: number, front_y: number) {
const front_id = region_block(region, front, front_y);
const front_sky = region_sky(region, front, front_y);
const front_block = region_block_light(region, front, front_y);
const front_ao = block_occludes[front_id] ? 0.2 : 1;
for (let corner = 0; corner < 4; corner++) {
const [a_offset, a_dy, b_offset, b_dy] = CORNER_SIDES[face][corner];
const a = front + a_offset;
const a_y = front_y + a_dy;
const b = front + b_offset;
const b_y = front_y + b_dy;
const a_id = region_block(region, a, a_y);
const b_id = region_block(region, b, b_y);
let a_sky = region_sky(region, a, a_y);
let a_block = region_block_light(region, a, a_y);
let b_sky = region_sky(region, b, b_y);
let b_block = region_block_light(region, b, b_y);
const a_ao = block_occludes[a_id] ? 0.2 : 1;
const b_ao = block_occludes[b_id] ? 0.2 : 1;
// with both sides closed the corner cell can't be seen, vanilla uses a side's values instead
let c_sky = a_sky;
let c_block = a_block;
let c_ao = a_ao;
if (block_lets_light_by[a_id] || block_lets_light_by[b_id]) {
const c = a + b_offset;
const c_y = a_y + b_dy;
c_sky = region_sky(region, c, c_y);
c_block = region_block_light(region, c, c_y);
c_ao = block_occludes[region_block(region, c, c_y)] ? 0.2 : 1;
}
// cells with no light at all are usually inside solid blocks, vanilla counts them as the front cell
// so corners against walls don't go black
if (a_sky === 0 && a_block === 0) {
a_sky = front_sky;
a_block = front_block;
}
if (b_sky === 0 && b_block === 0) {
b_sky = front_sky;
b_block = front_block;
}
if (c_sky === 0 && c_block === 0) {
c_sky = front_sky;
c_block = front_block;
}
corner_sky[corner] = (a_sky + b_sky + c_sky + front_sky) / 4;
corner_block[corner] = (a_block + b_block + c_block + front_block) / 4;
corner_ao[corner] = (a_ao + b_ao + c_ao + front_ao) / 4;
}
}
// sodium's rule for which diagonal splits the quad: the brighter one, otherwise the ambient occlusion
// gets smeared across the whole face
function should_flip() {
const ao_02 = corner_ao[0] + corner_ao[2];
const ao_13 = corner_ao[1] + corner_ao[3];
if (ao_02 !== ao_13) {
return ao_02 < ao_13;
}
const light = (corner: number) => corner_sky[corner] * 16 + corner_block[corner];
return light(0) + light(2) > light(1) + light(3);
}
// quads being built, in the terrain vertex format
class QuadBuffer {
count = 0;
bytes = new Uint8Array(TERRAIN_QUAD_BYTES * 64);
f32 = new Float32Array(this.bytes.buffer);
u16 = new Uint16Array(this.bytes.buffer);
// room for one more quad
reserve() {
if ((this.count + 1) * TERRAIN_QUAD_BYTES <= this.bytes.length) return;
const bytes = new Uint8Array(this.bytes.length * 2);
bytes.set(this.bytes);
this.bytes = bytes;
this.f32 = new Float32Array(bytes.buffer);
this.u16 = new Uint16Array(bytes.buffer);
}
}
// the lowest and highest y of any quad in the chunk being meshed
let mesh_min_y = Infinity;
let mesh_max_y = -Infinity;
// tint is 0xRRGGBB, multiplied into the quad's color
function push_quad(
buffer: QuadBuffer,
quad: MeshQuad,
x: number,
y: number,
z: number,
alpha: number,
tint = 0xffffff,
) {
buffer.reserve();
const { f32, u16, bytes } = buffer;
const sprite = quad.sprite;
// starting from the second corner moves the diagonal, the winding stays the same
const first = should_flip() ? 1 : 0;
const alpha_byte = Math.round(alpha * 255);
for (let k = 0; k < 4; k++) {
const corner = (first + k) & 3;
const byte = (buffer.count * 4 + k) * TERRAIN_VERTEX_BYTES;
const vy = y + quad.positions[corner * 3 + 1];
f32[byte / 4] = x + quad.positions[corner * 3];
f32[byte / 4 + 1] = vy;
f32[byte / 4 + 2] = z + quad.positions[corner * 3 + 2];
u16[byte / 2 + 6] = Math.round(atlas_u(sprite, quad.uvs[corner * 2]) * 65535);
u16[byte / 2 + 7] = Math.round(atlas_v(sprite, quad.uvs[corner * 2 + 1]) * 65535);
const brightness = quad.shade * corner_ao[corner];
bytes[byte + 16] = Math.round(brightness * (tint >> 16));
bytes[byte + 17] = Math.round(brightness * ((tint >> 8) & 0xff));
bytes[byte + 18] = Math.round(brightness * (tint & 0xff));
bytes[byte + 19] = alpha_byte;
// where to read the lightmap, block light across and sky light down
bytes[byte + 20] = Math.round((corner_block[corner] + 0.5) / 16 * 255);
bytes[byte + 21] = Math.round((corner_sky[corner] + 0.5) / 16 * 255);
if (vy < mesh_min_y) mesh_min_y = vy;
if (vy > mesh_max_y) mesh_max_y = vy;
}
buffer.count += 1;
}
// model uvs (0 to TEXTURE_SIZE across the sprite, whatever its size) to atlas coordinates. the atlas's border around
// each sprite (see ATLAS_BORDER) keeps lookups that round past its edge on its own pixels
function atlas_u(sprite: SpriteRegion, u: number) {
return (sprite.x + u * sprite.width / TEXTURE_SIZE) / image.width;
}
function atlas_v(sprite: SpriteRegion, v: number) {
return (sprite.y + v * sprite.height / TEXTURE_SIZE) / image.height;
}
// the model quads for a block value, baked the first time it's seen
function block_quads(value: number): MeshQuad[] {
const nid = value & ID_MASK;
const block = blocks_registry[nid];
const key = looks_by_state(block) ? value : nid;
let quads = baked.get(key);
if (quads) return quads;
quads = bake_block(block, value, models).map((quad) => ({
positions: quad.positions,
uvs: quad.uvs,
face: quad.face,
cull: quad.cull,
flush: quad.flush,
group: quad.aligned ? quad.face : UNALIGNED_GROUP,
shade: quad.shade ? FACE_SHADE[quad.face] : 1,
sprite: textures_info[quad.texture] ?? textures_info["cubi:missing"],
light_weights: light_weights(quad.face, quad.positions),
tint: quad_tint(block, quad.variables),
}));
baked.set(key, quads);
return quads;
}
// bilinear weights of the face's four corners at each of the quad's corners
function light_weights(face: number, positions: number[]) {
const axes = [0, 1, 2].filter((axis) => FACE_NORMALS[face][axis] === 0);
const weights: number[] = [];
for (let k = 0; k < 4; k++) {
for (const corner of FACE_CORNERS[face]) {
let weight = 1;
for (const axis of axes) {
const t = Math.min(Math.max(positions[k * 3 + axis], 0), 1);
weight *= corner[axis] ? t : 1 - t;
}
weights.push(weight);
}
}
return weights;
}
// light for a quad smaller than a face, or not on the block's edge at all
const face_sky = new Float32Array(4);
const face_block = new Float32Array(4);
const face_ao = new Float32Array(4);
function light_quad(quad: MeshQuad, index: number, y: number, face_offsets: number[]) {
if (quad.flush) {
light_face_corners(quad.face, index + face_offsets[quad.face], y + FACE_NORMALS[quad.face][1]);
face_sky.set(corner_sky);
face_block.set(corner_block);
face_ao.set(corner_ao);
const w = quad.light_weights;
for (let k = 0; k < 4; k++) {
let sky = 0;
let block = 0;
let ao = 0;
for (let c = 0; c < 4; c++) {
sky += w[k * 4 + c] * face_sky[c];
block += w[k * 4 + c] * face_block[c];
ao += w[k * 4 + c] * face_ao[c];
}
corner_sky[k] = sky;
corner_block[k] = block;
corner_ao[k] = ao;
}
return;
}
// inside the block: its own cell's light, or the cell it faces if the block stops light itself
let cell = index;
let cell_y = y;
if (light_tables.opacity[region_block(region, index, y)] === 15) {
cell = index + face_offsets[quad.face];
cell_y = y + FACE_NORMALS[quad.face][1];
}
corner_sky.fill(region_sky(region, cell, cell_y));
corner_block.fill(region_block_light(region, cell, cell_y));
corner_ao.fill(1);
}
// whether a block hides the face of a fluid against it, like show_face. air's layer isn't set, so it's checked first
function hides_fluid(nid: number) {
return nid !== AIR && block_layers[nid] === SOLID;
}
// 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) {
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;
}
// the surface of the fluid with this numeric id in a cell, if the cell is that fluid
function fluid_cell_height(nid: number, value: number) {
const level = ((value >>> 16) >>> fluid_level_shift[nid]) & 7;
return fluid_height(level, fluid_range[nid]);
}
const fluid_cells: FluidCell[] = Array.from(
{ length: 9 },
() => ({ same: false, height: 0, air: false, solid: false, top_same: false }),
);
// 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) {
const id = region_block(region, index, y);
if (fluid_range[id]) return id;
const fluid = waterlog_fluid[id];
if (!fluid) return 0;
return ((region_value(chunks, index, y) >>> 16) >>> waterlogged_shift[id]) & 1 ? fluid : 0;
}
// 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) {
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
const cell = fluid_cells[cell_index(dx, dz)];
const at = index + dx + dz * REGION_SIZE;
const id = region_block(region, at, y);
cell.same = cell_fluid(chunks, at, y) === nid;
cell.height = !cell.same ? 0 : id === nid ? fluid_cell_height(nid, region_value(chunks, at, y)) : 1;
cell.air = id === AIR;
cell.solid = hides_fluid(id);
cell.top_same = cell_fluid(chunks, at + REGION_LAYER, y + 1) === nid;
}
}
return fluid_cells;
}
// for a fluid with a flowing texture of its own, how much of it a block shows: as many pixels across as the still one,
// so minecraft's 32×32 flowing water next to its 16×16 still water shows half. see fluid_quads
function flowing_scale(block: BlockRegistry): number | undefined {
const textures = fluid_textures(block.textures);
if (textures.flowing === textures.still) return undefined;
const still = textures_info[textures.still] ?? textures_info["cubi:missing"];
const flowing = textures_info[textures.flowing] ?? textures_info["cubi:missing"];
return Math.min(1, still.width / flowing.width);
}
// a fluid's quad for the mesher, see fluid_mesh.ts. it's lit like a full block's face on that side
function fluid_mesh_quad(
block: BlockRegistry,
face: number,
positions: number[],
uvs: number[],
still: boolean,
): MeshQuad {
const textures = fluid_textures(block.textures);
const flat = FACE_AXIS[face] !== 1 || (positions[1] === positions[4] && positions[4] === positions[7] &&
positions[7] === positions[10]);
return {
positions,
uvs,
face,
cull: -1,
flush: true,
group: flat ? face : UNALIGNED_GROUP,
shade: FACE_SHADE[face],
sprite: textures_info[still ? textures.still : textures.flowing] ?? textures_info["cubi:missing"],
light_weights: light_weights(face, positions),
tint: quad_tint(block, [still ? "still" : "flowing"]),
};
}
// the fluid's surface seen from below, so it shows from under water: the top quad facing down, lit and shaded like
// the top. its corners go the other way round, the lighting the mesher just worked out with them
const UNDERSIDE_CORNERS = [0, 3, 2, 1];
function underside(top: MeshQuad): MeshQuad {
for (const light of [corner_sky, corner_block, corner_ao]) light.set(UNDERSIDE_CORNERS.map((k) => light[k]));
return {
...top,
face: 1,
positions: UNDERSIDE_CORNERS.flatMap((k) => top.positions.slice(k * 3, k * 3 + 3)),
uvs: UNDERSIDE_CORNERS.flatMap((k) => top.uvs.slice(k * 2, k * 2 + 2)),
};
}
// 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]!;
// 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 }))
);
const translucent_quads = new QuadBuffer();
mesh_min_y = Infinity;
mesh_max_y = -Infinity;
// for sorting the translucent quads
let centers = new Float32Array(256);
let faces = new Uint8Array(256);
// the blocks with visuals, see "meshed"
const visuals: number[] = [];
// where the neighbor on each face is, same order as FACE_NORMALS
const face_offsets = FACE_NORMALS.map(([nx, ny, nz]) => nx + ny * REGION_LAYER + nz * REGION_SIZE);
// adds a lit quad of the block at x y z in the chunk to its layer
const emit = (quad: MeshQuad, layer_id: number, x: number, y: number, z: number, alpha: number) => {
const wx = chunk_x * CHUNK_SIZE + x;
const wy = world_min_y + y;
const wz = chunk_z * CHUNK_SIZE + z;
const tint = quad.tint === GRASS
? blended[z * CHUNK_SIZE + x]
: quad.tint === FOLIAGE
? blended[CHUNK_AREA + z * CHUNK_SIZE + x]
: quad.tint === WATER
? blended[CHUNK_AREA * 2 + z * CHUNK_SIZE + x]
: quad.tint;
if (layer_id !== TRANSLUCENT) {
const group = opaque[layer_id][quad.group];
push_quad(group.buffer, quad, wx, wy, wz, alpha, tint);
if (quad.group !== UNALIGNED_GROUP) {
const axis = FACE_AXIS[quad.face];
const plane = (axis === 0 ? wx : axis === 1 ? wy : wz) + quad.positions[axis];
if (plane < group.min) group.min = plane;
if (plane > group.max) group.max = plane;
}
} else {
push_quad(translucent_quads, quad, wx, wy, wz, alpha, tint);
// sorting treats every quad as facing along an axis, rotated ones too
const q = translucent_quads.count - 1;
centers = ensure_capacity(centers, (q + 1) * 3);
faces = ensure_capacity(faces, q + 1);
const p = quad.positions;
centers[q * 3] = wx + (p[0] + p[6]) / 2;
centers[q * 3 + 1] = wy + (p[1] + p[7]) / 2;
centers[q * 3 + 2] = wz + (p[2] + p[8]) / 2;
faces[q] = quad.face;
}
};
for (let y = 0; y < region.height; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
for (let x = 0; x < CHUNK_SIZE; x++) {
// the middle chunk of the region
const index = y * REGION_LAYER + (z + CHUNK_SIZE) * REGION_SIZE + x + CHUNK_SIZE;
const block_nid = region.blocks[index];
if (block_nid === AIR) continue;
const block_info = blocks_registry[block_nid];
const layer_id = block_layers[block_nid];
const alpha = layer_id === TRANSLUCENT ? block_info.alpha ?? 1 : 1;
// the fluid here, the block's own or what it's waterlogged with, then the block in it
const fluid_nid = cell_fluid(chunks, index, y);
if (fluid_nid) {
const fluid_info = blocks_registry[fluid_nid];
const fluid_layer = block_layers[fluid_nid];
const fluid_alpha = fluid_layer === TRANSLUCENT ? fluid_info.alpha ?? 1 : 1;
const cells = fill_fluid_cells(chunks, fluid_nid, index, y);
const above = region_block(region, index + REGION_LAYER, y + 1);
const below = region_block(region, index - REGION_LAYER, y - 1);
const quads = fluid_quads(
cells,
{
same: cell_fluid(chunks, index + REGION_LAYER, y + 1) === fluid_nid,
solid: hides_fluid(above),
},
{
same: cell_fluid(chunks, index - REGION_LAYER, y - 1) === fluid_nid,
solid: hides_fluid(below),
},
flowing_scale(fluid_info),
);
for (const { face, positions, uvs, still } of quads) {
const quad = fluid_mesh_quad(fluid_info, face, positions, uvs, still);
light_quad(quad, index, y, face_offsets);
// like minecraft's fluids, no ambient occlusion
corner_ao.fill(1);
emit(quad, fluid_layer, x, y, z, fluid_alpha);
if (face === 0) emit(underside(quad), fluid_layer, x, y, z, fluid_alpha);
}
if (fluid_nid === block_nid) continue;
}
const value = values[y * CHUNK_AREA + z * CHUNK_SIZE + x];
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
if (world_min_y + y - 1 < mesh_min_y) mesh_min_y = world_min_y + y - 1;
if (world_min_y + y + 2 > mesh_max_y) mesh_max_y = world_min_y + y + 2;
if (block_visual[block_nid] === REPLACED_MODEL) continue;
}
for (const quad of block_quads(value)) {
if (quad.cull >= 0) {
const neighbor = region_block(
region,
index + face_offsets[quad.cull],
y + FACE_NORMALS[quad.cull][1],
);
if (!show_face(block_nid, neighbor)) continue;
}
light_quad(quad, index, y, face_offsets);
emit(quad, layer_id, x, y, z, alpha);
}
}
}
}
// each layer's groups one after another, in one buffer
const [solid, cutout] = opaque.map((groups) => {
const quad_count = groups.reduce((sum, group) => sum + group.buffer.count, 0);
const vertices = new Uint8Array(quad_count * TERRAIN_QUAD_BYTES);
const ranges: FaceGroup[] = [];
let first = 0;
for (const { buffer, min, max } of groups) {
vertices.set(buffer.bytes.subarray(0, buffer.count * TERRAIN_QUAD_BYTES), first * TERRAIN_QUAD_BYTES);
ranges.push({ first, count: buffer.count, min, max });
first += buffer.count;
}
return { vertices, quad_count, groups: ranges };
});
const translucent = {
vertices: translucent_quads.bytes.slice(0, translucent_quads.count * TERRAIN_QUAD_BYTES),
quad_count: translucent_quads.count,
};
const quads = { centers, faces, count: translucent.quad_count };
const sort_type = choose_sort_type(quads);
const [camera_x, camera_y, camera_z] = camera;
return {
min_y: mesh_min_y === Infinity ? 0 : mesh_min_y,
max_y: mesh_max_y === -Infinity ? 0 : mesh_max_y,
solid,
cutout,
translucent: {
...translucent,
indices: sort_quads(quads, sort_type, camera_x, camera_y, camera_z),
sort_type,
centers: centers.slice(0, quads.count * 3),
planes: quad_planes(quads),
},
visuals: Uint32Array.from(visuals),
};
}
function ensure_capacity<T extends Float32Array<ArrayBuffer> | Uint8Array<ArrayBuffer>>(
buffer: T,
required: number,
): T {
if (required <= buffer.length) return buffer;
let new_length = buffer.length;
while (new_length < required) {
new_length *= 2;
}
const new_buffer = new (buffer.constructor as new (length: number) => T)(new_length);
new_buffer.set(buffer as ArrayLike<number>);
return new_buffer;
}