Files
bworld/client/rendering/visuals.ts
T
2026-10-13 23:52:30 -03:00

308 lines
11 KiB
TypeScript

// 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, kept by chunk so chunks out of view are skipped, and drawn as instances of
// models. instances are worked out on the cpu each frame and drawn in the same batch as entities
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 { push_vertex, type Texture } from "$/client/renderer/mod.ts";
import { get_sprite_region } from "$/client/sprites.ts";
import { sprite_u, sprite_v } from "./item_renderer.ts";
import type { Vec3 } from "./model_math.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<number, VisualRegistration>();
const AXES: Record<string, vec3> = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };
// a rotating instance turns this many degrees per tick at 1 rpm
const DEGREES_PER_TICK = 360 / 60 / 20;
// a model's quads with the color each is tinted, white but for a block's own tinted quads, like leaves
interface ModelQuads {
quads: BakedQuad[];
tints: number[][];
}
// an instance as the engine keeps it, one of matrix or rotation
export interface DrawnInstance extends ModelQuads {
// from the model's space to the block's
matrix?: mat4;
rotation?: { axis: vec3; rpm: number; offset: number };
}
interface Entry {
x: number;
y: number;
z: number;
value: number;
mod: string;
// undefined when making it threw, until the block changes
visual?: Visual;
instances: Set<DrawnInstance>;
// 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<number, Map<number, Entry>>();
#client_data: (x: number, y: number, z: number) => Readonly<Record<string, unknown>> | undefined;
// baked once per level, since a level's mods don't change
#models?: Record<string, ModelJson>;
#model_quads = new Map<string, ModelQuads>();
#block_quads = new Map<number, ModelQuads>();
constructor(client_data: (x: number, y: number, z: number) => Readonly<Record<string, unknown>> | undefined) {
this.#client_data = client_data;
}
has(chunk_x: number, chunk_z: number) {
return this.#chunks.has(chunk_key(chunk_x, chunk_z));
}
// 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
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<number, Entry>();
const kept = new Map<number, Entry>();
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) {
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);
}
// the visuals in these chunks get their on_frame, then their instances are drawn
render(
chunks: Iterable<{ x: number; z: number }>,
time: number,
draw: (instance: DrawnInstance, x: number, y: number, z: number) => void,
) {
for (const chunk of chunks) {
const entries = this.#chunks.get(chunk_key(chunk.x, chunk.z));
if (!entries) continue;
for (const entry of entries.values()) {
const visual = entry.visual;
if (visual?.on_frame && !entry.frame_failed) {
entry.frame_failed = !run_visual(entry, "on_frame", () => visual.on_frame!(time));
}
for (const instance of entry.instances) draw(instance, entry.x, entry.y, entry.z);
}
}
}
#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<BlockRegistry>("blocks", value & ID_MASK);
if (!registration || !block) return undefined;
const entry: Entry = { x, y, z, value, mod: registration.mod, instances: new Set() };
const client_data = this.#client_data;
const view: VisualBlock = {
id: block.id,
x,
y,
z,
states: Object.freeze(states_of(block, value)),
get_client_data: (field) => structuredClone(client_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) entry.instances.clear();
return entry;
}
#delete(entry: Entry) {
const visual = entry.visual;
if (visual?.on_delete) run_visual(entry, "on_delete", () => visual.on_delete!());
entry.instances.clear();
}
#instances(entry: Entry, block: BlockRegistry): Instances {
const add = (model: ModelRef | undefined, instance: Omit<DrawnInstance, keyof ModelQuads>) => {
const quads = model === undefined ? this.#quads_of_block(block, entry.value) : this.#quads_of(model);
const added = { ...instance, ...quads };
entry.instances.add(added);
return added;
};
return {
transformed(model): TransformedInstance {
const instance = add(model, { matrix: mat4.create() });
return {
set_transform(matrix) {
if (matrix?.length !== 16) throw new Error("a transform is 16 numbers, a 4x4 matrix");
mat4.copy(instance.matrix!, matrix as mat4);
},
delete: () => void entry.instances.delete(instance),
};
},
rotating(model): RotatingInstance {
const instance = add(model, { rotation: { axis: AXES.y, rpm: 0, offset: 0 } });
return {
set_rotation(axis, rpm, offset = 0) {
if (!AXES[axis]) throw new Error(`an axis is "x", "y" or "z", not ${axis}`);
instance.rotation = { axis: AXES[axis], rpm, offset };
},
delete: () => void entry.instances.delete(instance),
};
},
};
}
#quads_of(ref: ModelRef): ModelQuads {
const { model, x = 0, y = 0 } = typeof ref === "string" ? { model: ref } : ref;
const key = `${model} ${x} ${y}`;
let quads = this.#model_quads.get(key);
if (!quads) {
this.#models ??= Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
const json = find_model(model, this.#models);
if (!json) throw new Error(`there's no model ${model}`);
const baked = bake_model(json, undefined, y, x);
quads = { quads: baked, tints: baked.map(() => [1, 1, 1]) };
this.#model_quads.set(key, quads);
}
return quads;
}
#quads_of_block(block: BlockRegistry, value: number): ModelQuads {
let quads = this.#block_quads.get(value);
if (!quads) {
this.#models ??= Object.fromEntries(EverythingRegistry.entries<ModelJson>("models"));
const baked = bake_block(block, value, this.#models);
quads = { quads: baked, tints: baked.map((quad) => item_tint(block, quad.variables)) };
this.#block_quads.set(value, quads);
}
return quads;
}
}
// 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;
}
}
// where an instance's model goes at a time, as a matrix from its space to the world's
export function instance_matrix(out: mat4, instance: DrawnInstance, x: number, y: number, z: number, time: number) {
mat4.fromTranslation(out, [x, y, z]);
if (instance.matrix) return mat4.multiply(out, out, instance.matrix);
const { axis, rpm, offset } = instance.rotation!;
const degrees = (time * rpm * DEGREES_PER_TICK + offset) % 360;
mat4.translate(out, out, [0.5, 0.5, 0.5]);
mat4.rotate(out, out, degrees * Math.PI / 180, axis);
return mat4.translate(out, out, [-0.5, -0.5, -0.5]);
}
// reused every quad of every frame
const matrix = mat4.create();
const corners = [vec3.create(), vec3.create(), vec3.create(), vec3.create()];
const edge_a = vec3.create();
const edge_b = vec3.create();
const normal = vec3.create();
// an instance's quads into the batch, lit by tint. each quad is shaded by the way it faces after turning, like a
// block's faces are by theirs. the atlas has to be the current texture
export function draw_instance(
atlas: Texture,
instance: DrawnInstance,
x: number,
y: number,
z: number,
time: number,
[tr, tg, tb]: Vec3,
) {
instance_matrix(matrix, instance, x, y, z, time);
for (const [q, quad] of instance.quads.entries()) {
const p = quad.positions;
for (let k = 0; k < 4; k++) {
vec3.set(corners[k], p[k * 3], p[k * 3 + 1], p[k * 3 + 2]);
vec3.transformMat4(corners[k], corners[k], matrix);
}
const shade = quad.shade ? facing_shade(corners) : 1;
const [r, g, b] = instance.tints[q];
const region = get_sprite_region(quad.texture);
for (const k of [0, 1, 2, 0, 2, 3]) {
const [px, py, pz] = corners[k];
const u = sprite_u(atlas, region, quad.uvs[k * 2]);
const v = sprite_v(atlas, region, quad.uvs[k * 2 + 1]);
push_vertex(px, py, pz, u, v, shade * r * tr, shade * g * tg, shade * b * tb, 1);
}
}
}
// how bright a quad facing this way is, blending the shades of the sides it faces between: 1 up, 0.5 down, 0.8
// north and south, 0.6 east and west, like the chunk mesher's
export function facing_shade([a, b, , d]: vec3[]) {
vec3.cross(normal, vec3.sub(edge_a, b, a), vec3.sub(edge_b, d, a));
vec3.normalize(normal, normal);
const [nx, ny, nz] = normal;
return nx * nx * 0.6 + nz * nz * 0.8 + ny * ny * (ny > 0 ? 1 : 0.5);
}