// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // blocks drawn with code, like a shaft that turns, see ctx.render.register_visual. like flywheel's visuals: one per // block, made when its chunk is meshed and kept by chunk. what they draw are instances of models, and every instance of // a model is drawn in one draw call from a buffer of where each is, how it spins and its light (see vs_instance in // client/renderer/core.ts). the gpu turns rotating ones by the time, so a shaft that keeps turning costs nothing per // frame. an item is a model too, one per way an item can look, and a fluid's box is a model of its own import { mat4, vec3 } from "gl-matrix"; import type { FluidInstance, Instances, ItemStack as ApiItemStack, ModelRef, RotatingInstance, TransformedInstance, Visual, VisualBlock, } from "@/common/mod_api/client.ts"; import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts"; import { bake_block, bake_model, type BakedQuad, find_model, item_tint, type ModelElementJson, type ModelJson, states_of, } from "@/common/block_models.ts"; import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "@/common/constants.ts"; import type { ModelFace } from "@/common/mod_data.ts"; import { ItemStack } from "@/common/inventory.ts"; import { chunk_key, item_texture } from "@/common/utils.ts"; import { create_vertex_buffer, destroy_buffer, draw_instances, INSTANCE_FLOATS, MODEL_VERTEX_BYTES, type Texture, write_buffer, } from "@/client/renderer/mod.ts"; import { get_sprite_region } from "@/client/sprites.ts"; import { fluid_look, ground_transform, item_layers, push_item, sprite_u, sprite_v } from "./item_renderer.ts"; export interface VisualRegistration { mod: string; create: (block: VisualBlock, instances: Instances) => Visual; // the block's model isn't in the terrain, the visual draws all of it replaces_model: boolean; } // each block's visual by the block's numeric id, see ctx.render.register_visual export const block_visuals = new Map(); const AXES: Record = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }; // what visuals read from their level export interface VisualsLevel { get_block_data(x: number, y: number, z: number): Readonly> | undefined; // block light << 4 | sky light get_light(x: number, y: number, z: number): number; } // an instance as the engine keeps it, see INSTANCE_FLOATS export interface DrawnInstance { group: InstanceGroup; // where it is in its group, -1 once it's deleted index: number; // takes its model to the world, after it spins around its block's middle placement: mat4; axis: vec3; rpm: number; // degrees offset: number; // packed like ClientLevel.get_light light: number; } // a quad of an instanced model: 4 corners counter clockwise seen from the front, x y z each in the model's space, their // uvs in atlas pixels, so they don't depend on the atlas's size, its tint, and whether the gpu shades it by the way it // faces export interface InstanceQuad { positions: number[]; uvs: number[]; tint: number[]; shade: boolean; } // what to give sprite_u and sprite_v for uvs in atlas pixels const ATLAS_PIXELS = { width: 1, height: 1 } as Texture; // a model's baked quads as an instanced model's, each tinted export function instance_quads(quads: BakedQuad[], tint: (quad: BakedQuad) => number[]): InstanceQuad[] { return quads.map((quad) => { const region = get_sprite_region(quad.texture); const uvs = quad.uvs.map((pixels, i) => i % 2 === 0 ? sprite_u(ATLAS_PIXELS, region, pixels) : sprite_v(ATLAS_PIXELS, region, pixels) ); return { positions: quad.positions, uvs, tint: tint(quad), shade: quad.shade }; }); } // the instances of one model, drawn in one draw call. their data is changed on the cpu and written to the gpu once a // frame, from the first instance that changed to the last export class InstanceGroup { quads: InstanceQuad[]; // drawn blended after the rest, back to front by center, like a fluid's box readonly translucent: boolean; // where it is in the world, for drawing translucent ones back to front center = vec3.create(); readonly instances: DrawnInstance[] = []; data = new Float32Array(INSTANCE_FLOATS * 16); // the instances changed since the gpu last got them, by index dirty_from = Infinity; dirty_to = -1; // quads changed since the gpu last got them model_changed = false; // made the first time it's drawn gpu?: { model: GPUBuffer; instances: GPUBuffer; capacity: number }; constructor(quads: InstanceQuad[], translucent = false) { this.quads = quads; this.translucent = translucent; } // for a model that changes, like a fluid's box filling up set_quads(quads: InstanceQuad[]) { this.quads = quads; this.model_changed = true; } add(instance: DrawnInstance) { instance.index = this.instances.length; this.instances.push(instance); if (this.data.length < this.instances.length * INSTANCE_FLOATS) { const data = new Float32Array(this.data.length * 2); data.set(this.data); this.data = data; } this.write(instance); } // the last instance moves into its place, so the ones drawn are always the first ones remove(instance: DrawnInstance) { if (instance.index < 0) return; const last = this.instances.pop()!; if (last !== instance) { last.index = instance.index; this.instances[last.index] = last; this.write(last); } instance.index = -1; } // after any of its fields changed write(instance: DrawnInstance) { const index = instance.index; if (index < 0) return; const at = index * INSTANCE_FLOATS; this.data.set(instance.placement, at); this.data.set(instance.axis, at + 16); this.data[at + 19] = instance.rpm; this.data[at + 20] = instance.offset; this.data[at + 21] = ((instance.light >> 4) + 0.5) / 16; this.data[at + 22] = ((instance.light & 15) + 0.5) / 16; this.dirty_from = Math.min(this.dirty_from, index); this.dirty_to = Math.max(this.dirty_to, index); } } interface Entry { x: number; y: number; z: number; value: number; mod: string; light: number; // undefined when making it threw, until the block changes visual?: Visual; instances: Set; // on_frame threw, so it isn't called again frame_failed?: boolean; } // a level's visuals export class Visuals { // by chunk_key, then the block's index in its chunk #chunks = new Map>(); #level: VisualsLevel; // baked once per level, since a level's mods don't change #models?: Record; // models from models/ by id and turns, blocks' own by value, and items by how they look #model_groups = new Map(); #block_groups = new Map(); #item_groups = new Map(); // a fluid box's model is its own, and goes with it #fluid_groups = new Set(); constructor(level: VisualsLevel) { this.#level = level; } has(chunk_x: number, chunk_z: number) { return this.#chunks.has(chunk_key(chunk_x, chunk_z)); } *groups(): Iterable { yield* this.#model_groups.values(); yield* this.#block_groups.values(); yield* this.#item_groups.values(); yield* this.#fluid_groups; } // the blocks with visuals a chunk was meshed with, as pairs of the block's index in the chunk and its value. visuals // for blocks that are gone or changed go, and new ones are made. the chunk's light came with its mesh, so the ones // that stay take it meshed(chunk_x: number, chunk_z: number, found: Uint32Array) { const key = chunk_key(chunk_x, chunk_z); const old = this.#chunks.get(key) ?? new Map(); const kept = new Map(); for (let i = 0; i < found.length; i += 2) { const index = found[i]; const value = found[i + 1]; const entry = old.get(index); old.delete(index); if (entry?.value === value) { this.#relight(entry); kept.set(index, entry); continue; } if (entry) this.#delete(entry); const x = chunk_x * CHUNK_SIZE + (index % CHUNK_SIZE); const z = chunk_z * CHUNK_SIZE + Math.floor(index / CHUNK_SIZE) % CHUNK_SIZE; const made = this.#create(x, Math.floor(index / CHUNK_AREA), z, value); if (made) kept.set(index, made); } for (const entry of old.values()) this.#delete(entry); if (kept.size > 0) this.#chunks.set(key, kept); else this.#chunks.delete(key); } // a field of the block's client data changed data_changed(x: number, y: number, z: number) { const entry = this.#entry(x, y, z); if (entry?.visual?.update) run_visual(entry, "update", () => entry.visual!.update!()); } unload(chunk_x: number, chunk_z: number) { const key = chunk_key(chunk_x, chunk_z); for (const entry of this.#chunks.get(key)?.values() ?? []) this.#delete(entry); this.#chunks.delete(key); } // every visual goes, and the gpu buffers with them dispose() { for (const key of this.#chunks.keys()) { for (const entry of this.#chunks.get(key)!.values()) this.#delete(entry); } this.#chunks.clear(); for (const group of this.groups()) destroy_group(group); this.#model_groups.clear(); this.#block_groups.clear(); this.#item_groups.clear(); } // the visuals in these chunks get their on_frame. every instance is drawn either way, it's the gpu that skips what's // out of view frame(chunks: Iterable<{ x: number; z: number }>, time: number) { for (const chunk of chunks) { for (const entry of this.#chunks.get(chunk_key(chunk.x, chunk.z))?.values() ?? []) { const visual = entry.visual; if (visual?.on_frame && !entry.frame_failed) { entry.frame_failed = !run_visual(entry, "on_frame", () => visual.on_frame!(time)); } } } } #entry(x: number, y: number, z: number) { const chunk_x = Math.floor(x / CHUNK_SIZE); const chunk_z = Math.floor(z / CHUNK_SIZE); const index = y * CHUNK_AREA + (z - chunk_z * CHUNK_SIZE) * CHUNK_SIZE + (x - chunk_x * CHUNK_SIZE); return this.#chunks.get(chunk_key(chunk_x, chunk_z))?.get(index); } #create(x: number, y: number, z: number, value: number): Entry | undefined { const registration = block_visuals.get(value & ID_MASK); const block = EverythingRegistry.get_by_id("blocks", value & ID_MASK); if (!registration || !block) return undefined; const light = this.#level.get_light(x, y, z); const entry: Entry = { x, y, z, value, mod: registration.mod, light, instances: new Set() }; const level = this.#level; const view: VisualBlock = { id: block.id, x, y, z, states: Object.freeze(states_of(block, value)), get_client_data: (field) => structuredClone(level.get_block_data(x, y, z)?.[field]) as never, }; const made = run_visual(entry, "create", () => { entry.visual = registration.create(view, this.#instances(entry, block)); }); // nothing it made before it threw is drawn if (!made) this.#remove_instances(entry); return entry; } #delete(entry: Entry) { const visual = entry.visual; if (visual?.on_delete) run_visual(entry, "on_delete", () => visual.on_delete!()); this.#remove_instances(entry); } #remove_instances(entry: Entry) { for (const instance of entry.instances) this.#remove_instance(instance); entry.instances.clear(); } #remove_instance(instance: DrawnInstance) { instance.group.remove(instance); if (this.#fluid_groups.delete(instance.group)) destroy_group(instance.group); } #relight(entry: Entry) { const light = this.#level.get_light(entry.x, entry.y, entry.z); if (light === entry.light) return; entry.light = light; for (const instance of entry.instances) { instance.light = light; instance.group.write(instance); } } #instances(entry: Entry, block: BlockRegistry): Instances { const corner = mat4.fromTranslation(mat4.create(), [entry.x, entry.y, entry.z]); const add = (group: InstanceGroup) => { const instance: DrawnInstance = { group, index: -1, placement: mat4.clone(corner), axis: AXES.y, rpm: 0, offset: 0, light: entry.light, }; group.add(instance); entry.instances.add(instance); return instance; }; const remove = (instance: DrawnInstance) => () => { this.#remove_instance(instance); entry.instances.delete(instance); }; const model_group = (model: ModelRef | undefined) => model === undefined ? this.#block_group(block, entry.value) : this.#model_group(model); const transformed = (instance: DrawnInstance): TransformedInstance => ({ set_transform(matrix) { if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix"); mat4.multiply(instance.placement, corner, matrix as mat4); instance.group.write(instance); }, delete: remove(instance), }); return { transformed: (model) => transformed(add(model_group(model))), item: (stack) => transformed(add(this.#item_group(stack))), fluid: (fluid) => { const { texture, tint } = fluid_look(fluid); const group = new InstanceGroup([], true); this.#fluid_groups.add(group); const instance = add(group); return { set_box(from, to) { const box = [from, to].map((corner) => [0, 1, 2].map((axis) => corner?.[axis])); if (!box.flat().every(Number.isFinite)) throw new Error("a box is from [x, y, z] to [x, y, z]"); group.set_quads(fluid_box(texture, tint, box[0], box[1])); vec3.set( group.center, entry.x + (box[0][0] + box[1][0]) / 32, entry.y + (box[0][1] + box[1][1]) / 32, entry.z + (box[0][2] + box[1][2]) / 32, ); }, delete: remove(instance), } satisfies FluidInstance; }, rotating(model): RotatingInstance { const instance = add(model_group(model)); return { set_rotation(axis, rpm, offset = 0) { if (!AXES[axis]) throw new Error(`an axis is "x", "y" or "z", not ${axis}`); instance.axis = AXES[axis]; instance.rpm = rpm; instance.offset = offset; instance.group.write(instance); }, delete: remove(instance), }; }, }; } #model_group(ref: ModelRef): InstanceGroup { const { model, x = 0, y = 0 } = typeof ref === "string" ? { model: ref } : ref; const key = `${model} ${x} ${y}`; let group = this.#model_groups.get(key); if (!group) { this.#models ??= Object.fromEntries(EverythingRegistry.entries("models")); const json = find_model(model, this.#models); if (!json) throw new Error(`there's no model ${model}`); group = new InstanceGroup(instance_quads(bake_model(json, undefined, y, x), () => [1, 1, 1])); this.#model_groups.set(key, group); } return group; } #block_group(block: BlockRegistry, value: number): InstanceGroup { let group = this.#block_groups.get(value); if (!group) { this.#models ??= Object.fromEntries(EverythingRegistry.entries("models")); const quads = bake_block(block, value, this.#models); group = new InstanceGroup(instance_quads(quads, (quad) => item_tint(block, quad.variables))); this.#block_groups.set(value, group); } return group; } // stacks that look the same share one: the same item, texture and layers in the same colors, like bottles of one // juice #item_group(stack: ApiItemStack): InstanceGroup { if (!EverythingRegistry.get("items", stack?.id)) throw new Error(`there's no item ${stack?.id}`); const item = new ItemStack(stack.id); if (stack.data !== undefined) item.data = structuredClone(stack.data); const key = JSON.stringify([item.type_id, item_texture(item), item_layers(item)]); let group = this.#item_groups.get(key); if (!group) { group = new InstanceGroup(item_quads(item)); this.#item_groups.set(key, group); } return group; } } // an item's model the way push_item draws it, the size it's drawn on the ground. its shading is in its tints already, // like a dropped item's, so the gpu doesn't shade it again function item_quads(item: ItemStack): InstanceQuad[] { const vertices: number[][] = []; push_item(ATLAS_PIXELS, item, ground_transform(item), [1, 1, 1], (x, y, z, u, v, r = 1, g = 1, b = 1) => { vertices.push([x, y, z, u, v, r, g, b]); }); const quads: InstanceQuad[] = []; // two triangles a quad, its corners 0 1 2 and 0 2 3 for (let i = 0; i < vertices.length; i += 6) { const corners = [vertices[i], vertices[i + 1], vertices[i + 2], vertices[i + 5]]; quads.push({ positions: corners.flatMap(([x, y, z]) => [x, y, z]), uvs: corners.flatMap(([, , , u, v]) => [u, v]), tint: corners[0].slice(5, 8), shade: false, }); } return quads; } // a box's faces, by the axis they're across and whether they're at its high end or its low one const BOX_FACES: { face: ModelFace; axis: number; high: boolean }[] = [ { face: "west", axis: 0, high: false }, { face: "east", axis: 0, high: true }, { face: "bottom", axis: 1, high: false }, { face: "top", axis: 1, high: true }, { face: "north", axis: 2, high: false }, { face: "south", axis: 2, high: true }, ]; // a box of a texture from one corner to the other, in pixels, like a fluid in a tank. it's cut where it goes from one // block into the next, and each piece is textured with the part of the texture it covers in its block, like a model // element's faces are, so the texture is never stretched and repeats once a block. only the outside faces are drawn. // nothing for a box that's flat or inside out export function fluid_box(texture: string, tint: number[], from: number[], to: number[]): InstanceQuad[] { if ([0, 1, 2].some((axis) => to[axis] <= from[axis])) return []; // where each axis's pieces start and end const cuts = [0, 1, 2].map((axis) => { const points = [from[axis]]; for (let at = (Math.floor(from[axis] / 16) + 1) * 16; at < to[axis]; at += 16) points.push(at); return [...points, to[axis]]; }); const model: ModelJson = { id: "cubi:fluid_box", textures: { fluid: texture }, elements: [] }; const quads: InstanceQuad[] = []; for (let i = 0; i < cuts[0].length - 1; i++) { for (let j = 0; j < cuts[1].length - 1; j++) { for (let k = 0; k < cuts[2].length - 1; k++) { const low = [cuts[0][i], cuts[1][j], cuts[2][k]]; const high = [cuts[0][i + 1], cuts[1][j + 1], cuts[2][k + 1]]; const block = low.map((at) => Math.floor(at / 16)); const element: ModelElementJson = { from: low.map((at, axis) => at - block[axis] * 16) as [number, number, number], to: high.map((at, axis) => at - block[axis] * 16) as [number, number, number], faces: {}, }; for (const { face, axis, high: side } of BOX_FACES) { if (side ? high[axis] === to[axis] : low[axis] === from[axis]) { element.faces[face] = { texture: "#fluid" }; } } const baked = bake_model({ ...model, elements: [element] }, undefined); for (const quad of baked) { quad.positions = quad.positions.map((at, n) => at + block[n % 3]); } quads.push(...instance_quads(baked, () => tint)); } } } return quads; } // a group's gpu buffers go, for a group that won't be drawn again function destroy_group(group: InstanceGroup) { if (!group.gpu) return; destroy_buffer(group.gpu.model); destroy_buffer(group.gpu.instances); group.gpu = undefined; } // false when it threw, which is logged with the mod and block function run_visual(entry: Entry, what: string, fn: () => void) { try { fn(); return true; } catch (e) { console.error(`[${entry.mod}] the visual at ${entry.x} ${entry.y} ${entry.z} threw in ${what}:`, e); return false; } } // every instance, a draw call per model, and the translucent ones after the rest, back to front from the camera so each // shows what's behind it. a group's model goes to the gpu the first time it's drawn and again when it changed, and its // instances whenever they changed. the atlas has to be the current texture export function draw_visuals(visuals: Visuals, atlas: Texture, camera: Readonly) { const translucent: InstanceGroup[] = []; for (const group of visuals.groups()) { if (group.translucent) translucent.push(group); else draw_group(group, atlas); } const distance = (group: InstanceGroup) => vec3.squaredDistance(group.center, camera); translucent.sort((a, b) => distance(b) - distance(a)); for (const group of translucent) draw_group(group, atlas); } function draw_group(group: InstanceGroup, atlas: Texture) { const count = group.instances.length; if (count === 0 || group.quads.length === 0) return; const capacity = group.data.length / INSTANCE_FLOATS; if (group.gpu && group.model_changed) { destroy_buffer(group.gpu.model); group.gpu.model = create_vertex_buffer(pack_model(group.quads, atlas)); } group.model_changed = false; if (!group.gpu || group.gpu.capacity !== capacity) { // the whole buffer again, when it's new or the cpu copy grew if (group.gpu) destroy_buffer(group.gpu.instances); group.gpu = { model: group.gpu?.model ?? create_vertex_buffer(pack_model(group.quads, atlas)), instances: create_vertex_buffer(group.data), capacity, }; } else if (group.dirty_to >= 0) { const from = group.dirty_from * INSTANCE_FLOATS; write_buffer( group.gpu.instances, from * 4, group.data, from, (group.dirty_to + 1) * INSTANCE_FLOATS - from, ); } group.dirty_from = Infinity; group.dirty_to = -1; draw_instances(group.gpu.model, group.quads.length, group.gpu.instances, count, group.translucent); } // a model's quads as vertices for vs_instance, 4 a quad, see MODEL_VERTEX_BYTES export function pack_model(quads: InstanceQuad[], atlas: Texture): Uint8Array { const bytes = new Uint8Array(quads.length * 4 * MODEL_VERTEX_BYTES); const view = new DataView(bytes.buffer); const normal = vec3.create(); quads.forEach((quad, q) => { const p = quad.positions; const corner = (k: number) => vec3.fromValues(p[k * 3], p[k * 3 + 1], p[k * 3 + 2]); // counterclockwise seen from the front, so it points out of the front const [a, b, d] = [corner(0), corner(1), corner(3)]; vec3.normalize(normal, vec3.cross(normal, vec3.sub(b, b, a), vec3.sub(d, d, a))); const tint = quad.tint; for (let k = 0; k < 4; k++) { const at = (q * 4 + k) * MODEL_VERTEX_BYTES; for (let axis = 0; axis < 3; axis++) view.setFloat32(at + axis * 4, p[k * 3 + axis], true); view.setUint16(at + 12, Math.round(quad.uvs[k * 2] / atlas.width * 65535), true); view.setUint16(at + 14, Math.round(quad.uvs[k * 2 + 1] / atlas.height * 65535), true); for (let c = 0; c < 3; c++) bytes[at + 16 + c] = Math.round(tint[c] * 255); bytes[at + 19] = quad.shade ? 255 : 0; for (let axis = 0; axis < 3; axis++) view.setInt8(at + 20 + axis, Math.round(normal[axis] * 127)); } }); return bytes; }