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: implement idle animation for pinned agents and enhance AR ceremony experience

nirholas1b2071894959
diff --git a/src/irl.js b/src/irl.js
index be3059dac..0ac14508d 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -5,6 +5,7 @@
// Walking + joystick from walk-embed. Camera mode makes the real floor the stage.
import {
+ ACESFilmicToneMapping,
AmbientLight,
Box3,
BoxGeometry,
@@ -19,7 +20,7 @@ import {
MeshStandardMaterial,
OctahedronGeometry,
OrthographicCamera,
- PCFShadowMap,
+ PCFSoftShadowMap,
PerspectiveCamera,
PlaneGeometry,
PMREMGenerator,
@@ -55,6 +56,7 @@ import { startOnboarding, ensurePermission, needsMotionGesture, setPermissionSta
import { reserveWebGLContext, releaseWebGLContext } from './webgl-budget.js';
import { detectTier, BUDGETS, TIER_ORDER, shiftTier } from './irl/perf-budget.js';
import { sharedGLTFLoader, createLoadQueue } from './irl/load-queue.js';
+import { mountPinIdle, getIdleClipJson } from './irl/pin-idle.js';
import { createWealthAura3D } from './shared/wealth-aura-3d.js';
import { fetchWealthState } from './shared/agent-wealth-state.js';
import { trackLevelUp, installLevelUpCelebrations } from './shared/wealth-levelup.js';
@@ -199,18 +201,27 @@ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.setClearColor(0x000000, 0);
renderer.shadowMap.enabled = true;
-renderer.shadowMap.type = PCFShadowMap;
+renderer.shadowMap.type = PCFSoftShadowMap;
+// Filmic tone mapping is what separates "sticker pasted on the camera feed"
+// from "object standing in the room" — highlight rolloff + midtone contrast,
+// the same treatment Quick Look applies to a USDZ. Exposure compensates for
+// ACES's overall darkening at these light levels.
+renderer.toneMapping = ACESFilmicToneMapping;
+renderer.toneMappingExposure = 1.15;
const scene = new Scene();
const pmrem = new PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
-const ambientLight = new AmbientLight(0xffffff, 0.55);
+// Keyed like a studio portrait, not a flood: the IBL carries the specular/rim
+// detail, the sun carries shape + shadow. The old 0.55 ambient + 0.6 hemi fill
+// flattened every model into a cardboard cutout.
+const ambientLight = new AmbientLight(0xffffff, 0.3);
scene.add(ambientLight);
-const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.6);
+const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.45);
hemi.position.set(0, 5, 0);
scene.add(hemi);
-const sun = new DirectionalLight(0xffffff, 1.4);
+const sun = new DirectionalLight(0xffffff, 1.55);
sun.position.set(4, 8, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
@@ -248,6 +259,32 @@ const glbQueue = createLoadQueue({
priorityOf: (pin) => (pin._lodDist != null ? pin._lodDist : (pin.distance_m != null ? pin.distance_m : 1e9)),
});
+// Warm the shared idle clip while the first GLBs are still downloading, so a
+// freshly mounted pin can start breathing on its very first frame.
+getIdleClipJson();
+
+// Anisotropic filtering on every model texture — cloth/skin detail stays sharp
+// at the oblique angles an avatar standing on the real floor is actually seen
+// from. Capped at 8: past that the visual gain is nil and the bandwidth isn't.
+const _maxAniso = Math.min(8, renderer.capabilities.getMaxAnisotropy() || 1);
+const _ANISO_SLOTS = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'aoMap', 'emissiveMap'];
+function sharpenModelTextures(root) {
+ root.traverse((n) => {
+ if (!n.isMesh) return;
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ for (const m of mats) {
+ if (!m) continue;
+ for (const slot of _ANISO_SLOTS) {
+ const tex = m[slot];
+ if (tex && tex.anisotropy < _maxAniso) {
+ tex.anisotropy = _maxAniso;
+ tex.needsUpdate = true;
+ }
+ }
+ }
+ });
+}
+
// Apply the active tier to the renderer + load queue. Called at boot and each
// time the watchdog steps the tier. Idempotent.
function applyTierToRenderer() {
@@ -1057,6 +1094,7 @@ async function loadAvatar(idOrUrl, nameOverride) {
if (n.material?.envMapIntensity !== undefined) n.material.envMapIntensity = 0.85;
}
});
+ sharpenModelTextures(avatar);
const box = new Box3().setFromObject(avatar);
avatar.position.y -= box.min.y;
avatarRig.add(avatar);
@@ -2737,6 +2775,11 @@ const xrViewer = {
_updateRenderLoop() { startTick(); },
};
+// While an immersive WebXR session runs, ITS loop renders the scene and IRL's
+// tick is parked — pins would freeze mid-idle without this hook (the XR loop
+// calls each after-animate hook with dt every frame).
+xrViewer._afterAnimateHooks.push((dt) => updatePinIdles(dt));
+
// Single owner of the IRL render loop's RAF handle so WebXRSession can pause it
// (cancelAnimationFrame on xrViewer._rafId) while the XR animation loop runs,
// then resume it on exit via _updateRenderLoop().
@@ -3656,6 +3699,8 @@ function flashPinLabel(pin) {
// drop the DOM label. The single place that knows the full E2 resource set.
function disposePin(p) {
cancelPinGLB(p);
+ // Idle mixer first — its actions bind the skeleton the group disposal frees.
+ if (p.animMgr) { p.animMgr.detach(); p.animMgr = null; }
// Tear the impostor down FIRST, in the correct order (null the sprite material's
// texture ref → dispose material → dispose RT + its texture). If the group
// traversal below reached the sprite instead, it would dispose the RT's texture
@@ -4233,8 +4278,10 @@ function _ensureSnapRig() {
if (_snapScene) return;
_snapScene = new Scene();
_snapCam = new OrthographicCamera(-1, 1, 1, -1, 0.01, 100);
- _snapScene.add(new AmbientLight(0xffffff, 0.9));
- const key = new DirectionalLight(0xffffff, 1.25);
+ // Balanced against the main scene's ambient/hemi/sun + IBL (the environment
+ // is assigned per-bake below) so an impostor reads like the model it replaces.
+ _snapScene.add(new AmbientLight(0xffffff, 0.45));
+ const key = new DirectionalLight(0xffffff, 1.4);
key.position.set(2, 4, 5);
_snapScene.add(key);
}
@@ -4247,6 +4294,9 @@ const _snapCenter = new Vector3();
// the impostor's feet land where the model's did.
function bakeImpostor(model) {
_ensureSnapRig();
+ // Share the live scene's IBL (re-read each bake — it's rebuilt on context
+ // restore) so a billboard's shading matches the full model it stands in for.
+ _snapScene.environment = scene.environment;
_snapBox.setFromObject(model);
_snapBox.getSize(_snapSize);
_snapBox.getCenter(_snapCenter);
@@ -4326,15 +4376,28 @@ function requestPinGLB(pin, bakeOnly = false) {
});
}
-function onPinGLBLoaded(pin, gltf) {
+async function onPinGLBLoaded(pin, gltf) {
// The pin may have been removed (walked out of the fetch radius) mid-flight.
if (!pin.group) { disposeObject3D(gltf.scene); return; }
const model = gltf.scene;
const castShadow = budget.shadow > 0;
model.traverse(n => { if (n.isMesh) { n.castShadow = castShadow; n.frustumCulled = false; } });
+ sharpenModelTextures(model);
const box = new Box3().setFromObject(model);
model.position.y -= box.min.y; // feet to ground
+ // Bring the rig to life BEFORE the impostor bake so the snapshot (and the
+ // mounted model) show a natural idle stance, never the bind-pose T. The await
+ // is bounded: the clip JSON is one page-wide cached fetch. A rig that can't
+ // be driven (prop, non-humanoid) returns null and stays static as before.
+ const animMgrForPin = await mountPinIdle(model, { avatarUrl: pin.avatar_url });
+ // Re-check: the pin may have been disposed while the clip was fetching.
+ if (!pin.group) {
+ animMgrForPin?.detach();
+ disposeObject3D(model);
+ return;
+ }
+
// Bake the impostor once; reused whenever this agent later recedes past lodNear.
if (!pin._impostorRT) {
try {
@@ -4346,6 +4409,7 @@ function onPinGLBLoaded(pin, gltf) {
// If the viewer receded past lodNear during the load (or this was a bake-only
// request), don't mount the skinned mesh — the impostor we just baked covers it.
if (pin._bakeOnly || pin._lod !== 'full') {
+ animMgrForPin?.detach();
disposeObject3D(model);
if (pin._lod === 'impostor') { hideDot(pin); showImpostor(pin); }
return;
@@ -4355,6 +4419,7 @@ function onPinGLBLoaded(pin, gltf) {
hideDot(pin); hideImpostor(pin);
pin.group.add(model);
pin.model = model;
+ pin.animMgr = animMgrForPin;
pin.glbLoaded = true;
pin.group.rotation.y = pinYawRad(pin);
pin.group.position.y = pinHeightM(pin);
@@ -4385,6 +4450,9 @@ function onPinGLBLoaded(pin, gltf) {
// memory regardless of how many pins the user walks past.
function evictPinGLB(pin) {
if (!pin.glbLoaded || !pin.model) return;
+ // Stop the idle mixer FIRST so no orphaned action keeps binding the skeleton
+ // we're about to dispose (same ordering the carried avatar's _clearAvatar uses).
+ if (pin.animMgr) { pin.animMgr.detach(); pin.animMgr = null; }
pin.group.remove(pin.model);
disposeObject3D(pin.model);
pin.model = null;
@@ -6377,6 +6445,16 @@ const _gazeTargetLocal = new Quaternion();
function _byAwareDist(a, b) { return a._dist2D - b._dist2D; }
+// Advance each mounted pin's idle mixer. Cost is bounded by the LOD budget:
+// only pins at the 'full' band ever hold an animMgr (≤ budget.maxGLB of them).
+// Runs from tick() in the normal loop and from the WebXR after-animate hook
+// while an immersive session drives rendering instead.
+function updatePinIdles(dt) {
+ for (const pin of nearbyPins) {
+ if (pin.animMgr) pin.animMgr.update(dt);
+ }
+}
+
// Rotate a head/torso bone so its neutral (rest) orientation is offset by a
// clamped yaw + pitch about WORLD axes — natural neck movement that reads right
// on any rig without knowing the bone's local "face" axis. `_gazePitchAxis`
@@ -6394,6 +6472,23 @@ function driveGazeBone(bone, restLocalQuat, yaw, pitch, slerpT) {
bone.quaternion.slerp(_gazeTargetLocal, slerpT);
}
+// Same clamped world-axis yaw+pitch offset as driveGazeBone, but composed ON TOP
+// of whatever pose the pin's idle mixer wrote this frame — newLocal = Wp⁻¹·O·Wp·L,
+// so worldAfter = O·worldBefore. driveGazeBone slerps from a captured rest pose,
+// which a running mixer would overwrite every frame; this variant is stateless
+// per frame (the easing lives in the caller's pin._gazeYaw/_gazePitch scalars).
+// `_gazePitchAxis` must already hold the horizontal axis to pitch about.
+function applyGazeOffset(bone, yaw, pitch) {
+ bone.parent.getWorldQuaternion(_gazeParentWorld);
+ _gazeYawQuat.setFromAxisAngle(upY, yaw);
+ _gazePitchQuat.setFromAxisAngle(_gazePitchAxis, pitch);
+ _gazeOffsetQuat.multiplyQuaternions(_gazeYawQuat, _gazePitchQuat);
+ _gazeParentInv.copy(_gazeParentWorld).invert();
+ _gazeTargetWorld.multiplyQuaternions(_gazeOffsetQuat, _gazeParentWorld);
+ _gazeTargetLocal.multiplyQuaternions(_gazeParentInv, _gazeTargetWorld);
+ bone.quaternion.premultiply(_gazeTargetLocal);
+}
+
// Turn loaded nearby agents toward the viewer. Called from tick() right after
// animMgr.update(dt) and before label projection. Pure client render logic over
// nearbyPins — no data, no network. Cheap: only the nearest few, on-screen,
@@ -6444,7 +6539,7 @@ function updateAgentAwareness(dt) {
pin.group.rotation.y = lerpAngle(pin.group.rotation.y, wantYaw, BODY_SLERP);
// 2) Head/torso: lead the body toward the camera inside a natural cone.
- if (gazeBone && restQuat) {
+ if (gazeBone && (pin.animMgr || restQuat)) {
// Yaw the head should add beyond the body's current facing.
let resYaw = ((wantYaw - pin.group.rotation.y + Math.PI) % (Math.PI * 2)) - Math.PI;
if (resYaw < -Math.PI) resYaw += Math.PI * 2;
@@ -6457,16 +6552,39 @@ function updateAgentAwareness(dt) {
);
const inv = 1 / Math.max(dist, 1e-6);
_gazePitchAxis.set(-dz * inv, 0, dx * inv); // = cross(toward-camera, up)
- driveGazeBone(gazeBone, restQuat, resYaw, pitch,
- pin.noticeT > 0 ? HEAD_SLERP_NOTICE : HEAD_SLERP);
+ const rate = pin.noticeT > 0 ? HEAD_SLERP_NOTICE : HEAD_SLERP;
+ if (pin.animMgr) {
+ // The idle mixer rewrites this bone every frame, so a persistent
+ // slerp can never accumulate. Ease scalar offsets instead and stamp
+ // the full clamped offset onto the mixer's pose each frame.
+ pin._gazeYaw = (pin._gazeYaw || 0) + (resYaw - (pin._gazeYaw || 0)) * rate;
+ pin._gazePitch = (pin._gazePitch || 0) + (pitch - (pin._gazePitch || 0)) * rate;
+ applyGazeOffset(gazeBone, pin._gazeYaw, pin._gazePitch);
+ } else {
+ driveGazeBone(gazeBone, restQuat, resYaw, pitch, rate);
+ }
}
pin.idleT = 0;
} else {
// Not engaged: ease the body back to its placed heading...
const baseYaw = pin.baseYaw != null ? pin.baseYaw : pin.group.rotation.y;
pin.group.rotation.y = lerpAngle(pin.group.rotation.y, baseYaw, BODY_RETURN_SLERP);
- // ...and play a slow gaze drift so an idle agent never reads as frozen.
- if (gazeBone && restQuat) {
+ if (gazeBone && pin.animMgr) {
+ // The idle clip already carries natural head motion; just bleed any
+ // leftover engaged-gaze offset back to zero so disengaging never snaps.
+ const gy = pin._gazeYaw || 0, gp = pin._gazePitch || 0;
+ if (Math.abs(gy) > 0.002 || Math.abs(gp) > 0.002) {
+ pin._gazeYaw = gy * (1 - HEAD_SLERP * 0.5);
+ pin._gazePitch = gp * (1 - HEAD_SLERP * 0.5);
+ const fy = pin.group.rotation.y; // body forward = (sin fy, 0, cos fy)
+ _gazePitchAxis.set(-Math.cos(fy), 0, Math.sin(fy)); // cross(forward, up)
+ applyGazeOffset(gazeBone, pin._gazeYaw, pin._gazePitch);
+ } else {
+ pin._gazeYaw = pin._gazePitch = 0;
+ }
+ } else if (gazeBone && restQuat) {
+ // No mixer on this rig — play the old scripted gaze drift so a static
+ // (non-humanoid / unriggable) agent still never reads as frozen.
pin.idleT = (pin.idleT || 0) + dt;
const driftYaw = Math.sin(pin.idleT * 0.4) * 0.12;
const driftPitch = Math.sin(pin.idleT * 0.27 + 1.3) * 0.05;
@@ -6853,6 +6971,9 @@ function tick() {
_lodAccum += dt;
if (_lodAccum >= LOD_INTERVAL) { _lodAccum = 0; enforceLOD(); }
+ // Advance every mounted pin's idle mixer BEFORE awareness, so the gaze offset
+ // composes on top of this frame's animated pose instead of being overwritten.
+ updatePinIdles(dt);
// Nearby agents notice the viewer — body/head turn, idle drift, greet pop.
updateAgentAwareness(dt);
diff --git a/src/irl/pin-idle.js b/src/irl/pin-idle.js
new file mode 100644
index 000000000..ce74d6395
--- /dev/null
+++ b/src/irl/pin-idle.js
@@ -0,0 +1,92 @@
+// src/irl/pin-idle.js — breathe life into pinned agents.
+//
+// Every pin used to mount its GLB in the authored bind pose and stay there: a
+// plaza of T-posed statues. This module gives each mounted pin the same idle
+// clip the carried avatar plays, retargeted per rig through the universal
+// canonicalize/retarget pipeline (AnimationManager), so ANY humanoid — Mixamo,
+// Avaturn, VRM, Daz — idles naturally. Non-humanoid props fail the
+// supportsCanonicalClips() gate and simply stay static, exactly as before.
+//
+// The idle clip JSON is fetched ONCE for the whole page (memoized promise) and
+// injected into a per-pin AnimationManager, so N pins cost N mixers but only
+// one network fetch. Animation is upside, never a gate: any failure (manifest
+// missing, clip 404, rig rejected by the fallen-pose guard) returns null and
+// the pin renders exactly as it did before this module existed.
+
+import { AnimationManager } from '../animation-manager.js';
+import { log } from '../shared/log.js';
+
+const MANIFEST_URL = '/animations/manifest.json';
+const CLIP_IDLE = 'idle';
+
+let _idleJsonPromise = null;
+
+/**
+ * Fetch (once) the pre-baked idle clip JSON from the animation manifest.
+ * Memoized across every pin on the page; a failed fetch clears the memo so a
+ * later mount retries instead of poisoning the whole session.
+ * @returns {Promise<object|null>} raw AnimationClip JSON, or null when unavailable
+ */
+export function getIdleClipJson() {
+ if (!_idleJsonPromise) {
+ _idleJsonPromise = (async () => {
+ const manifest = await fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => {
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ return r.json();
+ });
+ const def = Array.isArray(manifest) ? manifest.find((d) => d?.name === CLIP_IDLE) : null;
+ if (!def?.url) throw new Error('idle clip missing from manifest');
+ const res = await fetch(def.url, { cache: 'force-cache' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ return await res.json();
+ })().catch((err) => {
+ log.warn('[irl] idle clip unavailable:', err?.message || err);
+ _idleJsonPromise = null; // allow a later mount to retry
+ return null;
+ });
+ }
+ return _idleJsonPromise;
+}
+
+/**
+ * Attach an idle-playing AnimationManager to a freshly loaded pin model.
+ * Call BEFORE the model is added to the scene (the retarget maps are captured
+ * from the authored bind pose) and before any impostor bake, so the snapshot
+ * captures a natural stance instead of the bind-pose T.
+ *
+ * @param {import('three').Object3D} model the pin's gltf.scene
+ * @param {{ avatarUrl?: string }} [context] for the fallen-pose guard's reports
+ * @returns {Promise<AnimationManager|null>} a manager already playing idle
+ * (caller must call .update(dt) per frame and .detach() on evict), or null
+ * when this rig can't be driven — the pin then stays static as before.
+ */
+export async function mountPinIdle(model, context = {}) {
+ const clipJson = await getIdleClipJson();
+ if (!clipJson || !model) return null;
+ const mgr = new AnimationManager();
+ try {
+ mgr.attach(model, context);
+ if (!mgr.supportsCanonicalClips()) {
+ mgr.detach();
+ return null;
+ }
+ mgr.injectClip(CLIP_IDLE, clipJson, { loop: true });
+ const playing = await mgr.play(CLIP_IDLE);
+ if (!playing) {
+ mgr.detach();
+ return null;
+ }
+ // Desynchronize: start each agent at a random phase so a plaza of pins
+ // doesn't breathe in eerie lockstep.
+ const action = mgr.currentAction;
+ const duration = action?.getClip?.()?.duration || 0;
+ if (action && duration > 0) action.time = Math.random() * duration;
+ // Apply frame 0 now so the caller's impostor bake sees the posed skeleton.
+ mgr.update(0);
+ return mgr;
+ } catch (err) {
+ log.warn('[irl] pin idle mount failed:', err?.message || err);
+ try { mgr.detach(); } catch { /* already clean */ }
+ return null;
+ }
+}
diff --git a/src/irl/world-line-ar.js b/src/irl/world-line-ar.js
index 315f1d8c9..8b4126e44 100644
--- a/src/irl/world-line-ar.js
+++ b/src/irl/world-line-ar.js
@@ -17,6 +17,7 @@ import {
RingGeometry, Mesh, MeshBasicMaterial, Group,
} from 'three';
import { getMeshoptDecoder } from '../viewer/internal.js';
+import { mountPinIdle } from './pin-idle.js';
// ── Agent voice (TTS) ────────────────────────────────────────────────────────
let _voiceAudio = null;
@@ -299,10 +300,21 @@ export class WorldLineCeremony {
const gltf = await loader.loadAsync(this.avatarUrl);
root.add(gltf.scene);
gltf.scene.position.y = -1.2;
+ // Breathe: play the retargeted idle clip so the quest agent greets you
+ // mid-motion, not frozen in a bind-pose T. Null for unriggable models.
+ const idleMgr = await mountPinIdle(gltf.scene, { avatarUrl: this.avatarUrl });
let raf;
- const tick = () => { root.rotation.y += 0.01; renderer.render(scene, cam); raf = requestAnimationFrame(tick); };
+ let prevMs = performance.now();
+ const tick = () => {
+ const nowMs = performance.now();
+ idleMgr?.update(Math.min((nowMs - prevMs) / 1000, 0.05));
+ prevMs = nowMs;
+ root.rotation.y += 0.01;
+ renderer.render(scene, cam);
+ raf = requestAnimationFrame(tick);
+ };
tick();
- this._previewStop = () => { cancelAnimationFrame(raf); renderer.dispose(); };
+ this._previewStop = () => { cancelAnimationFrame(raf); idleMgr?.detach(); renderer.dispose(); };
} catch {
/* preview is decoration; the orb fallback already rendered */
}
@@ -334,11 +346,16 @@ export class WorldLineCeremony {
reticle.visible = false; reticle.matrixAutoUpdate = false; scene.add(reticle);
const root = new Group(); root.visible = false; scene.add(root);
+ let arIdleMgr = null;
import('three/addons/loaders/GLTFLoader.js').then(async ({ GLTFLoader }) => {
if (!this.avatarUrl) return;
const loader = new GLTFLoader();
loader.setMeshoptDecoder(await getMeshoptDecoder());
- loader.loadAsync(this.avatarUrl).then((g) => root.add(g.scene)).catch(() => {});
+ loader.loadAsync(this.avatarUrl).then(async (g) => {
+ root.add(g.scene);
+ // Idle in place on the real floor — same living treatment as /irl pins.
+ arIdleMgr = await mountPinIdle(g.scene, { avatarUrl: this.avatarUrl });
+ }).catch(() => {});
});
const overlay = document.createElement('div');
@@ -375,7 +392,12 @@ export class WorldLineCeremony {
// Hand off to the panel interaction (rendered into the dom-overlay) once placed.
setTimeout(() => { end(); this._begin(); }, 600);
});
- renderer.setAnimationLoop((_, frame) => {
+ let prevLoopMs = null;
+ renderer.setAnimationLoop((timeMs, frame) => {
+ if (arIdleMgr) {
+ arIdleMgr.update(prevLoopMs == null ? 0 : Math.min((timeMs - prevLoopMs) / 1000, 0.05));
+ }
+ prevLoopMs = timeMs;
if (frame && !placed) {
const hits = frame.getHitTestResults(hitSource);
if (hits.length) {
@@ -388,6 +410,7 @@ export class WorldLineCeremony {
});
session.addEventListener('end', () => {
renderer.setAnimationLoop(null);
+ arIdleMgr?.detach();
renderer.domElement.remove();
overlay.remove();
renderer.dispose();
diff --git a/tests/_helpers/glb-bone-graph.js b/tests/_helpers/glb-bone-graph.js
index 24a36d28a..71eb88f61 100644
--- a/tests/_helpers/glb-bone-graph.js
+++ b/tests/_helpers/glb-bone-graph.js
@@ -17,6 +17,7 @@ import fs from 'node:fs';
import {
Bone,
Object3D,
+ PropertyBinding,
SkinnedMesh,
Skeleton,
BufferGeometry,
@@ -65,7 +66,12 @@ export function buildBoneGraph(gltf) {
const gltfNodes = Array.isArray(gltf.nodes) ? gltf.nodes : [];
const nodes = gltfNodes.map((n) => {
const bone = new Bone();
- bone.name = typeof n.name === 'string' ? n.name : '';
+ // GLTFLoader sanitizes every node name for PropertyBinding compatibility
+ // (e.g. Mixamo's "mixamorig:Hips" → "mixamorigHips") before anything else
+ // sees it. Mirror that here, or an AnimationMixer bound to this graph
+ // silently fails to resolve any colon-named track — a fixture-only failure
+ // the production loader never exhibits.
+ bone.name = typeof n.name === 'string' ? PropertyBinding.sanitizeNodeName(n.name) : '';
if (Array.isArray(n.matrix) && n.matrix.length === 16) {
bone.matrix.fromArray(n.matrix);
bone.matrix.decompose(bone.position, bone.quaternion, bone.scale);
diff --git a/tests/irl-pin-idle.test.js b/tests/irl-pin-idle.test.js
new file mode 100644
index 000000000..db81d6b77
--- /dev/null
+++ b/tests/irl-pin-idle.test.js
@@ -0,0 +1,149 @@
+/**
+ * Pin idle animation (src/irl/pin-idle.js) — the "no more T-posed statues" lock.
+ *
+ * /irl pins used to mount their GLB in the authored bind pose and never move.
+ * mountPinIdle() must: fetch the shared idle clip ONCE for the whole page,
+ * retarget it per rig through the production AnimationManager pipeline, start
+ * playback at a randomized phase, and return null (never throw) for anything
+ * that can't be driven — a prop, a missing manifest, a failed clip fetch.
+ *
+ * Runs against the committed real rigs (cz.glb = canonical Avaturn convention,
+ * michelle.glb = Mixamo convention) via the same headless bone-graph loader the
+ * upright-invariant corpus uses, and the real committed idle clip JSON — what
+ * this suite exercises is what ships.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { fileURLToPath } from 'node:url';
+import { readFileSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import { Object3D, Quaternion } from 'three';
+import { loadBoneGraph } from './_helpers/glb-bone-graph.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const repoRoot = resolve(__dirname, '..');
+const avatar = (name) => resolve(repoRoot, 'public/avatars', name);
+const idleClipJson = JSON.parse(
+ readFileSync(resolve(repoRoot, 'public/animations/clips/idle.json'), 'utf8'),
+);
+const manifestJson = JSON.parse(
+ readFileSync(resolve(repoRoot, 'public/animations/manifest.json'), 'utf8'),
+);
+
+// The module memoizes the clip fetch across the whole page; tests need a fresh
+// module instance per scenario so one test's fetch outcome can't leak into the
+// next.
+async function freshModule() {
+ vi.resetModules();
+ return await import('../src/irl/pin-idle.js');
+}
+
+const okJson = (body) => ({ ok: true, json: async () => body });
+
+function stubFetchOk() {
+ const fn = vi.fn(async (url) => {
+ if (String(url).includes('manifest')) return okJson(manifestJson);
+ if (String(url).includes('idle.json')) return okJson(idleClipJson);
+ return { ok: false, status: 404, json: async () => ({}) };
+ });
+ vi.stubGlobal('fetch', fn);
+ return fn;
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('mountPinIdle on real humanoid rigs', () => {
+ for (const rig of ['cz.glb', 'michelle.glb']) {
+ it(`drives ${rig} out of its bind pose`, async () => {
+ stubFetchOk();
+ const { mountPinIdle } = await freshModule();
+ const { root, nodes } = loadBoneGraph(avatar(rig));
+
+ // Snapshot the bind pose before mounting.
+ const bind = new Map(nodes.map((n) => [n.uuid, n.quaternion.clone()]));
+
+ const mgr = await mountPinIdle(root, { avatarUrl: `/avatars/${rig}` });
+ expect(mgr).not.toBeNull();
+ expect(mgr.currentName).toBe('idle');
+ expect(mgr.mixer).toBeTruthy();
+
+ // Advance and confirm the skeleton actually moves — at least one bone's
+ // local rotation must differ from bind (a statue would stay identical).
+ mgr.update(0.25);
+ const scratch = new Quaternion();
+ let moved = 0;
+ for (const n of nodes) {
+ scratch.copy(bind.get(n.uuid));
+ if (Math.abs(1 - Math.abs(scratch.dot(n.quaternion))) > 1e-6) moved++;
+ }
+ expect(moved).toBeGreaterThan(0);
+
+ // Teardown must be clean and idempotent (evict/dispose paths call it).
+ mgr.detach();
+ mgr.detach();
+ expect(mgr.mixer).toBeNull();
+ });
+ }
+
+ it('randomizes the start phase so a plaza never breathes in lockstep', async () => {
+ stubFetchOk();
+ const { mountPinIdle } = await freshModule();
+ const times = [];
+ for (let i = 0; i < 4; i++) {
+ const { root } = loadBoneGraph(avatar('cz.glb'));
+ const mgr = await mountPinIdle(root, {});
+ expect(mgr).not.toBeNull();
+ times.push(mgr.currentAction.time);
+ mgr.detach();
+ }
+ expect(new Set(times.map((t) => t.toFixed(6))).size).toBeGreaterThan(1);
+ });
+
+ it('fetches the clip once across many mounts (memoized)', async () => {
+ const fetchFn = stubFetchOk();
+ const { mountPinIdle } = await freshModule();
+ for (let i = 0; i < 3; i++) {
+ const { root } = loadBoneGraph(avatar('cz.glb'));
+ (await mountPinIdle(root, {}))?.detach();
+ }
+ // One manifest fetch + one clip fetch, total — never per pin.
+ expect(fetchFn).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('mountPinIdle failure modes (animation is upside, never a gate)', () => {
+ it('returns null for a non-humanoid model', async () => {
+ stubFetchOk();
+ const { mountPinIdle } = await freshModule();
+ const prop = new Object3D();
+ prop.name = 'crate';
+ expect(await mountPinIdle(prop, {})).toBeNull();
+ });
+
+ it('returns null when the manifest fetch fails, then retries on the next mount', async () => {
+ let calls = 0;
+ vi.stubGlobal('fetch', vi.fn(async (url) => {
+ calls++;
+ if (calls === 1) return { ok: false, status: 503, json: async () => ({}) };
+ if (String(url).includes('manifest')) return okJson(manifestJson);
+ return okJson(idleClipJson);
+ }));
+ const { mountPinIdle } = await freshModule();
+
+ const first = await mountPinIdle(loadBoneGraph(avatar('cz.glb')).root, {});
+ expect(first).toBeNull();
+
+ // The failed fetch must not poison the memo — the next mount retries.
+ const second = await mountPinIdle(loadBoneGraph(avatar('cz.glb')).root, {});
+ expect(second).not.toBeNull();
+ second.detach();
+ });
+
+ it('returns null (no throw) when fetch itself rejects', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => { throw new Error('offline'); }));
+ const { mountPinIdle } = await freshModule();
+ expect(await mountPinIdle(loadBoneGraph(avatar('cz.glb')).root, {})).toBeNull();
+ });
+});