-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbabvrm.html
More file actions
332 lines (294 loc) · 15.4 KB
/
babvrm.html
File metadata and controls
332 lines (294 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Babylon.js VRM+VRMA</title>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<script src="https://preview.babylonjs.com/babylon.js"></script>
<script src="https://preview.babylonjs.com/loaders/babylonjs.loaders.js"></script>
<style>
html, body, #renderCanvas { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; background: #001a33; }
#ui {
position: absolute; bottom: 16px; left: 50%; transform: translateX(-50%);
display: flex; flex-direction: column; align-items: center; gap: 8px;
font: 13px monospace; color: #fff; text-align: center; pointer-events: none;
}
#ui { display: none; }
#description { max-width: 480px; opacity: 0.9; text-shadow: 0 1px 3px #000; }
#btn {
pointer-events: all; padding: 6px 18px; background: rgba(255,255,255,0.15);
border: 1px solid rgba(255,255,255,0.4); color: #fff; border-radius: 4px;
cursor: pointer; font: 13px monospace;
}
#btn:hover { background: rgba(255,255,255,0.3); }
#status { opacity: 0.6; font-size: 11px; }
</style>
</head>
<body>
<canvas id="renderCanvas"></canvas>
<div id="ui">
<div id="description">Loading…</div>
<button id="btn">⟳ Random animation</button>
<div id="status"></div>
</div>
<script type="module">
// Monkey-patch: AnimatorAvatar's getChildMeshes predicate calls getTotalVertices
// on ALL descendants including VRM TransformNode bones (which lack this method).
// Return 0 so TransformNodes are filtered out as zero-vertex meshes.
BABYLON.TransformNode.prototype.getTotalVertices ??= function() { return 0; };
const params = new URLSearchParams(window.location.search);
const VRM_FILE = params.get('model') || 'models/AIAN/AIAN_F_1_Casual.vrm';
// VRMA from hash (e.g. babvrm.html#vrma/13_29.vrma), else random
const HASH_VRMA = location.hash.slice(1) || null;
window.animationReady = false;
// ---------------------------------------------------------------------------
// VRM humanoid bone parent map (VRM spec / three-vrm VRMHumanBoneParentMap)
// ---------------------------------------------------------------------------
const BONE_PARENT = {
hips: null,
spine: 'hips', chest: 'spine', upperChest: 'chest',
neck: 'upperChest', head: 'neck',
leftEye: 'head', rightEye: 'head', jaw: 'head',
leftShoulder: 'upperChest', leftUpperArm: 'leftShoulder',
leftLowerArm: 'leftUpperArm', leftHand: 'leftLowerArm',
rightShoulder: 'upperChest', rightUpperArm: 'rightShoulder',
rightLowerArm: 'rightUpperArm', rightHand: 'rightLowerArm',
leftUpperLeg: 'hips', leftLowerLeg: 'leftUpperLeg',
leftFoot: 'leftLowerLeg', leftToes: 'leftFoot',
rightUpperLeg: 'hips', rightLowerLeg: 'rightUpperLeg',
rightFoot: 'rightLowerLeg', rightToes: 'rightFoot',
leftThumbMetacarpal: 'leftHand', leftThumbProximal: 'leftThumbMetacarpal', leftThumbDistal: 'leftThumbProximal',
leftIndexProximal: 'leftHand', leftIndexIntermediate: 'leftIndexProximal', leftIndexDistal: 'leftIndexIntermediate',
leftMiddleProximal: 'leftHand', leftMiddleIntermediate: 'leftMiddleProximal', leftMiddleDistal: 'leftMiddleIntermediate',
leftRingProximal: 'leftHand', leftRingIntermediate: 'leftRingProximal', leftRingDistal: 'leftRingIntermediate',
leftLittleProximal: 'leftHand', leftLittleIntermediate: 'leftLittleProximal', leftLittleDistal: 'leftLittleIntermediate',
rightThumbMetacarpal: 'rightHand', rightThumbProximal: 'rightThumbMetacarpal', rightThumbDistal: 'rightThumbProximal',
rightIndexProximal: 'rightHand', rightIndexIntermediate: 'rightIndexProximal', rightIndexDistal: 'rightIndexIntermediate',
rightMiddleProximal: 'rightHand', rightMiddleIntermediate: 'rightMiddleProximal', rightMiddleDistal: 'rightMiddleIntermediate',
rightRingProximal: 'rightHand', rightRingIntermediate: 'rightRingProximal', rightRingDistal: 'rightRingIntermediate',
rightLittleProximal: 'rightHand', rightLittleIntermediate: 'rightLittleProximal', rightLittleDistal: 'rightLittleIntermediate',
};
// Compute world-space quaternion by walking a node's parent chain.
function worldQuatOf(node) {
const chain = [];
let cur = node;
while (cur) {
chain.unshift(cur.rotationQuaternion?.clone() ?? BABYLON.Quaternion.Identity());
cur = cur.parent;
}
return chain.reduce((acc, q) => acc.multiply(q), BABYLON.Quaternion.Identity());
}
// ---------------------------------------------------------------------------
// DOM refs
// ---------------------------------------------------------------------------
const descEl = document.getElementById('description');
const statusEl = document.getElementById('status');
const btn = document.getElementById('btn');
// ---------------------------------------------------------------------------
// Load VRM loader + animations list
// ---------------------------------------------------------------------------
const [, animations] = await Promise.all([
new Promise((resolve, reject) => {
const s = document.createElement('script');
s.src = 'https://xuhuisheng.github.io/babylonjs-vrm/babylon-vrm-loader.js';
s.onload = resolve; s.onerror = reject;
document.head.appendChild(s);
}),
fetch('animations.json').then(r => r.json()),
]);
console.log(`[animations.json] ${animations.length} entries`);
// ---------------------------------------------------------------------------
// Scene setup
// ---------------------------------------------------------------------------
const canvas = document.getElementById('renderCanvas');
const engine = new BABYLON.Engine(canvas, true);
engine.setHardwareScalingLevel(1); // native resolution
const scene = new BABYLON.Scene(engine);
// Camera: VRM 1.0 loader applies 180°Y on __root__ → character faces +Z in world space.
// Camera at alpha=+π/2 sits at +Z, looks toward -Z → sees character front.
const camera = new BABYLON.ArcRotateCamera('cam', Math.PI / 2, Math.PI / 2 - 0.12, 5,
new BABYLON.Vector3(0, 0.9, 0), scene);
camera.attachControl(canvas, true);
camera.lowerRadiusLimit = 0.5;
camera.upperRadiusLimit = 15;
new BABYLON.HemisphericLight('hemi', new BABYLON.Vector3(0, 1, 0), scene);
const dirLight = new BABYLON.DirectionalLight('dir', new BABYLON.Vector3(-1, -2, -1), scene);
dirLight.intensity = 0.5;
// ---------------------------------------------------------------------------
// Load VRM (once)
// ---------------------------------------------------------------------------
descEl.textContent = 'Loading VRM…';
await BABYLON.ImportMeshAsync(VRM_FILE, scene);
const vrmManager = scene.metadata?.vrmManagers?.[0];
if (!vrmManager) throw new Error('VRM manager not found');
// --- Capture Rest Rotations for Robo Arm ---
const ROBO_CONSTRAINTS_LIST = [
{ target: 'robo_shoulder.L', source: 'shoulder.L' },
{ target: 'robo_upper_arm.L', source: 'upper_arm.L' },
{ target: 'robo_forearm.L', source: 'forearm.L' },
{ target: 'robo_hand.L', source: 'hand.L' },
// Fingers
{ target: 'robo_thumb.01.L', source: 'thumb.01.L' },
{ target: 'robo_thumb.02.L', source: 'thumb.02.L' },
{ target: 'robo_thumb.03.L', source: 'thumb.03.L' },
{ target: 'robo_f_index.01.L', source: 'f_index.01.L' },
{ target: 'robo_f_index.02.L', source: 'f_index.02.L' },
{ target: 'robo_f_index.03.L', source: 'f_index.03.L' },
{ target: 'robo_f_middle.01.L', source: 'f_middle.01.L' },
{ target: 'robo_f_middle.02.L', source: 'f_middle.02.L' },
{ target: 'robo_f_middle.03.L', source: 'f_middle.03.L' },
{ target: 'robo_f_ring.01.L', source: 'f_ring.01.L' },
{ target: 'robo_f_ring.02.L', source: 'f_ring.02.L' },
{ target: 'robo_f_ring.03.L', source: 'f_ring.03.L' },
{ target: 'robo_f_pinky.01.L', source: 'f_pinky.01.L' },
{ target: 'robo_f_pinky.02.L', source: 'f_pinky.02.L' },
{ target: 'robo_f_pinky.03.L', source: 'f_pinky.03.L' },
];
const constraintNodesGlobal = ROBO_CONSTRAINTS_LIST.map(c => {
const target = scene.getNodeByName(c.target);
const source = scene.getNodeByName(c.source);
if (target && source) {
return {
target,
source,
initialTargetRot: target.rotationQuaternion ? target.rotationQuaternion.clone() : target.rotation.toQuaternion(),
initialSourceRot: source.rotationQuaternion ? source.rotationQuaternion.clone() : source.rotation.toQuaternion(),
};
}
return null;
}).filter(c => c !== null);
if (constraintNodesGlobal.length > 0) {
console.log(`[Babylon] Initialized ${constraintNodesGlobal.length} manual delta-rotation constraints from rest pose`);
scene.onBeforeRenderObservable.add(() => {
constraintNodesGlobal.forEach(c => {
const currentSourceRot = c.source.rotationQuaternion ? c.source.rotationQuaternion : c.source.rotation.toQuaternion();
// Delta = currentSource * inverse(initialSource)
const invInitialSource = BABYLON.Quaternion.Inverse(c.initialSourceRot);
const delta = currentSourceRot.multiply(invInitialSource);
// target = delta * initialTarget
c.target.rotationQuaternion = delta.multiply(c.initialTargetRot);
});
});
}
// VRM hips bone (root reference for AnimatorAvatar fixRootPosition)
const vrmHipsBone = vrmManager.humanoidBone['hips'];
const vrmLeftFootBone = vrmManager.humanoidBone['leftFoot'];
// Build AnimatorAvatar once from the VRM __root__ mesh
const vrmRootMesh = scene.rootNodes?.find(n => n.name === '__root__')
?? scene.meshes?.[0];
const vrmAvatar = new BABYLON.AnimatorAvatar('vrm-avatar', vrmRootMesh);
// ---------------------------------------------------------------------------
// playAnimation — loads a VRMA and remaps it onto the VRM
// ---------------------------------------------------------------------------
let currentGroup = null;
let currentContainer = null;
// Optional: Reference to spring bone controller for manual updates if needed
let springController = null;
async function playAnimation(entry) {
btn.disabled = true;
statusEl.textContent = 'loading…';
descEl.textContent = entry.description;
// ... (existing cleanup code)
if (currentGroup) { currentGroup.stop(); currentGroup.dispose(); currentGroup = null; }
if (currentContainer) { currentContainer.dispose(); currentContainer = null; }
if (scene.metadata?.vrmAnimationManagers) { scene.metadata.vrmAnimationManagers = []; }
const assetContainer = await BABYLON.LoadAssetContainerAsync(entry.url, scene);
currentContainer = assetContainer;
const vrmAnimManager = scene.metadata?.vrmAnimationManagers?.[0];
const animGroup = assetContainer.animationGroups[0];
if (!vrmAnimManager?.animationMap || !animGroup) {
statusEl.textContent = 'failed — no animation data';
btn.disabled = false;
return;
}
// Build name map: VRMA source target name → VRM skeleton bone name
const mapNodeNames = new Map();
animGroup.targetedAnimations.forEach((targeted, i) => {
const boneName = vrmAnimManager.animationMap.get(i);
const bone = vrmManager.humanoidBone[boneName];
if (bone && targeted.target?.name) {
mapNodeNames.set(targeted.target.name, bone.name);
}
});
// Retarget via AnimatorAvatar
const remapped = vrmAvatar.retargetAnimationGroup(animGroup, {
animationGroupName: 'vrma-remapped',
fixRootPosition: true,
rootNodeName: vrmHipsBone.name,
groundReferenceNodeName: vrmLeftFootBone?.name,
mapNodeNames,
});
remapped.start(true, 1.0, remapped.from, remapped.to, false);
remapped.goToFrame(remapped.from);
// Ensure spring bones are discovered
springController = vrmManager.springBoneController10 || vrmManager.springBoneController;
// Node Constraints discovery (VRM 1.0)
const constraintManager = vrmManager.nodeConstraintManager || vrmManager.ext10?.nodeConstraintManager;
if (constraintManager) {
console.log('[Babylon] Node constraint manager found:', constraintManager);
}
scene.render();
currentGroup = remapped;
// Expose for Playwright sampling
window.scene = scene;
window.remappedGroup = remapped;
window.animationReady = true;
statusEl.textContent = entry.url;
btn.disabled = false;
console.log('[Done]', entry.url, '— tracks:', remapped.targetedAnimations.length);
}
// Playwright hook: seek both engines to the same timestamp and read bone quats.
window.getBoneQuats = function(t, extraBones = []) {
if (!window.remappedGroup || !window.scene) return null;
const fps = window.remappedGroup.targetedAnimations[0]?.animation?.framePerSecond ?? 60;
window.remappedGroup.goToFrame(t * fps);
// Manually update spring bones with a fixed delta if we are seeking
if (springController) {
// We need to simulate some time passing for physics to work
// Seek usually jumps, which breaks physics.
// We'll do a few small steps to let it settle.
for(let i=0; i<5; i++) springController.update(0.016);
}
window.scene.render();
const mgr = window.scene.metadata?.vrmManagers?.[0];
if (!mgr) return null;
const result = {};
const nm = mgr.humanoidBone?.nodeMap ?? {};
for (const [name, bone] of Object.entries(nm)) {
const q = bone?.rotationQuaternion;
if (q) result[name] = { x: +q.x.toFixed(4), y: +q.y.toFixed(4), z: +q.z.toFixed(4), w: +q.w.toFixed(4) };
}
// Add extra bones
for (const name of extraBones) {
const node = window.scene.getNodeByName(name);
const q = node?.rotationQuaternion;
if (q) result[name] = { x: +q.x.toFixed(4), y: +q.y.toFixed(4), z: +q.z.toFixed(4), w: +q.w.toFixed(4) };
}
return result;
};
// ---------------------------------------------------------------------------
// Random picker
// ---------------------------------------------------------------------------
let lastIdx = -1;
function pickRandom() {
let idx;
do { idx = Math.floor(Math.random() * animations.length); } while (idx === lastIdx);
lastIdx = idx;
return animations[idx];
}
btn.addEventListener('click', () => playAnimation(pickRandom()));
// If a specific VRMA was given via hash, use it; otherwise pick random
const firstEntry = HASH_VRMA
? (animations.find(a => a.url === HASH_VRMA) ?? { url: HASH_VRMA, description: HASH_VRMA })
: pickRandom();
await playAnimation(firstEntry);
// Cap render loop to ~30 fps to reduce GPU load when viewed alongside A-Frame.
let _lastRender = 0;
engine.runRenderLoop(() => {
const now = performance.now();
if (now - _lastRender >= 33) { _lastRender = now; scene.render(); }
});
window.addEventListener('resize', () => engine.resize());
</script>
</body>
</html>