// 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 import { mat4, vec3 } from "gl-matrix"; import type { Instances, 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 ModelJson, states_of, } from "$/common/block_models.ts"; import { CHUNK_AREA, CHUNK_SIZE, ID_MASK } from "$/common/constants.ts"; import { chunk_key } 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 { 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; } // 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 { readonly quads: BakedQuad[]; // each quad's tint, white but for a block's own tinted quads, like leaves readonly tints: number[][]; 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; // made the first time it's drawn gpu?: { model: GPUBuffer; instances: GPUBuffer; capacity: number }; constructor(quads: BakedQuad[], tints: number[][]) { this.quads = quads; this.tints = tints; } 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, and blocks' own by value #model_groups = new Map(); #block_groups = new Map(); 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(); } // 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()) { if (group.gpu) { destroy_buffer(group.gpu.model); destroy_buffer(group.gpu.instances); } } this.#model_groups.clear(); this.#block_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) instance.group.remove(instance); entry.instances.clear(); } #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 = (model: ModelRef | undefined) => { const group = model === undefined ? this.#block_group(block, entry.value) : this.#model_group(model); 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) => () => { instance.group.remove(instance); entry.instances.delete(instance); }; return { transformed(model): TransformedInstance { const instance = add(model); return { 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), }; }, rotating(model): RotatingInstance { const instance = add(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}`); const quads = bake_model(json, undefined, y, x); group = new InstanceGroup(quads, quads.map(() => [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(quads, quads.map((quad) => item_tint(block, quad.variables))); this.#block_groups.set(value, group); } return group; } } // 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. a group's model goes to the gpu the first time it's drawn, and its instances // whenever they changed. the atlas has to be the current texture export function draw_visuals(visuals: Visuals, atlas: Texture) { for (const group of visuals.groups()) { const count = group.instances.length; if (count === 0) continue; const capacity = group.data.length / INSTANCE_FLOATS; 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, group.tints, 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); } } // a model's quads as vertices for vs_instance, 4 a quad, see MODEL_VERTEX_BYTES export function pack_model(quads: BakedQuad[], tints: number[][], 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 region = get_sprite_region(quad.texture); const tint = tints[q]; 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(sprite_u(atlas, region, quad.uvs[k * 2]) * 65535), true); view.setUint16(at + 14, Math.round(sprite_v(atlas, region, quad.uvs[k * 2 + 1]) * 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; }