Curios slots rendering !

This commit is contained in:
2026-10-01 17:57:22 -03:00
parent ea9f3f61bb
commit f2c3cb8135
39 changed files with 1032 additions and 226 deletions
+3
View File
@@ -1,4 +1,5 @@
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
import { ItemStack } from "$/common/inventory.ts";
import type { ClientLevel } from "../level/client_level.ts";
import type { Texture } from "../renderer/mod.ts";
import { decode_skin } from "../skins.ts";
@@ -15,6 +16,8 @@ export abstract class Player extends Entity {
skin: Texture | undefined;
// 3 pixel wide arms, for skins made for them
slim = false;
// what they wear that shows, items with a worn model, see the server's player_worn
worn: ItemStack[] = [];
#skin_version = 0;
constructor(level: ClientLevel, id: string, name: string) {
+2
View File
@@ -1,5 +1,6 @@
import type { EntityEvent, PlayerInfo } from "$/common/protocol.ts";
import { TICK_DELTA } from "$/common/constants.ts";
import { ItemStack } from "$/common/inventory.ts";
import type { ClientLevel } from "../level/client_level.ts";
import { Player } from "./player.ts";
@@ -27,6 +28,7 @@ export class RemotePlayer extends Player {
if (info.skin) {
this.set_skin(info.skin, info.slim);
}
this.worn = (info.worn ?? []).map(ItemStack.from_data);
}
lerp_to(x: number, y: number, z: number, yaw: number, pitch: number) {
+7
View File
@@ -93,6 +93,13 @@ export class ClientPacketListener {
}
break;
}
case "player_worn": {
const player = level.entities.get(message.id);
if (player instanceof Player) {
player.worn = message.worn.map(ItemStack.from_data);
}
break;
}
case "player_skin": {
const player = level.entities.get(message.id);
if (player instanceof Player) {
+13 -82
View File
@@ -10,7 +10,9 @@ import { get_sprite_region } from "$/client/sprites.ts";
import type { SpriteRegion } from "$/common/constants.ts";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import type { EntityBoneJson, EntityJson, EntityModelJson } from "$/common/mod_data.ts";
import { HURT_TINT, push_box, type Vec3 } from "./player_renderer.ts";
import { HURT_TINT } from "./player_renderer.ts";
import { IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts";
import { push_model } from "./model_renderer.ts";
import { entity_tint } from "./entity_light.ts";
// models are in texture pixels, 16 to a block
@@ -31,42 +33,25 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_
const model = EverythingRegistry.get<EntityModelJson>("entity_models", json.model);
if (!model) return;
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 { x, y, z } = entity.render_position(partial_tick);
const yaw_sin = Math.sin(entity.yaw);
const yaw_cos = Math.cos(entity.yaw);
const to_world = (px: number, py: number, pz: number): Vec3 => {
const [mx, my, mz] = [px * PIXEL, py * PIXEL, pz * PIXEL];
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
};
const limbs = limb_angles(entity, partial_tick);
const bones = new Map<string, Matrix>();
for (const bone of model.bones) {
let matrix = bone_matrix(bone);
const pose = (bone: EntityBoneJson) => {
let matrix = IDENTITY;
if (bone.name === "head") {
const look = rotation_around(model_pivot(bone), entity.pitch, entity.head_yaw - entity.yaw, 0);
matrix = multiply(look, matrix);
matrix = rotation_around(model_pivot(bone), entity.pitch, entity.head_yaw - entity.yaw, 0);
}
const limb = limbs[bone.name];
if (limb) matrix = multiply(rotation_around(model_pivot(bone), limb, 0, 0), matrix);
if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix);
bones.set(bone.name, matrix);
const transform = (px: number, py: number, pz: number): Vec3 => {
const [mx, my, mz] = apply(matrix, px, py, pz).map((n) => n * PIXEL);
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
};
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);
}
}
return matrix;
};
push_model(model, pose, atlas, region, to_world, tint);
}
// how far each humanoid limb turns forward (radians), like minecraft's HumanoidModel.setupAnim: arms and legs swing
@@ -125,57 +110,3 @@ function render_sprite(
);
}
}
// 3 rows of 4, the last column moving: a turn and a move, from a bone's pixels to the model's
type Matrix = number[];
const IDENTITY: Matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
function model_pivot(bone: EntityBoneJson): Vec3 {
return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]];
}
// its own rotation around its pivot. mirroring x turns x and y rotations the other way
function bone_matrix(bone: EntityBoneJson): Matrix {
if (!bone.rotation) return IDENTITY;
const [rx, ry, rz] = bone.rotation.map((degrees) => degrees * Math.PI / 180);
return rotation_around(model_pivot(bone), -rx, -ry, rz);
}
// turns around pivot by x, then y, then z (radians). y turns like the whole model does (see render_mod_entity) and x
// like the player's head pitch
function rotation_around(pivot: Vec3, rx: number, ry: number, rz: number): Matrix {
const [sx, cx] = [Math.sin(rx), Math.cos(rx)];
const [sy, cy] = [Math.sin(ry), Math.cos(ry)];
const [sz, cz] = [Math.sin(rz), Math.cos(rz)];
const rot_x = [1, 0, 0, 0, 0, cx, -sx, 0, 0, sx, cx, 0];
const rot_y = [cy, 0, sy, 0, 0, 1, 0, 0, -sy, 0, cy, 0];
const rot_z = [cz, -sz, 0, 0, sz, cz, 0, 0, 0, 0, 1, 0];
const [px, py, pz] = pivot;
const rotation = multiply(rot_z, multiply(rot_y, rot_x));
return multiply(
[1, 0, 0, px, 0, 1, 0, py, 0, 0, 1, pz],
multiply(rotation, [1, 0, 0, -px, 0, 1, 0, -py, 0, 0, 1, -pz]),
);
}
// a after b
function multiply(a: Matrix, b: Matrix): Matrix {
const out: Matrix = [];
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 4; col++) {
let sum = col === 3 ? a[row * 4 + 3] : 0;
for (let k = 0; k < 3; k++) sum += a[row * 4 + k] * b[k * 4 + col];
out.push(sum);
}
}
return out;
}
function apply(m: Matrix, x: number, y: number, z: number): Vec3 {
return [
m[0] * x + m[1] * y + m[2] * z + m[3],
m[4] * x + m[5] * y + m[6] * z + m[7],
m[8] * x + m[9] * y + m[10] * z + m[11],
];
}
+9 -1
View File
@@ -7,7 +7,9 @@ import { AssetManager } from "$/client/assets.ts";
import type { LocalPlayer } from "$/client/entity/local_player.ts";
import { begin_view_model, end_mode_3d, flush_batch, set_current_texture, Texture } from "$/client/renderer/mod.ts";
import { item_block, push_item } from "./item_renderer.ts";
import { push_cube, right_arm, type Vec3 } from "./player_renderer.ts";
import { push_cube, type Vec3 } from "./player_renderer.ts";
import { right_arm } from "./player_model.ts";
import { render_worn_arm } from "./worn_renderer.ts";
import { entity_tint } from "./entity_light.ts";
// wider than the world's field of view, like minecraft's fixed 70 degrees for the hand
@@ -62,6 +64,12 @@ export class HandRenderer {
set_current_texture(skin.tex);
push_cube(skin, arm, arm.texture, 0, transform, tint);
push_cube(skin, arm, arm.overlay, arm.inflate, transform, tint);
// what's worn on it goes over it, from the atlas
if (player.worn.length > 0) {
flush_batch();
set_current_texture(AssetManager.instance.get<Texture>("bworld:textures").tex);
render_worn_arm(player, transform, tint);
}
}
flush_batch();
end_mode_3d();
+10 -2
View File
@@ -7,7 +7,10 @@ import type { Entity } from "$/client/entity/entity.ts";
import { RemotePlayer } from "$/client/entity/remote_player.ts";
import { ItemEntity } from "$/client/entity/item_entity.ts";
import { render_block_items, render_item_entity } from "./item_renderer.ts";
import { HURT_TINT, render_player } from "./player_renderer.ts";
import { HURT_TINT, player_pose, render_player } from "./player_renderer.ts";
import { render_worn } from "./worn_renderer.ts";
import type { PlayerPose } from "./player_model.ts";
import type { Vec3 } from "./model_math.ts";
import { render_mod_entity } from "./entity_renderer.ts";
import { entity_tint } from "./entity_light.ts";
import { RemoteEntity } from "$/client/entity/remote_entity.ts";
@@ -98,6 +101,8 @@ export class LevelRenderer {
render_entities(level: ClientLevel, camera: Camera, camera_entity: Entity, partial_tick: number) {
flush_batch();
const default_skin = AssetManager.instance.get<Texture>("bworld:skin");
// what they wear is drawn with the atlas, after every skin
const posed: { player: RemotePlayer; pose: PlayerPose; tint: Vec3 }[] = [];
for (const entity of level.entities.values()) {
if (entity !== camera_entity && entity instanceof RemotePlayer) {
const skin = entity.skin ?? default_skin;
@@ -106,12 +111,15 @@ export class LevelRenderer {
set_current_texture(skin.tex);
}
const tint = entity_tint(entity, partial_tick, entity.hurt_time > 0 ? HURT_TINT : undefined);
render_player(entity, skin, partial_tick, tint);
const pose = player_pose(entity, partial_tick);
render_player(skin, pose, tint);
posed.push({ player: entity, pose, tint });
}
}
flush_batch();
set_current_texture(level.image.tex);
for (const { player, pose, tint } of posed) render_worn(player, pose, tint);
for (const entity of level.entities.values()) {
if (entity instanceof ItemEntity) {
render_item_entity(entity, partial_tick);
+72
View File
@@ -0,0 +1,72 @@
// turning and moving the parts of models: entity models' bones, the player's parts and what's worn on them. no
// drawing here, so tests can use it
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
export type Vec3 = [number, number, number];
// 3 rows of 4, the last column moving: a turn and a move, from a bone's pixels to the model's
export type Matrix = number[];
export const IDENTITY: Matrix = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
// bedrock models are mirrored on x from the engine's, like blockbench shows them: +x is the model's right
export function model_pivot(bone: EntityBoneJson): Vec3 {
return [-bone.pivot[0], bone.pivot[1], bone.pivot[2]];
}
// its own rotation around its pivot. mirroring x turns x and y rotations the other way
export function bone_matrix(bone: EntityBoneJson): Matrix {
if (!bone.rotation) return IDENTITY;
const [rx, ry, rz] = bone.rotation.map((degrees) => degrees * Math.PI / 180);
return rotation_around(model_pivot(bone), -rx, -ry, rz);
}
// every bone's matrix: its own rotation, then pose's for it (like a head looking or a limb swinging), then its
// parent's. parents come before their children in the model
export function bone_matrices(model: EntityModelJson, pose: (bone: EntityBoneJson) => Matrix): Map<string, Matrix> {
const bones = new Map<string, Matrix>();
for (const bone of model.bones) {
let matrix = multiply(pose(bone), bone_matrix(bone));
if (bone.parent) matrix = multiply(bones.get(bone.parent) ?? IDENTITY, matrix);
bones.set(bone.name, matrix);
}
return bones;
}
// turns around pivot by x, then y, then z (radians). y turns like the whole model does and x like the player's head
// pitch
export function rotation_around(pivot: Vec3, rx: number, ry: number, rz: number): Matrix {
const [sx, cx] = [Math.sin(rx), Math.cos(rx)];
const [sy, cy] = [Math.sin(ry), Math.cos(ry)];
const [sz, cz] = [Math.sin(rz), Math.cos(rz)];
const rot_x = [1, 0, 0, 0, 0, cx, -sx, 0, 0, sx, cx, 0];
const rot_y = [cy, 0, sy, 0, 0, 1, 0, 0, -sy, 0, cy, 0];
const rot_z = [cz, -sz, 0, 0, sz, cz, 0, 0, 0, 0, 1, 0];
const [px, py, pz] = pivot;
const rotation = multiply(rot_z, multiply(rot_y, rot_x));
return multiply(
[1, 0, 0, px, 0, 1, 0, py, 0, 0, 1, pz],
multiply(rotation, [1, 0, 0, -px, 0, 1, 0, -py, 0, 0, 1, -pz]),
);
}
// a after b
export function multiply(a: Matrix, b: Matrix): Matrix {
const out: Matrix = [];
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 4; col++) {
let sum = col === 3 ? a[row * 4 + 3] : 0;
for (let k = 0; k < 3; k++) sum += a[row * 4 + k] * b[k * 4 + col];
out.push(sum);
}
}
return out;
}
export function apply(m: Matrix, x: number, y: number, z: number): Vec3 {
return [
m[0] * x + m[1] * y + m[2] * z + m[3],
m[4] * x + m[5] * y + m[6] * z + m[7],
m[8] * x + m[9] * y + m[10] * z + m[11],
];
}
+39
View File
@@ -0,0 +1,39 @@
// 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 } 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
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,
) {
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);
}
}
}
+188
View File
@@ -0,0 +1,188 @@
// minecraft's player model and how it's posed each frame, for drawing players and what they wear. no drawing here, so
// tests can use it
import { PLAYER_HEIGHT } from "$/common/constants.ts";
import { PLAYER_PARTS, type WornProperties } from "$/common/everything_registry.ts";
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
import { apply, IDENTITY, type Matrix, rotation_around, type Vec3 } from "./model_math.ts";
export type PartName = typeof PLAYER_PARTS[number];
// minecraft's player model is 32 skin pixels tall, it's scaled to the player's height
export const PIXEL = PLAYER_HEIGHT / 32;
// a part of minecraft's player model, like its ModelParts. sizes and positions are in skin pixels, the model faces
// -z with its right side towards +x and its feet at 0. each part is a box from `from` to `from + size` around the
// pivot it turns on, with its texture at `texture` in a 1.8 (64x64) skin and a second layer drawn a bit bigger
export interface ModelPart {
name: PartName;
size: Vec3;
pivot: Vec3;
from: Vec3;
texture: [number, number];
overlay: [number, number];
inflate: number;
}
export const PARTS: ModelPart[] = [
{
name: "head",
size: [8, 8, 8],
pivot: [0, 24, 0],
from: [-4, 0, -4],
texture: [0, 0],
overlay: [32, 0],
inflate: 0.5,
},
{
name: "body",
size: [8, 12, 4],
pivot: [0, 12, 0],
from: [-4, 0, -2],
texture: [16, 16],
overlay: [16, 32],
inflate: 0.25,
},
{
name: "right_arm",
size: [4, 12, 4],
pivot: [5, 22, 0],
from: [-1, -10, -2],
texture: [40, 16],
overlay: [40, 32],
inflate: 0.25,
},
{
name: "left_arm",
size: [4, 12, 4],
pivot: [-5, 22, 0],
from: [-3, -10, -2],
texture: [32, 48],
overlay: [48, 48],
inflate: 0.25,
},
{
name: "right_leg",
size: [4, 12, 4],
pivot: [2, 12, 0],
from: [-2, -12, -2],
texture: [0, 16],
overlay: [0, 32],
inflate: 0.25,
},
{
name: "left_leg",
size: [4, 12, 4],
pivot: [-2, 12, 0],
from: [-2, -12, -2],
texture: [16, 48],
overlay: [0, 48],
inflate: 0.25,
},
];
// slim (alex) skins have 3 pixel wide arms, half a pixel lower, like minecraft's PlayerModel with slim set
const SLIM_ARMS: ModelPart[] = [
{
name: "right_arm",
size: [3, 12, 4],
pivot: [5, 21.5, 0],
from: [-1, -10, -2],
texture: [40, 16],
overlay: [40, 32],
inflate: 0.25,
},
{
name: "left_arm",
size: [3, 12, 4],
pivot: [-5, 21.5, 0],
from: [-2, -10, -2],
texture: [32, 48],
overlay: [48, 48],
inflate: 0.25,
},
];
export const SLIM_PARTS = PARTS.map((part) => SLIM_ARMS.find((arm) => arm.name === part.name) ?? part);
// the right arm of the wide or slim model, for drawing it on its own in first person
export function right_arm(slim: boolean): ModelPart {
return (slim ? SLIM_PARTS : PARTS).find((part) => part.name === "right_arm")!;
}
// what a player's pose comes from, see Player and Entity.walk_animation
export interface PoseInput {
x: number;
y: number;
z: number;
yaw: number;
pitch: number;
walk: { position: number; speed: number };
slim: boolean;
}
// where a player is drawn this frame: each part's matrix, which turns its points (in skin pixels, around the model's
// feet, like a bone's) the way the part is turned, and where the model is
export interface PlayerPose {
x: number;
y: number;
z: number;
yaw: number;
slim: boolean;
parts: Record<PartName, Matrix>;
}
export function pose_at(input: PoseInput): PlayerPose {
// limbs swing opposite to each other, like minecraft's HumanoidModel.setupAnim
const swing = Math.cos(input.walk.position * 0.6662) * input.walk.speed;
const angles: Record<PartName, number> = {
head: input.pitch,
body: 0,
right_arm: -swing,
left_arm: swing,
right_leg: swing * 1.4,
left_leg: -swing * 1.4,
};
const parts = {} as Record<PartName, Matrix>;
for (const part of input.slim ? SLIM_PARTS : PARTS) {
parts[part.name] = rotation_around(part.pivot, angles[part.name], 0, 0);
}
return { x: input.x, y: input.y, z: input.z, yaw: input.yaw, slim: input.slim, parts };
}
// from the model's skin pixels to the world: scaled to the player's height, then turned to their yaw
export function pose_to_world(pose: PlayerPose): (x: number, y: number, z: number) => Vec3 {
const [sin, cos] = [Math.sin(pose.yaw), Math.cos(pose.yaw)];
return (px, py, pz) => {
const [mx, my, mz] = [px * PIXEL, py * PIXEL, pz * PIXEL];
return [pose.x + mx * cos + mz * sin, pose.y + my, pose.z - mx * sin + mz * cos];
};
}
// a point of a part, around its pivot like ModelPart.from, where it is in the pose, in the model's pixels
export function part_point(pose: PlayerPose, part: ModelPart, x: number, y: number, z: number): Vec3 {
const [px, py, pz] = part.pivot;
return apply(pose.parts[part.name], x + px, y + py, z + pz);
}
// the model and texture an item is drawn with on a player with or without slim arms
export function worn_look(worn: WornProperties, slim: boolean): { model: string; texture: string } {
if (slim && worn.slim_model) return { model: worn.slim_model, texture: worn.slim_texture ?? worn.texture };
return { model: worn.model, texture: (slim && worn.slim_texture) || worn.texture };
}
export function is_part(name: string): name is PartName {
return (PLAYER_PARTS as readonly string[]).includes(name);
}
// whether a bone is that part or under it, so it goes where the part goes
export function on_part(model: EntityModelJson, bone: EntityBoneJson, part: PartName): boolean {
for (let at: EntityBoneJson | undefined = bone; at; at = model.bones.find((b) => b.name === at!.parent)) {
if (at.name === part) return true;
}
return false;
}
// a worn model's bones: one named like a player part turns with it, around the part's pivot. the rest follow their
// parent, or stay with the body
export function worn_bone_pose(pose: PlayerPose): (bone: EntityBoneJson) => Matrix {
return (bone) => is_part(bone.name) ? pose.parts[bone.name] : IDENTITY;
}
+23 -130
View File
@@ -1,115 +1,24 @@
import { PLAYER_HEIGHT } from "$/common/constants.ts";
import type { Player } from "$/client/entity/player.ts";
import { push_vertex, type Texture } from "$/client/renderer/mod.ts";
import type { Vec3 } from "./model_math.ts";
import {
type ModelPart,
part_point,
PARTS,
type PlayerPose,
pose_at,
pose_to_world,
SLIM_PARTS,
} from "./player_model.ts";
export type Vec3 = [number, number, number];
export type { Vec3 };
// how much of each color is left while something flashes red after being hurt, like minecraft's
export const HURT_TINT: Vec3 = [1, 0.6, 0.6];
// minecraft's player model is 32 skin pixels tall, it's scaled to the player's height
const PIXEL = PLAYER_HEIGHT / 32;
// keeps nearest sampling from picking the texel next to a face's edge
const UV_INSET = 0.01;
// a part of minecraft's player model, like its ModelParts. sizes and positions are in skin pixels, the model faces
// -z with its right side towards +x and its feet at 0. each part is a box from `from` to `from + size` around the
// pivot it turns on, with its texture at `texture` in a 1.8 (64x64) skin and a second layer drawn a bit bigger
export interface ModelPart {
name: "head" | "body" | "right_arm" | "left_arm" | "right_leg" | "left_leg";
size: Vec3;
pivot: Vec3;
from: Vec3;
texture: [number, number];
overlay: [number, number];
inflate: number;
}
const PARTS: ModelPart[] = [
{
name: "head",
size: [8, 8, 8],
pivot: [0, 24, 0],
from: [-4, 0, -4],
texture: [0, 0],
overlay: [32, 0],
inflate: 0.5,
},
{
name: "body",
size: [8, 12, 4],
pivot: [0, 12, 0],
from: [-4, 0, -2],
texture: [16, 16],
overlay: [16, 32],
inflate: 0.25,
},
{
name: "right_arm",
size: [4, 12, 4],
pivot: [5, 22, 0],
from: [-1, -10, -2],
texture: [40, 16],
overlay: [40, 32],
inflate: 0.25,
},
{
name: "left_arm",
size: [4, 12, 4],
pivot: [-5, 22, 0],
from: [-3, -10, -2],
texture: [32, 48],
overlay: [48, 48],
inflate: 0.25,
},
{
name: "right_leg",
size: [4, 12, 4],
pivot: [2, 12, 0],
from: [-2, -12, -2],
texture: [0, 16],
overlay: [0, 32],
inflate: 0.25,
},
{
name: "left_leg",
size: [4, 12, 4],
pivot: [-2, 12, 0],
from: [-2, -12, -2],
texture: [16, 48],
overlay: [0, 48],
inflate: 0.25,
},
];
// slim (alex) skins have 3 pixel wide arms, half a pixel lower, like minecraft's PlayerModel with slim set
const SLIM_ARMS: ModelPart[] = [
{
name: "right_arm",
size: [3, 12, 4],
pivot: [5, 21.5, 0],
from: [-1, -10, -2],
texture: [40, 16],
overlay: [40, 32],
inflate: 0.25,
},
{
name: "left_arm",
size: [3, 12, 4],
pivot: [-5, 21.5, 0],
from: [-2, -10, -2],
texture: [32, 48],
overlay: [48, 48],
inflate: 0.25,
},
];
const SLIM_PARTS = PARTS.map((part) => SLIM_ARMS.find((arm) => arm.name === part.name) ?? part);
// the right arm of the wide or slim model, for drawing it on its own in first person
export function right_arm(slim: boolean): ModelPart {
return (slim ? SLIM_PARTS : PARTS).find((part) => part.name === "right_arm")!;
}
// a box's faces, like minecraft's ModelPart.Cube. `rect` is where the face is in the box's texture, which is laid
// out as in a skin: the top and bottom above the sides (right, front, left, back). corners go counter clockwise from
// outside as [x, y, z, u, v], 0 for the low end and 1 for the high one
@@ -152,36 +61,20 @@ const FACES: { rect: (w: number, h: number, d: number) => number[]; corners: num
},
];
// how a player is posed this frame, for drawing them and what they wear
export function player_pose(player: Player, partial_tick: number): PlayerPose {
const { x, y, z } = player.render_position(partial_tick);
const { yaw, pitch, slim } = player;
return pose_at({ x, y, z, yaw, pitch, slim, walk: player.walk_animation(partial_tick) });
}
// a player with a minecraft skin, like minecraft's PlayerRenderer. the skin has to be the current texture. tint
// multiplies its colors, for flashing red when hurt
export function render_player(player: Player, skin: Texture, partial_tick: number, tint?: Vec3) {
const { x, y, z } = player.render_position(partial_tick);
const yaw_sin = Math.sin(player.yaw);
const yaw_cos = Math.cos(player.yaw);
// limbs swing opposite to each other, like minecraft's HumanoidModel.setupAnim
const walk = player.walk_animation(partial_tick);
const swing = Math.cos(walk.position * 0.6662) * walk.speed;
const angles = {
head: player.pitch,
body: 0,
right_arm: -swing,
left_arm: swing,
right_leg: swing * 1.4,
left_leg: -swing * 1.4,
};
for (const part of player.slim ? SLIM_PARTS : PARTS) {
const sin = Math.sin(angles[part.name]);
const cos = Math.cos(angles[part.name]);
const [pivot_x, pivot_y, pivot_z] = part.pivot;
// turns around the pivot's x axis, then the whole model turns to the player's yaw
const transform = (px: number, py: number, pz: number): Vec3 => {
const mx = (px + pivot_x) * PIXEL;
const my = (py * cos - pz * sin + pivot_y) * PIXEL;
const mz = (py * sin + pz * cos + pivot_z) * PIXEL;
return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos];
};
export function render_player(skin: Texture, pose: PlayerPose, tint?: Vec3) {
const to_world = pose_to_world(pose);
for (const part of pose.slim ? SLIM_PARTS : PARTS) {
// from points around the part's pivot to where they are in the world
const transform = (x: number, y: number, z: number) => to_world(...part_point(pose, part, x, y, z));
push_cube(skin, part, part.texture, 0, transform, tint);
push_cube(skin, part, part.overlay, part.inflate, transform, tint);
}
+45
View File
@@ -0,0 +1,45 @@
// what players wear, like curios' render layer: each worn item's model (see WornProperties) on the player, its bones
// named like the player's parts turned the way those parts are, so it moves with them like minecraft's
// TransformCopyingHumanoidModel. see docs/modding/items/index.md
import { AssetManager } from "$/client/assets.ts";
import type { Player } from "$/client/entity/player.ts";
import type { Texture } from "$/client/renderer/mod.ts";
import { get_sprite_region } from "$/client/sprites.ts";
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import type { EntityBoneJson, EntityModelJson } from "$/common/mod_data.ts";
import { IDENTITY, type Vec3 } from "./model_math.ts";
import { push_model } from "./model_renderer.ts";
import { on_part, type PlayerPose, pose_to_world, right_arm, worn_bone_pose, worn_look } from "./player_model.ts";
// the atlas has to be the current texture. tint is the player's, for light and flashing red
export function render_worn(player: Player, pose: PlayerPose, tint?: Vec3) {
if (player.worn.length === 0) return;
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const to_world = pose_to_world(pose);
for (const stack of player.worn) {
const worn = EverythingRegistry.get<ItemRegistry>("items", stack.type_id)?.worn;
if (!worn) continue;
const look = worn_look(worn, pose.slim);
const model = EverythingRegistry.get<EntityModelJson>("entity_models", look.model);
if (!model) continue;
push_model(model, worn_bone_pose(pose), atlas, get_sprite_region(look.texture), to_world, tint);
}
}
// what's worn on a player's right arm, in first person, like artifacts' renderFirstPersonArm. transform is the arm's,
// from points around its pivot (see hand_renderer's arm_pose). the atlas has to be the current texture
export function render_worn_arm(player: Player, transform: (x: number, y: number, z: number) => Vec3, tint?: Vec3) {
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const [px, py, pz] = right_arm(player.slim).pivot;
// the model's pixels, standing still, to around the arm's pivot
const to_arm = (x: number, y: number, z: number) => transform(x - px, y - py, z - pz);
for (const stack of player.worn) {
const worn = EverythingRegistry.get<ItemRegistry>("items", stack.type_id)?.worn;
if (!worn) continue;
const look = worn_look(worn, player.slim);
const model = EverythingRegistry.get<EntityModelJson>("entity_models", look.model);
if (!model) continue;
const only = (bone: EntityBoneJson) => on_part(model, bone, "right_arm");
push_model(model, () => IDENTITY, atlas, get_sprite_region(look.texture), to_arm, tint, only);
}
}
+14
View File
@@ -163,6 +163,19 @@ export interface ToolProperties {
durability: number;
}
// how an item looks worn on a player, like bedrock's attachables: an entity model (see EntityModelJson) whose bones
// named like the player's parts (PLAYER_PARTS) move with them, drawn with a texture from the atlas. the slim ones are
// for players with 3 pixel wide arms, the others when not set. see docs/modding/items/index.md
export interface WornProperties {
model: string;
texture: string;
slim_model?: string;
slim_texture?: string;
}
// the parts of minecraft's player model, the bones of a worn model that move with them
export const PLAYER_PARTS = ["head", "body", "right_arm", "left_arm", "right_leg", "left_leg"] as const;
// what eating an item does, like minecraft's food properties
export interface FoodProperties {
// hunger points it restores, a bar is 20
@@ -187,6 +200,7 @@ export interface ItemRegistry<T = unknown | undefined> {
max_stack?: number;
lore?: string;
food?: FoodProperties;
worn?: WornProperties;
components?: Record<string, unknown>;
on_create?(item: ItemStack<T>): void;
+3
View File
@@ -215,6 +215,9 @@ export interface Player {
// what doesn't fit in the inventory drops at their feet
give_item(id: Id, count?: number, data?: unknown): void;
send_message(text: string): void;
// items drawn on them, under a key so each mod keeps its own list, like "bworld:curios". replaces what that key
// had, [] clears it. only items whose json has worn show. not saved: set it again when they join
set_worn(key: string, items: ItemStack[]): void;
teleport(x: number, y: number, z: number): void;
// health and hunger, like minecraft: 20 each, saturation is never above hunger. max_health is the
// bworld:max_health attribute
+24 -1
View File
@@ -13,6 +13,7 @@ import {
type TagJson,
type TagRegistry,
} from "./mod_data.ts";
import { PLAYER_PARTS } from "./everything_registry.ts";
import { BUILTIN_MODELS, type ModelJson } from "./block_models.ts";
import { resolve_tags } from "./tags.ts";
import { BIOMES } from "./worldgen/overworld.ts";
@@ -77,6 +78,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
const entity_owners = new Map<string, string[]>();
const entity_jsons = new Map<string, EntityJson>();
const entity_model_owners = new Map<string, string[]>();
const entity_model_jsons = new Map<string, EntityModelJson>();
const tag_owners = new Map<TagRegistry, Set<string>>();
const add = (map: Map<string, string[]>, id: string, mod: string) => map.set(id, [...(map.get(id) ?? []), mod]);
@@ -93,7 +95,10 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
add(entity_owners, json.id, mod.id);
entity_jsons.set(json.id, json);
}
for (const { json } of mod.entity_models) add(entity_model_owners, json.id, mod.id);
for (const { json } of mod.entity_models) {
add(entity_model_owners, json.id, mod.id);
entity_model_jsons.set(json.id, json);
}
for (const { json } of mod.tags) {
if (!tag_owners.has(json.registry)) tag_owners.set(json.registry, new Set());
tag_owners.get(json.registry)!.add(json.id);
@@ -177,6 +182,24 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
for (const texture of Object.values(json.data_textures ?? {})) uses(file, texture, "texture");
if (json.places) uses(file, json.places, "block");
if (json.food?.returns) uses(file, json.food.returns, "item");
if (json.worn) {
const { model, texture, slim_model, slim_texture } = json.worn;
for (const id of [model, slim_model]) {
if (id === undefined) continue;
uses(file, id, "entity model");
// nothing of it would move with the player
const bones = entity_model_jsons.get(id)?.bones;
if (bones && !bones.some((bone) => (PLAYER_PARTS as readonly string[]).includes(bone.name))) {
warnings.push(
`${file}: worn model ${id} has no bone named like a player part (${
PLAYER_PARTS.join(", ")
})`,
);
}
}
uses(file, texture, "texture");
if (slim_texture !== undefined) uses(file, slim_texture, "texture");
}
}
for (const { file, json } of mod.recipes) {
switch (json.type) {
+21
View File
@@ -9,6 +9,7 @@ import {
RENDER_LAYERS,
type RenderLayer,
type ToolProperties,
type WornProperties,
} from "./everything_registry.ts";
import { type BlockVariant, MODEL_FACES, type ModelFace } from "./block_models.ts";
import { expand_items, list_matches } from "./tags.ts";
@@ -101,6 +102,8 @@ export interface ItemJson {
places?: string;
max_stack?: number;
food?: FoodProperties;
// how it looks worn on a player
worn?: WornProperties;
name?: string;
lore?: string;
components?: Record<string, unknown>;
@@ -309,6 +312,7 @@ export function item_to_json(id: string, item: ItemRegistry): ItemJson {
if (item.block_id !== undefined) json.places = item.block_id;
if (item.max_stack !== undefined) json.max_stack = item.max_stack;
if (item.food !== undefined) json.food = item.food;
if (item.worn !== undefined) json.worn = item.worn;
if (item.name !== undefined) json.name = item.name;
if (item.lore !== undefined) json.lore = item.lore;
if (item.components) json.components = item.components;
@@ -322,6 +326,7 @@ export function item_from_json(json: ItemJson): ItemRegistry {
if (json.places !== undefined) item.block_id = json.places;
if (json.max_stack !== undefined) item.max_stack = json.max_stack;
if (json.food !== undefined) item.food = json.food;
if (json.worn !== undefined) item.worn = json.worn;
if (json.name !== undefined) item.name = json.name;
if (json.lore !== undefined) item.lore = json.lore;
if (json.components) item.components = json.components;
@@ -646,6 +651,22 @@ export function validate_item(json: unknown): Problems {
if (food.returns !== undefined) problems.push(...validate_id(food.returns, "food.returns"));
}
}
if (json.worn !== undefined) {
const worn = json.worn;
if (!is_object(worn)) {
problems.push("worn must be { model, texture }, an entity model and a texture");
} else {
problems.push(...validate_id(worn.model, "worn.model"), ...validate_id(worn.texture, "worn.texture"));
for (const field of ["slim_model", "slim_texture"]) {
if (worn[field] !== undefined) problems.push(...validate_id(worn[field], `worn.${field}`));
}
for (const field of Object.keys(worn)) {
if (!["model", "texture", "slim_model", "slim_texture"].includes(field)) {
problems.push(`worn.${field} isn't a field of worn`);
}
}
}
}
return problems;
}
+6 -1
View File
@@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air";
// bump when a client and server of different versions can't play together.
// the server rejects a different version before the client downloads anything
export const PROTOCOL_VERSION = 16;
export const PROTOCOL_VERSION = 17;
export interface PlayerInfo {
id: string;
@@ -21,6 +21,8 @@ export interface PlayerInfo {
skin?: string;
// the skin is for the model with 3 pixel wide arms
slim?: boolean;
// what they're wearing that shows, see player_worn
worn?: ItemData[];
}
// an entity that isn't a player, as the server first sends it. players have their own messages. items on the
@@ -156,6 +158,9 @@ export type ServerMessage =
| { type: "player_move"; id: string; x: number; y: number; z: number; yaw: number; pitch: number }
// a player changed their skin, including the one receiving it. without skin it's back to the default
| { type: "player_skin"; id: string; skin?: string; slim?: boolean }
// what a player wears that shows changed, to everyone including them: the items whose json has worn, see
// ctx's player.set_worn. also sent to a player right after join, for what they wear themselves
| { type: "player_worn"; id: string; worn: ItemData[] }
| { type: "add_entity"; entity: EntityInfo }
| {
type: "move_entity";
+10
View File
@@ -26,6 +26,7 @@ interface Player {
give_item(id: string, count?: number, data?: unknown): void; // what doesn't fit drops at their feet
send_message(text: string): void;
set_worn(key: string, items: ItemStack[]): void; // what's drawn on them, see Worn Items
teleport(x: number, y: number, z: number): void;
readonly health: number; // out of max_health
@@ -92,6 +93,15 @@ Like Minecraft, an attack right after the last one, or right after changing the
damage, rising to full after `20 / attack_speed` ticks. A bar under the crosshair shows it filling up, and the server
sends players their `attack_speed` whenever it changes so the bar matches.
## Worn Items
`set_worn(key, items)` says what a mod shows on a player, like the base game's curios slots do for what's in them. Each
mod uses its own key, like `"bworld:curios"`, and setting a key replaces its list, `[]` clears it. Only items whose JSON
has [`worn`](../items/index.md#worn-models) show.
Everyone is told what each player wears, the player too, and players joining later get it with the others. It isn't
saved: set it again when the player joins, the way the curios slots do.
## Death
When a player dies, everything they carried falls out where they died, and their tools lose durability (see
+37
View File
@@ -50,6 +50,7 @@ down to 0 is gone.
| `tool` | none | Makes it a [tool](tools.md). |
| `food` | none | Makes it [edible](food.md). |
| `data_textures` | none | Other textures, picked by the stack's `data`, see below. |
| `worn` | none | How it looks worn on a player, see [below](#worn-models). |
| `components` | none | [Item components](#item-components) and their parameters. |
### Textures From Data
@@ -63,6 +64,42 @@ is out:
A stack whose `data.cast` is truthy uses `bworld:fishing_rod_cast`. When several keys are, the first listed wins.
### Worn Models
`worn` says how an item looks on a player who wears it, like Bedrock's attachables. A server script says what a player
wears with [`set_worn`](../entities/players.md#worn-items), and every client draws it on them. There's no third person
view, so players see what others wear, and what's on their own right arm in first person. Artifacts' power glove and
feral claws (`mods/artifacts`) and the base game's giant chestplate are examples.
```json
"worn": {
"model": "artifacts:power_glove_wide",
"texture": "artifacts:power_glove_wide",
"slim_model": "artifacts:power_glove_slim",
"slim_texture": "artifacts:power_glove_slim"
}
```
| Field | Meaning |
| ---------------------------- | ----------------------------------------------------------------------------------------------------- |
| `model` | An [entity model](../entities/index.md#entity-models) from a `models/*.geo.json`, made in Blockbench. |
| `texture` | The texture it's drawn with, laid out for the model's `texture_width` and `texture_height`. |
| `slim_model`, `slim_texture` | Optional, for players with slim (3 pixel wide) arms. The others when not set. |
A bone named like a part of the player, `head`, `body`, `right_arm`, `left_arm`, `right_leg` or `left_leg`, moves with
that part, so a model made over Blockbench's player template lines up. check-mods warns about a model with none of them,
since nothing of it would move. Bones under one of them go with it, and other bones stay with the body.
Things to know when making one:
- **Armor** can use a Minecraft armor texture (64x32, like `textures/entity/equipment/humanoid/` in a mod's assets) as
it is: a box over each part, inflated by 1, with the UVs of Minecraft's armor model. The giant chestplate
(`mods/bworld/models/giant_chestplate.geo.json`) is `body` at `[16, 16]` and both arms at `[40, 16]`.
- **Blockbench's `mirror` isn't supported**, so a box's texture is never flipped. Minecraft mirrors the left arm's and
leg's armor, which here show the right one's texture as it is.
- **Porting a Java mod's model**, like Artifacts' `ArmsMeshDefinitions`: Java models measure y down from the top of the
head, bedrock up from the feet. Keep x and z, and make each y `24 - y`, with a box's origin at its bottom.
## Item Components
Like [block components](../blocks/components.md), item components give items behavior. The server script registers them:
+24 -3
View File
@@ -30,11 +30,14 @@ ores), server scripts (components, events, commands, timers, storage, recipes, c
NeoForge's (menu types, slots, data, buttons and `still_valid` on the server, menu screens on the client, and the
player's inventory as menu 0, which mods can add slots to), client scripts (item and recipe lookups, plain screens,
inventory overlays, `Graphics` in GUI pixels), mod channels, worldgen features and ores, the base game's block behavior
and screens as a mod, and world time. See [Menus](modding/inventories/menus.md) and [Screens](modding/gui/index.md).
and screens as a mod, world time, and worn items (an item's `worn` model, `player.set_worn`, synced to every client and
drawn on other players and on the first person arm). See [Menus](modding/inventories/menus.md),
[Screens](modding/gui/index.md) and [Worn Models](modding/items/index.md#worn-models).
The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.ts`, `common/bmod.ts`,
`server/game/mod_runtime.ts`, `server/game/menu.ts`, `server/load_bmods.ts`, `client/mods.ts`, `client/menu.ts` and
`common/worldgen_loader.ts`.
`server/game/mod_runtime.ts`, `server/game/menu.ts`, `server/load_bmods.ts`, `client/mods.ts`, `client/menu.ts`,
`common/worldgen_loader.ts`, and for worn items `client/rendering/worn_renderer.ts`, `player_model.ts` and
`model_math.ts`.
**In the API types but throwing:** forms, HUD elements, keybinds, `g.slider`, `register_terrain`.
@@ -47,6 +50,10 @@ The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.t
API, so a mod's bundled copy is a different class. Export it from `bworld/server`, or recognize it by `name`.
- Tools only lose durability when their owner dies. Nothing else uses it.
- The GUI scale is always 3: screens work in GUI pixels like NeoForge's, but there's no option to change it yet.
- Worn models haven't been looked at in the game yet, only tested: Artifacts' power glove and feral claws and the giant
chestplate on other players, wide and slim, and on the first person arm with its equip and swing.
- Blockbench's `mirror` isn't supported in entity models, so the giant chestplate's left sleeve has the right one's
texture unflipped.
## Planned API
@@ -222,6 +229,20 @@ if (!result.canceled && result.selection === 0) player.teleport(0, 100, 0);
- The engine checks every response against the form's definition (types, ranges, option counts, text length) before mod
code sees it.
### More Worn Items
Worn items are drawn by `render_worn`, which puts an item's `worn` model on a player's parts. The same can show more:
- **Mobs' equipment.** `EntityData.equipment` is already synced but never drawn. `render_worn` can draw it on mod
entities whose bones are named like a humanoid's, and held items in their `right_arm`, like Minecraft's
`ItemInHandLayer`.
- **Other players' held items**, in their right hand the same way.
- **Hiding curio slots**, like Curios' render toggles, sent by the client and kept by the curios script.
- **A third person view.** Players would see what they wear themselves with nothing else to change, the local player has
`worn` too.
- **Glint and glowing overlays**, as `glint` and a full bright `overlay_texture` in `worn`, once the renderer has a
glint pass.
### HUD, Keybinds and Mod Channels
- `ctx.hud.register(id, { on_render(g) })` draws every frame after the world, under open screens.
+5
View File
@@ -4,6 +4,11 @@
"id": "artifacts:feral_claws",
"texture": "artifacts:feral_claws",
"max_stack": 1,
"worn": {
"model": "artifacts:feral_claws_wide",
"texture": "artifacts:feral_claws_worn",
"slim_model": "artifacts:feral_claws_slim"
},
"components": {
"bworld:curio_modifiers": [
{ "attribute": "bworld:attack_speed", "amount": 0.3, "operation": "add_multiplied_base" }
+6
View File
@@ -4,6 +4,12 @@
"id": "artifacts:power_glove",
"texture": "artifacts:power_glove",
"max_stack": 1,
"worn": {
"model": "artifacts:power_glove_wide",
"texture": "artifacts:power_glove_wide",
"slim_model": "artifacts:power_glove_slim",
"slim_texture": "artifacts:power_glove_slim"
},
"components": {
"bworld:curio_modifiers": [
{ "attribute": "bworld:attack_damage", "amount": 4, "operation": "add_value" }
@@ -0,0 +1,40 @@
{
"format_version": "1.12.0",
"minecraft:geometry": [
{
"description": {
"identifier": "geometry.artifacts.feral_claws_slim",
"texture_width": 32,
"texture_height": 16
},
"bones": [
{
"name": "right_arm",
"pivot": [-5, 21.5, 0],
"cubes": [
{
"origin": [-6.5, 6.5, -1.5],
"size": [3, 5, 1],
"uv": [8, 0]
},
{
"origin": [-6.5, 6.5, 0.5],
"size": [3, 5, 1],
"uv": [8, 6]
},
{
"origin": [-7.5, 7.5, -1.5],
"size": [1, 4, 1],
"uv": [20, 0]
},
{
"origin": [-7.5, 7.5, 0.5],
"size": [1, 4, 1],
"uv": [20, 6]
}
]
}
]
}
]
}
@@ -0,0 +1,40 @@
{
"format_version": "1.12.0",
"minecraft:geometry": [
{
"description": {
"identifier": "geometry.artifacts.feral_claws_wide",
"texture_width": 32,
"texture_height": 16
},
"bones": [
{
"name": "right_arm",
"pivot": [-5, 22, 0],
"cubes": [
{
"origin": [-7.5, 7, -1.5],
"size": [3, 5, 1],
"uv": [8, 0]
},
{
"origin": [-7.5, 7, 0.5],
"size": [3, 5, 1],
"uv": [8, 6]
},
{
"origin": [-8.5, 8, -1.5],
"size": [1, 4, 1],
"uv": [20, 0]
},
{
"origin": [-8.5, 8, 0.5],
"size": [1, 4, 1],
"uv": [20, 6]
}
]
}
]
}
]
}
@@ -0,0 +1,32 @@
{
"format_version": "1.12.0",
"minecraft:geometry": [
{
"description": {
"identifier": "geometry.artifacts.power_glove_slim",
"texture_width": 32,
"texture_height": 32
},
"bones": [
{
"name": "right_arm",
"pivot": [-5, 21.5, 0],
"cubes": [
{
"origin": [-7, 11.5, -2],
"size": [3, 12, 4],
"uv": [16, 0],
"inflate": 0.5
},
{
"origin": [-7, 11.5, -2],
"size": [3, 12, 4],
"uv": [16, 16],
"inflate": 0.75
}
]
}
]
}
]
}
@@ -0,0 +1,32 @@
{
"format_version": "1.12.0",
"minecraft:geometry": [
{
"description": {
"identifier": "geometry.artifacts.power_glove_wide",
"texture_width": 32,
"texture_height": 32
},
"bones": [
{
"name": "right_arm",
"pivot": [-5, 22, 0],
"cubes": [
{
"origin": [-8, 12, -2],
"size": [4, 12, 4],
"uv": [16, 0],
"inflate": 0.5
},
{
"origin": [-8, 12, -2],
"size": [4, 12, 4],
"uv": [16, 16],
"inflate": 0.75
}
]
}
]
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 190 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 213 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 B

+30
View File
@@ -742,3 +742,33 @@ GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Curios. If not, see <https://www.gnu.org/licenses/>.
```
# The Undergarden
The giant chestplate's textures (`textures/giant_chestplate.png` and `textures/giant_chestplate_worn.png`) are utherium
armor's from [The Undergarden](https://github.com/quek04/undergarden) by quek, the 26.1 branch for NeoForge, which its
`neoforge.mods.toml` declares as MIT licensed:
```
MIT License
Copyright (c) quek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
+1
View File
@@ -4,6 +4,7 @@
"id": "bworld:giant_chestplate",
"texture": "bworld:giant_chestplate",
"max_stack": 1,
"worn": { "model": "bworld:giant_chestplate", "texture": "bworld:giant_chestplate_worn" },
"components": {
"bworld:curio_modifiers": [
{ "attribute": "bworld:max_health", "amount": 20, "operation": "add_value" }
@@ -0,0 +1,29 @@
{
"format_version": "1.12.0",
"minecraft:geometry": [
{
"description": {
"identifier": "geometry.bworld.giant_chestplate",
"texture_width": 64,
"texture_height": 32
},
"bones": [
{
"name": "body",
"pivot": [0, 24, 0],
"cubes": [{ "origin": [-4, 12, -2], "size": [8, 12, 4], "uv": [16, 16], "inflate": 1 }]
},
{
"name": "right_arm",
"pivot": [-5, 22, 0],
"cubes": [{ "origin": [-8, 12, -2], "size": [4, 12, 4], "uv": [40, 16], "inflate": 1 }]
},
{
"name": "left_arm",
"pivot": [5, 22, 0],
"cubes": [{ "origin": [4, 12, -2], "size": [4, 12, 4], "uv": [40, 16], "inflate": 1 }]
}
]
}
]
}
+8 -4
View File
@@ -1,7 +1,7 @@
// curios, from C4's Curios mod: accessory slots, in 2 columns left of the player's inventory. each player's curios are
// a container of their own, and fall out when they die like the rest of what they carry. items with the
// bworld:curio_modifiers component change the wearer's attributes, like curios' attribute modifiers
import type { AttributeModifier, Container, Player, ServerContext, TagApi } from "bworld/server";
import type { AttributeModifier, Container, ItemStack, Player, ServerContext, TagApi } from "bworld/server";
// where the left column of slots goes, from the inventory screen's left edge. the panel around them ends just left of it
const COLUMNS_X = -45;
@@ -43,16 +43,19 @@ export function register_curios(ctx: ServerContext) {
// keeps what their curios give them up to date
function watch(player: Player, curios: Container) {
stop_watching.get(player.id)?.();
stop_watching.set(player.id, curios.on_change(() => update_modifiers(player, curios)));
update_modifiers(player, curios);
stop_watching.set(player.id, curios.on_change(() => apply_worn(player, curios)));
apply_worn(player, curios);
}
function update_modifiers(player: Player, curios: Container) {
// what they wear: its attribute modifiers, and its worn model on them for everyone to see
function apply_worn(player: Player, curios: Container) {
for (const { attribute, id } of applied.get(player.id) ?? []) player.remove_modifier(attribute, id);
const now: { attribute: string; id: string }[] = [];
const worn: ItemStack[] = [];
for (const [index, slot] of SLOTS.entries()) {
const item = curios.get(index);
if (!item || !active.includes(slot)) continue;
worn.push(item);
for (const [i, { attribute, amount, operation }] of modifiers_of(item.id).entries()) {
const id = `bworld:curio/${slot}/${i}`;
player.add_modifier(attribute, { id, amount, operation });
@@ -60,6 +63,7 @@ export function register_curios(ctx: ServerContext) {
}
}
applied.set(player.id, now);
player.set_worn("bworld:curios", worn);
}
ctx.events.after.player_leave.subscribe(({ player }) => {
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

+15
View File
@@ -347,6 +347,7 @@ export class GameServer {
this.entities.sync();
for (const player of this.#players.values()) {
this.#sync_worn(player);
this.#sync(player);
}
this.#send_chunks();
@@ -728,6 +729,11 @@ export class GameServer {
time: this.world.time,
});
this.#players.set(conn, player);
// what they wear themselves, the others get it with player_join
player.worn_sent = JSON.stringify(player.worn_list());
if (player.worn_sent !== "[]") {
this.#send(player, { type: "player_worn", id: player.id, worn: player.worn_list() });
}
// the chunks come with the next ticks
this.#update_view(player);
this.#sync(player);
@@ -1555,6 +1561,15 @@ export class GameServer {
}
}
// what a player wears that shows, to everyone when it changed
#sync_worn(player: ServerPlayer) {
const worn = player.worn_list();
const json = JSON.stringify(worn);
if (json === player.worn_sent) return;
player.worn_sent = json;
this.#broadcast({ type: "player_worn", id: player.id, worn });
}
// tell the player what's really at a position, undoing anything their client guessed
#correct(player: ServerPlayer, x: number, y: number, z: number) {
if (y < 0 || y >= CHUNK_HEIGHT || !player.chunks.has_block(x, z)) {
+6
View File
@@ -931,6 +931,12 @@ function player_api(game: GameServer, player: ServerPlayer): Player {
send_message(text) {
game.send_chat(player, String(text));
},
set_worn(key, items) {
if (typeof key !== "string" || key.length === 0) throw new Error("set_worn needs a key, like \"mymod:hats\"");
if (!Array.isArray(items)) throw new Error("set_worn needs a list of items, [] for none");
if (items.length === 0) player.worn.delete(key);
else player.worn.set(key, items.map(new_stack));
},
teleport(x, y, z) {
game.teleport(player, x, y, z);
},
+13
View File
@@ -1,4 +1,5 @@
import { PLAYER_EYE_HEIGHT, PLAYER_HEIGHT, PLAYER_WIDTH } from "$/common/constants.ts";
import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import { Container, Cursor, ItemData, ItemStack } from "$/common/inventory.ts";
import type { GridRecipe } from "$/common/mod_data.ts";
import { Menu, PlayerMenu } from "./menu.ts";
@@ -66,6 +67,10 @@ export class ServerPlayer extends LivingEntity {
menu: Menu | undefined;
// the last menu id given out, they go 1 to 100 and around
menu_id = 0;
// what mods show on them, by each mod's key, see set_worn. not saved, mods set it again when they join
worn = new Map<string, ItemStack[]>();
// the json of the worn list everyone was last sent, to send it again when it changes
worn_sent = "[]";
// base64 png, see /skin. undefined is the default skin
skin: string | undefined;
// the skin is for the model with 3 pixel wide arms
@@ -186,9 +191,17 @@ export class ServerPlayer extends LivingEntity {
pitch: this.pitch,
skin: this.skin,
slim: this.slim || undefined,
...(this.worn_list().length ? { worn: this.worn_list() } : {}),
};
}
// what they wear that shows, every key's in the order they were first set: the items that have a worn model
worn_list(): ItemData[] {
return [...this.worn.values()].flat()
.filter((stack) => EverythingRegistry.get<ItemRegistry>("items", stack.type_id)?.worn)
.map((stack) => stack.to_data());
}
save_player(): SavedPlayer {
return {
x: this.x,
+55 -2
View File
@@ -1,7 +1,7 @@
// curios: accessory slots for items in the curios tags, next to the player's inventory, see
// mods/bworld/scripts/curios.ts
import { assert, assertEquals } from "@std/assert";
import { PLAYER_MENU_EXTRA } from "$/common/protocol.ts";
import { PLAYER_MENU_EXTRA, PROTOCOL_VERSION } from "$/common/protocol.ts";
import { copy_dir, test_game } from "./helpers.ts";
import type { WorldSave } from "$/server/game/saves.ts";
@@ -27,7 +27,20 @@ async function setup(save?: WorldSave) {
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
});
write("items/ring.json", { format_version: 1, item: { id: "jewelry:ring", texture: "bworld:coal" } });
// the ring shows on the player's right arm, the amulet doesn't show
const worn = { model: "jewelry:ring_worn", texture: "bworld:coal" };
write("items/ring.json", { format_version: 1, item: { id: "jewelry:ring", texture: "bworld:coal", worn } });
write("models/ring_worn.geo.json", {
format_version: "1.12.0",
"minecraft:geometry": [{
description: { identifier: "geometry.ring", texture_width: 16, texture_height: 16 },
bones: [{
name: "right_arm",
pivot: [-5, 22, 0],
cubes: [{ origin: [-8, 12, -2], size: [4, 1, 4], uv: [0, 0] }],
}],
}],
});
write("items/amulet.json", { format_version: 1, item: { id: "jewelry:amulet", texture: "bworld:coal" } });
write("tags/items/bworld/curios/ring.json", { format_version: 1, tag: { values: ["jewelry:ring"] } });
write("tags/items/bworld/curios/curio.json", { format_version: 1, tag: { values: ["jewelry:amulet"] } });
@@ -141,3 +154,43 @@ Deno.test("the giant chestplate goes in the body slot and gives 20 more health w
assertEquals(t.game.players()[0].max_health, 20);
assertEquals(t.game.players()[0].health, 20);
});
Deno.test("everyone sees what a player wears that has a worn model, and players joining later too", async () => {
const t = await setup();
const alice = t.game.players()[0].id;
t.join(2, "bob");
const worn_messages = (conn: number) => t.take(conn).filter((m: Msg) => m.type === "player_worn");
// the ring (given first) and the amulet, only the ring has a worn model
t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true });
t.send(1, { type: "click", menu: 0, slot: 1, button: 0, shift: true });
t.game.tick();
const ring = [{ id: alice, worn: [{ id: "jewelry:ring", count: 1 }] }];
for (const conn of [1, 2]) {
assertEquals(worn_messages(conn).map(({ id, worn }: Msg) => ({ id, worn })), ring);
}
t.game.tick();
assertEquals(worn_messages(2), [], "only sent when it changes");
// someone joining later gets it with the players already there
const carol = t.join(3, "carol");
assertEquals(carol.players.find((p: Msg) => p.id === alice).worn, ring[0].worn);
// rejoining wears it again: alice is told about herself, the others with player_join
t.game.on_disconnect(1);
t.take(2);
t.game.on_connect(1);
t.send(1, { type: "hello", name: "alice", protocol: PROTOCOL_VERSION });
t.send(1, { type: "ready" });
const messages = t.take(1);
const rejoined = messages.find((m: Msg) => m.type === "join");
assertEquals(messages.filter((m: Msg) => m.type === "player_worn").map((m: Msg) => m.worn), [ring[0].worn]);
const joined = t.take(2).find((m: Msg) => m.type === "player_join");
assertEquals(joined.player.worn, ring[0].worn);
// and taking it off
const ring_slot = PLAYER_MENU_EXTRA + curio_slot(t, "ring");
t.send(1, { type: "click", menu: 0, slot: ring_slot, button: 0, shift: true });
t.game.tick();
assertEquals(worn_messages(2).map((m: Msg) => [m.id, m.worn]), [[rejoined.id, []]]);
});
+57
View File
@@ -2,6 +2,7 @@ import { assert, assertEquals, assertThrows } from "@std/assert";
import { check_mods } from "$/tools/check_mods.ts";
import { MAX_TEXTURE_SIZE } from "$/common/constants.ts";
import { create_mod } from "$/tools/new_mod.ts";
import { item_from_json, item_to_json } from "$/common/mod_data.ts";
function temp_mods_dir() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_mods_" });
@@ -26,6 +27,21 @@ function write_json(path: string, value: unknown) {
Deno.writeTextFileSync(path, JSON.stringify(value));
}
// a blockbench model with one bone, a box like an arm's
function geo(bone: string) {
return {
format_version: "1.12.0",
"minecraft:geometry": [{
description: { identifier: "geometry.test", texture_width: 32, texture_height: 32 },
bones: [{
name: bone,
pivot: [-5, 22, 0],
cubes: [{ origin: [-8, 12, -2], size: [4, 12, 4], uv: [16, 0] }],
}],
}],
};
}
Deno.test("a mod made from the template passes the checks", async () => {
const dir = temp_mods_dir();
create_mod("copper_tools", "Copper Tools", dir);
@@ -82,6 +98,16 @@ Deno.test("check-mods finds broken mods", async () => {
});
// not json
Deno.writeTextFileSync(`${mod}/items/bad.json`, "{ nope");
// worn with a model that doesn't exist, as something that isn't { model, texture }, and with a model where nothing
// is named like a player part
const item = (id: string, worn: unknown) => ({ format_version: 1, item: { id, texture: "bworld:coal", worn } });
write_json(
`${mod}/items/ghost.json`,
item("broken:ghost", { model: "broken:no_such_worn", texture: "bworld:coal" }),
);
write_json(`${mod}/items/shapeless.json`, item("broken:shapeless", "broken:hat"));
write_json(`${mod}/items/stiff.json`, item("broken:stiff", { model: "broken:stiff", texture: "bworld:coal" }));
write_json(`${mod}/models/stiff.geo.json`, geo("hat"));
// uses a letter the key doesn't define
write_json(`${mod}/recipes/bad.json`, {
format_version: 1,
@@ -120,7 +146,38 @@ Deno.test("check-mods finds broken mods", async () => {
has(report.errors, "textures/huge.png: is");
has(report.errors, "scripts don't typecheck");
has(report.errors, `depends on "missing_mod", which isn't installed`);
has(report.errors, "entity model broken:no_such_worn doesn't exist");
has(report.errors, "worn must be { model, texture }");
has(report.warnings, "worn model broken:stiff has no bone named like a player part");
has(report.warnings, "texture broken:nope doesn't exist");
has(report.warnings, `uses bworld:stone but doesn't list "bworld" in dependencies`);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("an item can say how it looks worn, with a model for slim arms too", async () => {
const dir = temp_mods_dir();
create_mod("gloves", "Gloves", dir);
const mod = `${dir}/gloves`;
Deno.mkdirSync(`${mod}/models`);
write_json(`${mod}/models/glove_wide.geo.json`, geo("right_arm"));
write_json(`${mod}/models/glove_slim.geo.json`, geo("right_arm"));
const worn = {
model: "gloves:glove_wide",
texture: "gloves:example_item",
slim_model: "gloves:glove_slim",
slim_texture: "gloves:example_item",
};
write_json(`${mod}/items/glove.json`, {
format_version: 1,
item: { id: "gloves:glove", texture: "gloves:example_item", worn },
});
const report = (await check_mods(dir)).find((r) => r.id === "gloves")!;
assertEquals(report.errors, []);
assertEquals(report.warnings, []);
// and the registry, which clients draw from, has it
const glove = JSON.parse(Deno.readTextFileSync(`${mod}/items/glove.json`)).item;
assertEquals(item_from_json(glove).worn, worn);
assertEquals(item_to_json("gloves:glove", item_from_json(glove)).worn, worn);
Deno.removeSync(dir, { recursive: true });
});
+113
View File
@@ -0,0 +1,113 @@
// what players wear is drawn on their parts, moving with them, see client/rendering/worn_renderer.ts
import { assertAlmostEquals, assertEquals, assertNotEquals } from "@std/assert";
import { entity_model_from_geo } from "$/common/mod_data.ts";
import { apply, bone_matrices, type Vec3 } from "$/client/rendering/model_math.ts";
import {
on_part,
part_point,
PARTS,
pose_at,
SLIM_PARTS,
worn_bone_pose,
worn_look,
} from "$/client/rendering/player_model.ts";
// a glove made over blockbench's player template: its right arm's box, and a claw on a bone under it
const glove = entity_model_from_geo({
format_version: "1.12.0",
"minecraft:geometry": [{
description: { identifier: "geometry.glove", texture_width: 32, texture_height: 32 },
bones: [
{ name: "right_arm", pivot: [-5, 22, 0], cubes: [{ origin: [-8, 12, -2], size: [4, 12, 4], uv: [0, 0] }] },
{ name: "claw", parent: "right_arm", pivot: [-6, 12, 0], cubes: [] },
],
}],
}, "test:glove").model!;
const walking = (position: number, slim = false) =>
pose_at({ x: 0, y: 0, z: 0, yaw: 0, pitch: 0, slim, walk: { position, speed: 1 } });
const near = (actual: Vec3, expected: Vec3) => actual.forEach((n, i) => assertAlmostEquals(n, expected[i], 1e-9));
Deno.test("a worn bone named like a player part moves with that part as they walk", () => {
const arm = PARTS.find((part) => part.name === "right_arm")!;
const corners: Vec3[][] = [];
for (const position of [0, 1.5, 3]) {
const pose = walking(position);
const bones = bone_matrices(glove, worn_bone_pose(pose));
// the cube's corners, mirrored on x into the engine's axes like the renderer does, are the arm's corners
const low = apply(bones.get("right_arm")!, 4, 12, -2);
const high = apply(bones.get("right_arm")!, 8, 24, 2);
near(low, part_point(pose, arm, -1, -10, -2));
near(high, part_point(pose, arm, 3, 2, 2));
// and the bone under it goes along
near(apply(bones.get("claw")!, 6, 12, 0), apply(bones.get("right_arm")!, 6, 12, 0));
corners.push([low, high]);
}
assertNotEquals(corners[0], corners[1], "it swung");
});
Deno.test("slim players wear the slim model, on their slim arms", () => {
const worn = { model: "a:wide", texture: "a:wide_texture", slim_model: "a:slim", slim_texture: "a:slim_texture" };
assertEquals(worn_look(worn, false), { model: "a:wide", texture: "a:wide_texture" });
assertEquals(worn_look(worn, true), { model: "a:slim", texture: "a:slim_texture" });
// without slim ones, the wide ones
assertEquals(worn_look({ model: "a:wide", texture: "a:t" }, true), { model: "a:wide", texture: "a:t" });
// the slim arm turns around its own pivot, half a pixel lower
const slim_arm = SLIM_PARTS.find((part) => part.name === "right_arm")!;
const pose = walking(1.5, true);
const bones = bone_matrices(glove, worn_bone_pose(pose));
near(apply(bones.get("right_arm")!, ...slim_arm.pivot), slim_arm.pivot);
});
Deno.test("first person draws the bones on the right arm, and the ones under them", () => {
const [arm, claw] = glove.bones;
assertEquals([on_part(glove, arm, "right_arm"), on_part(glove, claw, "right_arm")], [true, true]);
assertEquals(on_part(glove, arm, "left_arm"), false);
});
// artifacts' models, see mods/artifacts/models: a cube's box in the engine's axes, mirrored like the renderer does
const artifact = (name: string) => {
const json = JSON.parse(Deno.readTextFileSync(`mods/artifacts/models/${name}.geo.json`));
return entity_model_from_geo(json, `artifacts:${name}`).model!;
};
const box = (
{ origin: [x, y, z], size: [w, h, d] }: { origin: Vec3; size: Vec3 },
) => [[-(x + w), y, z], [-x, y + h, z + d]];
Deno.test("artifacts' power glove is a sleeve over the right arm, wide and slim", () => {
for (const [name, parts] of [["power_glove_wide", PARTS], ["power_glove_slim", SLIM_PARTS]] as const) {
const arm = parts.find((part) => part.name === "right_arm")!;
const from = arm.from.map((n, i) => n + arm.pivot[i]);
const arm_box = [from, from.map((n, i) => n + arm.size[i])];
for (const cube of artifact(name).bones[0].cubes) assertEquals(box(cube), arm_box, name);
}
});
Deno.test("artifacts' feral claws come out of the bottom of the right hand, wide and slim", () => {
for (const [name, parts] of [["feral_claws_wide", PARTS], ["feral_claws_slim", SLIM_PARTS]] as const) {
const arm = parts.find((part) => part.name === "right_arm")!;
const hand = arm.pivot[1] + arm.from[1];
const claws = artifact(name).bones[0].cubes.map(box);
// they hang from the hand, the long ones across the arm. on slim arms they're half a pixel off its middle, like
// in artifacts' ArmsMeshDefinitions
for (const [, high] of claws) assertEquals(high[1], hand, name);
const [left, right] = [arm.pivot[0] + arm.from[0], arm.pivot[0] + arm.from[0] + arm.size[0]];
for (const [low, high] of claws.slice(0, 2)) {
assertEquals(Math.abs((low[0] + high[0]) / 2 - (left + right) / 2) <= 0.5, true, name);
}
}
});
Deno.test("the giant chestplate covers the player's body and arms, a pixel out like minecraft's armor", () => {
const json = JSON.parse(Deno.readTextFileSync("mods/bworld/models/giant_chestplate.geo.json"));
const chestplate = entity_model_from_geo(json, "bworld:giant_chestplate").model!;
for (const bone of chestplate.bones) {
const part = PARTS.find((part) => part.name === bone.name)!;
const from = part.from.map((n, i) => n + part.pivot[i]);
assertEquals(box(bone.cubes[0]), [from, from.map((n, i) => n + part.size[i])], bone.name);
assertEquals(bone.cubes[0].inflate, 1);
}
assertEquals(chestplate.bones.map((bone) => bone.name), ["body", "right_arm", "left_arm"]);
});