// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later // clips: bedrock animation files read into them, sampled at a time, and what they do to a model's bones import { assert, assertAlmostEquals, assertEquals, assertStringIncludes } from "@std/assert"; import { type ClipJson, clips_from_bedrock, entity_model_from_geo, type EntityModelJson } from "@/common/mod_data.ts"; import { sample_channel, sample_clip } from "@/client/rendering/animation.ts"; import { apply, bone_matrices, type BoneOffsets, IDENTITY, type Vec3 } from "@/client/rendering/model_math.ts"; import { create_mod } from "@/tools/new_mod.ts"; import { load_and_check } from "@/tools/check_mods.ts"; import { type AnimatedEntity, AnimationState, type Clip, type EntityAnimator } from "@/common/mod_api/client.ts"; import { animation_for, type AnimatorSource, entity_animators } from "@/client/rendering/entity_animators.ts"; import { EverythingRegistry } from "@/common/everything_registry.ts"; import type { EntityData } from "@/common/protocol.ts"; import { copy_dir, errors_during, test_game, test_mob } from "./helpers.ts"; // the one clip a file with one animation reads into function one_clip(animation: unknown): ClipJson { const { clips, problems } = clips_from_bedrock({ animations: { "animation.test.move": animation } }, "a:test"); assertEquals(problems, []); return clips[0]; } function problems_of(animation: unknown) { return clips_from_bedrock({ animations: { "animation.test.move": animation } }, "a:test").problems; } const key = (time: number, value: Vec3, smooth = false, post = value) => ({ time, pre: value, post, smooth }); Deno.test("every way bedrock writes a value reads into the same keyframe", () => { const at_zero = (value: unknown) => one_clip({ bones: { arm: { rotation: { "0.0": value } } } }).bones.arm.rotation; const expected = [key(0, [5, 5, 5])]; for (const value of [5, "5", [5, 5, 5], ["5", 5, 5.0], { post: [5, 5, 5] }, { pre: 5 }, { vector: [5, 5, 5] }]) { assertEquals(at_zero(value), expected, JSON.stringify(value)); } // a value for the whole clip, without times for (const value of [5, [5, 5, 5], { post: 5 }, { vector: 5 }]) { assertEquals(one_clip({ bones: { arm: { rotation: value } } }).bones.arm.rotation, expected); } assertEquals(at_zero({ pre: [1, 2, 3], post: [4, 5, 6], lerp_mode: "catmullrom" }), [ key(0, [1, 2, 3], true, [4, 5, 6]), ]); assertEquals(at_zero({ vector: [1, 2, 3], easing: "catmullrom" }), [key(0, [1, 2, 3], true)]); }); Deno.test("a clip's keyframes are in time order, its length is the last one's without animation_length", () => { const clip = one_clip({ bones: { arm: { position: { "1.5": [1, 0, 0], "0.25": [2, 0, 0] }, scale: 0 } } }); assertEquals(clip.bones.arm.position!.map((keyframe) => keyframe.time), [0.25, 1.5]); assertEquals(clip.length, 1.5); assertEquals(clip.loop, false); assertEquals(one_clip({ animation_length: 4, loop: true, bones: {} }).length, 4); assertEquals(one_clip({ loop: true, bones: {} }).loop, true); assertEquals(one_clip({ loop: "hold_on_last_frame", bones: {} }).loop, false); }); Deno.test("a file's animations are clips named after their last part", () => { const file = { animations: { "animation.Walker.WALK": { bones: {} }, "animation.walker.idle": { bones: {} } } }; const { clips } = clips_from_bedrock(file, "a:walker"); assertEquals(clips.map((clip) => clip.id), ["a:walker/walk", "a:walker/idle"]); const twice = { animations: { "animation.one.walk": { bones: {} }, "animation.two.walk": { bones: {} } } }; const { problems } = clips_from_bedrock(twice, "a:walker"); assertStringIncludes(problems.join(), "a:walker/walk is another animation's too"); assertStringIncludes(clips_from_bedrock({ format_version: "1.8.0" }, "a:b").problems.join(), "animation file"); }); Deno.test("expressions are problems, and what an animator does instead is a warning", () => { const expression = problems_of({ bones: { box: { rotation: ["math.cos(query.life_time * 180) * 2.5", 0, 0] } } }); assertEquals(expression.length, 1); assertStringIncludes(expression[0], "box rotation"); assertStringIncludes(expression[0], "an animator does that in code"); assertStringIncludes( problems_of({ bones: { box: { scale: { "0": { post: 1, lerp_mode: "bezier" } } } } }).join(), "bezier", ); assertStringIncludes(problems_of({ loop: "sometimes", bones: {} }).join(), "loop"); assertStringIncludes(problems_of({ bones: { box: { rotation: { soon: 0 } } } }).join(), "soon isn't a time"); const file = { animations: { "animation.box.crank": { sound_effects: { "0.5": { effect: "turn" } }, bones: { box: { rotation: 0, relative_to: { rotation: "entity" } } }, }, }, }; const { clips, warnings } = clips_from_bedrock(file, "a:box"); assertEquals(clips.length, 1); assertEquals(warnings.length, 2); assertStringIncludes(warnings.join(), "sound_effects"); assertStringIncludes(warnings.join(), "relative_to"); }); Deno.test("check-mods reads a mod's animation files into its clips", async () => { const dir = Deno.makeTempDirSync({ prefix: "bworld_mods_" }); create_mod("walkers", "Walkers", dir); Deno.mkdirSync(`${dir}/walkers/animations/monsters`, { recursive: true }); const animation = { animations: { "animation.walker.walk": { loop: true, bones: { leg: { rotation: 5 } } } } }; Deno.writeTextFileSync(`${dir}/walkers/animations/monsters/walker.animation.json`, JSON.stringify(animation)); const broken = { animations: { "animation.broken.walk": { bones: { leg: { rotation: "q.anim_time" } } } } }; Deno.writeTextFileSync(`${dir}/walkers/animations/broken.animation.json`, JSON.stringify(broken)); const mod = (await load_and_check(dir)).find((mod) => mod.id === "walkers")!; assertEquals(mod.animations.map((clip) => clip.json.id), ["walkers:monsters/walker/walk"]); const clip_errors = mod.report.errors.filter((error) => error.startsWith("animations/")); assertEquals(clip_errors.length, 1); assertStringIncludes(clip_errors[0], "animations/broken.animation.json"); Deno.removeSync(dir, { recursive: true }); }); Deno.test("between keyframes it's linear, and on or past them it's theirs", () => { const keyframes = [key(1, [0, 0, 0]), key(2, [10, 20, 30], false, [100, 100, 100]), key(3, [0, 0, 0])]; assertEquals(sample_channel(keyframes, 1.5, false), [5, 10, 15]); assertEquals(sample_channel(keyframes, 0, false), [0, 0, 0]); // on a keyframe that jumps it's what it comes in at, and after it what it leaves at assertEquals(sample_channel(keyframes, 2, false), [10, 20, 30]); assertEquals(sample_channel(keyframes, 2.5, false), [50, 50, 50]); assertEquals(sample_channel(keyframes, 9, false), [0, 0, 0]); }); Deno.test("catmullrom passes through its keyframes, and wraps around for its neighbours in a loop", () => { const keyframes = [key(0, [0, 0, 0], true), key(1, [10, 10, 10], true), key(2, [0, 0, 0], true)]; for (const keyframe of keyframes) assertEquals(sample_channel(keyframes, keyframe.time, false), keyframe.pre); const curve = sample_channel(keyframes, 0.5, false)[0]; assert(curve > 5, `${curve} curves up toward the peak, past the straight line`); // in a loop the keyframe before the first is the one before the last, so the trough at the seam is flatter assert(sample_channel(keyframes, 0.25, true)[0] < sample_channel(keyframes, 0.25, false)[0]); }); Deno.test("a clip that loops wraps around its length, and one that doesn't stays on its last frame", () => { const bones = { arm: { rotation: [key(0, [0, 0, 0]), key(1, [10, 0, 0])] } }; const rotation = (clip: ClipJson, seconds: number) => { const offsets = new Map(); sample_clip(clip, seconds, offsets); return offsets.get("arm")!.rotation[0]; }; const looping: ClipJson = { id: "a:b/c", length: 2, loop: true, bones }; const once: ClipJson = { ...looping, loop: false }; assertAlmostEquals(rotation(looping, 2.5), rotation(looping, 0.5)); assertAlmostEquals(rotation(looping, -1.5), rotation(looping, 0.5)); assertEquals(rotation(once, 2.5), 10); assertEquals(rotation(once, 50), 10); }); Deno.test("clips add up, scaled by their weight", () => { const clip = (rotation: Vec3, scale: Vec3): ClipJson => ({ id: "a:b/c", length: 1, loop: false, bones: { arm: { rotation: [key(0, rotation)], scale: [key(0, scale)] } }, }); const offsets = new Map(); sample_clip(clip([10, 0, 0], [3, 1, 1]), 0, offsets, 0.5); assertEquals(offsets.get("arm"), { rotation: [5, 0, 0], position: [0, 0, 0], scale: [2, 1, 1] }); sample_clip(clip([0, 20, 0], [1, 1, 0]), 0, offsets); assertEquals(offsets.get("arm"), { rotation: [5, 20, 0], position: [0, 0, 0], scale: [2, 1, 0] }); }); // a model with an arm and a hand on it, the arm turned by rotation function arm_model(rotation?: Vec3): EntityModelJson { const cubes = [{ origin: [0, 0, 0], size: [1, 1, 1], uv: [0, 0] }]; const arm = { name: "arm", pivot: [2, 3, 4], cubes, ...(rotation ? { rotation } : {}) }; const geometry = { description: { texture_width: 16, texture_height: 16 }, bones: [arm, { name: "hand", parent: "arm", pivot: [2, 0, 4], cubes }], }; return entity_model_from_geo({ "minecraft:geometry": [geometry] }, "a:arm").model!; } function offsets_for(bone: string, offsets: Partial) { const full = { rotation: [0, 0, 0], position: [0, 0, 0], scale: [1, 1, 1], ...offsets } as BoneOffsets; return new Map([[bone, full]]); } function assert_matrices_equal(actual: Map, expected: Map) { for (const [bone, matrix] of expected) { matrix.forEach((n, i) => assertAlmostEquals(actual.get(bone)![i], n, 1e-9, `${bone}[${i}]`)); } } Deno.test("a clip turning a bone turns it like the same rotation in the model, its children with it", () => { const turned = bone_matrices(arm_model([30, -45, 60]), () => IDENTITY); const animated = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { rotation: [30, -45, 60] })); assert_matrices_equal(animated, turned); // added to the model's own rotation const added = bone_matrices(arm_model([10, -45, 0]), () => IDENTITY, offsets_for("arm", { rotation: [20, 0, 60] })); assert_matrices_equal(added, turned); }); Deno.test("a clip moves bones in the model's pixels, and scales them around their pivot", () => { const point: Vec3 = [5, 7, 9]; const still = bone_matrices(arm_model(), () => IDENTITY); const moved = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { position: [1, 2, 3] })); // bedrock's +x is the engine's -x, like the pivots for (const bone of ["arm", "hand"]) { const [x, y, z] = apply(still.get(bone)!, ...point); assertEquals(apply(moved.get(bone)!, ...point), [x - 1, y + 2, z + 3]); } const scaled = bone_matrices(arm_model(), () => IDENTITY, offsets_for("arm", { scale: [2, 3, 0.5] })); const pivot = [-2, 3, 4]; assertEquals(apply(scaled.get("arm")!, ...point), point.map((n, i) => pivot[i] + (n - pivot[i]) * [2, 3, 0.5][i])); }); Deno.test("an animation state counts seconds from when it started, and knows when a clip has played through", () => { const once: Clip = { id: "a:b/once", length: 1, loop: false }; const state = new AnimationState(); assertEquals([state.started, state.seconds(100), state.finished(once, 100)], [false, 0, false]); state.animate_when(true, 10); state.animate_when(true, 15); assertEquals(state.seconds(20), 0.5); assert(!state.finished(once, 29)); assert(state.finished(once, 30)); assert(!state.finished({ ...once, loop: true }, 300)); state.animate_when(false, 40); assertEquals(state.started, false); state.start_if_stopped(50); state.start_if_stopped(60); assertEquals(state.seconds(70), 1); }); // an entity the way an animator sees it, standing still and looking ahead function animated(type: string, data: EntityData = {}): AnimatorSource & { data: EntityData } { return { id: "e1", type, data, age: 0, yaw: 0, head_yaw: 0, pitch: 0, walk_animation: () => ({ position: 0, speed: 0 }), attack_animation: () => 0, }; } // registers an animator for a new entity type, and a clip turning the arm up to 90 degrees over a second function animator_type(name: string, create: (entity: AnimatedEntity) => EntityAnimator) { const type = `test:${name}`; entity_animators.set(type, { mod: "test", create }); const clip_id = `test:${name}/raise`; if (!EverythingRegistry.get("animations", clip_id)) { EverythingRegistry.register("animations", clip_id, { id: clip_id, length: 1, loop: false, bones: { arm: { rotation: [key(0, [0, 0, 0]), key(1, [90, 0, 0])] } }, }); } return { type, raise: { id: clip_id, length: 1, loop: false } }; } Deno.test("an animator hears about each client data field as it changes, and the ones there from the start", () => { const heard: string[] = []; const { type } = animator_type("listener", () => ({ pose() {}, on_data: (field) => heard.push(field) })); const entity = animated(type, { client_data: { mood: 1 }, glowing: true }); const animation = animation_for(entity)!; assertEquals(heard, ["mood"]); const before = entity.data; entity.data = { client_data: { mood: 1, state: 2 } }; animation.data_changed(before); assertEquals(heard, ["mood", "state"]); const again = entity.data; entity.data = { client_data: { state: 3 } }; animation.data_changed(again); assertEquals(heard, ["mood", "state", "mood", "state"]); assertEquals(animation_for(animated("test:no_animator")), undefined); }); Deno.test("an animator's pose plays clips and moves bones", () => { const { type, raise } = animator_type("poser", () => ({ pose(pose, time) { pose.play(raise, time / 20, 0.5); pose.move("arm", 1, 2, 3); pose.scale("leg", 2, 2, 2); pose.look("head"); }, })); const entity = { ...animated(type), head_yaw: Math.PI / 2, pitch: -Math.PI / 4 }; const offsets = animation_for(entity)!.pose(10)!; assertEquals(offsets.get("arm"), { rotation: [22.5, 0, 0], position: [1, 2, 3], scale: [1, 1, 1] }); assertEquals(offsets.get("leg")!.scale, [2, 2, 2]); // mirrored like a model's own rotations const head = offsets.get("head")!.rotation; assertAlmostEquals(head[0], 45); assertAlmostEquals(head[1], -90); }); Deno.test("a clip plays from when its state started, and with walking as strongly as it walks", () => { const state = new AnimationState(); state.start(10); const { type, raise } = animator_type("stateful", (entity) => ({ pose(pose, time) { pose.play_state(raise, state, time); pose.play_walk(raise, entity, time); }, })); // half a second of clip walked, at half speed const animation = animation_for({ ...animated(type), walk_animation: () => ({ position: 10, speed: 0.5 }) })!; // a quarter of a second into the state is 22.5 degrees, and walking half of 45 assertAlmostEquals(animation.pose(15)!.get("arm")!.rotation[0], 22.5 + 22.5); state.stop(); assertAlmostEquals(animation.pose(15)!.get("arm")!.rotation[0], 22.5); }); Deno.test("an animator's step_sound picks each step's sound, and one without it keeps the entity's own", () => { const { type } = animator_type("stomper", (entity) => ({ pose() {}, step_sound: () => entity.get_client_data("angry") ? "test:stomp" : undefined, })); const entity = animated(type); const animation = animation_for(entity)!; assertEquals(animation.step_sound("test:own"), undefined); entity.data = { client_data: { angry: true } }; assertEquals(animation.step_sound("test:own"), "test:stomp"); const { type: quiet } = animator_type("quiet", () => ({ pose() {} })); assertEquals(animation_for(animated(quiet))!.step_sound("test:own"), "test:own"); }); Deno.test("an animator that throws is removed, and the entity is posed without it", async () => { const { type } = animator_type("thrower", () => ({ pose(pose) { pose.play({ id: "test:nowhere/nothing", length: 1, loop: false }, 0); }, })); const animation = animation_for(animated(type))!; const errors = await errors_during(() => assertEquals(animation.pose(0), undefined)); assertEquals(errors.length, 1); assertStringIncludes(errors[0], "[test] the animator of test:thrower e1 threw in pose"); assertStringIncludes(errors[0], "test:nowhere/nothing isn't a clip"); assertEquals(animation.pose(1), undefined); }); Deno.test("a mob's client data goes to the players who see it, and is saved with it", async () => { const dir = Deno.makeTempDirSync({ prefix: "bworld_client_data_" }); copy_dir("mods/dangerous_business", `${dir}/dangerous_business`); const t = await test_game(dir); t.join(1, "alice"); const mob = test_mob(t.game, {}, 0.5, 100, 0.5); const ref = t.game.mods.mob(mob); t.game.tick(); t.take(1); ref.set_client_data("state", { mood: 3 }); assertEquals(ref.get_client_data("state"), { mood: 3 }); t.game.tick(); const sent = t.take(1).find((m) => m.type === "entity_data" && m.id === mob.id); assertEquals(sent && "data" in sent ? sent.data.client_data : undefined, { state: { mood: 3 } }); const copy = test_mob(t.game, {}, 2.5, 100, 0.5); copy.load(mob.save()); assertEquals(t.game.mods.mob(copy).get_client_data("state"), { mood: 3 }); ref.set_client_data("state", undefined); assertEquals(mob.synced_data().client_data, undefined); Deno.removeSync(dir, { recursive: true }); });