diff --git a/client/benchmark/bench_level.ts b/client/benchmark/bench_level.ts index ca32cc7..5f700c8 100644 --- a/client/benchmark/bench_level.ts +++ b/client/benchmark/bench_level.ts @@ -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) { diff --git a/client/benchmark/benchmark.ts b/client/benchmark/benchmark.ts index 2910b21..34cc775 100644 --- a/client/benchmark/benchmark.ts +++ b/client/benchmark/benchmark.ts @@ -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)}%`; diff --git a/client/level/client_level.ts b/client/level/client_level.ts index ec16160..5afd241 100644 --- a/client/level/client_level.ts +++ b/client/level/client_level.ts @@ -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)); + }); } } diff --git a/client/workers/chunk_messages.ts b/client/workers/chunk_messages.ts index c614410..fe031db 100644 --- a/client/workers/chunk_messages.ts +++ b/client/workers/chunk_messages.ts @@ -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; + // 4 vertices per quad, TERRAIN_VERTEX_BYTES each export interface LayerMesh { vertices: Uint8Array; @@ -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; - // 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; } | { diff --git a/client/workers/chunk_worker.ts b/client/workers/chunk_worker.ts index 83c66ba..20643ea 100644 --- a/client/workers/chunk_worker.ts +++ b/client/workers/chunk_worker.ts @@ -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) => { 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) => { 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) => { } }; -// 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 diff --git a/client/workers/lighting.ts b/client/workers/lighting.ts index 63e244d..87f47b3 100644 --- a/client/workers/lighting.ts +++ b/client/workers/lighting.ts @@ -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; } } } diff --git a/common/chunk_streaming.ts b/common/chunk_streaming.ts index 3f055ed..173371c 100644 --- a/common/chunk_streaming.ts +++ b/common/chunk_streaming.ts @@ -5,7 +5,7 @@ // player, and which chunks are in a player's view. see "Chunk Streaming" in docs/modding_plan.md import { deflateSync, inflateSync } from "fflate"; import { Reader, Writer } from "./bytes.ts"; -import { type ChunkColumn, read_column, to_flat, write_column } from "./section.ts"; +import { type ChunkColumn, read_column, type Section, write_column } from "./section.ts"; // the view distances clients can ask for, in chunks, like minecraft's export const MIN_VIEW_DISTANCE = 2; @@ -35,9 +35,9 @@ export function is_within_view( export interface LevelChunk { x: number; z: number; - // block values (numeric id | state bits << 16) in the sender's numbering, y from the bottom of the world, then z, - // then x. the dimension's whole height - blocks: Uint32Array; + // block values (numeric id | state bits << 16) in the receiver's numbering, see decode_level_chunk. from the bottom + // of the world up, the dimension's whole height + sections: Section[]; // each column's biome, x then z biomes: string[]; } @@ -70,5 +70,5 @@ export function decode_level_chunk(bytes: Uint8Array, map: (value: number) => nu const reader = new Reader(inflateSync(bytes.subarray(9))); const { sections, biomes } = read_column(reader, map); if (!reader.done) throw new Error("Wrong size"); - return { x, z, blocks: to_flat(sections), biomes }; + return { x, z, sections, biomes }; } diff --git a/tests/benchmark_test.ts b/tests/benchmark_test.ts index 23df62c..958a549 100644 --- a/tests/benchmark_test.ts +++ b/tests/benchmark_test.ts @@ -57,7 +57,7 @@ Deno.test("a report reads back from what was copied", () => { Deno.test("the benchmark's level comes out the same every time, with terrain in every layer", async () => { await test_game("mods"); const blocks = bench_blocks(new Set()); - const chunk = (x: number, z: number) => new BenchTerrain(blocks).chunk(x, z).blocks; + const chunk = (x: number, z: number) => new BenchTerrain(blocks).chunk(x, z).to_flat(); const lake = [Math.floor(ZONES.lake.x / CHUNK_SIZE), Math.floor(ZONES.lake.z / CHUNK_SIZE)] as const; const near_lake = [lake[0] + 3, lake[1] + 3] as const; assertEquals(chunk(0, 0), chunk(0, 0)); diff --git a/tests/chunk_loading_test.ts b/tests/chunk_loading_test.ts index d3c5b78..9bd9553 100644 --- a/tests/chunk_loading_test.ts +++ b/tests/chunk_loading_test.ts @@ -6,6 +6,7 @@ // GameServer.use_worldgen_pool import { assert, assertEquals } from "@std/assert"; import { is_within_view } from "@/common/chunk_streaming.ts"; +import { to_flat } from "@/common/section.ts"; import { game_with_pool, load_view } from "./chunk_loading.ts"; // the workers and their ports live until the test closes them @@ -32,7 +33,11 @@ Deno.test({ if (!is_within_view(cx, cz, player.chunks.view_distance, x, z)) continue; const chunk = chunks.get(`${x},${z}`); assert(chunk, `chunk ${x},${z} wasn't sent`); - assertEquals(chunk.blocks, t.game.world.generated_blocks(x, z).to_flat(), `chunk ${x},${z}`); + assertEquals( + to_flat(chunk.sections), + t.game.world.generated_blocks(x, z).to_flat(), + `chunk ${x},${z}`, + ); } } assert(t.pool!.generated - generated > chunks.size, "the pool made them, and their neighbors"); diff --git a/tests/chunk_streaming_test.ts b/tests/chunk_streaming_test.ts index 274c8f8..b72a336 100644 --- a/tests/chunk_streaming_test.ts +++ b/tests/chunk_streaming_test.ts @@ -4,10 +4,10 @@ // the server sends the world in whole chunks, like minecraft java: nearest first, in batches the client paces, and // only to players who can see them import { assert, assertEquals } from "@std/assert"; -import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; +import { CHUNK_AREA } from "@/common/constants.ts"; import { decode_level_chunk, encode_level_chunk, is_within_view } from "@/common/chunk_streaming.ts"; import { PROTOCOL_VERSION } from "@/common/protocol.ts"; -import { ChunkColumn } from "@/common/section.ts"; +import { ChunkColumn, section_index, to_flat } from "@/common/section.ts"; import { WorldShape } from "@/common/world_shape.ts"; import { sent_block, test_game } from "./helpers.ts"; @@ -28,7 +28,8 @@ Deno.test("a chunk comes back as it was encoded, whatever its sections hold", () const decoded = decode_level_chunk(encode_level_chunk(ChunkColumn.from_flat(-3, 70000, shape, blocks, biomes))); assertEquals(decoded.x, -3); assertEquals(decoded.z, 70000); - assertEquals(decoded.blocks, blocks); + assertEquals(to_flat(decoded.sections), blocks); + assertEquals(decoded.sections.map((section) => section.blocks === null).indexOf(false), 1, "uniform ones stay so"); assertEquals(decoded.biomes, biomes); // one biome, and the receiver's numbering @@ -37,8 +38,8 @@ Deno.test("a chunk comes back as it was encoded, whatever its sections hold", () (value) => value === 7 ? 70 : value, ); assertEquals(one.biomes, biomes.map(() => "bworld:plains")); - assertEquals(one.blocks[0], 70); - assertEquals(one.blocks[section], 1); + assertEquals(one.sections[0].value, 70); + assertEquals(one.sections[1].get(0), 1); }); Deno.test("the view is round, with a ring of chunks past it for meshing its edge", () => { @@ -136,7 +137,7 @@ Deno.test("block changes only go to players who have the chunk, the others get t assertEquals(alice.blocks[game.world.block_ids["bworld:stone"]], "bworld:stone"); const chunk = decode_level_chunk(game.world.level_chunk(0, 0)); const y = 120 - game.world.shape.min_y; - assertEquals(chunk.blocks[y * CHUNK_AREA + 5 * CHUNK_SIZE + 3], game.world.get_block_value(3, 120, 5)); + assertEquals(chunk.sections[y >> 4].get(section_index(3, y, 5)), game.world.get_block_value(3, 120, 5)); }); Deno.test("/viewdistance caps every player's view distance, and raising it gives them what they asked for", async () => { diff --git a/tests/dimension_test.ts b/tests/dimension_test.ts index c9d83f5..ac8ec03 100644 --- a/tests/dimension_test.ts +++ b/tests/dimension_test.ts @@ -139,9 +139,9 @@ Deno.test("a dimension's blocks go from its min_y to max_y - 1, and are sent and // what clients get: every block from the bottom up const chunk = decode_level_chunk(world.level_chunk(2, 0)); - assertEquals(chunk.blocks.length, CHUNK_AREA * 384); - assertEquals(chunk.blocks[8], world.get_block_value(GROUND_X, -64, 0)); - assertEquals(chunk.blocks[383 * CHUNK_AREA + 8], world.get_block_value(GROUND_X, 319, 0)); + assertEquals(chunk.sections.length, 384 / 16); + assertEquals(chunk.sections[0].get(8), world.get_block_value(GROUND_X, -64, 0)); + assertEquals(chunk.sections[23].get(15 * CHUNK_AREA + 8), world.get_block_value(GROUND_X, 319, 0)); // a column of ground: glass up to 69 and air above, all one block in every section but the one with the ground's // top in it diff --git a/tests/entity_light_test.ts b/tests/entity_light_test.ts index 4a58236..ca8b7c7 100644 --- a/tests/entity_light_test.ts +++ b/tests/entity_light_test.ts @@ -1,12 +1,15 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// entities are lit from the light the chunk worker sends back with each mesh, one byte per block: block << 4 | sky +// entities are lit from the light the chunk worker sends back with each mesh, by section and one byte per block: +// block << 4 | sky import { assertEquals } from "@std/assert"; import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts"; import { DEFAULT_SHAPE, type WorldShapeJson } from "@/common/world_shape.ts"; -import { test_game } from "./helpers.ts"; +import { section_data, test_game } from "./helpers.ts"; +import type { SectionLight } from "@/client/workers/chunk_messages.ts"; +import { section_index } from "@/common/section.ts"; // the middle chunk's light, with a stone roof at y 20 over x 0-7 and a light block at 12, 5, 8. y counts from the // bottom of the world @@ -35,29 +38,32 @@ async function mesh_light(shape: WorldShapeJson = DEFAULT_SHAPE) { const empty = () => new Uint32Array(volume); const chunks = [empty(), empty(), empty(), empty(), chunk, empty(), empty(), empty(), empty()]; - const meshed = await new Promise<{ light: Uint8Array; max_y: number }>((resolve) => { + const meshed = await new Promise<{ light: SectionLight[]; max_y: number }>((resolve) => { worker.onmessage = (e) => resolve(e.data); worker.postMessage({ type: "mesh", chunk_x: 0, chunk_z: 0, version: 1, - chunks, + chunks: chunks.map(section_data), biome_colors: chunks.map(() => null), camera: [0, 0, 0], }); }); worker.terminate(); const light = (x: number, y: number, z: number) => { - const packed = meshed.light[at(x, y, z)]; + const section = meshed.light[y >> 4]; + const packed = typeof section === "number" ? section : section[section_index(x, y, z)]; return { block: packed >> 4, sky: packed & 15 }; }; - return { light, size: meshed.light.length, max_y: meshed.max_y }; + return { light, sections: meshed.light, max_y: meshed.max_y }; } Deno.test("each mesh comes with its chunk's block and sky light, packed a byte per block", async () => { - const { light, size } = await mesh_light(); - assertEquals(size, DEFAULT_SHAPE.volume); + const { light, sections } = await mesh_light(); + assertEquals(sections.length, DEFAULT_SHAPE.height / 16); + // the open sky well above the roof is the same everywhere + assertEquals(sections.at(-1), 15); assertEquals(light(12, 30, 8), { block: 0, sky: 15 }, "open sky"); assertEquals(light(12, 6, 8), { block: 13, sky: 15 }, "next to the light block"); // under the roof, sky light comes in sideways from the open side, a level less each block @@ -73,8 +79,8 @@ Deno.test("without sky light, only blocks light the world", async () => { }); Deno.test("a dimension that starts below 0 is lit the same, and meshed where its blocks are", async () => { - const { light, size, max_y } = await mesh_light({ min_y: -64, max_y: 320, sky_light: true }); - assertEquals(size, CHUNK_AREA * 384); + const { light, sections, max_y } = await mesh_light({ min_y: -64, max_y: 320, sky_light: true }); + assertEquals(sections.length, 384 / 16); assertEquals(light(12, 30, 8), { block: 0, sky: 15 }); assertEquals(light(4, 10, 8).sky, 11); assertEquals(max_y, -64 + 21, "the top of the roof"); diff --git a/tests/fluid_test.ts b/tests/fluid_test.ts index 67ff935..86bb5a4 100644 --- a/tests/fluid_test.ts +++ b/tests/fluid_test.ts @@ -17,7 +17,7 @@ import { DEFAULT_SHAPE } from "@/common/world_shape.ts"; import { get_state_value, set_state_value } from "@/common/utils.ts"; import { cell_index, corner_height, fluid_quads, type FluidCell } from "@/client/workers/fluid_mesh.ts"; import { TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; -import { test_game } from "./helpers.ts"; +import { section_data, test_game } from "./helpers.ts"; const OIL: BlockJson = { id: "oily:oil", @@ -194,7 +194,7 @@ async function mesh(blocks: [number, number, number, string, number?][]) { chunk_x: 0, chunk_z: 0, version: 1, - chunks, + chunks: chunks.map(section_data), biome_colors: chunks.map(() => null), camera: [0, 0, 0], }); diff --git a/tests/helpers.ts b/tests/helpers.ts index 08ed34d..231a084 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -11,7 +11,8 @@ import { start_game } from "@/server/game/load_mods.ts"; import { apply_config } from "@/server/load_mods.ts"; import { AIR_ID, PROTOCOL_VERSION } from "@/common/protocol.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts"; -import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; +import { CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; +import { Section, section_index, SECTION_VOLUME, type SectionData } from "@/common/section.ts"; import type { SavedChunk, SavedChunks, WorldSave } from "@/server/game/saves.ts"; import { FluidRules } from "@/common/fluids.ts"; import { BlockRules } from "@/common/block_rules.ts"; @@ -161,11 +162,18 @@ export function sent_block( const chunk_z = Math.floor(z / CHUNK_SIZE); const chunk = messages.findLast((m) => m.type === "level_chunk" && m.x === chunk_x && m.z === chunk_z); if (!chunk) return undefined; - const ly = y - join.shape.min_y; - const value = chunk.blocks[ly * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE)]; + const value = chunk.sections[(y - join.shape.min_y) >> 4].get(section_index(x, y, z)); return [join.blocks[value & ID_MASK], value >>> 16]; } +// a chunk's blocks in one array, y from the bottom of the world then z then x, as the sections a mesh request sends +export function section_data(blocks: Uint32Array): SectionData[] { + return Array.from( + { length: blocks.length / SECTION_VOLUME }, + (_, i) => Section.of(blocks.subarray(i * SECTION_VOLUME, (i + 1) * SECTION_VOLUME)).data, + ); +} + // a stone floor at y 99 from -radius to radius on x and z, high above the terrain, for players to stand on at y 100 export function stone_floor(game: GameServer, radius = 3) { for (let x = -radius; x <= radius; x++) { diff --git a/tests/mod_test.ts b/tests/mod_test.ts index 01a5db2..5b515d6 100644 --- a/tests/mod_test.ts +++ b/tests/mod_test.ts @@ -411,7 +411,12 @@ Deno.test({ ); const second = await run(); assert(second.length >= 49); - for (const chunk of second) assert(chunk.blocks[255 * 256] !== 0, `${chunk.x},${chunk.z} is from the save`); + for (const chunk of second) { + assert( + chunk.sections.at(-1)!.get(section_index(0, 15, 0)) !== 0, + `${chunk.x},${chunk.z} is from the save`, + ); + } } finally { for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true }); } diff --git a/tests/natural_spawn_test.ts b/tests/natural_spawn_test.ts index 6f670f5..869d532 100644 --- a/tests/natural_spawn_test.ts +++ b/tests/natural_spawn_test.ts @@ -90,7 +90,7 @@ Deno.test("the server's light is the same as what clients work out", async () => const chunks = []; for (let dz = -1; dz <= 1; dz++) { for (let dx = -1; dx <= 1; dx++) { - chunks.push(decode_level_chunk(world.level_chunk(CHUNK + dx, CHUNK + dz)).blocks); + chunks.push(decode_level_chunk(world.level_chunk(CHUNK + dx, CHUNK + dz)).sections); } } region.fill(chunks); diff --git a/tests/terrain_culling_test.ts b/tests/terrain_culling_test.ts index 56bd30c..dfc9ecd 100644 --- a/tests/terrain_culling_test.ts +++ b/tests/terrain_culling_test.ts @@ -10,6 +10,7 @@ import { Frustum } from "@/client/rendering/frustum.ts"; import { group_faces_camera } from "@/client/rendering/level_renderer.ts"; import { FACE_GROUPS, type LayerMesh, TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; import { decode_level_chunk } from "@/common/chunk_streaming.ts"; +import type { Section } from "@/common/section.ts"; import { test_game } from "./helpers.ts"; // the matrix the renderer makes for a camera, see update_camera in client/renderer/core.ts @@ -62,10 +63,10 @@ async function mesh_chunks(radius: number) { visuals: [], }); - const generated = new Map(); + const generated = new Map(); for (let x = -radius - 1; x <= radius + 1; x++) { for (let z = -radius - 1; z <= radius + 1; z++) { - generated.set(`${x},${z}`, decode_level_chunk(game.world.level_chunk(x, z)).blocks); + generated.set(`${x},${z}`, decode_level_chunk(game.world.level_chunk(x, z)).sections); } } const meshes = []; @@ -73,7 +74,9 @@ async function mesh_chunks(radius: number) { for (let z = -radius; z <= radius; z++) { const chunks = []; for (let dz = -1; dz <= 1; dz++) { - for (let dx = -1; dx <= 1; dx++) chunks.push(generated.get(`${x + dx},${z + dz}`)!.slice()); + for (let dx = -1; dx <= 1; dx++) { + chunks.push(generated.get(`${x + dx},${z + dz}`)!.map((section) => section.data)); + } } meshes.push( await ask({ diff --git a/tests/tint_test.ts b/tests/tint_test.ts index 1211620..345cf0a 100644 --- a/tests/tint_test.ts +++ b/tests/tint_test.ts @@ -9,7 +9,7 @@ import { DEFAULT_SHAPE } from "@/common/world_shape.ts"; import { generate_raw_chunk } from "@/common/generation.ts"; import { get_biome } from "@/common/worldgen/biomes.ts"; import { type LayerMesh, TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts"; -import { test_game } from "./helpers.ts"; +import { section_data, test_game } from "./helpers.ts"; type Colors = { grass: number; foliage: number; water?: number }; @@ -53,7 +53,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors | chunk_x: 0, chunk_z: 0, version: 1, - chunks, + chunks: chunks.map(section_data), biome_colors: colors, camera: [0, 0, 0], }); diff --git a/tests/visuals_test.ts b/tests/visuals_test.ts index 81732b8..71872e3 100644 --- a/tests/visuals_test.ts +++ b/tests/visuals_test.ts @@ -19,7 +19,7 @@ import { AssetManager } from "@/client/assets.ts"; import { load_client_mods } from "@/client/mods.ts"; import { load_and_check } from "@/tools/check_mods.ts"; import { pack_mod } from "@/tools/pack_mod.ts"; -import { copy_dir, test_game } from "./helpers.ts"; +import { copy_dir, section_data, test_game } from "./helpers.ts"; const HALF = { textures: { "0": "testmod:shaft" }, @@ -108,7 +108,7 @@ Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models chunk_x: 0, chunk_z: 0, version: 1, - chunks, + chunks: chunks.map(section_data), biome_colors: chunks.map(() => null), camera: [0, 0, 0], });