|
| 1 | +/** |
| 2 | + * glTF / GLB animation export. |
| 3 | + * |
| 4 | + * Bakes a Posecode movement into a standard glTF asset — the rig plus a baked |
| 5 | + * animation clip — so it can drop into an existing web animation pipeline and |
| 6 | + * load with Three.js' `GLTFLoader`. |
| 7 | + * |
| 8 | + * ## What is exported |
| 9 | + * |
| 10 | + * The procedural mannequin rig (bone hierarchy with limb meshes parented to |
| 11 | + * each joint) and one `AnimationClip` that drives the joint rotations and the |
| 12 | + * root travel/turn. Like the BVH path, this bakes the **authored** joint motion |
| 13 | + * plus root choreography; it does not re-run the renderer's contact/IK solve, |
| 14 | + * so IK-dependent movements export their authored pose. Exporting the fully |
| 15 | + * solved motion, and retargeting onto external/humanoid skeletons, are |
| 16 | + * documented future work (see issue #90). |
| 17 | + * |
| 18 | + * ## Conventions |
| 19 | + * |
| 20 | + * - Right-handed, **Y-up**, figure faces **+Z** at rest (Three.js default). |
| 21 | + * - Units are metres. |
| 22 | + * - Joint nodes are named by their Posecode bone id (`elbow_left`, `hip_right`, |
| 23 | + * …); the animated root group is `posecode_root`. |
| 24 | + * - The full looped runtime (cycle incl. loop-reset wrap × repeats) is baked as |
| 25 | + * keyframes, so duration and loop count survive without a runtime loop flag. |
| 26 | + */ |
| 27 | + |
| 28 | +import * as THREE from "three"; |
| 29 | +import { GLTFExporter } from "three/examples/jsm/exporters/GLTFExporter.js"; |
| 30 | +import type { PosecodeIR } from "posecode-parser"; |
| 31 | +import { buildMannequin, type Proportions } from "./mannequin.js"; |
| 32 | +import { buildTimeline } from "./timeline.js"; |
| 33 | + |
| 34 | +const DEFAULT_FPS = 30; |
| 35 | +const ROOT_NODE_NAME = "posecode_root"; |
| 36 | + |
| 37 | +export interface GltfExportOptions { |
| 38 | + /** Keyframe sample rate. Defaults to 30 fps. */ |
| 39 | + fps?: number; |
| 40 | + /** true → GLB binary ArrayBuffer (default); false → glTF JSON object. */ |
| 41 | + binary?: boolean; |
| 42 | + /** Rig proportions, if exporting for a calibrated character. */ |
| 43 | + proportions?: Proportions; |
| 44 | +} |
| 45 | + |
| 46 | +const _up = new THREE.Vector3(0, 1, 0); |
| 47 | +const _yaw = new THREE.Quaternion(); |
| 48 | + |
| 49 | +/** |
| 50 | + * Build the mannequin rig and a baked `AnimationClip` for a movement, without |
| 51 | + * touching the DOM. Exposed for tests and advanced callers; most consumers want |
| 52 | + * {@link exportGLTF}. |
| 53 | + */ |
| 54 | +export function buildAnimatedRig( |
| 55 | + ir: PosecodeIR, |
| 56 | + options: GltfExportOptions = {}, |
| 57 | +): { root: THREE.Group; clip: THREE.AnimationClip } { |
| 58 | + const fps = options.fps && options.fps > 0 ? options.fps : DEFAULT_FPS; |
| 59 | + const mannequin = buildMannequin(undefined, options.proportions); |
| 60 | + const timeline = buildTimeline(ir); |
| 61 | + |
| 62 | + // Name every joint node by its bone id so animation tracks bind by name and |
| 63 | + // the exported glTF uses a stable, documented joint-naming convention. |
| 64 | + mannequin.root.name = ROOT_NODE_NAME; |
| 65 | + const animatedBones: string[] = []; |
| 66 | + for (const [id, node] of mannequin.bones) { |
| 67 | + node.name = id; |
| 68 | + animatedBones.push(id); |
| 69 | + } |
| 70 | + |
| 71 | + const cycle = Math.max(timeline.duration, 1e-6); |
| 72 | + const total = cycle * Math.max(1, timeline.repeat); |
| 73 | + const dt = 1 / fps; |
| 74 | + const frameCount = Math.max(1, Math.round(total * fps)) + 1; |
| 75 | + |
| 76 | + const times = new Float32Array(frameCount); |
| 77 | + const rootPos = new Float32Array(frameCount * 3); |
| 78 | + const rootQuat = new Float32Array(frameCount * 4); |
| 79 | + const boneQuat = new Map<string, Float32Array>(); |
| 80 | + for (const id of animatedBones) boneQuat.set(id, new Float32Array(frameCount * 4)); |
| 81 | + |
| 82 | + for (let f = 0; f < frameCount; f++) { |
| 83 | + const t = Math.min(f * dt, total); |
| 84 | + times[f] = t; |
| 85 | + const info = timeline.sample(t, mannequin.bones); |
| 86 | + |
| 87 | + // Root group carries the world travel (x,z) and the body yaw. |
| 88 | + rootPos[f * 3] = info.rootOffset.x; |
| 89 | + rootPos[f * 3 + 1] = 0; |
| 90 | + rootPos[f * 3 + 2] = info.rootOffset.z; |
| 91 | + _yaw.setFromAxisAngle(_up, info.rootYaw); |
| 92 | + rootQuat[f * 4] = _yaw.x; |
| 93 | + rootQuat[f * 4 + 1] = _yaw.y; |
| 94 | + rootQuat[f * 4 + 2] = _yaw.z; |
| 95 | + rootQuat[f * 4 + 3] = _yaw.w; |
| 96 | + |
| 97 | + for (const id of animatedBones) { |
| 98 | + const q = mannequin.bones.get(id)!.quaternion; |
| 99 | + const buf = boneQuat.get(id)!; |
| 100 | + buf[f * 4] = q.x; |
| 101 | + buf[f * 4 + 1] = q.y; |
| 102 | + buf[f * 4 + 2] = q.z; |
| 103 | + buf[f * 4 + 3] = q.w; |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + const tracks: THREE.KeyframeTrack[] = [ |
| 108 | + new THREE.VectorKeyframeTrack(`${ROOT_NODE_NAME}.position`, Array.from(times), Array.from(rootPos)), |
| 109 | + new THREE.QuaternionKeyframeTrack(`${ROOT_NODE_NAME}.quaternion`, Array.from(times), Array.from(rootQuat)), |
| 110 | + ]; |
| 111 | + for (const id of animatedBones) { |
| 112 | + tracks.push( |
| 113 | + new THREE.QuaternionKeyframeTrack( |
| 114 | + `${id}.quaternion`, |
| 115 | + Array.from(times), |
| 116 | + Array.from(boneQuat.get(id)!), |
| 117 | + ), |
| 118 | + ); |
| 119 | + } |
| 120 | + |
| 121 | + const clip = new THREE.AnimationClip(ir.name || "posecode", total, tracks); |
| 122 | + // Reset the rig to its rest pose so the exported node transforms are neutral; |
| 123 | + // the clip supplies all motion. |
| 124 | + timeline.sample(0, mannequin.bones); |
| 125 | + return { root: mannequin.root, clip }; |
| 126 | +} |
| 127 | + |
| 128 | +/** |
| 129 | + * Export a parsed Posecode movement as a glTF/GLB asset. |
| 130 | + * |
| 131 | + * Returns a GLB `ArrayBuffer` (default) or a glTF JSON object when |
| 132 | + * `binary: false`. The result loads with Three.js `GLTFLoader`, and the baked |
| 133 | + * clip plays on the included rig. |
| 134 | + */ |
| 135 | +export async function exportGLTF( |
| 136 | + ir: PosecodeIR, |
| 137 | + options: GltfExportOptions = {}, |
| 138 | +): Promise<ArrayBuffer | Record<string, unknown>> { |
| 139 | + const { root, clip } = buildAnimatedRig(ir, options); |
| 140 | + const exporter = new GLTFExporter(); |
| 141 | + const binary = options.binary ?? true; |
| 142 | + return await new Promise((resolve, reject) => { |
| 143 | + exporter.parse( |
| 144 | + root, |
| 145 | + (result) => resolve(result as ArrayBuffer | Record<string, unknown>), |
| 146 | + (error) => reject(error), |
| 147 | + { binary, animations: [clip] }, |
| 148 | + ); |
| 149 | + }); |
| 150 | +} |
0 commit comments