Files
bworld/client/rendering/model_renderer.ts
T
2026-10-12 15:09:22 -03:00

44 lines
2.1 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// entity models' boxes, for mod entities and for what players wear. the atlas has to be the current texture
import type { Texture } from "$/client/renderer/mod.ts";
import type { SpriteRegion } from "$/common/constants.ts";
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
import { apply, bone_matrices, type Matrix, type Vec3 } from "./model_math.ts";
import { push_box, type VertexSink } from "./player_renderer.ts";
// pose is each bone's turn before its parent's, like a head looking or a limb swinging. to_world takes the model's
// pixels, after the bones are turned, to the world. the texture is region of the atlas, stretched to the model's
// texture size. only picks the bones drawn, all of them when not given. emit gets the vertices, the batch by default
export function push_model(
model: EntityModelJson,
pose: (bone: EntityBoneJson) => Matrix,
atlas: Texture,
region: SpriteRegion,
to_world: (x: number, y: number, z: number) => Vec3,
tint?: Vec3,
only?: (bone: EntityBoneJson) => boolean,
emit?: VertexSink,
) {
const to_uv = (u: number, v: number): [number, number] => [
(region.x + u * region.width / model.texture_width) / atlas.width,
(region.y + v * region.height / model.texture_height) / atlas.height,
];
const matrices = bone_matrices(model, pose);
for (const bone of model.bones) {
if (only && !only(bone)) continue;
const matrix = matrices.get(bone.name)!;
const transform = (px: number, py: number, pz: number) => to_world(...apply(matrix, px, py, pz));
for (const cube of bone.cubes) {
const inflate = cube.inflate ?? 0;
const [ox, oy, oz] = cube.origin;
const [w, h, d] = cube.size;
// bedrock models are mirrored on x from the engine's, like blockbench shows them: +x is the model's right
const low: Vec3 = [-(ox + w) - inflate, oy - inflate, oz - inflate];
const high: Vec3 = [-ox + inflate, oy + h + inflate, oz + d + inflate];
push_box(cube.size, low, high, cube.uv, to_uv, transform, tint, emit);
}
}
}