Skip to content

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.

feat(pose): trim/blend/loop edit controls and save-to-library for any clip

nirholas58bd13cb9590
diff --git a/pages/pose.html b/pages/pose.html
index f986737c0..b116c8bf1 100644
--- a/pages/pose.html
+++ b/pages/pose.html
@@ -1235,6 +1235,147 @@
border-color: rgba(248, 113, 113, 0.6);
color: var(--danger);
}
+ .al-edit-row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-wrap: wrap;
+ font-size: 11.5px;
+ color: var(--text-3);
+ }
+ .al-edit-field {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ }
+ .al-trim-input,
+ .al-blend-input {
+ appearance: none;
+ width: 56px;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text);
+ font: inherit;
+ font-size: 11.5px;
+ font-family: ui-monospace, monospace;
+ padding: 4px 6px;
+ border-radius: 6px;
+ }
+ .al-trim-input:focus-visible,
+ .al-blend-input:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+ }
+ .al-loop {
+ appearance: none;
+ margin-left: auto;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text-3);
+ font: inherit;
+ font-size: 11.5px;
+ padding: 5px 10px;
+ border-radius: 7px;
+ cursor: pointer;
+ transition: background var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard);
+ }
+ .al-loop:hover {
+ background: rgba(255, 255, 255, 0.09);
+ }
+ .al-loop:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .al-loop.is-on {
+ background: rgba(34, 211, 238, 0.16);
+ border-color: rgba(34, 211, 238, 0.4);
+ color: var(--text);
+ }
+ .al-save {
+ appearance: none;
+ flex: 0 0 auto;
+ border: 1px solid rgba(34, 211, 238, 0.45);
+ background: rgba(34, 211, 238, 0.12);
+ color: var(--text);
+ font: inherit;
+ font-size: 12px;
+ font-weight: 600;
+ padding: 7px 12px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: background var(--duration-fast) var(--ease-standard);
+ }
+ .al-save:hover {
+ background: rgba(34, 211, 238, 0.22);
+ }
+ .al-save:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
+ .al-save:disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
+ }
+ .al-save-form {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .al-save-label {
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ font-size: 12px;
+ color: var(--text-3);
+ }
+ .al-save-name,
+ .al-save-vis {
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text);
+ font: inherit;
+ font-size: 13px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ }
+ .al-save-name:focus-visible,
+ .al-save-vis:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 1px;
+ }
+ .al-save-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ }
+ .al-save-cancel,
+ .al-save-submit {
+ appearance: none;
+ border: 1px solid var(--border);
+ background: rgba(255, 255, 255, 0.04);
+ color: var(--text);
+ font: inherit;
+ font-size: 12.5px;
+ padding: 7px 14px;
+ border-radius: 8px;
+ cursor: pointer;
+ }
+ .al-save-submit {
+ border-color: rgba(34, 211, 238, 0.45);
+ background: rgba(34, 211, 238, 0.16);
+ font-weight: 600;
+ }
+ .al-save-cancel:hover {
+ background: rgba(255, 255, 255, 0.09);
+ }
+ .al-save-submit:hover {
+ background: rgba(34, 211, 238, 0.26);
+ }
+ .al-save-cancel:focus-visible,
+ .al-save-submit:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
+ }
/* ── Timeline ───────────────────────────────────────── */
#pose-timeline {
diff --git a/src/animation-library.js b/src/animation-library.js
index 214eabecc..9e32e82ab 100644
--- a/src/animation-library.js
+++ b/src/animation-library.js
@@ -12,7 +12,7 @@
// the constructor, and signals the host when a preview takes over the figure so
// the keyframe timeline can yield.
-import { AnimationMixer, LoopOnce, LoopRepeat } from 'three';
+import { AnimationClip, AnimationMixer, LoopOnce, LoopRepeat } from 'three';
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
import { curate } from './animation-presets.js';
@@ -21,10 +21,15 @@ import {
retargetClipToRig,
scaleClipSpeed,
parseClipJSON,
+ trimClip,
+ blendClipLoop,
MIN_COVERAGE,
} from './animation-retarget.js';
+import { Modal } from './shared/modal.js';
import { log } from './shared/log.js';
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
const MANIFEST_URL = '/animations/manifest.json';
// A rig needs a real share of the canonical skeleton before presets read as
// performances rather than twitches. Mirrors AnimationManager's bar.
@@ -58,6 +63,7 @@ export class AnimationLibrary {
* @param {{
* host: HTMLElement,
* getRig: () => object|null,
+ * getAvatarId?: () => string|null,
* onPreviewStart?: () => void,
* onPreviewStop?: () => void,
* setStatus?: (msg: string, kind?: string) => void,
@@ -66,6 +72,7 @@ export class AnimationLibrary {
constructor(opts) {
this.host = opts.host;
this.getRig = opts.getRig;
+ this.getAvatarId = opts.getAvatarId || (() => null);
this.onPreviewStart = opts.onPreviewStart || (() => {});
this.onPreviewStop = opts.onPreviewStop || (() => {});
this.setStatus = opts.setStatus || (() => {});
@@ -89,6 +96,17 @@ export class AnimationLibrary {
this._scrubbing = false;
this._state = 'loading';
+ // Trim/blend/loop edits, applied to the active clip before preview,
+ // export, and save. `_baseClip` is the untrimmed canonical clip the
+ // active def resolved to; edits are recomputed from it, never baked in
+ // place, so adjusting a slider always starts from the original motion.
+ this._baseClip = null;
+ this._trimStart = 0;
+ this._trimEnd = null;
+ this._blendMs = 0;
+ this._loopOn = true;
+ this._editDebounce = null;
+
// Resolves once mount() has finished loading the manifest (success or
// failure) — openByName() awaits this so a ?anim=<preset> deep-link works
// even before the gallery has rendered.
@@ -545,7 +563,9 @@ export class AnimationLibrary {
this.setStatus(`Couldn’t load “${def.label || def.name}”: ${err.message}`, 'error');
return;
}
- this._playClip(clip, def);
+ this._baseClip = clip;
+ this._resetEdits(clip.duration, def.loop !== false);
+ this._playClip(this._computeEditedClip(clip), { ...def, loop: this._loopOn });
}
/**
@@ -651,7 +671,9 @@ export class AnimationLibrary {
loop: true,
generated: true,
};
- this._playClip(clip, def);
+ this._baseClip = clip;
+ this._resetEdits(clip.duration, true);
+ this._playClip(this._computeEditedClip(clip), { ...def, loop: this._loopOn });
} catch (err) {
if (token !== this._genToken) return;
this._stopGenTimer();
@@ -735,7 +757,9 @@ export class AnimationLibrary {
loop: false,
spelled: true,
};
- return this._playClip(clip, def);
+ this._baseClip = clip;
+ this._resetEdits(clip.duration, false);
+ return this._playClip(this._computeEditedClip(clip), { ...def, loop: this._loopOn });
}
_stopGenTimer() {
@@ -780,6 +804,175 @@ export class AnimationLibrary {
this._updateTransport();
}
+ // ── Trim / blend / loop edits ────────────────────────────────────────────
+ /** Reset the trim/blend/loop controls for a newly-loaded clip. */
+ _resetEdits(duration, loopDefault) {
+ this._trimStart = 0;
+ this._trimEnd = duration;
+ this._blendMs = 0;
+ this._loopOn = loopDefault !== false;
+ const { trimStartInput, trimEndInput, blendInput, loopBtn } = this._refs;
+ if (trimStartInput) {
+ trimStartInput.max = duration.toFixed(2);
+ trimStartInput.value = '0';
+ }
+ if (trimEndInput) {
+ trimEndInput.max = duration.toFixed(2);
+ trimEndInput.value = duration.toFixed(2);
+ }
+ if (blendInput) blendInput.value = '0';
+ if (loopBtn) {
+ loopBtn.setAttribute('aria-pressed', String(this._loopOn));
+ loopBtn.classList.toggle('is-on', this._loopOn);
+ }
+ }
+
+ /** Apply the current trim range and loop-blend to `base`, never mutating it. */
+ _computeEditedClip(base) {
+ const duration = base.duration;
+ const start = Math.max(0, Math.min(this._trimStart, duration));
+ const end = Math.max(start + 1 / 60, Math.min(this._trimEnd ?? duration, duration));
+ const trimmed =
+ start > 1e-3 || end < duration - 1e-3 ? trimClip(base, start, end) : base;
+ const edited =
+ this._loopOn && this._blendMs > 0 ? blendClipLoop(trimmed, this._blendMs / 1000) : trimmed;
+ if (edited !== base) edited.name = base.name;
+ return edited;
+ }
+
+ /** Re-derive and replay the edited clip after a trim/blend/loop control changes. */
+ _onEditsChanged() {
+ if (!this._baseClip || !this._activeDef) return;
+ const wasPaused = this._paused;
+ const edited = this._computeEditedClip(this._baseClip);
+ const played = this._playClip(edited, { ...this._activeDef, loop: this._loopOn });
+ if (played && wasPaused) {
+ this._action.paused = true;
+ this._paused = true;
+ this._updatePlayIcon();
+ }
+ }
+
+ _debounceEdits() {
+ clearTimeout(this._editDebounce);
+ this._editDebounce = setTimeout(() => this._onEditsChanged(), 180);
+ }
+
+ _onTrimInput() {
+ const { trimStartInput, trimEndInput } = this._refs;
+ const duration = this._baseClip?.duration || 0;
+ let start = Math.max(0, parseFloat(trimStartInput.value) || 0);
+ let end = parseFloat(trimEndInput.value);
+ if (!Number.isFinite(end)) end = duration;
+ if (end <= start) end = Math.min(duration, start + 0.1);
+ start = Math.min(start, duration);
+ this._trimStart = start;
+ this._trimEnd = end;
+ this._debounceEdits();
+ }
+
+ // ── Save to library ──────────────────────────────────────────────────────
+ /**
+ * Save the active clip (with current trim/blend/loop edits applied) to the
+ * signed-in user's animation library. Saves the canonical, pre-retarget
+ * clip, the same basis AnimationManager plays everywhere, so it plays on
+ * any future rig, not just the one currently loaded.
+ */
+ async _saveToLibrary(btn) {
+ if (!this._baseClip || !this._activeDef) return;
+
+ const defaultName = this._activeDef.label || this._activeDef.name || 'My animation';
+ const nameInput = el('input', {
+ type: 'text',
+ class: 'al-save-name',
+ value: defaultName,
+ maxlength: '120',
+ required: 'true',
+ autocomplete: 'off',
+ 'aria-label': 'Animation name',
+ });
+ const visSelect = el('select', { class: 'al-save-vis', 'aria-label': 'Visibility' }, [
+ el('option', { value: 'private' }, ['Private (only you)']),
+ el('option', { value: 'unlisted' }, ['Unlisted (anyone with the link)']),
+ el('option', { value: 'public' }, ['Public (listed in the library)']),
+ ]);
+ const cancelBtn = el('button', { type: 'button', class: 'al-save-cancel' }, ['Cancel']);
+ const submitBtn = el('button', { type: 'submit', class: 'al-save-submit' }, ['Save']);
+ const form = el('form', { class: 'al-save-form' }, [
+ el('label', { class: 'al-save-label' }, ['Name', nameInput]),
+ el('label', { class: 'al-save-label' }, ['Visibility', visSelect]),
+ el('div', { class: 'al-save-actions' }, [cancelBtn, submitBtn]),
+ ]);
+
+ let resolved = false;
+ const choice = await new Promise((resolve) => {
+ const settle = (v) => {
+ if (resolved) return;
+ resolved = true;
+ resolve(v);
+ };
+ const modal = new Modal({
+ title: 'Save to your animation library',
+ body: form,
+ dismissible: true,
+ onClose: () => settle(null),
+ });
+ cancelBtn.addEventListener('click', () => modal.close());
+ form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ settle({ name: nameInput.value.trim(), visibility: visSelect.value });
+ modal.close();
+ });
+ modal.open(btn);
+ nameInput.focus();
+ nameInput.select();
+ });
+ if (!choice || !choice.name) return;
+
+ const original = btn.textContent;
+ btn.disabled = true;
+ btn.textContent = 'Saving…';
+ try {
+ const clip = this._computeEditedClip(this._baseClip);
+ const avatarId = this.getAvatarId();
+ const res = await fetch('/api/animations/clips', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ name: choice.name,
+ visibility: choice.visibility,
+ kind: this._loopOn ? 'loop' : 'animation',
+ loop: this._loopOn,
+ avatar_id: avatarId && UUID_RE.test(avatarId) ? avatarId : undefined,
+ clip: AnimationClip.toJSON(clip),
+ }),
+ });
+ if (res.status === 401) {
+ btn.disabled = false;
+ btn.textContent = original;
+ this.setStatus('Sign in to save animations to your library.', 'error');
+ window.location.assign(
+ `/login?next=${encodeURIComponent(window.location.pathname + window.location.search)}`,
+ );
+ return;
+ }
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data.message || `HTTP ${res.status}`);
+ btn.textContent = 'Saved ✓';
+ this.setStatus(`Saved “${choice.name}” to your animation library.`);
+ } catch (err) {
+ log.warn('[AnimationLibrary] save failed:', err);
+ btn.textContent = 'Failed';
+ this.setStatus(`Save failed: ${err.message}`, 'error');
+ } finally {
+ setTimeout(() => {
+ btn.disabled = false;
+ btn.textContent = original;
+ }, 2400);
+ }
+ }
+
// ── Transport bar (now-playing + speed + loop + stop + export) ────────────
_renderTransport() {
const label = el('span', { class: 'al-now-label' });
@@ -838,11 +1031,86 @@ export class AnimationLibrary {
);
exportBtn.addEventListener('click', () => this._exportGLB(exportBtn));
+ const saveBtn = el(
+ 'button',
+ {
+ class: 'al-save',
+ type: 'button',
+ title: 'Save this clip to your animation library',
+ },
+ ['💾 Save to library'],
+ );
+ saveBtn.addEventListener('click', () => this._saveToLibrary(saveBtn));
+
+ // Trim / blend / loop: cut the clip to a range and crossfade the loop seam,
+ // the same editing affordances a Theatre.js-style timeline offers, applied
+ // to the resolved clip (preset, generated, or spelled) before preview,
+ // export, and save all see it.
+ const trimStartInput = el('input', {
+ type: 'number',
+ class: 'al-trim-input',
+ min: '0',
+ step: '0.1',
+ value: '0',
+ 'aria-label': 'Trim start, in seconds',
+ title: 'Trim start (s)',
+ });
+ const trimEndInput = el('input', {
+ type: 'number',
+ class: 'al-trim-input',
+ min: '0',
+ step: '0.1',
+ value: '0',
+ 'aria-label': 'Trim end, in seconds',
+ title: 'Trim end (s)',
+ });
+ trimStartInput.addEventListener('input', () => this._onTrimInput());
+ trimEndInput.addEventListener('input', () => this._onTrimInput());
+
+ const blendInput = el('input', {
+ type: 'number',
+ class: 'al-blend-input',
+ min: '0',
+ max: '2000',
+ step: '50',
+ value: '0',
+ 'aria-label': 'Loop blend, in milliseconds',
+ title: 'Crossfade the loop seam (ms)',
+ });
+ blendInput.addEventListener('input', () => {
+ this._blendMs = Math.max(0, Math.min(2000, parseFloat(blendInput.value) || 0));
+ this._debounceEdits();
+ });
+
+ const loopBtn = el(
+ 'button',
+ {
+ class: 'al-loop is-on',
+ type: 'button',
+ 'aria-pressed': 'true',
+ title: 'Toggle looping',
+ },
+ ['🔁 Loop'],
+ );
+ loopBtn.addEventListener('click', () => {
+ this._loopOn = !this._loopOn;
+ loopBtn.setAttribute('aria-pressed', String(this._loopOn));
+ loopBtn.classList.toggle('is-on', this._loopOn);
+ this._onEditsChanged();
+ });
+
+ const editRow = el('div', { class: 'al-edit-row' }, [
+ el('label', { class: 'al-edit-field' }, ['Trim', trimStartInput, 'to', trimEndInput, 's']),
+ el('label', { class: 'al-edit-field' }, ['Blend', blendInput, 'ms']),
+ loopBtn,
+ ]);
+
const root = el('div', { class: 'al-transport', style: 'display:none' }, [
el('div', { class: 'al-now' }, [el('span', { class: 'al-now-dot' }), label]),
el('div', { class: 'al-scrub-row' }, [play, scrub, timeLabel]),
el('div', { class: 'al-speed-row' }, [el('label', {}, ['Speed']), speed, speedVal]),
- el('div', { class: 'al-transport-actions' }, [stop, exportBtn]),
+ editRow,
+ el('div', { class: 'al-transport-actions' }, [stop, saveBtn, exportBtn]),
]);
this._refs = {
@@ -854,6 +1122,11 @@ export class AnimationLibrary {
transportScrub: scrub,
transportTime: timeLabel,
exportBtn,
+ saveBtn,
+ trimStartInput,
+ trimEndInput,
+ blendInput,
+ loopBtn,
};
return { root };
}
@@ -869,7 +1142,7 @@ export class AnimationLibrary {
async _exportGLB(btn) {
const rig = this.getRig();
- if (!rig || !this._activeDef) return;
+ if (!rig || !this._activeDef || !this._baseClip) return;
const original = btn.textContent;
const done = (txt, cls) => {
btn.classList.remove('is-busy', 'is-ok', 'is-err');
@@ -883,7 +1156,7 @@ export class AnimationLibrary {
btn.classList.add('is-busy');
btn.textContent = 'Baking…';
try {
- const base = await this._loadClip(this._activeDef);
+ const base = this._computeEditedClip(this._baseClip);
const { clip } = retargetClipToRig(base, rig);
if (!clip) throw new Error('retarget failed');
const exportClip = scaleClipSpeed(clip, this._speed);
diff --git a/src/animation-retarget.js b/src/animation-retarget.js
index ecb02f078..a7a8f79af 100644
--- a/src/animation-retarget.js
+++ b/src/animation-retarget.js
@@ -925,3 +925,112 @@ export function parseClipJSON(json, name) {
if (name) clip.name = name;
return clip;
}
+
+/**
+ * Cut a clip down to [startTime, endTime] (seconds, clamped to the clip's own
+ * duration) and re-zero its times so the trimmed clip starts at 0. Used by
+ * Animation Studio's trim handles before export/save so a generated or preset
+ * clip can be shortened to the useful part without re-authoring it as
+ * keyframes.
+ *
+ * Boundary samples are taken through each track's own interpolant (quaternion
+ * tracks slerp, vector tracks lerp) rather than nearest-keyframe, so a cut that
+ * lands between two keyframes still starts and ends on the exact pose the
+ * player would have shown there.
+ *
+ * @param {AnimationClip} clip
+ * @param {number} startTime
+ * @param {number} endTime
+ * @returns {AnimationClip}
+ */
+export function trimClip(clip, startTime, endTime) {
+ const duration = clip.duration;
+ const start = Math.max(0, Math.min(startTime, duration));
+ const end = Math.max(start + 1 / 1000, Math.min(endTime, duration));
+ if (start <= 1e-6 && end >= duration - 1e-6) return clip.clone();
+
+ const out = clip.clone();
+ for (let i = 0; i < out.tracks.length; i++) {
+ const srcTrack = clip.tracks[i];
+ const track = out.tracks[i];
+ const itemSize = track.values.length / track.times.length;
+ const interpolant = srcTrack.createInterpolant();
+
+ const newTimes = [start];
+ const newValues = Array.from(interpolant.evaluate(start));
+ for (let t = 0; t < srcTrack.times.length; t++) {
+ const time = srcTrack.times[t];
+ if (time > start && time < end) {
+ newTimes.push(time);
+ const i0 = t * itemSize;
+ for (let c = 0; c < itemSize; c++) newValues.push(srcTrack.values[i0 + c]);
+ }
+ }
+ newTimes.push(end);
+ newValues.push(...interpolant.evaluate(end));
+
+ const ctor = track.constructor;
+ out.tracks[i] = new ctor(
+ track.name,
+ newTimes.map((t) => t - start),
+ newValues,
+ );
+ }
+ out.duration = end - start;
+ out.resetDuration();
+ return out;
+}
+
+// Quaternion track names end in `.quaternion`; every other track this platform
+// authors (`.position`, `.scale`) blends with plain per-component lerp.
+const QUATERNION_TRACK_RE = /\.quaternion$/;
+
+/**
+ * Crossfade the tail of a clip into its own first pose so it loops without a
+ * pop. Standard game-animation "loop blend": over the last `blendSeconds` of
+ * the clip, each track's samples are interpolated (slerp for quaternion
+ * tracks, lerp otherwise) toward the value the clip started with, weighted by
+ * how far into the blend window the sample sits, so the last frame equals the
+ * first frame exactly, and the approach is gradual rather than a jump cut.
+ *
+ * @param {AnimationClip} clip
+ * @param {number} blendSeconds
+ * @returns {AnimationClip}
+ */
+export function blendClipLoop(clip, blendSeconds) {
+ const maxBlend = clip.duration / 2;
+ const blend = Math.max(0, Math.min(blendSeconds, maxBlend));
+ if (blend <= 1e-6) return clip.clone();
+
+ const out = clip.clone();
+ const blendStart = clip.duration - blend;
+ const q1 = new Quaternion();
+ const q2 = new Quaternion();
+
+ for (let i = 0; i < out.tracks.length; i++) {
+ const srcTrack = clip.tracks[i];
+ const track = out.tracks[i];
+ const isQuat = QUATERNION_TRACK_RE.test(track.name);
+ const itemSize = track.values.length / track.times.length;
+ const startValues = Array.from(srcTrack.createInterpolant().evaluate(0));
+
+ for (let t = 0; t < track.times.length; t++) {
+ const time = track.times[t];
+ if (time < blendStart) continue;
+ const weight = Math.min(1, (time - blendStart) / blend);
+ const i0 = t * itemSize;
+ if (isQuat) {
+ q1.fromArray(track.values, i0);
+ q2.fromArray(startValues, 0);
+ q1.slerp(q2, weight).toArray(track.values, i0);
+ } else {
+ for (let c = 0; c < itemSize; c++) {
+ const a = track.values[i0 + c];
+ const b = startValues[c];
+ track.values[i0 + c] = a + (b - a) * weight;
+ }
+ }
+ }
+ }
+ return out;
+}
diff --git a/src/pose-studio.js b/src/pose-studio.js
index b171d123a..52226d205 100644
--- a/src/pose-studio.js
+++ b/src/pose-studio.js
@@ -1286,6 +1286,7 @@ function boot() {
const animLibrary = new AnimationLibrary({
host: animLibraryHost,
getRig: () => state.rig,
+ getAvatarId: () => state.avatar?.id || null,
setStatus,
onPreviewStart: () => {
timeline?.pause?.();
diff --git a/tests/animation-retarget.test.js b/tests/animation-retarget.test.js
index f7363ffe7..3e7b31131 100644
--- a/tests/animation-retarget.test.js
+++ b/tests/animation-retarget.test.js
@@ -40,6 +40,8 @@ import {
retargetClip,
retargetClipToObject,
scaleClipSpeed,
+ trimClip,
+ blendClipLoop,
MIN_COVERAGE,
} from '../src/animation-retarget.js';
import { CANONICAL_REST, CANONICAL_REST_WORLD } from '../src/animation-canonical-rest.js';
@@ -97,6 +99,18 @@ function makeCanonicalClip() {
return new AnimationClip('test', 1, [q, spine, arm, pos]);
}
+// A 3-keyframe clip with distinct values at every sample (makeCanonicalClip's
+// identity-at-both-ends shape can't tell slerp/lerp apart), for trim/blend math.
+function makeMovingClip() {
+ const q = new QuaternionKeyframeTrack(
+ 'Hips.quaternion',
+ [0, 1, 2],
+ [0, 0, 0, 1, 0, 0.7071067811865476, 0, 0.7071067811865476, 0, 1, 0, 0],
+ );
+ const pos = new VectorKeyframeTrack('Hips.position', [0, 1, 2], [0, 1, 0, 0, 1, 1, 0, 1, 2]);
+ return new AnimationClip('moving', 2, [q, pos]);
+}
+
const CANONICAL_RIG = ['Hips', 'Spine', 'LeftArm', 'RightArm', 'Head'];
describe('canonicalNodeMapFromObject', () => {
@@ -487,6 +501,89 @@ describe('scaleClipSpeed', () => {
});
});
+describe('trimClip', () => {
+ it('returns a clone, unchanged, when the range covers the whole clip', () => {
+ const clip = makeMovingClip();
+ const out = trimClip(clip, 0, clip.duration);
+ expect(out).not.toBe(clip);
+ expect(out.duration).toBeCloseTo(clip.duration, 5);
+ expect(Array.from(out.tracks[0].values)).toEqual(Array.from(clip.tracks[0].values));
+ });
+
+ it('shortens duration and shifts kept keyframes to start at 0', () => {
+ const clip = makeMovingClip(); // duration 2, keyframes at 0/1/2
+ const out = trimClip(clip, 1, 2);
+ expect(out.duration).toBeCloseTo(1, 5);
+ const posTrack = out.tracks.find((t) => t.name === 'Hips.position');
+ expect(Array.from(posTrack.times)).toEqual([0, 1]);
+ // Original values at t=1 and t=2 were [0,1,1] and [0,1,2].
+ expect(Array.from(posTrack.values)).toEqual([0, 1, 1, 0, 1, 2]);
+ });
+
+ it('interpolates a boundary that falls between keyframes', () => {
+ const clip = makeMovingClip();
+ const out = trimClip(clip, 0.5, 1.5);
+ const posTrack = out.tracks.find((t) => t.name === 'Hips.position');
+ // Lerp of [0,1,0]→[0,1,1] at 0.5 is [0,1,0.5]; the start boundary sample.
+ expect(posTrack.values[0]).toBeCloseTo(0, 5);
+ expect(posTrack.values[1]).toBeCloseTo(1, 5);
+ expect(posTrack.values[2]).toBeCloseTo(0.5, 5);
+ });
+
+ it('does not mutate the source clip', () => {
+ const clip = makeMovingClip();
+ const beforeDur = clip.duration;
+ const beforeValues = Array.from(clip.tracks[0].values);
+ trimClip(clip, 1, 2);
+ expect(clip.duration).toBe(beforeDur);
+ expect(Array.from(clip.tracks[0].values)).toEqual(beforeValues);
+ });
+});
+
+describe('blendClipLoop', () => {
+ it('returns a clone, unchanged, when blendSeconds is 0', () => {
+ const clip = makeMovingClip();
+ const out = blendClipLoop(clip, 0);
+ expect(out).not.toBe(clip);
+ expect(Array.from(out.tracks[0].values)).toEqual(Array.from(clip.tracks[0].values));
+ });
+
+ it('slerps the quaternion tail toward the clip start as the seam approaches', () => {
+ const clip = makeMovingClip(); // duration 2, blend of 1s starts at t=1
+ const out = blendClipLoop(clip, 1);
+ const quatTrack = out.tracks.find((t) => t.name === 'Hips.quaternion');
+ // At the blend start (t=1, weight 0) the value is untouched.
+ expect(quatTrack.values[4]).toBeCloseTo(0, 5);
+ expect(quatTrack.values[5]).toBeCloseTo(0.7071067811865476, 5);
+ // At the seam (t=2, weight 1) it fully matches the clip's own start pose.
+ expect(quatTrack.values[8]).toBeCloseTo(0, 5);
+ expect(quatTrack.values[9]).toBeCloseTo(0, 5);
+ expect(quatTrack.values[10]).toBeCloseTo(0, 5);
+ expect(quatTrack.values[11]).toBeCloseTo(1, 5);
+ });
+
+ it('lerps a vector track toward its start value at the seam', () => {
+ const clip = makeMovingClip();
+ const out = blendClipLoop(clip, 1);
+ const posTrack = out.tracks.find((t) => t.name === 'Hips.position');
+ expect(Array.from(posTrack.values.slice(6, 9))).toEqual([0, 1, 0]); // t=2 → start value
+ });
+
+ it('clamps the blend window to half the clip length', () => {
+ const clip = makeMovingClip(); // duration 2 → max blend 1s
+ const out = blendClipLoop(clip, 10);
+ const posTrack = out.tracks.find((t) => t.name === 'Hips.position');
+ expect(Array.from(posTrack.values.slice(6, 9))).toEqual([0, 1, 0]);
+ });
+
+ it('does not mutate the source clip', () => {
+ const clip = makeMovingClip();
+ const beforeValues = Array.from(clip.tracks[0].values);
+ blendClipLoop(clip, 1);
+ expect(Array.from(clip.tracks[0].values)).toEqual(beforeValues);
+ });
+});
+
// ---------------------------------------------------------------------------
// Cross-rig locomotion invariants, validated against the real shipped GLB rigs
// (cz.glb, michelle.glb) plus two synthetic conventions, using a raw GLB parse