// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // blocks drawn with code: the chunk mesher finds them, their visuals come and go with them and their chunks, and the gpu // draws their instances, placed and turned by the time import { assert, assertEquals, assertRejects } from "@std/assert"; import { mat4 } from "gl-matrix"; import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts"; import { CHUNK_AREA, CHUNK_HEIGHT, CHUNK_SIZE } from "$/common/constants.ts"; import { block_value } from "$/common/utils.ts"; import type { ModListing } from "$/common/mod_loader.ts"; import { read_bmod } from "$/common/bmod.ts"; import type { RotatingInstance, Visual } from "$/common/mod_api/client.ts"; import { block_visuals, InstanceGroup, pack_model, Visuals } from "$/client/rendering/visuals.ts"; import { INSTANCE_FLOATS, INSTANCED_BUFFERS, terrain_shader_src, type Texture } from "$/client/renderer/mod.ts"; import type { BakedQuad } from "$/common/block_models.ts"; 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"; const HALF = { textures: { "0": "testmod:shaft" }, elements: [{ from: [6, 0, 6], to: [10, 8, 10], faces: { north: { texture: "#0" } } }], }; // testmod: a shaft with an axis state and a model of half of one, and maybe a client script function write_testmod(dir: string, client_script?: string) { const mod = `${dir}/testmod`; for (const folder of ["blocks", "models", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true }); const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json)); write("manifest.json", { format_version: 1, id: "testmod", name: "Test", version: "1.0.0", ...(client_script && { scripts: { client: "scripts/client.ts" } }), }); write("blocks/shaft.json", { format_version: 1, block: { id: "testmod:shaft", textures: "testmod:shaft", render_layer: "cutout", states: [{ name: "axis", bits: 2, default: 1 }], mining: { toughness: 1 }, }, }); write("models/half.json", { format_version: 1, model: { id: "testmod:half", ...HALF } }); if (client_script) Deno.writeTextFileSync(`${mod}/scripts/client.ts`, client_script); } // a game's registries with mods/bworld and testmod async function registries() { const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" }); copy_dir("mods/bworld", `${dir}/bworld`); write_testmod(dir); await test_game(dir); Deno.removeSync(dir, { recursive: true }); const nid = (id: string) => EverythingRegistry.get_id("blocks", id)!; const value = (id: string, state = 0) => block_value(nid(id), state); return { nid, value }; } const index_of = (x: number, y: number, z: number) => y * CHUNK_AREA + z * CHUNK_SIZE + x; 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", blocks_registry: JSON.parse(JSON.stringify(EverythingRegistry.get_registry("blocks"))), models: Object.fromEntries(EverythingRegistry.entries("models")), textures_info: { "engine:missing": { x: 0, y: 0, width: 16, height: 16 } }, image: { width: 1024, height: 1024 }, visuals: [[nid("bworld:stone"), true], [nid("bworld:cobblestone"), false]], }); const chunks = Array.from({ length: 9 }, () => new Uint32Array(CHUNK_AREA * CHUNK_HEIGHT)); 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((resolve) => { worker.onmessage = (e) => resolve(e.data); worker.postMessage({ type: "mesh", chunk_x: 0, chunk_z: 0, version: 1, chunks, biome_colors: chunks.map(() => null), camera: [0, 0, 0], }); }); worker.terminate(); assertEquals([...meshed.visuals], [ index_of(1, 64, 1), value("bworld:stone"), index_of(4, 64, 1), value("bworld:cobblestone"), ]); // the cobblestone and the dirt, not the stone assertEquals(meshed.solid.quad_count, 12); // a visual can reach past its block, so the chunk is in view when that might be assert(meshed.min_y <= 63 && meshed.max_y >= 66, `${meshed.min_y} to ${meshed.max_y}`); }); // what the gpu would draw: each model's quad count and how many of it, for the models drawn at all const drawn = (visuals: Visuals) => [...visuals.groups()].filter((group) => group.instances.length > 0) .map((group) => `${group.quads.length} quads x${group.instances.length}`); Deno.test("a visual is made with its block, told when its client data changes, and goes with it", async () => { const { nid, value } = await registries(); const log: string[] = []; const data: Record = { speed: 16 }; const visuals = new Visuals({ get_block_data: (x, y, z) => x === 1 && y === 64 && z === 1 ? data : undefined, get_light: () => 0, }); block_visuals.clear(); block_visuals.set(nid("testmod:shaft"), { mod: "testmod", replaces_model: true, create(block, instances): Visual { log.push(`create ${block.id} ${block.x} ${block.y} ${block.z} axis ${block.states.axis}`); instances.rotating().set_rotation("y", block.get_client_data("speed")!); instances.transformed("testmod:half"); return { update: () => log.push(`update ${block.get_client_data("speed")}`), on_frame: (time) => log.push(`frame ${time}`), on_delete: () => log.push(`delete ${block.x} ${block.y} ${block.z}`), }; }, }); const shaft = (axis: number) => Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", axis)); visuals.meshed(0, 0, 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, shaft(1)); assertEquals(log.splice(0), []); data.speed = 32; visuals.data_changed(1, 64, 1); visuals.data_changed(2, 64, 1); assertEquals(log.splice(0), ["update 32"]); // only visuals in chunks in view get on_frame visuals.frame([{ x: 1, z: 0 }], 10.5); assertEquals(log.splice(0), []); visuals.frame([{ x: 0, z: 0 }], 10.5); assertEquals(log.splice(0), ["frame 10.5"]); // its states changing makes it again visuals.meshed(0, 0, 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, new Uint32Array()); assertEquals(log.splice(0), ["delete 1 64 1"]); assert(!visuals.has(0, 0)); assertEquals(drawn(visuals), []); visuals.meshed(0, 0, 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), []); block_visuals.clear(); }); Deno.test("a visual that throws is logged and left out, and not made again until its block changes", async () => { const { nid, value } = await registries(); let made = 0; block_visuals.clear(); block_visuals.set(nid("testmod:shaft"), { mod: "testmod", replaces_model: false, create(block, instances) { made += 1; instances.rotating(); if (block.states.axis === 1) throw new Error("broken"); return { on_frame() { made += 1; throw new Error("broken every frame"); }, }; }, }); const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => 0 }); const errors: unknown[] = []; const console_error = console.error; console.error = (...args) => errors.push(args); try { visuals.meshed(0, 0, Uint32Array.of(index_of(1, 64, 1), value("testmod:shaft", 1))); visuals.meshed(0, 0, Uint32Array.of(index_of(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, Uint32Array.of(index_of(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 { console.error = console_error; block_visuals.clear(); } }); Deno.test("an instance's placement, spin and light are kept for the gpu, and only what changed is sent again", async () => { const { nid, value } = await registries(); let light = 0xf0; const visuals = new Visuals({ get_block_data: () => undefined, get_light: () => light }); const made: RotatingInstance[] = []; block_visuals.clear(); block_visuals.set(nid("testmod:shaft"), { mod: "testmod", replaces_model: true, create(block, instances) { const instance = instances.rotating("testmod:half"); instance.set_rotation("x", block.x * 10, 22.5); made.push(instance); return {}; }, }); const shafts = Uint32Array.of( ...[1, 2, 3].flatMap((x) => [index_of(x, 64, 1), value("testmod:shaft")]), ); visuals.meshed(0, 0, 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 = () => { const dirty = [group.dirty_from, group.dirty_to]; group.dirty_from = Infinity; group.dirty_to = -1; return dirty; }; // at its block's corner, spinning around x at its rpm from its offset, lit by its block's light: block light 15 // and sky light 0, as lightmap coordinates assertEquals(at(1), [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 2, 64, 1, 1, 1, 0, 0, 20, 22.5, 15.5 / 16, 0.5 / 16, 0]); assertEquals(sent(), [0, 2]); made[2].set_rotation("y", 5); assertEquals(sent(), [2, 2]); // the last one moves into a deleted one's place, so the ones drawn are always the first ones made[0].delete(); assertEquals(group.instances.length, 2); assertEquals(at(0)[12], 3); assertEquals(sent(), [0, 0]); // a new light comes with the chunk's mesh light = 0x0f; visuals.meshed(0, 0, shafts); assertEquals([at(0)[21], at(0)[22]], [0.5 / 16, 15.5 / 16]); assertEquals(sent(), [0, 1]); block_visuals.clear(); }); const adapter = await navigator.gpu?.requestAdapter().catch(() => null) ?? null; Deno.test({ name: "the gpu turns a rotating instance by the time, rpm and offset, and shades it by the way it faces", ignore: !adapter, async fn() { const device = await adapter!.requestDevice(); const module = device.createShaderModule({ code: terrain_shader_src }); const pipeline = device.createRenderPipeline({ layout: "auto", vertex: { module, entryPoint: "vs_instance", buffers: INSTANCED_BUFFERS }, fragment: { module, entryPoint: "fs_cutout_discard", targets: [{ format: "rgba8unorm" }] }, primitive: { topology: "triangle-list", cullMode: "back", frontFace: "ccw" }, }); const buffer = (usage: number, data: Uint8Array | Uint32Array | Float32Array) => { const made = device.createBuffer({ size: data.byteLength, usage: usage | GPUBufferUsage.COPY_DST }); device.queue.writeBuffer(made, 0, data); return made; }; const white = (size: number) => { const texture = device.createTexture({ size: [size, size], format: "rgba8unorm", usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, }); const pixels = new Uint8Array(size * size * 4).fill(255); device.queue.writeTexture({ texture }, pixels, { bytesPerRow: size * 4 }, [size, size]); return texture.createView(); }; const uniforms = device.createBuffer({ size: 80, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST }); const sampler = device.createSampler(); const bind = (index: number, entries: GPUBindGroupEntry[]) => device.createBindGroup({ layout: pipeline.getBindGroupLayout(index), entries }); const bind_groups = [ bind(0, [{ binding: 0, resource: { buffer: uniforms } }]), bind(1, [{ binding: 0, resource: white(1) }, { binding: 1, resource: sampler }]), bind(2, [{ binding: 0, resource: white(16) }, { binding: 1, resource: sampler }]), ]; // the left half of a block's south face, seen from the south by a camera that shows just the block const quad: BakedQuad = { positions: [0, 0, 1, 0.5, 0, 1, 0.5, 1, 1, 0, 1, 1], uvs: [0, 16, 16, 16, 16, 0, 0, 0], texture: "testmod:shaft", variables: [], face: 2, cull: -1, flush: false, aligned: true, shade: true, }; // the atlas is just its texture AssetManager.instance.assets["bworld:textures_info"] = { "testmod:shaft": { x: 0, y: 0, width: 16, height: 16 }, }; const model = buffer( GPUBufferUsage.VERTEX, pack_model([quad], [[1, 1, 1]], { width: 16, height: 16 } as Texture), ); const indices = buffer(GPUBufferUsage.INDEX, Uint32Array.of(0, 1, 2, 0, 2, 3)); const camera = mat4.orthoZO(mat4.create(), 0, 1, 0, 1, -10, 10); // the red of the 2x2 pixels the block covers: top left, top right, bottom left, bottom right const render = async (time: number, rpm: number, offset: number) => { const group = new InstanceGroup([quad], [[1, 1, 1]]); group.add({ group, index: -1, placement: mat4.create(), axis: [0, 0, 1], rpm, offset, light: 0xff }); device.queue.writeBuffer(uniforms, 0, Float32Array.of(...camera, time, 0, 0, 0)); const target = device.createTexture({ size: [2, 2], format: "rgba8unorm", usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, }); const encoder = device.createCommandEncoder(); const pass = encoder.beginRenderPass({ colorAttachments: [{ view: target.createView(), loadOp: "clear", storeOp: "store", clearValue: [0, 0, 0, 1], }], }); pass.setPipeline(pipeline); bind_groups.forEach((group, index) => pass.setBindGroup(index, group)); pass.setIndexBuffer(indices, "uint32"); pass.setVertexBuffer(0, model); pass.setVertexBuffer(1, buffer(GPUBufferUsage.VERTEX, group.data)); pass.drawIndexed(6, 1); pass.end(); const read = device.createBuffer({ size: 512, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); encoder.copyTextureToBuffer({ texture: target }, { buffer: read, bytesPerRow: 256 }, [2, 2]); device.queue.submit([encoder.finish()]); await read.mapAsync(GPUMapMode.READ); const pixels = new Uint8Array(read.getMappedRange()); return [pixels[0], pixels[4], pixels[256], pixels[260]]; }; // facing south it's shaded 0.8 like a block's south face assertEquals(await render(0, 50, 0), [204, 0, 204, 0]); // 50 rpm is 15 degrees a tick, so a quarter turn counterclockwise takes the left half to the bottom assertEquals(await render(6, 50, 0), [0, 0, 204, 204]); assertEquals(await render(6, -50, 0), [204, 204, 0, 0]); // still, but half a turn along assertEquals(await render(1000, 0, 180), [0, 204, 0, 204]); device.destroy(); }, }); Deno.test("client scripts register visuals during setup, for blocks that exist", async () => { const load = async (script: string) => { const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" }); write_testmod(dir, script); const mod = load_and_check(dir)[0]; const bmod = read_bmod(await pack_mod(mod), "testmod.bmod"); Deno.removeSync(dir, { recursive: true }); const listing: ModListing = { id: "testmod", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 }; EverythingRegistry.clear(); await load_client_mods([listing], [bmod]); }; await load(` import type { ClientContext } from "bworld/client"; export function setup(ctx: ClientContext) { ctx.render.register_visual("testmod:shaft", (_block, instances) => { instances.rotating(); return {}; }, { replaces_model: true }); } `); const visual = block_visuals.get(EverythingRegistry.get_id("blocks", "testmod:shaft")!); assertEquals([visual?.mod, visual?.replaces_model], ["testmod", true]); await assertRejects( () => load(` import type { ClientContext } from "bworld/client"; export function setup(ctx: ClientContext) { ctx.render.register_visual("testmod:gear", () => ({})); } `), Error, "unknown block testmod:gear", ); block_visuals.clear(); });