Meshing and lighting per section

This commit is contained in:
2026-11-07 11:41:21 -03:00
parent 71cbf901a5
commit b726ce9695
21 changed files with 736 additions and 544 deletions
+1 -1
View File
@@ -22,7 +22,7 @@ Deno.test("the lows are the fps of the slowest frames", () => {
});
Deno.test("a report reads back from what was copied", () => {
const scene = { draw_calls: 10, quads: 1000, chunks_in_view: 4, entities_in_view: 0 };
const scene = { draw_calls: 10, quads: 1000, sections_in_view: 4, entities_in_view: 0 };
const report: BenchmarkReport = {
version: 1,
date: "2026-01-01T00:00:00.000Z",
+104
View File
@@ -0,0 +1,104 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the client meshes a section at a time, and a block changing only meshes again the sections it can change the look
// or the light of, see ClientLevel's #block_changed
import { assertEquals } from "@std/assert";
import { ClientLevel } from "@/client/level/client_level.ts";
import { AssetManager } from "@/client/assets.ts";
import { Camera } from "@/client/camera.ts";
import type { ToChunkWorker } from "@/client/workers/chunk_messages.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { CHUNK_AREA } from "@/common/constants.ts";
import { ChunkColumn } from "@/common/section.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { test_game } from "./helpers.ts";
const GROUND_TOP = 63;
const ROOF = 200;
// a level of 5x5 chunks of stone up to GROUND_TOP, with a stone roof at ROOF over chunk 0, 0, all meshed. what it asks
// its chunk workers is kept in requests instead of being sent
async function meshed_level() {
await test_game("mods");
AssetManager.instance.assets["cubi:textures"] = { width: 16, height: 16 };
AssetManager.instance.assets["cubi:textures_info"] = {};
const requests: Extract<ToChunkWorker, { type: "mesh" }>[] = [];
const real = globalThis.Worker;
globalThis.Worker = class {
postMessage(message: ToChunkWorker) {
if (message.type === "mesh") requests.push(message);
}
terminate() {}
} as unknown as typeof Worker;
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
let level: ClientLevel;
try {
level = new ClientLevel(Array.from(blocks, (block) => block?.id), DEFAULT_SHAPE, 2);
} finally {
globalThis.Worker = real;
}
const stone = EverythingRegistry.get_id("blocks", "bworld:stone")!;
for (let x = -2; x <= 2; x++) {
for (let z = -2; z <= 2; z++) {
const flat = new Uint32Array(DEFAULT_SHAPE.volume).fill(stone, 0, (GROUND_TOP + 1) * CHUNK_AREA);
if (x === 0 && z === 0) flat.fill(stone, ROOF * CHUNK_AREA, (ROOF + 1) * CHUNK_AREA);
const biomes = new Array(CHUNK_AREA).fill("bworld:plains");
level.set_chunk(ChunkColumn.from_flat(x, z, DEFAULT_SHAPE, flat, biomes));
}
}
const camera = new Camera();
level.request_meshes(camera);
requests.length = 0;
// the sections asked for since the last call, as "chunk x,chunk z: indexes"
const remeshed = () => {
level.request_meshes(camera);
const asked = requests.map(({ chunk_x, chunk_z, sections }) =>
`${chunk_x},${chunk_z}: ${sections.map(({ index }) => index).sort((a, b) => a - b).join(" ")}`
).sort();
requests.length = 0;
return asked;
};
return { level, requests, remeshed };
}
Deno.test("a block that doesn't change the light remeshes its section, and the ones whose border it's on", async () => {
const { level, remeshed } = await meshed_level();
level.add_block({ id: "bworld:cobblestone", x: 8, y: 40, z: 8 });
assertEquals(remeshed(), ["0,0: 2"]);
// at x 0, z 15 and y 32 of its chunk, so next to the chunks to -x and +z and the section below
level.add_block({ id: "bworld:cobblestone", x: 0, y: 32, z: 15 });
assertEquals(remeshed(), ["-1,0: 1 2", "-1,1: 1 2", "0,0: 1 2", "0,1: 1 2"]);
});
Deno.test("a request sends the sections around the ones it's for, and their columns' sky heights", async () => {
const { level, requests } = await meshed_level();
level.add_block({ id: "bworld:cobblestone", x: 8, y: 40, z: 8 });
level.request_meshes(new Camera());
const [request] = requests;
assertEquals(request.first, 1);
assertEquals(request.chunks.map((chunk) => chunk?.length), new Array(9).fill(3));
assertEquals(request.sky[4]![8 * 16 + 8], ROOF + 1);
assertEquals(request.sky[0]![0], GROUND_TOP + 1);
});
Deno.test("opening a hole to the sky remeshes the columns around it from the old sky height to the new", async () => {
const { level, remeshed } = await meshed_level();
level.break_block(8, ROOF, 8);
// the light reaches 15 blocks past where it changes, and a section's faces are lit from the block past them
const from = (GROUND_TOP + 1 - 16) >> 4;
const to = (ROOF + 1 + 16) >> 4;
const sections = Array.from({ length: to - from + 1 }, (_, i) => from + i).join(" ");
const chunks = [];
for (let x = -1; x <= 1; x++) {
for (let z = -1; z <= 1; z++) chunks.push(`${x},${z}: ${sections}`);
}
assertEquals(remeshed(), chunks.sort());
// a light block under the roof changes the light around it, in the sections next to its own
level.add_block({ id: "bworld:light", x: 4, y: 100, z: 4 });
assertEquals(remeshed(), chunks.map((chunk) => chunk.replace(sections, "5 6 7")));
});
+33 -25
View File
@@ -7,8 +7,7 @@ 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 { section_data, test_game } from "./helpers.ts";
import type { SectionLight } from "@/client/workers/chunk_messages.ts";
import { chunk_worker, mesh_column, test_game } from "./helpers.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
@@ -18,17 +17,7 @@ async function mesh_light(shape: WorldShapeJson = DEFAULT_SHAPE) {
await test_game("mods");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const nid = (id: string) => blocks.findIndex((b) => b?.id === id);
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
worker.postMessage({
type: "init",
shape,
blocks_registry: JSON.parse(JSON.stringify(blocks)),
models: {},
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [],
});
const worker = chunk_worker(shape);
const chunk = new Uint32Array(volume);
const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
for (let x = 0; x < 8; x++) {
@@ -38,18 +27,7 @@ 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: 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.map(section_data),
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
});
});
const meshed = await mesh_column(worker, shape, chunks);
worker.terminate();
const light = (x: number, y: number, z: number) => {
const section = meshed.light[y >> 4];
@@ -85,3 +63,33 @@ Deno.test("a dimension that starts below 0 is lit the same, and meshed where its
assertEquals(light(4, 10, 8).sky, 11);
assertEquals(max_y, -64 + 21, "the top of the roof");
});
Deno.test("a section meshed on its own is lit and drawn the same as when its whole column is", async () => {
await test_game("mods");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const nid = (id: string) => blocks.findIndex((b) => b?.id === id);
const at = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x;
// ground up to 40 everywhere, and in the middle chunk a roof far above it over x 0-7, which shades sections well
// below it, and a light just under a section's top, which lights the one above
const ground = () => new Uint32Array(DEFAULT_SHAPE.volume).fill(nid("bworld:stone"), 0, at(0, 41, 0));
const chunks = Array.from({ length: 9 }, ground);
for (let x = 0; x < 8; x++) {
for (let z = 0; z < CHUNK_SIZE; z++) chunks[4][at(x, 200, z)] = nid("bworld:stone");
}
chunks[4][at(12, 47, 8)] = nid("bworld:light");
chunks[4][at(3, 41, 3)] = nid("bworld:glass");
const worker = chunk_worker(DEFAULT_SHAPE);
const whole = await mesh_column(worker, DEFAULT_SHAPE, chunks);
for (const [index, expected] of whole.sections.entries()) {
const [alone] = (await mesh_column(worker, DEFAULT_SHAPE, chunks, { sections: [index] })).sections;
assertEquals(alone.light, expected.light, `section ${index}'s light`);
for (const layer of ["solid", "cutout", "translucent"] as const) {
assertEquals(alone[layer].vertices, expected[layer].vertices, `section ${index}'s ${layer} quads`);
}
}
worker.terminate();
// the roof's shade and the light are in the sections looked at
assertEquals(typeof whole.light[2], "object");
assertEquals(typeof whole.light[3], "object");
});
+3 -25
View File
@@ -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 { section_data, test_game } from "./helpers.ts";
import { chunk_worker, mesh_column, test_game } from "./helpers.ts";
const OIL: BlockJson = {
id: "oily:oil",
@@ -170,35 +170,13 @@ async function mesh(blocks: [number, number, number, string, number?][]) {
const registry = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const ids: Record<string, number> = {};
registry.forEach((b, nid) => ids[b.id] = nid);
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
worker.postMessage({
type: "init",
shape: DEFAULT_SHAPE,
// with the registry's gaps, like the client sends it
blocks_registry: registry.map((block) => JSON.parse(JSON.stringify(block))),
models: {},
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [],
});
const worker = chunk_worker(DEFAULT_SHAPE);
const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume));
for (const [x, y, z, id, level] of blocks) {
const chunk = x < 0 ? chunks[3] : chunks[4];
chunk[y * CHUNK_AREA + z * CHUNK_SIZE + ((x + CHUNK_SIZE) % CHUNK_SIZE)] = ids[id] | ((level ?? 0) << 16);
}
// deno-lint-ignore no-explicit-any
const meshed = await new Promise<any>((resolve) => {
worker.onmessage = (e) => resolve(e.data);
worker.postMessage({
type: "mesh",
chunk_x: 0,
chunk_z: 0,
version: 1,
chunks: chunks.map(section_data),
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
});
});
const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks);
worker.terminate();
const f32 = new Float32Array(meshed.translucent.vertices.buffer);
const quads: number[][][] = [];
+99 -8
View File
@@ -2,7 +2,12 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
import { resolve, toFileUrl } from "@std/path";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import {
type BlockRegistry,
EverythingRegistry,
light_tables,
type RenderLayer,
} from "@/common/everything_registry.ts";
import { load_and_check, load_order } from "@/tools/check_mods.ts";
import { mod_data } from "@/common/mod_check.ts";
import type { ServerModSource } from "@/server/game/load_mods.ts";
@@ -11,8 +16,11 @@ 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_SIZE, ID_MASK } from "@/common/constants.ts";
import { Section, section_index, SECTION_VOLUME, type SectionData } from "@/common/section.ts";
import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts";
import { ChunkColumn, column_heights, section_index, SECTION_VOLUME } from "@/common/section.ts";
import { WorldShape, type WorldShapeJson } from "@/common/world_shape.ts";
import type { LayerMesh, SectionMesh, ToChunkWorker } from "@/client/workers/chunk_messages.ts";
import type { ModelJson } from "@/common/block_models.ts";
import type { SavedChunk, SavedChunks, WorldSave } from "@/server/game/saves.ts";
import { FluidRules } from "@/common/fluids.ts";
import { BlockRules } from "@/common/block_rules.ts";
@@ -166,12 +174,95 @@ export function sent_block(
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 chunk worker set up the way the client sets one up, with the loaded mods' blocks. models are the mods' block models
// and visuals the blocks with them, see ToChunkWorker's init
export function chunk_worker(
shape: WorldShapeJson,
models: Record<string, ModelJson> = {},
visuals: [number, boolean][] = [],
): Worker {
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
worker.postMessage({
type: "init",
shape,
// with the registry's gaps, like the client sends it
blocks_registry: EverythingRegistry.get_registry<BlockRegistry>("blocks").map((block) =>
JSON.parse(JSON.stringify(block))
),
models,
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals,
});
return worker;
}
// the sections of the middle one of 3x3 chunks meshed by a chunk worker, asked for the way the client asks: all of
// them, or the indexes in options.sections. the chunks are each block's value in one array, y from the bottom of the
// world then z then x, null where there's none. what comes back is each section's mesh, and all of them put together:
// their layers' quads one after another, their light, their visuals with indexes in the whole chunk (like an array's)
// and the bounds of them all
export async function mesh_column(
worker: Worker,
shape: WorldShapeJson,
chunks: (Uint32Array | null)[],
options: {
chunk_x?: number;
chunk_z?: number;
biome_colors?: (Uint32Array | null)[];
camera?: number[];
sections?: number[];
} = {},
) {
const { opacity } = light_tables(EverythingRegistry.get_registry<BlockRegistry>("blocks"));
const columns = chunks.map((blocks) =>
blocks && ChunkColumn.from_flat(0, 0, new WorldShape(shape), blocks, new Array(CHUNK_AREA).fill(""))
);
const count = columns[4]!.sections.length;
const indexes = options.sections ?? Array.from({ length: count }, (_, index) => index);
// with the section below and above them, like ClientLevel.request_meshes
const first = Math.max(0, Math.min(...indexes) - 1);
const end = Math.min(count, Math.max(...indexes) + 2);
const message: ToChunkWorker = {
type: "mesh",
chunk_x: options.chunk_x ?? 0,
chunk_z: options.chunk_z ?? 0,
sections: indexes.map((index) => ({ index, version: 1 })),
first,
chunks: columns.map((column) => column?.sections.slice(first, end).map((section) => section.data) ?? null),
sky: columns.map((column) => column && column_heights(column, opacity).slice(CHUNK_AREA)),
biome_colors: options.biome_colors ?? chunks.map(() => null),
camera: options.camera ?? [0, 0, 0],
};
const sections = await new Promise<SectionMesh[]>((resolve) => {
worker.onmessage = (e) => resolve(e.data.sections);
worker.postMessage(message);
});
const layer = (name: RenderLayer): LayerMesh => {
const meshes = sections.map((section) => section[name]);
const vertices = new Uint8Array(meshes.reduce((sum, mesh) => sum + mesh.vertices.length, 0));
let at = 0;
for (const mesh of meshes) {
vertices.set(mesh.vertices, at);
at += mesh.vertices.length;
}
return { vertices, quad_count: meshes.reduce((sum, mesh) => sum + mesh.quad_count, 0) };
};
return {
sections,
solid: layer("solid"),
cutout: layer("cutout"),
translucent: layer("translucent"),
light: sections.map((section) => section.light),
visuals: Uint32Array.from(
sections.flatMap(({ index, visuals }) =>
[...visuals].map((value, i) => i % 2 === 0 ? index * SECTION_VOLUME + value : value)
),
),
min_y: Math.min(...sections.map((section) => section.min_y)),
max_y: Math.max(...sections.map((section) => section.max_y)),
};
}
// 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
+2 -2
View File
@@ -6,7 +6,7 @@ import { assert, assertEquals, assertRejects } from "@std/assert";
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
import type { FluidJson } from "@/common/mod_data.ts";
import type { ClientContext, Instances, Visual, VisualBlock } from "@/common/mod_api/client.ts";
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { section_index } from "@/common/section.ts";
import { block_value, display_name } from "@/common/utils.ts";
import { sell_value } from "@/common/inventory.ts";
import { block_visuals, Visuals } from "@/client/rendering/visuals.ts";
@@ -295,7 +295,7 @@ async function drawn_juicer() {
block_visuals.set(juicer, { mod: "bworld", replaces_model: false, create: made.get("bworld:juicer")! });
const data: Record<string, unknown> = {};
const visuals = new Visuals({ get_block_data: () => data, get_light: () => 0 });
visuals.meshed(0, 0, 0, Uint32Array.of(100 * CHUNK_AREA + 1 * CHUNK_SIZE + 1, block_value(juicer, 0)));
visuals.meshed(0, 0, 96, Uint32Array.of(section_index(1, 100, 1), block_value(juicer, 0)));
const set = (field: string, value: unknown) => {
data[field] = value;
visuals.data_changed(1, 100, 1);
+11 -16
View File
@@ -4,14 +4,10 @@
// monsters spawning on their own in the dark near players, like undergarden's rotwalkers, see natural_spawner.ts and
// mods/undergarden/worldgen/spawns.json
import { assert, assertEquals } from "@std/assert";
import { CHUNK_SIZE } from "@/common/constants.ts";
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { decode_level_chunk } from "@/common/chunk_streaming.ts";
import {
block_light_emission,
block_light_opacity,
BlockRegistry,
EverythingRegistry,
} from "@/common/everything_registry.ts";
import { BlockRegistry, EverythingRegistry, light_tables } from "@/common/everything_registry.ts";
import { ChunkColumn, column_heights } from "@/common/section.ts";
import { LightRegion, REGION_LAYER, REGION_SIZE, REGION_VOID } from "@/client/workers/lighting.ts";
import { create_entity } from "@/server/game/entity/entity_types.ts";
import { Mob } from "@/server/game/entity/mob.ts";
@@ -78,22 +74,21 @@ Deno.test("the server's light is the same as what clients work out", async () =>
world.set_block(x0 + 3, FLOOR + 1, x0 + 3, "bworld:light");
world.set_block(x0 + 12, ROOF, x0 + 12, "cubi:air");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const opacity = new Uint8Array(REGION_VOID + 1);
const emission = new Uint8Array(REGION_VOID + 1);
blocks.forEach((block, nid) => {
opacity[nid] = block_light_opacity(block);
emission[nid] = block_light_emission(block);
});
// the 3x3 chunks lit whole, like the client lights sections
const { opacity, emission } = light_tables(EverythingRegistry.get_registry<BlockRegistry>("blocks"));
opacity[REGION_VOID] = 15;
const region = new LightRegion(world.shape);
const chunks = [];
const sky = [];
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)).sections);
const { sections, biomes } = decode_level_chunk(world.level_chunk(CHUNK + dx, CHUNK + dz));
chunks.push(sections);
const column = new ChunkColumn(CHUNK + dx, CHUNK + dz, world.shape, sections, biomes);
sky.push(column_heights(column, opacity).slice(CHUNK_AREA));
}
}
region.fill(chunks);
region.fill(chunks, sky, world.shape.min_y);
region.compute({ opacity, emission });
const check = (x: number, y: number, z: number) => {
+16 -48
View File
@@ -5,13 +5,17 @@
// would have shown
import { assert, assertEquals } from "@std/assert";
import { mat4 } from "gl-matrix";
import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
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 {
FACE_GROUPS,
type LayerMesh,
type SectionMesh,
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";
import { to_flat } from "@/common/section.ts";
import { chunk_worker, mesh_column, test_game } from "./helpers.ts";
// the matrix the renderer makes for a camera, see update_camera in client/renderer/core.ts
function camera_matrix(x: number, y: number, z: number, yaw: number, pitch: number) {
@@ -34,61 +38,25 @@ Deno.test("the frustum keeps what's in front of the camera and drops what's behi
assert(!frustum.intersects_box(-8, 60, -1100, 8, 80, -1090), "past the far plane");
});
// real chunks as the server sends them, meshed the way the client does it
// real chunks as the server sends them, meshed the way the client does it. each section's mesh
async function mesh_chunks(radius: number) {
const { game } = await test_game("mods", undefined, "culling-seed");
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
// deno-lint-ignore no-explicit-any
const replies = new Map<string, (message: any) => void>();
worker.onmessage = (e) => {
const key = `${e.data.type} ${e.data.chunk_x} ${e.data.chunk_z}`;
replies.get(key)?.(e.data);
replies.delete(key);
};
// deno-lint-ignore no-explicit-any
const ask = (message: any, reply: string) =>
// deno-lint-ignore no-explicit-any
new Promise<any>((resolve) => {
replies.set(`${reply} ${message.chunk_x} ${message.chunk_z}`, resolve);
worker.postMessage(message);
});
worker.postMessage({
type: "init",
shape: game.world.shape,
blocks_registry: JSON.parse(JSON.stringify(blocks)),
models: {},
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [],
});
const generated = new Map<string, Section[]>();
const worker = chunk_worker(game.world.shape);
const generated = new Map<string, Uint32Array>();
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)).sections);
generated.set(`${x},${z}`, to_flat(decode_level_chunk(game.world.level_chunk(x, z)).sections));
}
}
const meshes = [];
const meshes: SectionMesh[] = [];
for (let x = -radius; x <= radius; x++) {
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}`)!.map((section) => section.data));
}
for (let dx = -1; dx <= 1; dx++) chunks.push(generated.get(`${x + dx},${z + dz}`)!);
}
meshes.push(
await ask({
type: "mesh",
chunk_x: x,
chunk_z: z,
version: 1,
chunks,
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
}, "meshed"),
);
const { sections } = await mesh_column(worker, game.world.shape, chunks, { chunk_x: x, chunk_z: z });
meshes.push(...sections);
}
}
worker.terminate();
+4 -24
View File
@@ -8,8 +8,8 @@ import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
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 { section_data, test_game } from "./helpers.ts";
import { TERRAIN_VERTEX_BYTES } from "@/client/workers/chunk_messages.ts";
import { chunk_worker, mesh_column, test_game } from "./helpers.ts";
type Colors = { grass: number; foliage: number; water?: number };
@@ -20,16 +20,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
const blocks = EverythingRegistry.get_registry<BlockRegistry>("blocks");
const block_ids: Record<string, number> = {};
blocks.forEach((b, nid) => block_ids[b.id] = nid);
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
worker.postMessage({
type: "init",
shape: DEFAULT_SHAPE,
blocks_registry: JSON.parse(JSON.stringify(blocks)),
models: {},
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [],
});
const worker = chunk_worker(DEFAULT_SHAPE);
const chunk = new Uint32Array(DEFAULT_SHAPE.volume);
chunk[10 * CHUNK_AREA + 8 * CHUNK_SIZE + x] = block_ids[id];
@@ -46,18 +37,7 @@ async function mesh_block(id: string, x: number, middle: Colors, west: Colors |
colors[4] = biome_colors(middle);
if (west) colors[3] = biome_colors(west);
const meshed = await new Promise<{ solid: LayerMesh; cutout: LayerMesh; translucent: LayerMesh }>((resolve) => {
worker.onmessage = (e) => resolve(e.data);
worker.postMessage({
type: "mesh",
chunk_x: 0,
chunk_z: 0,
version: 1,
chunks: chunks.map(section_data),
biome_colors: colors,
camera: [0, 0, 0],
});
});
const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks, { biome_colors: colors });
worker.terminate();
const top: number[][] = [];
+25 -41
View File
@@ -5,7 +5,7 @@
// draws their instances, placed and turned by the time
import { assert, assertEquals, assertRejects, assertThrows } from "@std/assert";
import { mat4 } from "gl-matrix";
import { BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import { CHUNK_AREA, CHUNK_SIZE } from "@/common/constants.ts";
import { DEFAULT_SHAPE } from "@/common/world_shape.ts";
import { block_value } from "@/common/utils.ts";
@@ -19,7 +19,8 @@ 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, section_data, test_game } from "./helpers.ts";
import { chunk_worker, copy_dir, mesh_column, test_game } from "./helpers.ts";
import { section_index } from "@/common/section.ts";
const HALF = {
textures: { "0": "testmod:shaft" },
@@ -85,34 +86,16 @@ const index_of = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK
Deno.test("the chunk mesher lists the blocks with visuals, and leaves out models they replace", async () => {
const { nid, value } = await registries();
const worker = new Worker(new URL("../client/workers/chunk_worker.ts", import.meta.url).href, { type: "module" });
worker.postMessage({
type: "init",
shape: DEFAULT_SHAPE,
blocks_registry: JSON.parse(JSON.stringify(EverythingRegistry.get_registry<BlockRegistry>("blocks"))),
models: Object.fromEntries(EverythingRegistry.entries("models")),
textures_info: { "cubi:missing": { x: 0, y: 0, width: 16, height: 16 } },
image: { width: 1024, height: 1024 },
visuals: [[nid("bworld:stone"), true], [nid("bworld:cobblestone"), false]],
});
const worker = chunk_worker(DEFAULT_SHAPE, Object.fromEntries(EverythingRegistry.entries("models")), [
[nid("bworld:stone"), true],
[nid("bworld:cobblestone"), false],
]);
const chunks = Array.from({ length: 9 }, () => new Uint32Array(DEFAULT_SHAPE.volume));
const middle = chunks[4];
middle[index_of(1, 64, 1)] = value("bworld:stone");
middle[index_of(4, 64, 1)] = value("bworld:cobblestone");
middle[index_of(7, 64, 1)] = value("bworld:dirt");
// deno-lint-ignore no-explicit-any
const meshed = await new Promise<any>((resolve) => {
worker.onmessage = (e) => resolve(e.data);
worker.postMessage({
type: "mesh",
chunk_x: 0,
chunk_z: 0,
version: 1,
chunks: chunks.map(section_data),
biome_colors: chunks.map(() => null),
camera: [0, 0, 0],
});
});
const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks);
worker.terminate();
assertEquals([...meshed.visuals], [
@@ -155,14 +138,14 @@ Deno.test("a visual is made with its block, told when its client data changes, a
};
},
});
const shaft = (axis: number) => Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", axis));
const shaft = (axis: number) => Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", axis));
visuals.meshed(0, 0, 0, shaft(1));
visuals.meshed(0, 0, 64, shaft(1));
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1"]);
// the half model has one face, the block's own model is a cube
assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]);
// meshed again for something else, it stays
visuals.meshed(0, 0, 0, shaft(1));
visuals.meshed(0, 0, 64, shaft(1));
assertEquals(log.splice(0), []);
data.speed = 32;
@@ -177,15 +160,15 @@ Deno.test("a visual is made with its block, told when its client data changes, a
assertEquals(log.splice(0), ["frame 10.5"]);
// its states changing makes it again
visuals.meshed(0, 0, 0, shaft(2));
visuals.meshed(0, 0, 64, shaft(2));
assertEquals(log.splice(0), ["delete 1 64 1", "create testmod:shaft 1 64 1 axis 2"]);
assertEquals(drawn(visuals), ["1 quads x1", "6 quads x1"]);
// and it goes with the block, or with the chunk, and so do its instances
visuals.meshed(0, 0, 0, new Uint32Array());
visuals.meshed(0, 0, 64, new Uint32Array());
assertEquals(log.splice(0), ["delete 1 64 1"]);
assert(!visuals.has(0, 0));
assertEquals(drawn(visuals), []);
visuals.meshed(0, 0, 0, shaft(1));
visuals.meshed(0, 0, 64, shaft(1));
visuals.unload(0, 0);
assertEquals(log.splice(0), ["create testmod:shaft 1 64 1 axis 1", "delete 1 64 1"]);
assertEquals(drawn(visuals), []);
@@ -216,13 +199,13 @@ Deno.test("a visual that throws is logged and left out, and not made again until
const console_error = console.error;
console.error = (...args) => errors.push(args);
try {
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1)));
visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 1)));
visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 1)));
assertEquals([made, errors.length], [1, 1]);
assertEquals(drawn(visuals), []);
// an on_frame that throws isn't called again
visuals.meshed(0, 0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 2)));
visuals.meshed(0, 0, 64, Uint32Array.of(section_index(1, 64, 1), value("testmod:shaft", 2)));
for (let frame = 0; frame < 3; frame++) visuals.frame([{ x: 0, z: 0 }], frame);
assertEquals([made, errors.length], [3, 2]);
} finally {
@@ -248,9 +231,9 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl
},
});
const shafts = Uint32Array.of(
...[1, 2, 3].flatMap((x) => [index_of(x, 64, 1), value("testmod:shaft")]),
...[1, 2, 3].flatMap((x) => [section_index(x, 64, 1), value("testmod:shaft")]),
);
visuals.meshed(0, 0, 0, shafts);
visuals.meshed(0, 0, 64, shafts);
const group = [...visuals.groups()].find((group) => group.instances.length > 0)!;
const at = (i: number) => [...group.data.subarray(i * INSTANCE_FLOATS, (i + 1) * INSTANCE_FLOATS)];
const sent = () => {
@@ -275,13 +258,14 @@ Deno.test("an instance's placement, spin and light are kept for the gpu, and onl
// a new light comes with the chunk's mesh
light = 0x0f;
visuals.meshed(0, 0, 0, shafts);
visuals.meshed(0, 0, 64, shafts);
assertEquals([at(0)[21], at(0)[22]], [0.5 / 16, 15.5 / 16]);
assertEquals(sent(), [0, 1]);
block_visuals.clear();
});
// a visual on one shaft, at 1 64 1, that makes what make does
// a visual on one shaft, at 1 64 1, that makes what make does. mesh meshes the section from y 64 with blocks at their
// indexes in it
function one_visual(nid: (id: string) => number, value: (id: string) => number, make: (instances: Instances) => void) {
const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => 0 });
block_visuals.clear();
@@ -293,8 +277,8 @@ function one_visual(nid: (id: string) => number, value: (id: string) => number,
return {};
},
});
const mesh = (blocks: number[]) => visuals.meshed(0, 0, 0, Uint32Array.from(blocks));
mesh([index_of(1, 64, 1), value("testmod:shaft")]);
const mesh = (blocks: number[]) => visuals.meshed(0, 0, 64, Uint32Array.from(blocks));
mesh([section_index(1, 64, 1), value("testmod:shaft")]);
return { visuals, mesh };
}
@@ -378,7 +362,7 @@ Deno.test("a fluid's box is its texture cut to fit and tinted in its color, a mo
box!.delete();
assertEquals(boxes(), []);
mesh([]);
mesh([index_of(1, 64, 1), value("testmod:shaft")]);
mesh([section_index(1, 64, 1), value("testmod:shaft")]);
assertEquals(boxes().length, 1);
visuals.unload(0, 0);
assertEquals(boxes(), []);