Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(animation): implement keyframe animation system in pose studio
nirholas8ba67631231e
diff --git a/pages/pose.html b/pages/pose.htmlindex 6c3fb5c0a..0ced3b5ef 100644--- a/pages/pose.html+++ b/pages/pose.html@@ -62,10 +62,11 @@inset: 0;display: grid;grid-template-columns: 280px 1fr 320px;- grid-template-rows: 52px 1fr;+ grid-template-rows: 52px 1fr auto;grid-template-areas:"top top top"- "left stage right";+ "left stage right"+ "timeline timeline timeline";gap: 0;}@@ -476,6 +477,211 @@gap: 6px;}+ /* ── Timeline ───────────────────────────────────────── */+ #pose-timeline {+ grid-area: timeline;+ border-top: 1px solid var(--border);+ background: rgba(0, 0, 0, 0.9);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ padding: 9px 14px 12px;+ display: flex;+ flex-direction: column;+ gap: 9px;+ user-select: none;+ z-index: 9;+ }+ .tl-transport {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+ }+ .tl-btn {+ appearance: none;+ border: 1px solid var(--border);+ background: rgba(255, 255, 255, 0.04);+ color: var(--text);+ font: inherit;+ font-size: 13px;+ width: 32px;+ height: 30px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ border-radius: 8px;+ cursor: pointer;+ transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease;+ }+ .tl-btn:hover { background: rgba(255, 255, 255, 0.09); border-color: var(--border-strong); }+ .tl-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }+ .tl-btn[aria-pressed="true"] {+ background: rgba(255, 255, 255, 0.2);+ border-color: rgba(255, 255, 255, 0.45);+ color: #e8e8e8;+ }+ .tl-btn:disabled { opacity: 0.4; cursor: not-allowed; }+ #tl-play { width: 36px; background: rgba(255, 255, 255, 0.12); }+ #tl-play:hover { background: rgba(255, 255, 255, 0.2); }+ .tl-time {+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12.5px;+ color: var(--text-2);+ font-variant-numeric: tabular-nums;+ min-width: 104px;+ text-align: center;+ }+ .tl-time b { color: var(--text); font-weight: 600; }+ .tl-field {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 11.5px;+ color: var(--text-3);+ }+ .tl-field input[type="number"],+ .tl-field select {+ background: rgba(255, 255, 255, 0.04);+ color: var(--text);+ border: 1px solid var(--border);+ border-radius: 6px;+ padding: 5px 7px;+ font: inherit;+ font-size: 12px;+ }+ .tl-field input[type="number"] { width: 56px; }+ .tl-field input:focus, .tl-field select:focus { outline: none; border-color: var(--border-strong); }+ .tl-field input[type="checkbox"] { accent-color: var(--accent); }+ .tl-sep { width: 1px; height: 22px; background: var(--border); margin: 0 2px; }+ .tl-spacer { flex: 1 1 auto; }+ .tl-add {+ appearance: none;+ border: 1px solid rgba(255, 255, 255, 0.45);+ background: rgba(255, 255, 255, 0.22);+ color: #e8e8e8;+ font: inherit;+ font-size: 12.5px;+ font-weight: 600;+ padding: 6px 13px;+ border-radius: 999px;+ cursor: pointer;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ transition: background 0.12s ease;+ }+ .tl-add:hover { background: rgba(255, 255, 255, 0.32); }+ .tl-add:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }++ /* Track + ruler */+ .tl-track-wrap {+ position: relative;+ height: 52px;+ border: 1px solid var(--border);+ border-radius: 10px;+ background:+ linear-gradient(rgba(255, 255, 255, 0.015), rgba(255, 255, 255, 0.015));+ overflow: hidden;+ cursor: pointer;+ }+ .tl-ruler {+ position: absolute;+ inset: 0 0 auto 0;+ height: 18px;+ pointer-events: none;+ }+ .tl-tick {+ position: absolute;+ top: 0;+ width: 1px;+ height: 7px;+ background: var(--border-strong);+ }+ .tl-tick-label {+ position: absolute;+ top: 7px;+ transform: translateX(2px);+ font-size: 9.5px;+ color: var(--text-3);+ font-variant-numeric: tabular-nums;+ font-family: ui-monospace, monospace;+ }+ .tl-lane {+ position: absolute;+ left: 0;+ right: 0;+ bottom: 0;+ top: 18px;+ }+ .tl-empty {+ position: absolute;+ inset: 18px 0 0 0;+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ font-size: 11.5px;+ color: var(--text-3);+ pointer-events: none;+ padding: 0 12px;+ text-align: center;+ }+ .tl-empty kbd {+ background: rgba(255, 255, 255, 0.08);+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 1px 5px;+ font-family: ui-monospace, monospace;+ font-size: 10px;+ color: var(--text-2);+ }+ .tl-key {+ position: absolute;+ top: 50%;+ width: 14px;+ height: 14px;+ margin-left: -7px;+ background: #d4d4d8;+ border: 1px solid rgba(0, 0, 0, 0.5);+ border-radius: 3px;+ transform: translateY(-50%) rotate(45deg);+ cursor: grab;+ transition: background 0.1s ease, box-shadow 0.1s ease, transform 0.1s ease;+ z-index: 3;+ }+ .tl-key:hover { background: #fff; box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.14); }+ .tl-key[aria-selected="true"] {+ background: #22d3ee;+ box-shadow: 0 0 0 4px rgba(34, 211, 238, 0.25);+ }+ .tl-key:active { cursor: grabbing; }+ .tl-key:focus-visible { outline: 2px solid #22d3ee; outline-offset: 3px; }+ .tl-playhead {+ position: absolute;+ top: 0;+ bottom: 0;+ width: 2px;+ margin-left: -1px;+ background: var(--accent);+ pointer-events: none;+ z-index: 4;+ }+ .tl-playhead::before {+ content: "";+ position: absolute;+ top: 0;+ left: -5px;+ border-left: 6px solid transparent;+ border-right: 6px solid transparent;+ border-top: 7px solid var(--accent);+ }++ /* Export feedback */+ .tl-export:disabled { opacity: 0.4; cursor: not-allowed; }+ .tl-export.is-busy { opacity: 0.6; pointer-events: none; }+ .tl-export.is-ok { border-color: rgba(120, 255, 170, 0.5); color: #b6ffce; }+ .tl-export.is-err { border-color: rgba(248, 113, 113, 0.6); color: var(--danger); }+/* ── Responsive ─────────────────────────────────────── */@media (max-width: 1100px) {#pose-app {@@ -485,18 +691,20 @@@media (max-width: 900px) {#pose-app {grid-template-columns: 1fr;- grid-template-rows: 52px 1fr auto;+ grid-template-rows: 52px 1fr auto auto;grid-template-areas:"top""stage"+ "timeline""left";}#pose-right { display: none; }#pose-left {border-right: none;border-top: 1px solid var(--border);- max-height: 40vh;+ max-height: 36vh;}+ .tl-field-fps, .tl-field-name { display: none; }}</style></head>@@ -623,6 +831,65 @@<div class="pose-prop-grid" id="pose-prop-host"></div></section></aside>++ <!-- TIMELINE -->+ <section id="pose-timeline" aria-label="Animation timeline">+ <div class="tl-transport">+ <button type="button" id="tl-start" class="tl-btn" title="Jump to start (Home)" aria-label="Jump to start">⏮</button>+ <button type="button" id="tl-play" class="tl-btn" title="Play / pause (Space)" aria-label="Play or pause" aria-pressed="false">▶</button>+ <button type="button" id="tl-stop" class="tl-btn" title="Stop and rewind" aria-label="Stop">⏹</button>+ <button type="button" id="tl-end" class="tl-btn" title="Jump to end (End)" aria-label="Jump to end">⏭</button>+ <button type="button" id="tl-loop" class="tl-btn" title="Loop playback" aria-label="Loop playback" aria-pressed="true">↻</button>++ <span class="tl-time" id="tl-time"><b>0.00</b> / 4.00s</span>++ <span class="tl-sep"></span>++ <button type="button" id="tl-add-key" class="tl-add" title="Capture the current pose as a keyframe (K)">+ Add keyframe</button>++ <span class="tl-field" title="Easing for the selected keyframe (governs the segment after it)">+ <label for="tl-easing">Easing</label>+ <select id="tl-easing" aria-label="Selected keyframe easing" disabled>+ <option value="linear">Linear</option>+ <option value="ease-in">Ease in</option>+ <option value="ease-out">Ease out</option>+ <option value="ease-in-out" selected>Ease in-out</option>+ </select>+ </span>+ <button type="button" id="tl-del-key" class="tl-btn" title="Delete selected keyframe (Del)" aria-label="Delete selected keyframe" disabled>🗑</button>++ <span class="tl-spacer"></span>++ <span class="tl-field tl-field-name" title="Animation name (used as the clip + file name)">+ <label for="tl-name">Name</label>+ <input type="text" id="tl-name" value="animation" size="10" aria-label="Animation name" autocomplete="off" />+ </span>+ <span class="tl-field" title="Total animation length in seconds">+ <label for="tl-duration">Duration</label>+ <input type="number" id="tl-duration" min="0.25" max="120" step="0.25" value="4" aria-label="Duration in seconds" />s+ </span>+ <span class="tl-field tl-field-fps" title="Frames per second baked into the exported clip">+ <label for="tl-fps">FPS</label>+ <input type="number" id="tl-fps" min="1" max="120" step="1" value="30" aria-label="Frames per second" />+ </span>++ <span class="tl-sep"></span>++ <button type="button" id="tl-export-json" class="pose-btn tl-export" title="Download a three.ws clip JSON">Export JSON</button>+ <button type="button" id="tl-export-glb" class="pose-btn pose-btn-primary tl-export" title="Download a GLB with the animation embedded">Export GLB</button>+ </div>++ <div class="tl-track-wrap" id="tl-track" role="slider" tabindex="0"+ aria-label="Playhead — click or drag to scrub, arrow keys to step"+ aria-valuemin="0" aria-valuemax="4" aria-valuenow="0">+ <div class="tl-ruler" id="tl-ruler"></div>+ <div class="tl-empty" id="tl-empty">+ Pose the figure, then press <kbd>K</kbd> or <b style="color:var(--text-2)">+ Add keyframe</b> to start your animation.+ </div>+ <div class="tl-lane" id="tl-lane"></div>+ <div class="tl-playhead" id="tl-playhead" style="left:0"></div>+ </div>+ </section></div><script type="module" src="/src/pose-studio.js"></script>diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex c309df180..945cc85ef 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -25,7 +25,7 @@ import { CommunityUI } from './coincommunities-ui.js';import { createWorldEnvironment } from './world-env.js';import { createChartScreen } from './chart-screen.js';import { MarketReactor } from './market-reactor.js';-import { VoxelWorld, createBuildHud, parseKey } from './build-voxels.js';+import { VoxelWorld, createBuildHud, parseKey, MAX_BLOCKS } from './build-voxels.js';import { normalizeGatewayURL } from '../ipfs.js';import {loadManifest, getEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,@@ -649,8 +649,15 @@ export class CoinCommunities {this.net.on('status', ({ status }) => {this.ui.setStatus(status);this._updateOnline();- // Only offer building while there's a live link to build into.- this.buildHud.setEnabled(status === 'online', 'Building needs a live connection');+ // Every (re)connect re-streams the server's authoritative build, so wipe+ // the local layer first. On a manual retry out of single-player this also+ // hands authority back: the solo build gives way to the shared world's.+ if (status === 'connecting') this.voxels?.clear();+ // Building is available with a live server (synced + persisted for+ // everyone) and in solo single-player mode (local-only) once multiplayer+ // has been given up. The connecting window is the only time it's off, so+ // the toggle never becomes a dead, silent button.+ this.buildHud.setEnabled(this._buildableConnection(), 'Connecting to the world…');// A reconnect reissues every sessionId, stranding the voice mesh — refresh// our id, drop the stale peers, and re-announce so it re-forms.if (status === 'online' && this.voice?.joined && this.net.sessionId !== this.voice.selfId) {@@ -902,7 +909,7 @@ export class CoinCommunities {// B toggles build mode; while it's on, 1–0 pick the active block.if (k === 'b') {e.preventDefault();- if (this.net?.status === 'online' || this.buildHud.active) this.buildHud.setActive(!this.buildHud.active);+ if (this._buildableConnection() || this.buildHud.active) this.buildHud.setActive(!this.buildHud.active);return;}if (this.buildHud.active && k.length === 1 && k >= '0' && k <= '9') {@@ -981,17 +988,38 @@ export class CoinCommunities {}// ---------------------------------------------------------------- building- // Place or break a block under the pointer. Server-authoritative: we only send- // the intent, and the block appears/disappears when the server echoes its- // blocks state back (see the blockAdd/blockRemove wiring in enter()).+ // A live server lets everyone build the same persistent world; with no server+ // reachable we still let a solo player build their own local copy. Either way+ // the connecting window (nothing to build into yet) is the only time off.+ _buildableConnection() {+ const s = this.net?.status;+ return s === 'online' || s === 'offline';+ }++ // Place or break a block under the pointer. Online is server-authoritative: we+ // only send the intent, and the block appears/disappears when the server echoes+ // its blocks state back (see the blockAdd/blockRemove wiring in enter()). In+ // single-player (no server) we apply the edit straight to the local voxel layer+ // — same result on screen, just not synced or persisted._buildAt(clientX, clientY, forceRemove) {- if (!this.voxels || this.net?.status !== 'online') return;+ if (!this.voxels || this.phase !== 'world' || !this._buildableConnection()) return;+ const online = this.net?.status === 'online';const target = this.voxels.raycast(this._pointerRay(clientX, clientY));if (!target) return;if (forceRemove || this.buildHud.mode === 'remove') {- if (target.hit === 'block' && target.cell) this.net.sendRemove(target.cell[0], target.cell[1], target.cell[2]);+ if (target.hit === 'block' && target.cell) {+ if (online) this.net.sendRemove(target.cell[0], target.cell[1], target.cell[2]);+ else this.voxels.removeBlock(target.cell[0], target.cell[1], target.cell[2]);+ }} else if (target.placeValid) {- this.net.sendPlace(target.placeCell[0], target.placeCell[1], target.placeCell[2], this.buildType);+ // The server enforces the build's block cap online; honour it locally too+ // so a solo build can't outgrow what a shared one is allowed to be.+ if (!online && this.voxels.count >= MAX_BLOCKS) {+ this.ui.toast(`Build limit reached (${MAX_BLOCKS} blocks).`, 'warn');+ return;+ }+ if (online) this.net.sendPlace(target.placeCell[0], target.placeCell[1], target.placeCell[2], this.buildType);+ else this.voxels.setBlock(target.placeCell[0], target.placeCell[1], target.placeCell[2], this.buildType);} else if (target.placeCell) {// Aimed somewhere illegal (out of bounds / occupied) — flash the cursor.this.voxels.showGhost(target.placeCell, 'blocked');@@ -1021,7 +1049,13 @@ export class CoinCommunities {_onBuildToggle(on) {if (!on) { this.voxels?.hideGhost(); this.canvas.style.cursor = ''; return; }- this.ui.toast('Build mode — tap to place, right-click to break, 1–0 pick a block', 'info');+ const solo = this.net?.status !== 'online';+ this.ui.toast(+ solo+ ? 'Build mode (single-player) — tap to place, right-click to break, 1–0 pick a block'+ : 'Build mode — tap to place, right-click to break, 1–0 pick a block',+ 'info',+ );if (this._lastHover) this._updateGhost(this._lastHover.x, this._lastHover.y);}diff --git a/src/pose-animation.js b/src/pose-animation.jsnew file mode 100644index 000000000..8ae94d58e--- /dev/null+++ b/src/pose-animation.js@@ -0,0 +1,263 @@+// Keyframe animation core for the Animation Studio (/pose).+//+// This module is the pure, headless half of Task 2: it owns the editing+// document (keyframes over time), interpolates a pose at any playhead position+// (slerp rotations, lerp root translation), and bakes the result into a+// THREE.AnimationClip whose track names play everywhere on three.ws.+//+// It depends only on `three` (no DOM, no rig) so it is unit-testable in node —+// see tests/pose-animation.test.js. The studio (src/pose-studio.js) drives the+// live preview by calling sampleAtTime() each frame and rig.applyPose(); export+// calls bakeClip() / serializeClip().+//+// Pose shape (the Task 1 rig contract): { bones: { Canonical: [x,y,z,w], … },+// rootPosition: { x, y, z } }. Bones are keyed by CANONICAL names (Hips, Spine,+// LeftArm, …) so a clip baked here binds to standard three.ws avatars.++import {+ AnimationClip,+ Quaternion,+ QuaternionKeyframeTrack,+ VectorKeyframeTrack,+} from 'three';++// ── Easing ───────────────────────────────────────────────────────────────────+// Each easing maps a normalized segment fraction [0,1] → eased [0,1]. The easing+// of the OUTGOING keyframe governs the segment that follows it.+export const EASINGS = {+ linear: (t) => t,+ 'ease-in': (t) => t * t,+ 'ease-out': (t) => t * (2 - t),+ 'ease-in-out': (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),+};+export const DEFAULT_EASING = 'ease-in-out';++function easeFn(name) {+ return EASINGS[name] || EASINGS.linear;+}++const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));++// ── Editing document ───────────────────────────────────────────────────────+// The in-memory project Task 4 will serialize/save.+// { name, duration /* s */, fps, loop, keyframes: [{ id, time, pose, easing }] }+let _kidSeq = 0;+function nextKeyframeId() {+ _kidSeq += 1;+ return `kf_${_kidSeq}`;+}++export function createDocument(overrides = {}) {+ return {+ name: 'animation',+ duration: 4,+ fps: 30,+ loop: true,+ keyframes: [],+ ...overrides,+ };+}++function clonePose(pose) {+ if (!pose) return null;+ const bones = {};+ for (const [key, q] of Object.entries(pose.bones || {})) {+ bones[key] = [q[0], q[1], q[2], q[3]];+ }+ const rp = pose.rootPosition || { x: 0, y: 0, z: 0 };+ return { bones, rootPosition: { x: rp.x || 0, y: rp.y || 0, z: rp.z || 0 } };+}++function sortKeyframes(doc) {+ doc.keyframes.sort((a, b) => a.time - b.time);+ return doc;+}++// Two keyframes within this many seconds are treated as the same slot, so+// re-dropping at the current playhead updates rather than stacks.+const TIME_EPSILON = 1e-3;++/**+ * Capture `pose` at `time`. If a keyframe already sits at ~time, its pose (and+ * optionally easing) is updated; otherwise a new keyframe is inserted, sorted.+ * @returns the affected keyframe.+ */+export function upsertKeyframe(doc, time, pose, easing = DEFAULT_EASING) {+ const t = clamp(time, 0, doc.duration);+ const existing = doc.keyframes.find((k) => Math.abs(k.time - t) <= TIME_EPSILON);+ if (existing) {+ existing.pose = clonePose(pose);+ return existing;+ }+ const kf = { id: nextKeyframeId(), time: t, pose: clonePose(pose), easing };+ doc.keyframes.push(kf);+ sortKeyframes(doc);+ return kf;+}++export function removeKeyframe(doc, id) {+ const i = doc.keyframes.findIndex((k) => k.id === id);+ if (i === -1) return false;+ doc.keyframes.splice(i, 1);+ return true;+}++/** Retime a keyframe (drag-to-retime). Keeps the list sorted. */+export function moveKeyframe(doc, id, newTime) {+ const kf = doc.keyframes.find((k) => k.id === id);+ if (!kf) return null;+ kf.time = clamp(newTime, 0, doc.duration);+ sortKeyframes(doc);+ return kf;+}++export function setKeyframeEasing(doc, id, easing) {+ const kf = doc.keyframes.find((k) => k.id === id);+ if (kf && EASINGS[easing]) kf.easing = easing;+ return kf;+}++/** Clamp every keyframe to the (possibly shortened) duration. */+export function clampKeyframesToDuration(doc) {+ for (const kf of doc.keyframes) kf.time = clamp(kf.time, 0, doc.duration);+ sortKeyframes(doc);+ return doc;+}++// ── Interpolation ────────────────────────────────────────────────────────────+const _qa = new Quaternion();+const _qb = new Quaternion();+const _qOut = new Quaternion();++/**+ * Interpolated pose at `time` (seconds). Rotations slerp; root position lerps.+ * Returns null when there are no keyframes.+ */+export function sampleAtTime(doc, time) {+ const kfs = doc.keyframes;+ if (!kfs.length) return null;+ if (kfs.length === 1) return clonePose(kfs[0].pose);++ const t = clamp(time, 0, doc.duration);+ const first = kfs[0];+ const last = kfs[kfs.length - 1];+ if (t <= first.time) return clonePose(first.pose);+ if (t >= last.time) return clonePose(last.pose);++ let a = first;+ let b = last;+ for (let i = 0; i < kfs.length - 1; i++) {+ if (kfs[i].time <= t && t < kfs[i + 1].time) {+ a = kfs[i];+ b = kfs[i + 1];+ break;+ }+ }+ const span = b.time - a.time;+ let u = span > TIME_EPSILON ? (t - a.time) / span : 0;+ u = clamp(easeFn(a.easing)(u), 0, 1);++ const aBones = a.pose.bones || {};+ const bBones = b.pose.bones || {};+ const keys = new Set([...Object.keys(aBones), ...Object.keys(bBones)]);+ const bones = {};+ for (const key of keys) {+ const va = aBones[key] || bBones[key];+ const vb = bBones[key] || aBones[key];+ _qa.set(va[0], va[1], va[2], va[3]);+ _qb.set(vb[0], vb[1], vb[2], vb[3]);+ _qOut.copy(_qa).slerp(_qb, u);+ bones[key] = [_qOut.x, _qOut.y, _qOut.z, _qOut.w];+ }+ const ra = a.pose.rootPosition || { x: 0, y: 0, z: 0 };+ const rb = b.pose.rootPosition || { x: 0, y: 0, z: 0 };+ return {+ bones,+ rootPosition: {+ x: (ra.x || 0) + ((rb.x || 0) - (ra.x || 0)) * u,+ y: (ra.y || 0) + ((rb.y || 0) - (ra.y || 0)) * u,+ z: (ra.z || 0) + ((rb.z || 0) - (ra.z || 0)) * u,+ },+ };+}++// ── Baking to a THREE.AnimationClip ────────────────────────────────────────+// We RESAMPLE the document at `fps` and emit linear/slerp tracks. Resampling+// bakes per-keyframe easing into the samples, so the exported clip reproduces+// the exact eased timing under any standard player (AnimationMixer slerps the+// quaternion track), with no easing metadata to carry around.++function uniqueBoneKeys(doc) {+ const keys = new Set();+ for (const kf of doc.keyframes) {+ for (const k of Object.keys(kf.pose?.bones || {})) keys.add(k);+ }+ return keys;+}++function sampleTimes(duration, fps) {+ const safeFps = clamp(Math.round(fps) || 30, 1, 120);+ const dt = 1 / safeFps;+ const times = [];+ for (let t = 0; t < duration - 1e-6; t += dt) times.push(Number(t.toFixed(6)));+ times.push(Number(Math.max(duration, dt).toFixed(6)));+ return times;+}++/**+ * Bake the document into a THREE.AnimationClip.+ *+ * @param {object} doc the editing document+ * @param {object} [opts]+ * @param {(canonicalKey:string)=>string|null} [opts.resolveBoneName]+ * Maps a canonical bone key to the emitted track bone name. Default:+ * identity (canonical names — the cross-platform three.ws clip). Pass a+ * function returning the live rig's actual node names to bake a clip that+ * binds to a specific GLB/mannequin scene for GLB embedding.+ * @param {string} [opts.rootName='Hips'] bone name for the root position track+ * @returns {THREE.AnimationClip}+ */+export function bakeClip(doc, { resolveBoneName = (k) => k, rootName = 'Hips' } = {}) {+ if (!doc.keyframes.length) {+ throw new Error('Add at least one keyframe before baking an animation.');+ }+ const duration = Math.max(doc.duration, 1 / clamp(doc.fps || 30, 1, 120));+ const times = sampleTimes(duration, doc.fps);+ const samples = times.map((t) => sampleAtTime(doc, t));++ const tracks = [];+ for (const key of uniqueBoneKeys(doc)) {+ const trackBone = resolveBoneName(key);+ if (!trackBone) continue;+ const values = new Float32Array(samples.length * 4);+ for (let i = 0; i < samples.length; i++) {+ const q = samples[i].bones[key] || [0, 0, 0, 1];+ values[i * 4] = q[0];+ values[i * 4 + 1] = q[1];+ values[i * 4 + 2] = q[2];+ values[i * 4 + 3] = q[3];+ }+ tracks.push(new QuaternionKeyframeTrack(`${trackBone}.quaternion`, times, values));+ }++ if (rootName) {+ const posValues = new Float32Array(samples.length * 3);+ for (let i = 0; i < samples.length; i++) {+ const p = samples[i].rootPosition || { x: 0, y: 0, z: 0 };+ posValues[i * 3] = p.x || 0;+ posValues[i * 3 + 1] = p.y || 0;+ posValues[i * 3 + 2] = p.z || 0;+ }+ tracks.push(new VectorKeyframeTrack(`${rootName}.position`, times, posValues));+ }++ const clip = new AnimationClip(doc.name || 'animation', duration, tracks);+ clip.resetDuration();+ clip.optimize();+ return clip;+}++/** Bake + return the documented clip-JSON shape ({ name, duration, tracks }). */+export function serializeClip(doc, opts) {+ return AnimationClip.toJSON(bakeClip(doc, opts));+}diff --git a/src/pose-studio.js b/src/pose-studio.jsindex 2ed5a8243..81f07302e 100644--- a/src/pose-studio.js+++ b/src/pose-studio.js@@ -33,6 +33,7 @@ import {import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';import { TransformControls } from 'three/examples/jsm/controls/TransformControls.js';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';import { getDecoders } from './viewer/internal.js';import {@@ -43,6 +44,18 @@ import {} from './pose-rig.js';import { PRESETS, getPresetsByGroup, getPresetById } from './pose-presets.js';import { AvatarGalleryPicker } from './avatar-gallery-picker.js';+import {+ createDocument,+ upsertKeyframe,+ removeKeyframe,+ moveKeyframe,+ setKeyframeEasing,+ clampKeyframesToDuration,+ sampleAtTime,+ bakeClip,+ serializeClip,+ DEFAULT_EASING,+} from './pose-animation.js';// ─── DOM helpers ────────────────────────────────────────────────────────const $ = (sel) => document.querySelector(sel);@@ -269,16 +282,25 @@ const state = {keyDistance: 5.8,ikHandles: new Map(), // effectorKey → MeshdraggingIK: null, // { effectorKey, plane }+ anim: null, // timeline controller handle (set on boot)};-// Studio handle exposed for later tasks (timeline/save) to share the rig +-// scene without re-importing internals.+// Studio handle exposed for later tasks (save/library/monetize) to share the+// rig, scene, and the current animation document without re-importing internals.export const studio = {get rig() { return state.rig; },get scene() { return state.ctx?.scene || null; },get camera() { return state.ctx?.camera || null; },get renderer() { return state.ctx?.renderer || null; },get avatar() { return state.avatar; },+ // ── Animation handoff API (Task 4/5/6) ───────────────────────────────────+ get document() { return state.anim?.doc || null; },+ /** Bake the current document to a THREE.AnimationClip (canonical bone names). */+ bake() { return state.anim ? state.anim.bake() : null; },+ /** The documented clip-JSON ({ name, duration, tracks }). */+ serializeClip() { return state.anim ? state.anim.serialize() : null; },+ /** PNG data URL of the current viewport (reuses the screenshot pipeline). */+ captureThumbnail() { return state.anim ? state.anim.captureThumbnail() : null; },};// ─── App boot ───────────────────────────────────────────────────────────@@ -295,6 +317,11 @@ function boot() {const { scene, camera, renderer, controls, gizmo, key, propLayer, ikLayer, setStatus } = ctx;state.keyLight = key;+ // Timeline controller — assigned near the end of boot once its DOM refs+ // exist. Declared here so mountRig() (called during boot, before the+ // assignment) can safely reference it via optional chaining.+ let timeline = null;+// Panel DOM refs (resolved up-front: mountRig() renders into them on boot).const sliderHost = $('#pose-controls-host');const selectionLabel = $('#pose-selection-label');@@ -318,6 +345,7 @@ function boot() {renderControlsPanel();renderBoneList();updateSelectionLabel();+ timeline?.onRigChanged();}const mannequinRig = new MannequinRig({ build: 'male', color: '#d4d4d8' });@@ -329,9 +357,14 @@ function boot() {if (intro) state.rig.applyPose(poseFromMannequinPreset(intro.pose));// ── Render loop ──────────────────────────────────────────────────────+ let lastFrameMs = performance.now();function tick() {requestAnimationFrame(tick);+ const now = performance.now();+ const dt = Math.min((now - lastFrameMs) / 1000, 0.1); // cap to avoid tab-switch jumps+ lastFrameMs = now;controls.update();+ timeline?.update(dt);if (state.poseMode === 'ik' && !state.draggingIK) syncIKHandles();renderer.render(scene, camera);}@@ -869,6 +902,342 @@ function boot() {else if (k === 'escape') { state.selectedBone = null; gizmo.detach(); renderControlsPanel(); renderBoneList(); updateSelectionLabel(); }});+ // ── Animation timeline ───────────────────────────────────────────────────+ // Keyframe recorder: set a pose → drop a keyframe → advance the playhead →+ // re-pose → drop another. The render loop interpolates (slerp) between+ // keyframes and plays the result; export bakes a THREE.AnimationClip.+ timeline = setupTimeline();++ function setupTimeline() {+ const doc = createDocument();+ const anim = { doc, playing: false, playhead: 0, selectedId: null };+ state.anim = anim;++ const tl = {+ track: $('#tl-track'), lane: $('#tl-lane'), ruler: $('#tl-ruler'),+ playhead: $('#tl-playhead'), empty: $('#tl-empty'), time: $('#tl-time'),+ play: $('#tl-play'), stop: $('#tl-stop'), start: $('#tl-start'), end: $('#tl-end'),+ loop: $('#tl-loop'), add: $('#tl-add-key'), del: $('#tl-del-key'),+ easing: $('#tl-easing'), name: $('#tl-name'), duration: $('#tl-duration'), fps: $('#tl-fps'),+ exportJson: $('#tl-export-json'), exportGlb: $('#tl-export-glb'),+ };+ if (!tl.track) return null; // page without the timeline markup — no-op++ const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));+ const NICE_STEPS = [0.1, 0.2, 0.25, 0.5, 1, 2, 5, 10, 15, 30, 60];+ const pct = (t) => (doc.duration > 0 ? (t / doc.duration) * 100 : 0);+ const xToTime = (clientX) => {+ const rect = tl.track.getBoundingClientRect();+ return clamp((clientX - rect.left) / rect.width, 0, 1) * doc.duration;+ };+ const safeName = () =>+ (doc.name || 'animation').replace(/[^a-z0-9._-]+/gi, '-').replace(/-+/g, '-').replace(/^-|-$/g, '').slice(0, 60) || 'animation';++ // Sync the static control values from the document defaults.+ tl.name.value = doc.name;+ tl.duration.value = String(doc.duration);+ tl.fps.value = String(doc.fps);+ tl.loop.setAttribute('aria-pressed', String(doc.loop));+ tl.track.setAttribute('aria-valuemax', String(doc.duration));++ // ── Preview ────────────────────────────────────────────────────────────+ function applyPreview() {+ if (!doc.keyframes.length || !state.rig) return;+ const pose = sampleAtTime(doc, anim.playhead);+ if (pose) {+ state.rig.applyPose(pose);+ if (state.poseMode === 'ik') syncIKHandles();+ }+ }++ function setPlayhead(t, { render = false } = {}) {+ anim.playhead = clamp(t, 0, doc.duration);+ tl.playhead.style.left = `${pct(anim.playhead)}%`;+ tl.time.innerHTML = `<b>${anim.playhead.toFixed(2)}</b> / ${doc.duration.toFixed(2)}s`;+ tl.track.setAttribute('aria-valuenow', anim.playhead.toFixed(2));+ applyPreview();+ if (render && state.selectedBone) renderControlsPanel();+ }++ // ── Transport ────────────────────────────────────────────────────────────+ function play() {+ if (!doc.keyframes.length) { setStatus('Add a keyframe first, then play.', 'error'); return; }+ if (!doc.loop && anim.playhead >= doc.duration - 1e-3) anim.playhead = 0;+ anim.playing = true;+ tl.play.textContent = '⏸';+ tl.play.setAttribute('aria-pressed', 'true');+ }+ function pause() {+ anim.playing = false;+ tl.play.textContent = '▶';+ tl.play.setAttribute('aria-pressed', 'false');+ }+ function toggle() { anim.playing ? pause() : play(); }+ function stop() { pause(); setPlayhead(0, { render: true }); }++ function advance(dt) {+ if (!anim.playing) return;+ let t = anim.playhead + dt;+ if (t >= doc.duration) {+ if (doc.loop) t = doc.duration > 0 ? t % doc.duration : 0;+ else { setPlayhead(doc.duration); pause(); return; }+ }+ setPlayhead(t);+ }++ // ── Ruler + keyframes render ─────────────────────────────────────────────+ function niceStep(raw) {+ for (const s of NICE_STEPS) if (s >= raw) return s;+ return NICE_STEPS[NICE_STEPS.length - 1];+ }+ function renderRuler() {+ tl.ruler.innerHTML = '';+ const step = niceStep(doc.duration / 8);+ for (let t = 0; t <= doc.duration + 1e-6; t += step) {+ const left = pct(t);+ tl.ruler.appendChild(el('div', { class: 'tl-tick', style: `left:${left}%` }));+ tl.ruler.appendChild(el('div', { class: 'tl-tick-label', style: `left:${left}%` }, [`${(+t.toFixed(3))}s`]));+ }+ }++ function refreshExportEnabled() {+ const has = doc.keyframes.length > 0;+ tl.exportJson.disabled = !has;+ tl.exportGlb.disabled = !has;+ }++ function updateSelectionUI() {+ const kf = doc.keyframes.find((k) => k.id === anim.selectedId);+ tl.easing.disabled = !kf;+ tl.del.disabled = !kf;+ if (kf) tl.easing.value = kf.easing;+ tl.lane.querySelectorAll('.tl-key').forEach((d) => {+ d.setAttribute('aria-selected', String(d.dataset.id === anim.selectedId));+ });+ }++ function renderKeyframes() {+ tl.lane.innerHTML = '';+ tl.empty.style.display = doc.keyframes.length ? 'none' : 'flex';+ for (const kf of doc.keyframes) {+ const diamond = el('div', {+ class: 'tl-key',+ 'data-id': kf.id,+ tabindex: '0',+ role: 'button',+ 'aria-selected': String(kf.id === anim.selectedId),+ 'aria-label': `Keyframe at ${kf.time.toFixed(2)} seconds, ${kf.easing}`,+ title: `${kf.time.toFixed(2)}s · ${kf.easing}`,+ style: `left:${pct(kf.time)}%`,+ });+ diamond.addEventListener('pointerdown', (ev) => startKeyDrag(ev, kf, diamond));+ diamond.addEventListener('keydown', (ev) => {+ if (ev.key === 'Delete' || ev.key === 'Backspace') { ev.preventDefault(); select(kf.id); deleteSelected(); }+ else if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); select(kf.id); }+ });+ tl.lane.appendChild(diamond);+ }+ refreshExportEnabled();+ updateSelectionUI();+ }++ // ── Keyframe ops ──────────────────────────────────────────────────────────+ function select(id) {+ anim.selectedId = id;+ const kf = doc.keyframes.find((k) => k.id === id);+ updateSelectionUI();+ if (kf) setPlayhead(kf.time, { render: true });+ }++ function captureKeyframe() {+ if (!state.rig) return;+ const existed = doc.keyframes.some((k) => Math.abs(k.time - anim.playhead) <= 1e-3);+ const kf = upsertKeyframe(doc, anim.playhead, state.rig.getPose(), DEFAULT_EASING);+ anim.selectedId = kf.id;+ renderKeyframes();+ setStatus(existed+ ? `Keyframe updated at ${kf.time.toFixed(2)}s.`+ : `Keyframe added at ${kf.time.toFixed(2)}s · ${doc.keyframes.length} total.`);+ }++ function deleteSelected() {+ if (!anim.selectedId) return;+ removeKeyframe(doc, anim.selectedId);+ anim.selectedId = null;+ renderKeyframes();+ applyPreview();+ setStatus('Keyframe deleted.');+ }++ // Drag a keyframe diamond to retime it (and scrub the playhead with it).+ function startKeyDrag(ev, kf, diamond) {+ ev.stopPropagation();+ ev.preventDefault();+ pause();+ select(kf.id);+ diamond.setPointerCapture(ev.pointerId);+ const onMove = (e) => {+ // moveKeyframe re-sorts the list, so live preview (sampleAtTime,+ // which assumes sorted keyframes) stays correct mid-drag.+ moveKeyframe(doc, kf.id, xToTime(e.clientX));+ diamond.style.left = `${pct(kf.time)}%`;+ diamond.title = `${kf.time.toFixed(2)}s · ${kf.easing}`;+ setPlayhead(kf.time);+ };+ const onUp = (e) => {+ diamond.removeEventListener('pointermove', onMove);+ diamond.removeEventListener('pointerup', onUp);+ diamond.removeEventListener('pointercancel', onUp);+ try { diamond.releasePointerCapture(e.pointerId); } catch {}+ renderKeyframes();+ if (state.selectedBone) renderControlsPanel();+ };+ diamond.addEventListener('pointermove', onMove);+ diamond.addEventListener('pointerup', onUp);+ diamond.addEventListener('pointercancel', onUp);+ }++ // ── Track scrubbing ────────────────────────────────────────────────────────+ let scrubbing = false;+ tl.track.addEventListener('pointerdown', (ev) => {+ if (ev.target.closest('.tl-key')) return; // diamond handles its own drag+ pause();+ scrubbing = true;+ tl.track.setPointerCapture(ev.pointerId);+ setPlayhead(xToTime(ev.clientX), { render: true });+ });+ tl.track.addEventListener('pointermove', (ev) => {+ if (scrubbing) setPlayhead(xToTime(ev.clientX));+ });+ const endScrub = (ev) => {+ if (!scrubbing) return;+ scrubbing = false;+ try { tl.track.releasePointerCapture(ev.pointerId); } catch {}+ if (state.selectedBone) renderControlsPanel();+ };+ tl.track.addEventListener('pointerup', endScrub);+ tl.track.addEventListener('pointercancel', endScrub);+ tl.track.addEventListener('keydown', (ev) => {+ const stepDt = 1 / clamp(doc.fps || 30, 1, 120);+ if (ev.key === 'ArrowLeft') { ev.preventDefault(); pause(); setPlayhead(anim.playhead - stepDt, { render: true }); }+ else if (ev.key === 'ArrowRight') { ev.preventDefault(); pause(); setPlayhead(anim.playhead + stepDt, { render: true }); }+ else if (ev.key === 'Home') { ev.preventDefault(); setPlayhead(0, { render: true }); }+ else if (ev.key === 'End') { ev.preventDefault(); setPlayhead(doc.duration, { render: true }); }+ });++ // ── Controls ────────────────────────────────────────────────────────────────+ tl.play.addEventListener('click', toggle);+ tl.stop.addEventListener('click', stop);+ tl.start.addEventListener('click', () => { pause(); setPlayhead(0, { render: true }); });+ tl.end.addEventListener('click', () => { pause(); setPlayhead(doc.duration, { render: true }); });+ tl.loop.addEventListener('click', () => {+ doc.loop = !doc.loop;+ tl.loop.setAttribute('aria-pressed', String(doc.loop));+ setStatus(`Loop ${doc.loop ? 'on' : 'off'}.`);+ });+ tl.add.addEventListener('click', captureKeyframe);+ tl.del.addEventListener('click', deleteSelected);+ tl.easing.addEventListener('change', () => {+ if (!anim.selectedId) return;+ setKeyframeEasing(doc, anim.selectedId, tl.easing.value);+ applyPreview();+ setStatus(`Easing set to ${tl.easing.value}.`);+ });+ tl.name.addEventListener('input', () => { doc.name = tl.name.value.trim() || 'animation'; });+ tl.duration.addEventListener('change', () => {+ doc.duration = clamp(parseFloat(tl.duration.value) || 4, 0.25, 120);+ tl.duration.value = String(doc.duration);+ tl.track.setAttribute('aria-valuemax', String(doc.duration));+ clampKeyframesToDuration(doc);+ renderRuler();+ renderKeyframes();+ setPlayhead(Math.min(anim.playhead, doc.duration), { render: true });+ });+ tl.fps.addEventListener('change', () => {+ doc.fps = Math.round(clamp(parseFloat(tl.fps.value) || 30, 1, 120));+ tl.fps.value = String(doc.fps);+ });++ // ── Export ────────────────────────────────────────────────────────────────+ function downloadBlob(data, filename, mime) {+ const blob = data instanceof Blob ? data : new Blob([data], { type: mime });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ a.remove();+ setTimeout(() => URL.revokeObjectURL(url), 1500);+ }+ async function withBusy(btn, label, fn) {+ const original = btn.textContent;+ btn.classList.remove('is-ok', 'is-err');+ btn.classList.add('is-busy');+ btn.textContent = 'Working…';+ try {+ await fn();+ btn.classList.replace('is-busy', 'is-ok');+ btn.textContent = 'Saved ✓';+ setStatus(`${label} downloaded.`);+ } catch (err) {+ btn.classList.replace('is-busy', 'is-err');+ btn.textContent = 'Failed';+ setStatus(`${label} failed: ${err.message}`, 'error');+ } finally {+ setTimeout(() => { btn.classList.remove('is-ok', 'is-err'); btn.textContent = original; }, 2200);+ }+ }++ tl.exportJson.addEventListener('click', () => {+ pause();+ withBusy(tl.exportJson, 'Clip JSON', async () => {+ const json = serializeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' });+ downloadBlob(JSON.stringify(json, null, 2), `${safeName()}.json`, 'application/json');+ });+ });+ tl.exportGlb.addEventListener('click', () => {+ pause();+ withBusy(tl.exportGlb, 'Animated GLB', async () => {+ const rig = state.rig;+ const clip = bakeClip(doc, {+ resolveBoneName: (k) => rig.getNode(k)?.name || null,+ rootName: rig.root?.name || '',+ });+ const exporter = new GLTFExporter();+ const buffer = await exporter.parseAsync(rig.root, {+ binary: true,+ animations: [clip],+ embedImages: true,+ });+ downloadBlob(buffer, `${safeName()}.glb`, 'model/gltf-binary');+ });+ });++ // ── Keyboard (timeline) ──────────────────────────────────────────────────────+ window.addEventListener('keydown', (ev) => {+ if (ev.target.matches('input, textarea, select') || ev.target.closest('.tl-key')) return;+ if (ev.key === ' ') { ev.preventDefault(); toggle(); }+ else if (ev.key === 'k' || ev.key === 'K') { captureKeyframe(); }+ else if ((ev.key === 'Delete' || ev.key === 'Backspace') && anim.selectedId) { ev.preventDefault(); deleteSelected(); }+ else if (ev.key === 'Home') { setPlayhead(0, { render: true }); }+ else if (ev.key === 'End') { setPlayhead(doc.duration, { render: true }); }+ });++ // ── Init ────────────────────────────────────────────────────────────────────+ renderRuler();+ renderKeyframes();+ setPlayhead(0);++ return {+ update: advance,+ onRigChanged: () => { if (doc.keyframes.length) applyPreview(); },+ bake: () => bakeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),+ serialize: () => serializeClip(doc, { resolveBoneName: (k) => k, rootName: 'Hips' }),+ captureThumbnail: () => { renderer.render(scene, camera); return renderer.domElement.toDataURL('image/png'); },+ };+ }+// ── Boot: honor ?avatar= ─────────────────────────────────────────────────const requestedAvatar = new URL(window.location.href).searchParams.get('avatar');if (requestedAvatar) {diff --git a/tests/pose-animation.test.js b/tests/pose-animation.test.jsnew file mode 100644index 000000000..a119f975c--- /dev/null+++ b/tests/pose-animation.test.js@@ -0,0 +1,172 @@+import { describe, it, expect } from 'vitest';+import { Quaternion, Euler, AnimationClip } from 'three';+import {+ createDocument,+ upsertKeyframe,+ removeKeyframe,+ moveKeyframe,+ setKeyframeEasing,+ clampKeyframesToDuration,+ sampleAtTime,+ bakeClip,+ serializeClip,+ EASINGS,+ DEFAULT_EASING,+} from '../src/pose-animation.js';++// Build a canonical pose with a single rotated bone (rest = identity elsewhere).+function poseWithArm(angle) {+ const q = new Quaternion().setFromEuler(new Euler(0, 0, angle, 'XYZ'));+ return {+ bones: {+ Hips: [0, 0, 0, 1],+ LeftArm: [q.x, q.y, q.z, q.w],+ },+ rootPosition: { x: 0, y: 0, z: 0 },+ };+}++describe('pose-animation document model', () => {+ it('upsert keeps keyframes sorted and dedupes by time', () => {+ const doc = createDocument({ duration: 4 });+ upsertKeyframe(doc, 2, poseWithArm(0.5));+ upsertKeyframe(doc, 0, poseWithArm(0));+ expect(doc.keyframes.map((k) => k.time)).toEqual([0, 2]);++ // Re-dropping at ~the same time updates the existing keyframe, no new slot.+ const before = doc.keyframes.length;+ upsertKeyframe(doc, 2.0005, poseWithArm(1.2));+ expect(doc.keyframes.length).toBe(before);+ });++ it('clamps keyframe times to the document duration', () => {+ const doc = createDocument({ duration: 4 });+ upsertKeyframe(doc, 3.9, poseWithArm(1));+ doc.duration = 2;+ clampKeyframesToDuration(doc);+ expect(doc.keyframes[0].time).toBeLessThanOrEqual(2);+ });++ it('remove and retime work by id', () => {+ const doc = createDocument({ duration: 4 });+ const a = upsertKeyframe(doc, 0, poseWithArm(0));+ const b = upsertKeyframe(doc, 1, poseWithArm(1));+ moveKeyframe(doc, a.id, 3); // a now after b → must re-sort+ expect(doc.keyframes[0].id).toBe(b.id);+ expect(removeKeyframe(doc, b.id)).toBe(true);+ expect(doc.keyframes).toHaveLength(1);+ });+});++describe('sampleAtTime interpolation', () => {+ it('returns null with no keyframes, the pose with one', () => {+ const doc = createDocument();+ expect(sampleAtTime(doc, 0)).toBeNull();+ upsertKeyframe(doc, 1, poseWithArm(0.7));+ const p = sampleAtTime(doc, 0.3);+ expect(p.bones.LeftArm).toBeDefined();+ });++ it('slerps the midpoint to a unit quaternion between the two keyframes', () => {+ const doc = createDocument({ duration: 2 });+ upsertKeyframe(doc, 0, poseWithArm(0), 'linear');+ upsertKeyframe(doc, 2, poseWithArm(Math.PI / 2), 'linear');++ const mid = sampleAtTime(doc, 1);+ const q = new Quaternion(...mid.bones.LeftArm);+ // Unit length preserved (no lerp drift).+ expect(q.length()).toBeCloseTo(1, 5);++ // Halfway slerp of a 90° z-rotation is exactly 45°.+ const expected = new Quaternion().setFromEuler(new Euler(0, 0, Math.PI / 4, 'XYZ'));+ expect(Math.abs(q.dot(expected))).toBeCloseTo(1, 4);+ });++ it('holds the endpoints outside the keyframe range', () => {+ const doc = createDocument({ duration: 4 });+ upsertKeyframe(doc, 1, poseWithArm(0.2), 'linear');+ upsertKeyframe(doc, 3, poseWithArm(0.9), 'linear');+ const start = sampleAtTime(doc, 0);+ const end = sampleAtTime(doc, 4);+ expect(start.bones.LeftArm).toEqual(doc.keyframes[0].pose.bones.LeftArm);+ expect(end.bones.LeftArm).toEqual(doc.keyframes[1].pose.bones.LeftArm);+ });++ it('easing changes the timing without changing the endpoints', () => {+ const lin = createDocument({ duration: 2 });+ upsertKeyframe(lin, 0, poseWithArm(0), 'linear');+ upsertKeyframe(lin, 2, poseWithArm(Math.PI / 2), 'linear');++ const eased = createDocument({ duration: 2 });+ upsertKeyframe(eased, 0, poseWithArm(0), 'ease-in');+ upsertKeyframe(eased, 2, poseWithArm(Math.PI / 2), 'ease-in');++ const angle = (p) => 2 * Math.acos(Math.min(1, Math.abs(p.bones.LeftArm[3])));+ // Ease-in lags behind linear at the first quarter (t²=0.0625 < 0.25).+ expect(angle(sampleAtTime(eased, 0.5))).toBeLessThan(angle(sampleAtTime(lin, 0.5)));+ // Endpoints identical regardless of easing.+ expect(angle(sampleAtTime(eased, 2))).toBeCloseTo(angle(sampleAtTime(lin, 2)), 5);+ });++ it('every easing maps 0→0 and 1→1', () => {+ for (const fn of Object.values(EASINGS)) {+ expect(fn(0)).toBeCloseTo(0, 6);+ expect(fn(1)).toBeCloseTo(1, 6);+ }+ expect(EASINGS[DEFAULT_EASING]).toBeTypeOf('function');+ });+});++describe('bakeClip → toJSON → parse round-trip', () => {+ function walkDoc() {+ const doc = createDocument({ name: 'wave', duration: 2, fps: 24, loop: true });+ upsertKeyframe(doc, 0, poseWithArm(0));+ upsertKeyframe(doc, 1, poseWithArm(Math.PI / 3));+ upsertKeyframe(doc, 2, poseWithArm(0));+ return doc;+ }++ it('bakes canonical track names matching the three.ws clip schema', () => {+ const clip = bakeClip(walkDoc());+ expect(clip).toBeInstanceOf(AnimationClip);+ expect(clip.name).toBe('wave');+ expect(clip.duration).toBeGreaterThan(0);++ const names = clip.tracks.map((t) => t.name);+ expect(names).toContain('LeftArm.quaternion');+ expect(names).toContain('Hips.position');+ // Track name = "<CanonicalBone>.<property>".+ for (const t of clip.tracks) expect(t.name).toMatch(/^[A-Za-z0-9]+\.(quaternion|position)$/);+ });++ it('produces JSON that AnimationClip.parse accepts and round-trips', () => {+ const json = serializeClip(walkDoc());+ expect(json).toHaveProperty('name', 'wave');+ expect(json).toHaveProperty('duration');+ expect(Array.isArray(json.tracks)).toBe(true);++ const reparsed = AnimationClip.parse(json);+ expect(reparsed).toBeInstanceOf(AnimationClip);+ expect(reparsed.tracks.length).toBe(json.tracks.length);+ // No NaN leaked into any keyframe value.+ for (const t of reparsed.tracks) {+ for (const v of t.values) expect(Number.isNaN(v)).toBe(false);+ }+ });++ it('honors a custom bone-name resolver (for GLB embedding)', () => {+ const clip = bakeClip(walkDoc(), {+ resolveBoneName: (k) => (k === 'LeftArm' ? 'mixamorigLeftArm' : null),+ rootName: 'mannequin-root',+ });+ const names = clip.tracks.map((t) => t.name);+ expect(names).toContain('mixamorigLeftArm.quaternion');+ expect(names).toContain('mannequin-root.position');+ // Hips was resolved to null → dropped.+ expect(names.some((n) => n.startsWith('Hips.'))).toBe(false);+ });++ it('throws when baking an empty document', () => {+ expect(() => bakeClip(createDocument())).toThrow(/keyframe/i);+ });+});