Files
bworld/common/block_models.ts
2026-11-22 12:24:14 -03:00

584 lines
24 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// block models, in the shape of minecraft's block model json: boxes ("elements") with a texture per face.
// a block picks one with "model" and fills in its texture variables with "textures". baking turns a model
// into quads in block space (0 to 1) that the chunk mesher and the item renderers draw
import { type BlockRegistry, type BlockTextures, fluid_textures } from "./everything_registry.ts";
import { color_rgb, tint_without_biome } from "./worldgen/biome_colors.ts";
import { get_state_value } from "./utils.ts";
import { type DisplayContext, MODEL_FACES, type ModelFace } from "./mod_data.ts";
export interface ModelFaceJson {
// a texture variable like "#side", or a texture id
texture: string;
// the part of the texture, [u1, v1, u2, v2] in pixels (0-16). defaults to the part the face covers
uv?: [number, number, number, number];
// turns the texture on the face clockwise: 0, 90, 180 or 270
rotation?: number;
// hidden when the neighbor on this side hides faces (a solid block)
cullface?: ModelFace;
}
export interface ModelElementJson {
// corners of the box in pixels, 0-16 is the block
from: [number, number, number];
to: [number, number, number];
rotation?: {
origin: [number, number, number];
axis: "x" | "y" | "z";
// degrees, any from -180 to 180. minecraft only takes -45, -22.5, 0, 22.5 or 45, blockbench's newer models any
angle: number;
// stretch the rotated faces back to the block's size, like the cross model does
rescale?: boolean;
};
// directional shading, off for plants so they look the same from every side
shade?: boolean;
faces: Partial<Record<ModelFace, ModelFaceJson>>;
}
// how an item drawn with a model is placed in one of the places it's shown. all around the model's middle: moved by
// translation (pixels), turned by rotation (degrees, around the z axis first, then y, then x) and sized by scale
export interface DisplayTransform {
rotation?: [number, number, number];
translation?: [number, number, number];
scale?: [number, number, number];
}
export type ModelDisplay = Partial<Record<DisplayContext, DisplayTransform>>;
// a model as a mod writes it in models/. it can start from a parent, like minecraft's: it gets the parent's elements
// unless it has its own, and the parent's texture defaults and display transforms under its own. one with no elements
// is only there to be a parent, or draws nothing
export interface ModelFileJson {
id: string;
parent?: string;
// defaults for texture variables, can point at other variables ("top": "#side")
textures?: Record<string, string>;
elements?: ModelElementJson[];
display?: ModelDisplay;
}
// a model with its parents merged in, which is what blocks are drawn with. see resolve_models
export interface ModelJson {
id: string;
textures?: Record<string, string>;
elements: ModelElementJson[];
display?: ModelDisplay;
}
// mods' models with their parents merged in. a parent is another of these, or one existing finds (a model of a mod
// loaded before, or a built-in one). a model whose parent doesn't exist or whose parents loop keeps only what it has
// itself, and gets a problem
export function resolve_models(
models: ModelFileJson[],
existing: (id: string) => ModelJson | undefined,
): { models: ModelJson[]; problems: { id: string; problem: string }[] } {
const files = new Map(models.map((model) => [model.id, model]));
const problems: { id: string; problem: string }[] = [];
// a model in a loop is resolved without its parent, so resolving never goes round one
const looped = new Set<string>();
for (const { id } of models) {
const loop = parent_loop(id, (other) => files.get(other)?.parent);
if (loop) {
looped.add(id);
problems.push({ id, problem: `its parents loop: ${loop.join(" -> ")}` });
}
}
const resolved = new Map<string, ModelJson>();
const resolve = (id: string): ModelJson | undefined => {
const file = files.get(id);
if (!file) return existing(id);
const done = resolved.get(id);
if (done) return done;
let parent: ModelJson | undefined;
if (file.parent !== undefined && !looped.has(id)) {
parent = resolve(file.parent);
// a parent of this mod that has a problem of its own still resolves, so this is only for missing ones
if (!parent) problems.push({ id, problem: `its parent ${file.parent} doesn't exist` });
}
const textures = { ...parent?.textures, ...file.textures };
// each place's transform is the model's own or its parent's, whole
const display = { ...parent?.display, ...file.display };
const model: ModelJson = {
id,
...(Object.keys(textures).length > 0 ? { textures } : {}),
elements: file.elements ?? parent?.elements ?? [],
...(Object.keys(display).length > 0 ? { display } : {}),
};
resolved.set(id, model);
return model;
};
return { models: models.map(({ id }) => resolve(id)!), problems };
}
// the parents from a model back round to it, when its parents loop. parent_of gives a model's parent, if it has one
export function parent_loop(id: string, parent_of: (id: string) => string | undefined): string[] | undefined {
const chain = [id];
for (let next = parent_of(id); next !== undefined; next = parent_of(next)) {
if (next === id) return [...chain, id];
// a loop further up, which isn't this model's to report
if (chain.includes(next)) return undefined;
chain.push(next);
}
return undefined;
}
// a model a block uses, and the textures it fills in
export interface BlockVariant {
model?: string;
textures?: BlockTextures;
// turns the model around the vertical axis, clockwise seen from above: 0, 90, 180 or 270
y?: number;
// turns the model around the east-west axis first, like minecraft's: 0, 90, 180 or 270. 90 tips its top to the north,
// so a model pointing up points north, then y turns it to face the rest of the ways
x?: number;
// keeps the textures where they'd be on an unturned block when x or y turn the model, so a turned stair's planks
// still run the same way as the planks next to it
uvlock?: boolean;
// what the player points at and bumps into, as boxes in pixels: [x1, y1, z1, x2, y2, z2]. the model's boxes when
// not set, see common/block_shapes.ts
shape?: number[][];
// what entities bump into, when it isn't the shape. can go up to 24 pixels high, like a fence's
collision_shape?: number[][];
}
// one piece of a block made of pieces, like minecraft's multipart blockstates: a fence is a post, and a bar for each
// side it connects on. every part whose "when" matches is drawn, and adds its shape
export interface BlockPart {
// a condition on the block's states like a variant's key, "north=1". always when not set
when?: string;
model: string;
// the block's textures when not set
textures?: BlockTextures;
y?: number;
x?: number;
uvlock?: boolean;
shape?: number[][];
collision_shape?: number[][];
}
// a model with everything it's drawn with, a variant or a part
export interface PlacedModel {
model: string;
textures: BlockTextures;
y: number;
x: number;
uvlock: boolean;
shape?: number[][];
collision_shape?: number[][];
}
export const DEFAULT_MODEL = "cubi:cube";
const cube_face = (texture: string, cullface: ModelFace): ModelFaceJson => ({ texture, cullface });
// the engine's own models
export const BUILTIN_MODELS: Record<string, ModelJson> = {
// a full block. "textures" can be one texture, { top, bottom, side } or { front, side }. the front is north, like
// minecraft's furnace, so a facing state turns it towards whoever placed it
"cubi:cube": {
id: "cubi:cube",
textures: { top: "#side", bottom: "#side", front: "#side" },
elements: [{
from: [0, 0, 0],
to: [16, 16, 16],
faces: {
top: cube_face("#top", "top"),
bottom: cube_face("#bottom", "bottom"),
north: cube_face("#front", "north"),
south: cube_face("#side", "south"),
west: cube_face("#side", "west"),
east: cube_face("#side", "east"),
},
}],
},
// two crossed planes, like flowers and saplings. uses the "cross" texture
"cubi:cross": {
id: "cubi:cross",
elements: [
cross_plane(45),
cross_plane(-45),
],
},
// four planes in a # shape, like wheat. uses the "crop" texture
"cubi:crop": {
id: "cubi:crop",
elements: [
{ from: [4, 0, 0], to: [4, 16, 16], shade: false, faces: both_ways("west", "east", "#crop") },
{ from: [12, 0, 0], to: [12, 16, 16], shade: false, faces: both_ways("west", "east", "#crop") },
{ from: [0, 0, 4], to: [16, 16, 4], shade: false, faces: both_ways("north", "south", "#crop") },
{ from: [0, 0, 12], to: [16, 16, 12], shade: false, faces: both_ways("north", "south", "#crop") },
],
},
};
function cross_plane(angle: number): ModelElementJson {
return {
from: [0.8, 0, 8],
to: [15.2, 16, 8],
rotation: { origin: [8, 8, 8], axis: "y", angle, rescale: true },
shade: false,
faces: both_ways("north", "south", "#cross"),
};
}
// a flat element seen from both sides, since faces are only drawn from the front
function both_ways(a: ModelFace, b: ModelFace, texture: string) {
return { [a]: { texture, uv: [0, 0, 16, 16] }, [b]: { texture, uv: [0, 0, 16, 16] } } as Partial<
Record<ModelFace, ModelFaceJson>
>;
}
export function find_model(id: string, models: Record<string, ModelJson>): ModelJson | undefined {
return BUILTIN_MODELS[id] ?? models[id];
}
// what a texture reference means for a block: "#name" looks up the block's textures, then the model's
// defaults, and anything else is already a texture id
export function resolve_texture(reference: string, textures: BlockTextures | undefined, model?: ModelJson): string {
for (let depth = 0; depth < 8 && reference.startsWith("#"); depth++) {
const name = reference.slice(1);
if (typeof textures === "string") return textures;
const next = (textures as Record<string, string> | undefined)?.[name] ?? model?.textures?.[name];
if (next === undefined) return "cubi:missing";
reference = next;
}
return reference.startsWith("#") ? "cubi:missing" : reference;
}
// the variables a texture reference goes through before it's a texture id, "#front" on a cube is front then side
export function texture_variables(reference: string, textures: BlockTextures | undefined, model?: ModelJson) {
const variables: string[] = [];
for (let depth = 0; depth < 8 && reference.startsWith("#"); depth++) {
const name = reference.slice(1);
variables.push(name);
if (typeof textures === "string") break;
const next = (textures as Record<string, string> | undefined)?.[name] ?? model?.textures?.[name];
if (next === undefined) break;
reference = next;
}
return variables;
}
// the block's model, textures, turn and shape for a value with state bits. each comes from the first variant whose conditions
// match that sets it, so "lit=1" can change the textures and "facing=1" the turn of the same block
export function block_variant(block: BlockRegistry, states?: Record<string, number>): PlacedModel {
let model: string | undefined;
let textures: BlockTextures | undefined;
let y: number | undefined;
let x: number | undefined;
let uvlock: boolean | undefined;
let shape: number[][] | undefined;
let collision_shape: number[][] | undefined;
if (block.variants && states) {
for (const [condition, override] of Object.entries(block.variants)) {
if (!variant_matches(condition, states)) continue;
model ??= override.model;
textures ??= override.textures;
y ??= override.y;
x ??= override.x;
uvlock ??= override.uvlock;
shape ??= override.shape;
collision_shape ??= override.collision_shape;
}
}
return {
model: model ?? block.model ?? DEFAULT_MODEL,
textures: textures ?? cube_textures(block),
y: y ?? 0,
x: x ?? 0,
uvlock: uvlock ?? false,
shape: shape ?? block.shape,
collision_shape: collision_shape ?? block.collision_shape,
};
}
// what a block is drawn with at a value with state bits: every matching part for a block made of parts, or its variant.
// parts take the variant's textures when they don't set their own
export function block_parts(block: BlockRegistry, states?: Record<string, number>): PlacedModel[] {
const variant = block_variant(block, states);
if (!block.parts) return [variant];
return block.parts
.filter((part) => variant_matches(part.when ?? "", states ?? {}))
.map((part) => ({
model: part.model,
textures: part.textures ?? variant.textures,
y: part.y ?? 0,
x: part.x ?? 0,
uvlock: part.uvlock ?? false,
shape: part.shape,
collision_shape: part.collision_shape,
}));
}
// whether it's a full cube in every state, so it hides what's behind it from light like minecraft's solid render
// shape. slabs, fences and pots aren't, even with collision
export function is_full_cube(block: BlockRegistry) {
const cube = (model: string | undefined) => (model ?? DEFAULT_MODEL) === DEFAULT_MODEL;
return !block.parts && !block.shape && cube(block.model) &&
Object.values(block.variants ?? {}).every((variant) => !variant.shape && cube(variant.model ?? block.model));
}
// whether how the block looks depends on its states, so it has to be worked out per value and not per block
export function looks_by_state(block: BlockRegistry) {
return block.variants !== undefined || block.parts !== undefined;
}
// the states of a value with state bits, by name
export function states_of(block: BlockRegistry, value: number): Record<string, number> {
const states: Record<string, number> = {};
for (const state of block.states ?? []) states[state.name] = get_state_value(value, block, state.name)!;
return states;
}
// every quad of the block at a value with state bits, its parts' quads together
export function bake_block(block: BlockRegistry, value: number, models: Record<string, ModelJson>): BakedQuad[] {
const states = looks_by_state(block) ? states_of(block, value) : undefined;
return block_parts(block, states).flatMap((part) => {
const model = find_model(part.model, models) ?? BUILTIN_MODELS[DEFAULT_MODEL];
return bake_model(model, part.textures, part.y, part.x, part.uvlock);
});
}
// "age=7" or "age=7,facing=2", "" matches everything
export function variant_matches(condition: string, states: Record<string, number>) {
if (condition === "") return true;
return condition.split(",").every((part) => {
const [name, value] = part.split("=");
return states[name.trim()] === Number(value);
});
}
// for inventories and dropped items: blocks with a full cube or an item_model draw as that model, anything else as a
// flat sprite of its first texture, like minecraft's items for plants
export function block_item_texture(block: BlockRegistry): string | undefined {
if (block.item_model !== undefined || (!block.parts && (block.model ?? DEFAULT_MODEL) === DEFAULT_MODEL)) {
return undefined;
}
const textures = block.textures;
if (typeof textures === "string") return textures;
return Object.values(textures)[0] ?? "cubi:missing";
}
export function cube_face_texture(block: BlockRegistry, face: "top" | "bottom" | "front" | "side") {
return resolve_texture(`#${face}`, cube_textures(block), BUILTIN_MODELS[DEFAULT_MODEL]);
}
// the block's textures as cubi:cube's. a fluid's { still, flowing } are its top and bottom, and its sides, for its
// item and its particles. the chunk mesher draws fluids itself
export function cube_textures(block: BlockRegistry): BlockTextures {
if (!block.fluid) return block.textures;
// through the variables, so a "tint" on still or flowing still finds them
return { ...fluid_textures(block.textures), top: "#still", bottom: "#still", side: "#flowing" };
}
// the color to draw a face of a block's item in, as r g b from 0 to 1. items aren't in a biome, so a biome "tint"
// gets the default grass or foliage color, like minecraft's grass block item
export function cube_face_tint(block: BlockRegistry, face: "top" | "bottom" | "front" | "side"): number[] {
return item_tint(block, texture_variables(`#${face}`, cube_textures(block), BUILTIN_MODELS[DEFAULT_MODEL]));
}
// the color to draw a part of a block's item in that got its texture through these variables, see cube_face_tint
export function item_tint(block: BlockRegistry, variables: string[]): number[] {
if (!is_tinted(block, variables)) return [1, 1, 1];
return color_rgb(tint_without_biome(block.tint!.color));
}
// how much darker each side of an item's model is drawn, like the mesher's: top, bottom, south, north, west, east
export const ITEM_FACE_SHADE = [1.0, 0.5, 0.8, 0.8, 0.6, 0.6];
// whether a face that got its texture through these variables is drawn in the block's tint
export function is_tinted(block: BlockRegistry, variables: string[]) {
if (!block.tint) return false;
return !block.tint.textures || block.tint.textures.some((name) => variables.includes(name));
}
// baking
export interface BakedQuad {
// 4 corners counter clockwise seen from the front, x y z in block space
positions: number[];
// u v per corner, in pixels of the texture (0-16)
uvs: number[];
texture: string;
// the texture variables it went through to get there, like ["front", "side"], for "tint"
variables: string[];
// the side it faces most, as the mesher's face index (see FACE_INDEX)
face: number;
// the side whose neighbor can hide it, or -1
cull: number;
// on the block's edge facing straight out, so it's lit like a full block's face
flush: boolean;
// flat on a plane facing straight along face's axis, so it can only be seen from that side of the plane.
// rotated quads, like the cross model's, aren't
aligned: boolean;
shade: boolean;
}
// the mesher's face order: top, bottom, front (+z), back (-z), left (-x), right (+x)
export const FACE_INDEX: Record<ModelFace, number> = { top: 0, bottom: 1, south: 2, north: 3, west: 4, east: 5 };
const FACE_NORMALS = [[0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1], [-1, 0, 0], [1, 0, 0]];
// each face's corners in drawing order as which end of the box they're at, same as the mesher
export const FACE_CORNERS = [
[[0, 1, 1], [1, 1, 1], [1, 1, 0], [0, 1, 0]],
[[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]],
[[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]],
[[1, 0, 0], [0, 0, 0], [0, 1, 0], [1, 1, 0]],
[[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]],
[[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]],
] as const;
// which end of the uv rectangle each corner gets, u then v
export const CORNER_UVS = [[0, 1], [1, 1], [1, 0], [0, 0]] as const;
// the face a face becomes after turning the model 90 degrees clockwise seen from above
const TURN_Y = [0, 1, 4, 5, 3, 2];
// the face a face becomes after a quarter turn around the east-west axis, the top tipping north: top to north, north to
// bottom, bottom to south and south to top
const TURN_X = [3, 2, 0, 1, 4, 5];
// a quarter turn's count for a turn of 0, 90, 180 or 270 degrees
const quarters = (degrees: number) => ((Math.round(degrees / 90) % 4) + 4) % 4;
// minecraft's default uvs: the part of the texture the face would cover if the texture was wrapped around the block
function default_uv(face: ModelFace, from: number[], to: number[]): [number, number, number, number] {
switch (face) {
case "top":
return [from[0], from[2], to[0], to[2]];
case "bottom":
return [from[0], 16 - to[2], to[0], 16 - from[2]];
case "north":
return [16 - to[0], 16 - to[1], 16 - from[0], 16 - from[1]];
case "south":
return [from[0], 16 - to[1], to[0], 16 - from[1]];
case "west":
return [from[2], 16 - to[1], to[2], 16 - from[1]];
case "east":
return [16 - to[2], 16 - to[1], 16 - from[2], 16 - from[1]];
}
}
const EPSILON = 1e-4;
// a model's quads with its textures, turned by x and then y like a block variant's turns, with uvlock or without
export function bake_model(
model: ModelJson,
textures: BlockTextures | undefined,
y_rotation = 0,
x_rotation = 0,
uvlock = false,
): BakedQuad[] {
const quads: BakedQuad[] = [];
const turns = quarters(y_rotation);
const x_turns = quarters(x_rotation);
for (const element of model.elements) {
const rotate = element_rotation(element);
for (const face of MODEL_FACES) {
const face_json = element.faces[face];
if (!face_json) continue;
const index = FACE_INDEX[face];
const uv = face_json.uv ?? default_uv(face, element.from, element.to);
// each corner takes the uv of the corner a quarter turn along, per 90 degrees
const uv_turns = Math.round((face_json.rotation ?? 0) / 90) % 4;
const lock_turns = uvlock ? uvlock_turns(index, x_turns, turns) : 0;
const positions: number[] = [];
const uvs: number[] = [];
FACE_CORNERS[index].forEach((corner, k) => {
let point = corner.map((end, axis) => (end ? element.to[axis] : element.from[axis]) / 16);
point = rotate(point);
for (let t = 0; t < x_turns; t++) point = [point[0], point[2], 1 - point[1]];
for (let t = 0; t < turns; t++) point = [1 - point[2], point[1], point[0]];
positions.push(...point);
const [cu, cv] = CORNER_UVS[(k + uv_turns) % 4];
let [u, v] = [cu ? uv[2] : uv[0], cv ? uv[3] : uv[1]];
// a quarter turn of the texture around its middle, which takes each of CORNER_UVS to the next
for (let t = 0; t < lock_turns; t++) [u, v] = [v, 16 - u];
uvs.push(u, v);
});
let cull = face_json.cullface ? FACE_INDEX[face_json.cullface] : -1;
for (let t = 0; t < x_turns && cull >= 0; t++) cull = TURN_X[cull];
for (let t = 0; t < turns && cull >= 0; t++) cull = TURN_Y[cull];
const { face: facing, flush, aligned } = classify_quad(positions);
quads.push({
positions,
uvs,
texture: resolve_texture(face_json.texture, textures, model),
variables: texture_variables(face_json.texture, textures, model),
face: facing,
cull,
flush,
aligned,
shade: element.shade ?? true,
});
}
}
return quads;
}
// how many corners along a face's corners end up on the face the model's turns take it to, which is how many quarter
// turns its texture needs to sit there like that face's texture on an unturned block. a face's default uvs (see
// default_uv) give its full face's corners CORNER_UVS in order, and turning keeps the order, so one corner says it
function uvlock_turns(face: number, x_turns: number, y_turns: number) {
let point: number[] = [...FACE_CORNERS[face][0]];
let turned = face;
for (let t = 0; t < x_turns; t++) {
point = [point[0], point[2], 1 - point[1]];
turned = TURN_X[turned];
}
for (let t = 0; t < y_turns; t++) {
point = [1 - point[2], point[1], point[0]];
turned = TURN_Y[turned];
}
return FACE_CORNERS[turned].findIndex((corner) => corner.every((end, axis) => end === point[axis]));
}
// turns a point (in block space) by the element's rotation
export function element_rotation(element: ModelElementJson): (point: number[]) => number[] {
const rotation = element.rotation;
if (!rotation || rotation.angle === 0) return (point) => point;
const axis = { x: 0, y: 1, z: 2 }[rotation.axis];
// the two axes that move, in the order that makes a positive angle counter clockwise looking down the axis
const [a, b] = axis === 0 ? [1, 2] : axis === 1 ? [2, 0] : [0, 1];
const radians = rotation.angle * Math.PI / 180;
const cos = Math.cos(radians);
const sin = Math.sin(radians);
// minecraft's rescale keeps a 45 degree face as wide as the block
const scale = rotation.rescale ? 1 / Math.max(Math.abs(cos), Math.abs(sin)) : 1;
const origin = rotation.origin.map((v) => v / 16);
return (point) => {
const out = [...point];
const da = point[a] - origin[a];
const db = point[b] - origin[b];
out[a] = origin[a] + (da * cos - db * sin) * scale;
out[b] = origin[b] + (da * sin + db * cos) * scale;
return out;
};
}
// which way a quad faces most, whether it's flat against the block's edge, and whether it faces straight along an axis
export function classify_quad(p: number[]): { face: number; flush: boolean; aligned: boolean } {
const e1 = [p[3] - p[0], p[4] - p[1], p[5] - p[2]];
const e2 = [p[9] - p[0], p[10] - p[1], p[11] - p[2]];
const normal = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
let face = 0;
let best = -Infinity;
FACE_NORMALS.forEach((n, i) => {
const dot = n[0] * normal[0] + n[1] * normal[1] + n[2] * normal[2];
if (dot > best) {
best = dot;
face = i;
}
});
const axis = FACE_NORMALS[face].findIndex((v) => v !== 0);
const edge = FACE_NORMALS[face][axis] > 0 ? 1 : 0;
const aligned = [1, 2, 3].every((k) => Math.abs(p[k * 3 + axis] - p[axis]) < EPSILON);
const flush = aligned && Math.abs(p[axis] - edge) < EPSILON;
return { face, flush, aligned };
}