Animation clips

This commit is contained in:
2026-11-21 20:07:10 -03:00
parent 607be76ca6
commit 69ad4b80d0
10 changed files with 514 additions and 6 deletions
+4
View File
@@ -8,6 +8,7 @@ import type { ModelFileJson } from "./block_models.ts";
import { MAX_ANIMATED_TEXTURE_SIZE, MAX_TEXTURE_SIZE } from "./constants.ts";
import {
type BlockJson,
type ClipJson,
type EffectJson,
type EntityJson,
type EntityModelJson,
@@ -19,6 +20,7 @@ import {
type SpawnJson,
type TagJson,
validate_block,
validate_clip,
validate_effect,
validate_entity,
validate_entity_model,
@@ -189,6 +191,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
validate_entity_model,
problems,
) as EntityModelJson[],
animations: checked(raw_data.animations, "animations", validate_clip, problems) as ClipJson[],
effects: checked(raw_data.effects, "effects", validate_effect, problems) as EffectJson[],
fluids: checked(raw_data.fluids, "fluids", validate_fluid, problems) as FluidJson[],
tags: checked(raw_data.tags, "tags", validate_tag, problems) as TagJson[],
@@ -228,6 +231,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
...data.items,
...data.entities,
...data.entity_models,
...data.animations!,
...data.effects,
...data.fluids,
];
+4
View File
@@ -6,6 +6,7 @@
import {
type BlockJson,
choice_list,
type ClipJson,
type EffectJson,
entity_category,
type EntityJson,
@@ -64,6 +65,8 @@ export interface LoadedMod {
spawns: { file: string; json: SpawnJson }[];
entities: { file: string; json: EntityJson }[];
entity_models: { file: string; json: EntityModelJson }[];
// clips, see ANIMATION.md
animations: { file: string; json: ClipJson }[];
effects: { file: string; json: EffectJson }[];
fluids: { file: string; json: FluidJson }[];
tags: { file: string; json: TagJson }[];
@@ -98,6 +101,7 @@ export function mod_data(mod: LoadedMod): ModData {
spawns: mod.spawns.map((s) => s.json),
entities: mod.entities.map((e) => e.json),
entity_models: mod.entity_models.map((m) => m.json),
animations: mod.animations.map((a) => a.json),
effects: mod.effects.map((e) => e.json),
fluids: mod.fluids.map((f) => f.json),
tags: mod.tags.map((t) => t.json),
+184
View File
@@ -574,6 +574,37 @@ const entity_model_schema = z.object({
export type EntityModelJson = z.infer<typeof entity_model_schema>;
// a channel's value at a time in seconds. pre is what it comes into the keyframe at and post what it leaves at, the
// same unless it jumps there. smooth is catmullrom to and from it, linear otherwise
const clip_keyframe = z.object({ time: z.number().min(0), pre: vec3, post: vec3, smooth: z.boolean() });
export type ClipKeyframe = z.infer<typeof clip_keyframe>;
const clip_channel = z.array(clip_keyframe).min(1).refine(
(keyframes) => keyframes.every((keyframe, i) => i === 0 || keyframes[i - 1].time <= keyframe.time),
"keyframes must be in time order",
);
// an entity model animation (one of those in animations/<name>.animation.json) with only what the engine uses, see
// ANIMATION.md. values are as bedrock has them, mirrored on x from the engine's like models: rotation in degrees,
// added to a bone's own, position in pixels, and scale multiplying
const clip_schema = z.object({
id: z.string('must be a clip id like "my_mod:thing/walk"').regex(TAG_ID_PATTERN),
// seconds
length: z.number().min(0),
loop: z.boolean(),
bones: z.record(
z.string(),
z.object({
rotation: clip_channel.optional(),
position: clip_channel.optional(),
scale: clip_channel.optional(),
}),
),
});
export type ClipJson = z.infer<typeof clip_schema>;
// something in a tag file's values or remove: an id, a "#tag", or either with whether it must exist. a plain one must
const tag_entry = z.union(
[id_or_tag, z.object({ id: id_or_tag, required: z.boolean().optional() })],
@@ -982,6 +1013,159 @@ export function entity_model_from_geo(json: unknown, id: string): { model?: Enti
return problems.length === 0 ? { model: model as EntityModelJson, problems } : { problems };
}
export function validate_clip(json: unknown): Problems {
return find_problems(clip_schema, json);
}
// what a bedrock animation can have that clips leave to an animator's code
const ANIMATOR_FIELDS = [
"anim_time_update",
"blend_weight",
"start_delay",
"loop_delay",
"override_previous_animation",
"sound_effects",
"particle_effects",
"timeline",
];
// an animations/<name>.animation.json, as blockbench exports it for bedrock, to its clips. each is <file_id>/ and the
// last part of its name, so animation.jester.walk in dangerous_business:jester is dangerous_business:jester/walk.
// warnings are what it has that clips don't use
export function clips_from_bedrock(
json: unknown,
file_id: string,
): { clips: ClipJson[]; problems: Problems; warnings: Problems } {
const problems: Problems = [];
const warnings: Problems = [];
if (!is_object(json) || !is_object(json.animations)) {
problems.push('must be a bedrock animation file: { "animations": { "animation.thing.walk": { ... } } }');
return { clips: [], problems, warnings };
}
const clips: ClipJson[] = [];
for (const [name, animation] of Object.entries(json.animations)) {
const problem = (message: string) => problems.push(`${name}: ${message}`);
const id = `${file_id}/${name.split(".").at(-1)!.toLowerCase()}`;
if (clips.some((clip) => clip.id === id)) {
problem(`its id ${id} is another animation's too`);
continue;
}
if (!is_object(animation)) {
problem("must be an object");
continue;
}
for (const field of ANIMATOR_FIELDS) {
if (field in animation) warnings.push(`${name}: ${field} isn't used, an animator does that in code`);
}
if (![undefined, true, false, "hold_on_last_frame"].includes(animation.loop as string)) {
problem('loop must be true, false or "hold_on_last_frame"');
}
const length = animation.animation_length;
if (length !== undefined && (typeof length !== "number" || length < 0)) {
problem("animation_length must be a number of seconds");
}
const bones: ClipJson["bones"] = {};
let last = 0;
for (const [bone, channels] of Object.entries(is_object(animation.bones) ? animation.bones : {})) {
if (!is_object(channels)) {
problem(`${bone} must be an object of channels`);
continue;
}
const read: ClipJson["bones"][string] = {};
for (const [channel, value] of Object.entries(channels)) {
if (channel !== "rotation" && channel !== "position" && channel !== "scale") {
warnings.push(`${name}: ${bone}'s ${channel} isn't used`);
continue;
}
const keyframes = read_channel(value, (message) => problem(`${bone} ${channel}: ${message}`));
if (!keyframes) continue;
read[channel] = keyframes;
last = Math.max(last, keyframes.at(-1)!.time);
}
bones[bone] = read;
}
const clip = { id, length: typeof length === "number" ? length : last, loop: animation.loop === true, bones };
for (const message of validate_clip(clip)) problem(message);
clips.push(clip);
}
return { clips: problems.length === 0 ? clips : [], problems, warnings };
}
// a channel: one value for the whole clip, or keyframes by time in seconds
function read_channel(value: unknown, problem: (message: string) => void): ClipKeyframe[] | undefined {
const single = !is_object(value) || "pre" in value || "post" in value || "vector" in value;
if (single) {
const keyframe = read_keyframe(0, value, problem);
return keyframe && [keyframe];
}
const keyframes: ClipKeyframe[] = [];
for (const [time, keyframe_value] of Object.entries(value)) {
const seconds = Number(time);
if (time.trim() === "" || !(seconds >= 0)) {
problem(`${time} isn't a time in seconds`);
return undefined;
}
const keyframe = read_keyframe(seconds, keyframe_value, (message) => problem(`at ${time}: ${message}`));
if (!keyframe) return undefined;
keyframes.push(keyframe);
}
if (keyframes.length === 0) {
problem("has no keyframes");
return undefined;
}
return keyframes.sort((a, b) => a.time - b.time);
}
// a value, { "pre": value, "post": value, "lerp_mode": ... } with either of pre and post, or geckolib's older
// { "vector": value, "easing": ... }
function read_keyframe(time: number, value: unknown, problem: (message: string) => void): ClipKeyframe | undefined {
if (!is_object(value)) {
const vector = read_vector(value, problem);
return vector && { time, pre: vector, post: vector, smooth: false };
}
const lerp = "vector" in value ? value.easing : value.lerp_mode;
if (lerp !== undefined && lerp !== "linear" && lerp !== "catmullrom") {
problem(`${"vector" in value ? "easing" : "lerp_mode"} ${JSON.stringify(lerp)} isn't supported`);
return undefined;
}
if ("vector" in value) {
const vector = read_vector(value.vector, problem);
return vector && { time, pre: vector, post: vector, smooth: lerp === "catmullrom" };
}
if (value.pre === undefined && value.post === undefined) {
problem("needs pre or post");
return undefined;
}
const pre = read_vector(value.pre ?? value.post, problem);
const post = read_vector(value.post ?? value.pre, problem);
return pre && post && { time, pre, post, smooth: lerp === "catmullrom" };
}
// [x, y, z], or one number for all three. numbers can be written as text, but not expressions, which are code
function read_vector(value: unknown, problem: (message: string) => void): [number, number, number] | undefined {
if (!Array.isArray(value)) {
const number = read_number(value, problem);
return number === undefined ? undefined : [number, number, number];
}
if (value.length !== 3) {
problem("must be [x, y, z] or a number");
return undefined;
}
const numbers = value.map((part) => read_number(part, problem));
return numbers.every((number) => number !== undefined) ? numbers as [number, number, number] : undefined;
}
function read_number(value: unknown, problem: (message: string) => void): number | undefined {
const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
if (typeof number === "number" && Number.isFinite(number)) return number;
problem(
typeof value === "string"
? `${JSON.stringify(value)} is an expression, which clips can't run: an animator does that in code`
: "must be [x, y, z] or a number",
);
return undefined;
}
// a tag file's contents, with the registry and id its path gives it
export function validate_tag(json: unknown): Problems {
return find_problems(tag_schema, json);
+6
View File
@@ -10,6 +10,7 @@ import {
choice_ids,
choice_list,
choice_problems,
ClipJson,
EffectJson,
EntityJson,
EntityModelJson,
@@ -59,6 +60,8 @@ export interface ModData {
spawns: SpawnJson[];
entities: EntityJson[];
entity_models: EntityModelJson[];
// clips, see ANIMATION.md. missing from mods packed before there were any
animations?: ClipJson[];
// status effects, see EffectJson
effects: EffectJson[];
// kinds of fluid, see FluidJson
@@ -224,6 +227,9 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
for (const model of data.entity_models) {
EverythingRegistry.register<EntityModelJson>("entity_models", model.id, model);
}
for (const clip of data.animations ?? []) {
EverythingRegistry.register<ClipJson>("animations", clip.id, clip);
}
for (const json of data.entities) {
EverythingRegistry.register<EntityJson>("entities", json.id, json);
}
+1
View File
@@ -98,6 +98,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise<LoadedBundle>
spawns: [],
entities: [],
entity_models: [],
animations: [],
effects: [],
fluids: [],
loot_tables: [],