World shape for dimension

This commit is contained in:
2026-11-06 22:49:43 -03:00
parent 7458a2d42a
commit 818ce22dd6
60 changed files with 749 additions and 349 deletions
+8 -4
View File
@@ -6,7 +6,8 @@
// entities, visuals and changing blocks. it's made of what the loaded mods' worldgen data makes the ground of, and other
// blocks picked by what they are (a cutout plant, a translucent cube), not by their ids
import { Alea } from "@paulaboks/rng";
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "@/common/constants.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.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";
@@ -19,6 +20,9 @@ const SEED = "benchmark";
// can be meshed, see ClientLevel.can_mesh
export const LEVEL_RADIUS = 13;
export const SEA_LEVEL = 62;
// 0 to 256 with sky light whatever the world's dimension is, so runs compare. y in its chunks counts from 0
export const LEVEL_SHAPE = DEFAULT_SHAPE;
const TOP = LEVEL_SHAPE.max_y;
// the lake, and flat ground for the scenes. the terrain eases into each over BLEND blocks
export const ZONES = {
@@ -143,12 +147,12 @@ export class BenchTerrain {
const t = smoothstep(zone.radius, zone.radius + BLEND, Math.hypot(x - zone.x, z - zone.z));
height = zone.height + (height - zone.height) * t;
}
return Math.min(CHUNK_HEIGHT - 32, Math.round(height));
return Math.min(TOP - 32, Math.round(height));
}
chunk(chunk_x: number, chunk_z: number): { blocks: Uint32Array; biomes: string[] } {
const b = this.#blocks;
const blocks = new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT);
const blocks = new Uint32Array(LEVEL_SHAPE.volume);
const random = new Alea(`${SEED}_${chunk_x}_${chunk_z}`);
const x0 = chunk_x * CHUNK_SIZE;
const z0 = chunk_z * CHUNK_SIZE;
@@ -156,7 +160,7 @@ export class BenchTerrain {
const set = (x: number, y: number, z: number, value: number, only_air = false) => {
const lx = x - x0;
const lz = z - z0;
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= CHUNK_HEIGHT) return;
if (lx < 0 || lx >= CHUNK_SIZE || lz < 0 || lz >= CHUNK_SIZE || y < 0 || y >= TOP) return;
const index = y * CHUNK_AREA + lz * CHUNK_SIZE + lx;
if (!only_air || blocks[index] === AIR) blocks[index] = value;
};
+2 -1
View File
@@ -40,6 +40,7 @@ import {
type BenchBlocks,
BenchTerrain,
LEVEL_RADIUS,
LEVEL_SHAPE,
SEA_LEVEL,
UPDATE_WALL,
ZONES,
@@ -145,7 +146,7 @@ export class RenderBenchmark {
(_, row) => names.slice(row * GUI_LINE_LENGTH, (row + 1) * GUI_LINE_LENGTH),
);
this.#level = new ClientLevel([], LEVEL_RADIUS);
this.#level = new ClientLevel([], LEVEL_SHAPE, LEVEL_RADIUS);
this.#level.time = TIMES_OF_DAY.noon;
this.#level.max_meshes_in_flight = this.#level.workers.size * MESHES_PER_WORKER;
this.#system = system_info(this.#level.workers.size);
+1 -1
View File
@@ -77,7 +77,7 @@ export class Client {
this.connection = connection;
this.#on_disconnect = on_disconnect;
this.level = new ClientLevel(connection.server_blocks, this.options.render_distance);
this.level = new ClientLevel(connection.server_blocks, connection.shape, this.options.render_distance);
this.level.time = connection.time;
this.#sent_view_distance = this.options.render_distance;
+34 -40
View File
@@ -21,7 +21,8 @@ import {
RENDER_LAYERS,
RenderLayer,
} from "@/common/everything_registry.ts";
import { AIR, CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, Faces, ID_MASK, VOID } from "../../common/constants.ts";
import type { WorldShape } from "@/common/world_shape.ts";
import { AssetManager } from "../assets.ts";
import { ChunkWorkerPool } from "../chunk_workers.ts";
import type { FaceGroup, FromChunkWorker } from "../workers/chunk_messages.ts";
@@ -41,11 +42,12 @@ export interface Block {
z: number;
}
export { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE };
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;
dirty: boolean;
// bumped on every mesh request so late results from older requests get ignored
@@ -112,8 +114,6 @@ const ALL_NEIGHBOR_OFFSETS = [...NEIGHBOR_OFFSETS, [-1, -1], [1, -1], [-1, 1], [
// 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;
// block light 0 and sky light 15, packed like Chunk.light
export const FULL_SKY_LIGHT = 15;
// 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
@@ -131,6 +131,8 @@ export class ClientLevel {
ticks = 0;
// in chunks, what the server was asked to send
view_distance: number;
// the dimension's height and sky light
readonly shape: WorldShape;
// the chunk the server says the player is in
center: { x: number; z: number } | undefined;
// what this client changed ahead of the server, see MultiPlayerGameMode.predict
@@ -151,8 +153,9 @@ export class ClientLevel {
break_progress = new Map<string, { x: number; y: number; z: number; stage: number }>();
// server_blocks is the server's block id for each of its numeric ids
constructor(server_blocks: string[], view_distance: number) {
constructor(server_blocks: string[], shape: WorldShape, view_distance: number) {
this.view_distance = view_distance;
this.shape = shape;
this.#to_local = new Uint32Array(server_blocks.length);
server_blocks.forEach((id, nid) => {
if (!id) return;
@@ -173,6 +176,7 @@ export class ClientLevel {
textures_info: AssetManager.instance.get("cubi:textures_info"),
image: { width: this.image.width, height: this.image.height },
visuals: [...block_visuals].map(([nid, visual]) => [nid, visual.replaces_model]),
shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light },
});
}
@@ -202,6 +206,9 @@ export class ClientLevel {
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);
}
@@ -286,14 +293,16 @@ export class ClientLevel {
return;
}
if (!this.shape.contains(block.y)) {
return;
}
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 ly = block.y;
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
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);
@@ -301,19 +310,18 @@ export class ClientLevel {
this.#mark_neighbors_dirty(block_chunk_x, block_chunk_z, lx, lz, old_nid, nid);
}
// block light << 4 | sky light there, as of its chunk's last mesh. full sky light above the world and where it isn't
// known yet, so entities don't go dark while their chunk loads
// block light << 4 | sky light there, as of its chunk'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 >= CHUNK_HEIGHT) return FULL_SKY_LIGHT;
if (block_y < 0) return 0;
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 FULL_SKY_LIGHT;
const lx = Math.floor(x) - chunk_x * CHUNK_SIZE;
const lz = Math.floor(z) - chunk_z * CHUNK_SIZE;
return light[block_y * CHUNK_AREA + lz * CHUNK_SIZE + lx];
if (!light) return this.shape.open_light;
return light[this.#index(Math.floor(x), block_y, Math.floor(z), chunk_x, chunk_z)];
}
// the id with its state bits, VOID outside loaded chunks
@@ -324,8 +332,7 @@ export class ClientLevel {
if (!chunk) {
return VOID;
}
return chunk.blocks[y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)] ??
AIR;
return this.shape.contains(y) ? chunk.blocks[this.#index(x, y, z, chunk_x, chunk_z)] : AIR;
}
get_block(x: number, y: number, z: number) {
@@ -337,14 +344,13 @@ 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;
}
const lx = x - chunk_x * CHUNK_SIZE;
const lz = z - chunk_z * CHUNK_SIZE;
const ly = y;
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
return chunk.blocks[index] & ID_MASK;
// 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);
}
// whether entities bump into the block there. unloaded chunks count as solid, so nothing falls out of the world
@@ -400,7 +406,7 @@ export class ClientLevel {
const block_chunk_x = Math.floor(x / CHUNK_SIZE);
const block_chunk_z = Math.floor(z / CHUNK_SIZE);
const chunk = this.get_chunk(block_chunk_x, block_chunk_z);
if (!chunk) {
if (!chunk || !this.shape.contains(y)) {
return;
}
@@ -408,9 +414,7 @@ export class ClientLevel {
const lx = x - block_chunk_x * CHUNK_SIZE;
const lz = z - block_chunk_z * CHUNK_SIZE;
const ly = y;
const index = ly * CHUNK_SIZE * CHUNK_SIZE + lz * CHUNK_SIZE + lx;
const index = this.#index(x, y, z, block_chunk_x, block_chunk_z);
const old_value = chunk.blocks[index];
const old_nid = old_value & ID_MASK;
const old_block = this.#blocks[old_nid];
@@ -472,16 +476,6 @@ export class ClientLevel {
}
}
index_to_xyz(index: number) {
const y = Math.floor(index / CHUNK_AREA);
const rem = index % CHUNK_AREA;
const z = Math.floor(rem / CHUNK_SIZE);
const x = rem % CHUNK_SIZE;
return [x, y, z];
}
// set a block the server told us about. the server only sends them for chunks this client has. a block this
// client guessed waits for the server's ack instead, see BlockPredictions
apply_change(x: number, y: number, z: number, id: string, state = 0) {
@@ -691,7 +685,7 @@ export class ClientLevel {
chunk.light = message.light;
chunk.min_y = message.min_y;
chunk.max_y = message.max_y;
this.visuals.meshed(chunk.x, chunk.z, message.visuals);
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];
+6
View File
@@ -360,6 +360,12 @@ function client_context(listing: ModListing): ClientContext {
structuredClone(need_client().level.get_block_data(x, y, z)?.[field]) as never,
biome_at: (x, z) => rules_world.biome_at(x, z),
season_at: (x, z) => rules_world.season_at(x, z),
get min_y() {
return need_client().level.shape.min_y;
},
get max_y() {
return need_client().level.shape.max_y;
},
get time() {
return need_client().level.time;
},
+4
View File
@@ -3,6 +3,7 @@
import { ClientMessage, EntityInfo, MenuSlotInfo, PlayerInfo, ServerMessage } from "@/common/protocol.ts";
import type { ModListing } from "@/common/mod_loader.ts";
import { WorldShape } from "@/common/world_shape.ts";
import type { Join, ServerSocket, Welcome } from "./handshake.ts";
export class Connection {
@@ -12,6 +13,8 @@ export class Connection {
mods: ModListing[];
// the server's block id for each of its numeric ids, for reading chunks
server_blocks: string[];
// the dimension's height and sky light
shape: WorldShape;
spawn: { x: number; y: number; z: number; yaw: number; pitch: number };
selected_slot: number;
// the slots mods added to menu 0
@@ -27,6 +30,7 @@ export class Connection {
this.name = join.name;
this.mods = welcome.mods;
this.server_blocks = join.blocks;
this.shape = new WorldShape(join.shape);
this.spawn = join.spawn;
this.selected_slot = join.selected_slot;
this.player_menu = join.player_menu;
+10 -9
View File
@@ -186,7 +186,7 @@ interface Entry {
// a level's visuals
export class Visuals {
// by chunk_key, then the block's index in its chunk
// by chunk_key, then the block's index in its chunk counted from y 0, see #entry
#chunks = new Map<number, Map<number, Entry>>();
#level: VisualsLevel;
// baked once per level, since a level's mods don't change
@@ -213,15 +213,16 @@ export class Visuals {
yield* this.#fluid_groups;
}
// the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals
// for blocks that are gone or changed go, and new ones are made. the chunk's light came with its mesh, so the ones
// that stay take it
meshed(chunk_x: number, chunk_z: number, found: Uint32Array) {
// the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk (from min_y, the
// bottom of the world) and its value. visuals for blocks that are gone or changed go, and new ones are made. the
// chunk's light came with its mesh, so the ones that stay take it
meshed(chunk_x: number, chunk_z: number, min_y: number, found: Uint32Array) {
const key = chunk_key(chunk_x, chunk_z);
const old = this.#chunks.get(key) ?? new Map<number, Entry>();
const kept = new Map<number, Entry>();
for (let i = 0; i < found.length; i += 2) {
const index = found[i];
const local = found[i];
const index = local + min_y * CHUNK_AREA;
const value = found[i + 1];
const entry = old.get(index);
old.delete(index);
@@ -231,9 +232,9 @@ export class Visuals {
continue;
}
if (entry) this.#delete(entry);
const x = chunk_x * CHUNK_SIZE + (index % CHUNK_SIZE);
const z = chunk_z * CHUNK_SIZE + Math.floor(index / CHUNK_SIZE) % CHUNK_SIZE;
const made = this.#create(x, Math.floor(index / CHUNK_AREA), z, value);
const x = chunk_x * CHUNK_SIZE + (local % CHUNK_SIZE);
const z = chunk_z * CHUNK_SIZE + Math.floor(local / CHUNK_SIZE) % CHUNK_SIZE;
const made = this.#create(x, min_y + Math.floor(local / CHUNK_AREA), z, value);
if (made) kept.set(index, made);
}
for (const entry of old.values()) this.#delete(entry);
+5 -2
View File
@@ -4,6 +4,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 { SortType } from "./translucent_sort.ts";
// messages between the main thread and the chunk workers
@@ -38,6 +39,8 @@ export type ToChunkWorker =
// the numeric ids of blocks with visuals, and whether each visual replaces the block's model, see
// ctx.render.register_visual
visuals: [number, boolean][];
// the dimension's height and sky light. the chunks meshed hold all of its height
shape: WorldShapeJson;
}
| {
type: "mesh";
@@ -75,7 +78,7 @@ export type FromChunkWorker =
chunk_x: number;
chunk_z: number;
version: number;
// the lowest and highest y of the chunk's quads, for frustum culling
// the lowest and highest y of the chunk's quads in the world, for frustum culling
min_y: number;
max_y: number;
solid: LayerMesh;
@@ -89,7 +92,7 @@ export type FromChunkWorker =
planes: [Float32Array, Float32Array, Float32Array];
};
camera: number[];
// the chunk's light, one byte per block indexed like its blocks: block light << 4 | sky light, like sodium's
// 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
+19 -20
View File
@@ -9,15 +9,7 @@ import {
type BlockRegistry,
type RenderLayer,
} from "@/common/everything_registry.ts";
import {
AIR,
CHUNK_AREA,
CHUNK_HEIGHT,
CHUNK_SIZE,
ID_MASK,
type SpriteRegion,
TEXTURE_SIZE,
} from "@/common/constants.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,
@@ -104,7 +96,11 @@ const waterlogged_shift = new Uint8Array(TABLE_SIZE);
const block_visual = new Uint8Array(TABLE_SIZE);
const HAS_VISUAL = 1;
const REPLACED_MODEL = 2;
const region = new LightRegion();
// 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
@@ -145,6 +141,8 @@ self.onmessage = (event: MessageEvent<ToChunkWorker>) => {
}
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);
@@ -203,8 +201,8 @@ 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 * CHUNK_HEIGHT);
for (let y = 0; y < CHUNK_HEIGHT; y++) {
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;
@@ -546,7 +544,7 @@ 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) {
if (y < 0 || y >= CHUNK_HEIGHT) return AIR;
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)];
@@ -663,6 +661,7 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
// 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]
@@ -674,28 +673,28 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
if (layer_id !== TRANSLUCENT) {
const group = opaque[layer_id][quad.group];
push_quad(group.buffer, quad, wx, y, wz, alpha, tint);
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 ? y : wz) + quad.positions[axis];
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, y, wz, alpha, tint);
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] = y + (p[1] + p[7]) / 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 < CHUNK_HEIGHT; y++) {
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
@@ -743,8 +742,8 @@ function make_chunk_mesh(chunk_x: number, chunk_z: number, chunks: (Uint32Array
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 (y - 1 < mesh_min_y) mesh_min_y = y - 1;
if (y + 2 > mesh_max_y) mesh_max_y = y + 2;
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;
}
+31 -14
View File
@@ -9,12 +9,15 @@
// minecraft stores light and updates it as blocks change. here it's worked out from scratch for the
// 3x3 chunks around the chunk being meshed, which gives the same result: light reaches at most 15
// blocks, so nothing outside those chunks can light the middle one or its border
//
// 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_HEIGHT, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import { AIR, CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import type { WorldShapeJson } from "@/common/world_shape.ts";
export const REGION_SIZE = CHUNK_SIZE * 3;
export const REGION_LAYER = REGION_SIZE * REGION_SIZE;
export const REGION_VOLUME = REGION_LAYER * CHUNK_HEIGHT;
// what unloaded chunks and the space below the world are made of: opaque, dark, never shown
export const REGION_VOID = ID_MASK;
@@ -25,22 +28,34 @@ export interface LightTables {
}
export class LightRegion {
// the dimension's, in blocks
readonly height: number;
readonly sky_light: boolean;
// block ids without their state bits, indexed y * REGION_LAYER + z * REGION_SIZE + x
blocks = new Uint16Array(REGION_VOLUME);
sky = new Uint8Array(REGION_VOLUME);
block_light = new Uint8Array(REGION_VOLUME);
blocks: Uint16Array;
sky: Uint8Array;
block_light: Uint8Array;
// the lowest y that still sees the sky, per column
#heights = new Int32Array(REGION_LAYER);
#queue = new Int32Array(1 << 18);
#queue_length = 0;
constructor(shape: WorldShapeJson) {
this.height = shape.max_y - shape.min_y;
this.sky_light = shape.sky_light;
const volume = REGION_LAYER * this.height;
this.blocks = new Uint16Array(volume);
this.sky = new Uint8Array(volume);
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)[]) {
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 < CHUNK_HEIGHT; y++) {
for (let y = 0; y < this.height; y++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const to = y * REGION_LAYER + origin + z * REGION_SIZE;
if (!source) {
@@ -62,13 +77,14 @@ export class LightRegion {
}
#compute_sky({ opacity }: LightTables) {
const { blocks, sky } = this;
const { blocks, sky, height: world_height } = this;
sky.fill(0);
this.#queue_length = 0;
if (!this.sky_light) return;
// straight down from the top, until something isn't fully clear
for (let column = 0; column < REGION_LAYER; column++) {
let y = CHUNK_HEIGHT - 1;
let y = world_height - 1;
while (y >= 0 && opacity[blocks[y * REGION_LAYER + column]] === 0) {
sky[y * REGION_LAYER + column] = 15;
y--;
@@ -89,7 +105,7 @@ export class LightRegion {
if (z < REGION_SIZE - 1) {
highest_neighbor = Math.max(highest_neighbor, this.#heights[column + REGION_SIZE]);
}
const top = Math.min(CHUNK_HEIGHT - 1, Math.max(height, highest_neighbor - 1));
const top = Math.min(world_height - 1, Math.max(height, highest_neighbor - 1));
for (let y = height; y <= top; y++) {
this.#push(y * REGION_LAYER + column);
}
@@ -104,7 +120,7 @@ export class LightRegion {
block_light.fill(0);
this.#queue_length = 0;
for (let i = 0; i < REGION_VOLUME; i++) {
for (let i = 0; i < blocks.length; i++) {
const level = emission[blocks[i]];
if (level > 0) {
block_light[i] = level;
@@ -127,6 +143,7 @@ export class LightRegion {
// breadth first from everything queued. a cell can be queued again when a brighter path reaches it
#propagate(light: Uint8Array, opacity: Uint8Array, is_sky: boolean) {
const blocks = this.blocks;
const top = this.height - 1;
const spread = (to: number, level: number, down: boolean) => {
const block_opacity = opacity[blocks[to]];
@@ -150,7 +167,7 @@ export class LightRegion {
const x = rest - z * REGION_SIZE;
if (y > 0) spread(index - REGION_LAYER, level, true);
if (y < CHUNK_HEIGHT - 1) spread(index + REGION_LAYER, level, false);
if (y < top) spread(index + REGION_LAYER, level, false);
if (x > 0) spread(index - 1, level, false);
if (x < REGION_SIZE - 1) spread(index + 1, level, false);
if (z > 0) spread(index - REGION_SIZE, level, false);
@@ -162,18 +179,18 @@ export class LightRegion {
// what a cell looks like to the mesher, including above and below the world
export function region_block(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT) return AIR;
if (y >= region.height) return AIR;
if (y < 0) return REGION_VOID;
return region.blocks[index];
}
export function region_sky(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT) return 15;
if (y >= region.height) return region.sky_light ? 15 : 0;
if (y < 0) return 0;
return region.sky[index];
}
export function region_block_light(region: LightRegion, index: number, y: number) {
if (y >= CHUNK_HEIGHT || y < 0) return 0;
if (y >= region.height || y < 0) return 0;
return region.block_light[index];
}