Files
bworld/tests/visuals_test.ts
T
2026-11-14 12:18:41 -03:00

512 lines
21 KiB
TypeScript

// 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, assertThrows } from "@std/assert";
import { mat4 } from "gl-matrix";
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";
import type { ModListing } from "@/common/mod_loader.ts";
import { read_mod } from "@/common/mod.ts";
import type { FluidInstance, Instances, RotatingInstance, Visual } from "@/common/mod_api/client.ts";
import { block_visuals, instance_quads, 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 { chunk_worker, copy_dir, mesh_column, test_game } from "./helpers.ts";
import { section_index } from "@/common/section.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, syrup, a jar drawn with the syrup in it, and maybe a
// client phase
function write_testmod(dir: string, client_script?: string) {
const mod = `${dir}/testmod`;
for (const folder of ["blocks", "models", "scripts", "fluids", "items"]) {
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 && { main: "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 } });
write("fluids/syrup.json", {
format_version: 1,
fluid: { id: "testmod:syrup", color: "#a0522d", texture: "testmod:syrup_still" },
});
write("items/jar.json", {
format_version: 1,
item: {
id: "testmod:jar",
texture: "cubi:missing",
fluid_container: { capacity: 250 },
layers: [{ texture: "cubi:break_0", tint: "fluid" }],
},
});
if (client_script) Deno.writeTextFileSync(`${mod}/scripts/client.ts`, client_script);
}
// a game's registries with mods/bworld and testmod. there's no atlas, so every texture is where the missing one would be
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 });
AssetManager.instance.assets["cubi:textures_info"] = {};
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 = 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");
const meshed = await mesh_column(worker, DEFAULT_SHAPE, chunks);
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<string, unknown> = { 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<number>("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(section_index(1, 64, 1), value("testmod:shaft", axis));
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, 64, 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, 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, 64, new Uint32Array());
assertEquals(log.splice(0), ["delete 1 64 1"]);
assert(!visuals.has(0, 0));
assertEquals(drawn(visuals), []);
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), []);
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, 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, 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 {
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) => [section_index(x, 64, 1), value("testmod:shaft")]),
);
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 = () => {
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, 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. 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();
block_visuals.set(nid("testmod:shaft"), {
mod: "testmod",
replaces_model: false,
create(_block, instances) {
make(instances);
return {};
},
});
const mesh = (blocks: number[]) => visuals.meshed(0, 0, 64, Uint32Array.from(blocks));
mesh([section_index(1, 64, 1), value("testmod:shaft")]);
return { visuals, mesh };
}
// the smallest and biggest of every nth number from the first'th, like an axis of a model's positions or uvs
const range = (groups: InstanceGroup[], numbers: "positions" | "uvs", nth: number, first: number) => {
const picked = groups.flatMap((group) => group.quads.flatMap((quad) => quad[numbers]))
.filter((_, i) => i % nth === first);
return [Math.min(...picked), Math.max(...picked)];
};
const SYRUP = [0xa0 / 255, 0x52 / 255, 0x2d / 255];
Deno.test("an item is drawn the size it is on the ground, with one model for every stack that looks the same", async () => {
const { nid, value } = await registries();
const full = { fluid: { id: "testmod:syrup" } };
const { visuals } = one_visual(nid, value, (instances) => {
instances.item({ id: "testmod:jar", count: 16 });
instances.item({ id: "testmod:jar", count: 1 });
instances.item({ id: "testmod:jar", count: 1, data: full });
instances.item({ id: "testmod:shaft", count: 1 });
assertThrows(
() => instances.item({ id: "testmod:nothing", count: 1 }),
Error,
"there's no item testmod:nothing",
);
});
// the jar's front and back, and its syrup's when it's full, and the shaft's item is a cube. one of each, whatever the
// count
assertEquals(drawn(visuals), ["2 quads x2", "4 quads x1", "6 quads x1"]);
const [empty, filled, cube] = [...visuals.groups()].filter((group) => group.instances.length > 0);
assertEquals(filled.quads.slice(2).map((quad) => quad.tint), [SYRUP, SYRUP]);
// half a block across like a dropped item, and a block a quarter, around the block's middle
assertEquals([range([empty], "positions", 3, 0), range([empty], "positions", 3, 1)], [[0.25, 0.75], [0.25, 0.75]]);
assertEquals([0, 1, 2].map((axis) => range([cube], "positions", 3, axis)), [
[0.375, 0.625],
[0.375, 0.625],
[0.375, 0.625],
]);
block_visuals.clear();
});
Deno.test("a fluid's box is its texture cut to fit and tinted in its color, a model of its own that goes with it", async () => {
const { nid, value } = await registries();
AssetManager.instance.assets["cubi:textures_info"] = {
"testmod:syrup_still": { x: 32, y: 0, width: 16, height: 16 },
};
let box: FluidInstance | undefined;
const { visuals, mesh } = one_visual(nid, value, (instances) => {
box = instances.fluid({ id: "testmod:syrup" });
assertThrows(() => instances.fluid({ id: "testmod:nothing" }), Error, "there's no fluid testmod:nothing");
});
const boxes = () => [...visuals.groups()].filter((group) => group.translucent);
// nothing until it has a box
assertEquals(boxes().map((group) => group.quads.length), [0]);
box!.set_box([2, 2, 2], [14, 8, 14]);
const [group] = boxes();
assertEquals(group.quads.length, 6);
assert(group.quads.every((quad) => quad.tint === group.quads[0].tint && quad.shade));
assertEquals(group.quads[0].tint, SYRUP);
// in the block's space, and its top is the middle 12 pixels of the texture, not all 16 squeezed into it
assertEquals([0, 1, 2].map((axis) => range([group], "positions", 3, axis)), [
[0.125, 0.875],
[0.125, 0.5],
[0.125, 0.875],
]);
const top = new InstanceGroup(
group.quads.filter((quad) => quad.positions.every((at, i) => i % 3 !== 1 || at === 0.5)),
);
assertEquals([range([top], "uvs", 2, 0), range([top], "uvs", 2, 1)], [[34, 46], [2, 14]]);
// where it's drawn back to front from
assertEquals([...group.center], [1.5, 64 + 5 / 16, 1.5]);
// two blocks long it's a piece in each, and the texture repeats
box!.set_box([0, 0, 0], [32, 16, 16]);
assertEquals([group.quads.length, group.model_changed], [10, true]);
assertEquals(range([group], "positions", 3, 0), [0, 2]);
assertEquals([range([group], "uvs", 2, 0), range([group], "uvs", 2, 1)], [[32, 48], [0, 16]]);
// it goes with its instance, or its visual
box!.delete();
assertEquals(boxes(), []);
mesh([]);
mesh([section_index(1, 64, 1), value("testmod:shaft")]);
assertEquals(boxes().length, 1);
visuals.unload(0, 0);
assertEquals(boxes(), []);
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<ArrayBuffer> | 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["cubi:textures_info"] = {
"testmod:shaft": { x: 0, y: 0, width: 16, height: 16 },
};
const quads = instance_quads([quad], () => [1, 1, 1]);
const model = buffer(GPUBufferUsage.VERTEX, pack_model(quads, { 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(quads);
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 phases 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 = (await load_and_check(dir))[0];
const packed = read_mod(await pack_mod(mod), "testmod.cubi");
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], [packed]);
};
await load(`
import type { ClientContext } from "cubi/client";
export function client(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 "cubi/client";
export function client(ctx: ClientContext) {
ctx.render.register_visual("testmod:gear", () => ({}));
}
`),
Error,
"unknown block testmod:gear",
);
block_visuals.clear();
});