-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.ts
More file actions
1686 lines (1615 loc) · 66.5 KB
/
Copy pathindex.ts
File metadata and controls
1686 lines (1615 loc) · 66.5 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* posecode-render: public API.
*
* `createViewer(canvas)` sets up a Three.js studio scene with the procedural
* mannequin and returns a controller. `load(ir)` builds a timeline from a parsed
* PosecodeIR; the render loop applies forward kinematics each frame, then keeps
* ground-locked contacts (hands/forearms/feet/back) planted via floating-root
* solving. The camera auto-frames the figure and eases smoothly when a new
* movement loads.
*/
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
import type { PosecodeIR, ReachTarget, PinTarget, GripTarget } from "posecode-parser";
import { buildMannequin, type Mannequin } from "./mannequin.js";
import { applyGroundLock as applyGroundLockTo, groundFigure as groundFigureOf } from "./groundlock.js";
import {
buildTimeline,
type BuiltTimeline,
type PhaseSegment,
type WeightedReachTarget,
} from "./timeline.js";
import {
buildFloorGuideData,
createFloorGuide,
syncFloorGuideToSolvedRoot,
type FloorGuideData,
type FloorGuideInfo,
type FloorGuideScene,
} from "./floor-guide.js";
import { buildProps, type PropScene } from "./props.js";
import { loadCharacter, type Character } from "./character.js";
import {
loadClipSource,
retargetMocapClip,
createClipLayer,
type ClipLayer,
type ClipSource,
} from "./clips.js";
import { createLatestResourceLoader } from "./latest-resource-loader.js";
import { depenetrate } from "./depenetrate.js";
import {
measureConstraintDiagnostics,
type ConstraintDiagnostic,
} from "./diagnostics.js";
import { resolvePropContacts, propContactExemptions } from "./propcontact.js";
import {
alignFloorContacts,
alignGripFrames,
enforceContactRom,
floorContactHeight,
floorTargetForEffector,
formFists,
isDipBarGrip,
levelPlantedFeet,
prepareGripFrames,
wrapGrip,
relaxHands,
swingArms,
aimHead,
} from "./contacts.js";
import {
REACH_TOLERANCE,
effectorBoneId,
missingReachTarget,
reachChain,
solveReachToPoint,
type ReachResidual,
} from "./reach.js";
import { solveCCD } from "./ik.js";
const DEG = Math.PI / 180;
/** Live diagnostics match the playground warning refresh cadence (~5Hz). */
const CONSTRAINT_DIAGNOSTIC_INTERVAL_MS = 200;
export interface ViewerPhaseInfo {
/** Zero-based real phase index, or -1 while blending through loop reset. */
phaseIndex: number;
phaseName: string;
/** Display-only coaching text from the phase; it never drives the animation. */
cue?: string;
}
export interface TimelineInfo {
duration: number;
repeat: number;
segments: PhaseSegment[];
}
export interface Viewer {
load(ir: PosecodeIR): void;
play(): void;
pause(): void;
toggle(): boolean;
seek(seconds: number): void;
setSpeed(multiplier: number): void;
setLoop(loop: boolean): void;
get playing(): boolean;
get duration(): number;
get time(): number;
/** True once the skinned character (characterUrl) is loaded and visible. */
get characterActive(): boolean;
/** True while a retargeted mocap clip is driving (or fading over) the pose. */
get clipActive(): boolean;
getTimeline(): TimelineInfo | null;
/** Floor scale/orientation and authored root-path metadata for the loaded clip. */
getFloorGuideInfo(): FloorGuideInfo | null;
/** Diagnostics for every active reach, including missing/unreachable targets. */
getReachResiduals(): readonly ReachResidual[];
/** Procedural-driver grounding/collision outcomes, before optional skin/mocap reconciliation. */
getConstraintDiagnostics(): readonly ConstraintDiagnostic[];
/** Precise visible world bounds; intended for audits and deterministic export. */
getVisibleBounds(): THREE.Box3;
/**
* Highlight canonical bone ids at their live joint positions. Unknown ids
* are ignored; pass an empty list to clear the selection.
*/
selectBones(boneIds: readonly string[]): void;
getMannequin(): any;
getCharacter(): any;
/**
* Render the current time synchronously and return the frame as a PNG data
* URL. Works without preserveDrawingBuffer because the read happens in the
* same task as the render (no buffer swap in between). Powers GIF/poster
* export and headless capture tooling.
*/
captureFrame(): string;
onPhase(cb: (info: ViewerPhaseInfo) => void): void;
onTick(cb: (time: number, duration: number) => void): void;
onLoop(cb: () => void): void;
dispose(): void;
}
export interface ViewerOptions {
/** Slowly orbit the camera when idle. Defaults to true. */
autoRotate?: boolean;
/**
* Show the metric floor, load origin, live facing arrow, and authored travel
* path. Defaults to true; set false for a completely clean embed.
*/
floorGuide?: boolean;
/**
* URL of a rigged human character GLB (Mixamo bone naming) to render instead
* of the procedural figure. Loaded asynchronously; until it resolves — and if
* it fails — the viewer shows the procedural figure, so a missing or slow
* asset can never blank the scene. All solving still runs on the driver
* skeleton, rebuilt to the character's exact proportions (see character.ts).
*
* Fixed for the viewer's lifetime: it wins over `characterUrls` regardless of
* a loaded document's `avatar` value, so callers that only ever want one
* character can ignore `characterUrls` entirely.
*/
characterUrl?: string;
/**
* Character selector → GLB URL. `load(ir)` uses `ir.avatar` when present and
* otherwise falls back to `ir.rig`, so hosts can map `humanoid` to their
* default character while `avatar avatar2` selects a different appearance.
* A selector absent from this map — or any load failure — falls back to the
* procedural figure.
*/
characterUrls?: Partial<Record<string, string>>;
/**
* Mocap clip library: clip name (as written in a document's `clip "<name>"`
* directive) → FBX/GLB asset URL. When a loaded document names a clip found
* here and the skinned character is active, the viewer retargets the clip
* onto the character and crossfades it over the procedural pose. Documents
* naming clips absent from this map — and any load/retarget failure — play
* the procedural keyframes as always, so clips can never blank a movement.
*/
clips?: Record<string, string>;
/**
* Keep the procedural figure visible while a skinned `characterUrl` loads.
* Defaults to `true` (the procedural figure poses the scene during the load,
* matching callers that never set this). Set `false` alongside a
* `characterUrl` to hide the procedural meshes until the character resolves —
* so a page load shows the skinned figure or nothing, never a blink of the
* crude procedural figure. On load failure the procedural figure is revealed
* regardless, so the scene never stays blank.
*/
showProceduralWhileLoading?: boolean;
}
export function createViewer(
canvas: HTMLCanvasElement,
opts: ViewerOptions = {},
): Viewer {
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0c0f15);
scene.fog = new THREE.Fog(0x0c0f15, 9, 18);
// Text-editor selection overlay. Markers live outside the mannequin and
// character trees so they never affect grounding, camera framing, bounds,
// exports, or contact diagnostics.
const boneSelection = new THREE.Group();
boneSelection.name = "posecode-bone-selection";
scene.add(boneSelection);
const selectionDotGeometry = new THREE.SphereGeometry(0.018, 16, 12);
const selectionRingGeometry = new THREE.TorusGeometry(0.055, 0.006, 8, 32);
const selectionDotMaterial = new THREE.MeshBasicMaterial({
color: 0xd4ff3f,
transparent: true,
opacity: 0.96,
depthTest: false,
depthWrite: false,
});
const selectionRingMaterial = new THREE.MeshBasicMaterial({
color: 0xd4ff3f,
transparent: true,
opacity: 0.82,
depthTest: false,
depthWrite: false,
});
let selectedBoneIds: string[] = [];
let selectionMarkers: THREE.Group[] = [];
function rebuildBoneSelection(): void {
boneSelection.clear();
selectionMarkers = selectedBoneIds.map(() => {
const marker = new THREE.Group();
marker.renderOrder = 1000;
const dot = new THREE.Mesh(selectionDotGeometry, selectionDotMaterial);
dot.renderOrder = 1000;
const ring = new THREE.Mesh(selectionRingGeometry, selectionRingMaterial);
ring.renderOrder = 1000;
marker.add(dot, ring);
boneSelection.add(marker);
return marker;
});
}
// Image-based environment light: soft bounced light that gives the matte
// figure materials realistic shading gradients instead of flat CG plastic.
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
scene.environmentIntensity = 0.35;
pmrem.dispose();
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
camera.position.set(2.6, 1.6, 3.4);
const controls = new OrbitControls(camera, canvas);
controls.target.set(0, 0.9, 0);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.minDistance = 1.2;
controls.maxDistance = 9;
controls.maxPolarAngle = Math.PI * 0.92;
controls.autoRotate = opts.autoRotate ?? true;
controls.autoRotateSpeed = 0.5;
// --- Studio lighting ---
// Trimmed from 0.85 to keep exposure level after adding the environment map.
const hemi = new THREE.HemisphereLight(0xdfe9ff, 0x20242c, 0.6);
scene.add(hemi);
const key = new THREE.DirectionalLight(0xfff4e6, 2.0);
key.position.set(3.5, 6, 4);
key.castShadow = true;
key.shadow.mapSize.set(2048, 2048);
key.shadow.camera.near = 0.5;
key.shadow.camera.far = 22;
key.shadow.camera.left = -3;
key.shadow.camera.right = 3;
key.shadow.camera.top = 3;
key.shadow.camera.bottom = -3;
key.shadow.bias = -0.0004;
key.shadow.radius = 4;
scene.add(key);
const fill = new THREE.DirectionalLight(0x9fb8ff, 0.5);
fill.position.set(-4, 2.5, -2);
scene.add(fill);
const rim = new THREE.DirectionalLight(0xffffff, 0.7);
rim.position.set(-1, 3, -5);
scene.add(rim);
// --- Ground ---
const ground = new THREE.Mesh(
new THREE.CircleGeometry(8, 64),
new THREE.MeshStandardMaterial({ color: 0x14181f, roughness: 0.95, metalness: 0 }),
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
let mannequin: Mannequin = buildMannequin();
enableShadows(mannequin.root);
scene.add(mannequin.root);
// A fixed character URL is known immediately, so callers can hide the
// procedural meshes up front to avoid a flash while it loads. A
// document-driven URL is hidden later, in requestCharacter(), once load(ir)
// has actually selected a mapped asset. Either path reveals the fallback if
// loading fails.
const deferProceduralMeshes =
Boolean(opts.characterUrl) && opts.showProceduralWhileLoading === false;
if (deferProceduralMeshes) setMeshVisibility(mannequin.root, false);
// Skinned character layer (optional). While loading (and on failure) the
// procedural figure stays — unless deferred above; once ready, the driver
// skeleton is rebuilt with the character's proportions, its meshes are hidden
// (they keep feeding the bounding-box grounding), and the character mirrors it
// every frame.
let character: Character | null = null;
/** Install a newly loaded character and re-solve the current document. */
function installCharacter(char: Character): void {
scene.remove(mannequin.root);
disposeTree(mannequin.root);
mannequin = buildMannequin(undefined, char.proportions);
setMeshVisibility(mannequin.root, false);
scene.add(mannequin.root);
if (character) {
scene.remove(character.group);
character.dispose();
}
scene.add(char.group);
character = char;
clipLayer?.dispose();
clipLayer = null;
clipLayerName = null;
clipWeight = 0;
clipTargetWeight = 0;
// The life layer's mesh handles died with the old procedural figure.
eyes = [];
ribcage = undefined;
ribcageRestScale = null;
if (lastIR) api.load(lastIR);
else char.sync(mannequin);
}
/** Drop the active character (if any) and go back to the procedural figure. */
function revertToProcedural(): void {
clipLayer?.dispose();
clipLayer = null;
clipLayerName = null;
clipWeight = 0;
clipTargetWeight = 0;
if (character) {
scene.remove(character.group);
character.dispose();
character = null;
scene.remove(mannequin.root);
disposeTree(mannequin.root);
mannequin = buildMannequin();
enableShadows(mannequin.root);
scene.add(mannequin.root);
}
setMeshVisibility(mannequin.root, true);
eyes = ["eye_left", "eye_right"]
.map((n) => mannequin.root.getObjectByName(n))
.filter((o): o is THREE.Object3D => Boolean(o));
ribcage = mannequin.root.getObjectByName("ribcage");
ribcageRestScale = ribcage ? ribcage.scale.clone() : null;
}
const characterLoader = createLatestResourceLoader<Character>({
load: loadCharacter,
activate: installCharacter,
fallback: revertToProcedural,
onError(error) {
console.warn("Posecode character load failed; using procedural fallback", error);
},
});
/**
* Resolve which character (if any) this document should show and
* switch to it. No-ops when the caller pinned a fixed `characterUrl` (that
* always wins over any document's `avatar`).
*/
function requestCharacter(ir: PosecodeIR): void {
if (opts.characterUrl) return;
const selector = ir.avatar ?? ir.rig;
const url = opts.characterUrls?.[selector] ?? null;
// Unlike a fixed URL, a document-driven URL is unknown until `load(ir)`.
// Hide only once that request actually starts, so a viewer that has not
// loaded a document can never sit blank indefinitely.
if (url && !character && opts.showProceduralWhileLoading === false) {
setMeshVisibility(mannequin.root, false);
}
characterLoader.request(url);
}
// Mocap-clip layer (optional, character-only). When the loaded document
// names a clip present in opts.clips, the asset is fetched once, retargeted
// onto the character skeleton, and crossfaded over the procedural pose. The
// weight eases toward its target each frame, so switching documents (or a
// clip arriving mid-play) fades rather than pops; every failure path leaves
// the procedural keyframes driving the figure.
const CLIP_FADE_PER_SEC = 2.5; // full crossfade in ~0.4s
let clipLayer: ClipLayer | null = null;
let clipLayerName: string | null = null;
let clipWeight = 0;
let clipTargetWeight = 0;
let clipToken = 0;
const clipSources = new Map<string, Promise<ClipSource>>();
/** (Re)aim the clip layer at the current document's `clip` request. */
function requestClip(ir: PosecodeIR | null): void {
clipToken++;
const token = clipToken;
const name = ir?.clip;
const url = name ? opts.clips?.[name] : undefined;
if (!name || !url || !character?.skinnedMesh) {
clipTargetWeight = 0;
clipWeight = 0;
clipLayer?.dispose();
clipLayer = null;
clipLayerName = null;
return;
}
if (clipLayerName === name && clipLayer) {
clipTargetWeight = 1;
return;
}
clipTargetWeight = 0; // fade out whatever plays while the new clip loads
let source = clipSources.get(url);
if (!source) {
source = loadClipSource(url);
clipSources.set(url, source);
}
source
.then((src) => {
const mesh = character?.skinnedMesh;
if (token !== clipToken || !mesh || !character) return;
const retargeted = retargetMocapClip(mesh, src.root, src.clip);
clipLayer?.dispose();
clipLayer = createClipLayer(mesh, retargeted, character.drivenNodes);
clipLayerName = name;
clipWeight = 0;
clipTargetWeight = 1;
})
.catch(() => {
// Missing/broken clip asset: the procedural keyframes keep playing.
// Deliberately silent, matching the characterUrl fallback.
clipSources.delete(url);
});
}
// --- Life layer: breathing + blinking so the figure reads as alive even
// when the movement is paused. Both are MESH-only effects. Breathing must
// never rotate skeleton bones: an earlier version breathed via tiny
// chest/spine rotations, but those ran before ground-lock/pin solving,
// which translated the whole figure to re-plant the displaced hands/feet,
// so every movement visibly swayed and the head bobbed. Swelling the
// ribcage mesh cannot disturb any joint, so authored poses stay exact.
const BREATH_PERIOD = 3.8; // seconds per breath cycle
const BLINK_DURATION = 0.13;
let eyes = ["eye_left", "eye_right"]
.map((n) => mannequin.root.getObjectByName(n))
.filter((o): o is THREE.Object3D => Boolean(o));
let ribcage = mannequin.root.getObjectByName("ribcage");
let ribcageRestScale = ribcage ? ribcage.scale.clone() : null;
let nextBlink = performance.now() / 1000 + 2;
function applyLife(nowSec: number): void {
if (ribcage && ribcageRestScale) {
// 0..1 inhale fraction; the chest swells mostly front-to-back.
const breath = 0.5 + 0.5 * Math.sin((nowSec * Math.PI * 2) / BREATH_PERIOD);
ribcage.scale.set(
ribcageRestScale.x * (1 + breath * 0.015),
ribcageRestScale.y * (1 + breath * 0.01),
ribcageRestScale.z * (1 + breath * 0.05),
);
}
if (nowSec >= nextBlink + BLINK_DURATION) {
nextBlink = nowSec + 2.5 + Math.random() * 3;
}
const closed = nowSec >= nextBlink && nowSec < nextBlink + BLINK_DURATION;
for (const eye of eyes) eye.scale.y = closed ? 0.12 : 1;
}
let timeline: BuiltTimeline | null = null;
const floorGuideEnabled = opts.floorGuide ?? true;
let floorGuideData: FloorGuideData | null = null;
let floorGuide: FloorGuideScene | null = null;
// True for a GAIT clip: it authors root travel AND alternates its floor
// foot-pins between both feet (box-step, grapevine, chassé, walk). There a
// floor foot-pin is a STANCE foot — the body travels to its authored waypoint
// while the leg reaches back to keep the foot planted. A same-foot travel pin
// (a forward lunge's weight-shift) or a vertical support (pull-up bar, box)
// still translates the whole body onto its anchor.
let clipIsGait = false;
// Finger bones the loaded document explicitly poses (make-a-fist, finger-spell,
// hand-wave): the L4.1 resting-hand curl leaves these alone.
let authoredFingers = new Set<string>();
// Shoulders the document poses: L4.2 arm-swing leaves these to the author.
let authoredShoulders = new Set<string>();
// True when the document poses the head/neck: L4.3 look-at then stays off.
let authoredHead = false;
// The last loaded document, kept so the viewer can re-solve base pose and
// ground anchors when the character (with its own proportions) arrives.
let lastIR: PosecodeIR | null = null;
// Rebuilt on every solved frame. Missing target names and unreachable
// effectors remain visible here instead of disappearing behind `continue`.
let reachResiduals: ReachResidual[] = [];
let constraintDiagnostics: ConstraintDiagnostic[] = [];
let constraintDiagnosticsDirty = true;
let lastConstraintDiagnosticsAt = -Infinity;
type ReachResidualTarget =
| { kind: "fixed"; point: THREE.Vector3 }
| { kind: "floor"; point: THREE.Vector3 }
| { kind: "landmark"; boneId: string };
let reachResidualTargets: Array<ReachResidualTarget | null> = [];
let groundTargets = new Map<string, THREE.Vector3>();
const segmentStartEffectors: Map<string, THREE.Vector3>[] = [];
// World-space anchor points contributed by scene props (chair seat, bar grip,
// wall surface). Populated when a doc declares props; empty otherwise.
let propAnchors = new Map<string, THREE.Vector3>();
let propScene: PropScene | null = null;
// The grounded base transform captured at load. Each frame resets the root to
// this before ground-lock / pins / reach recompute, so those root adjustments
// never accumulate across frames (and the body returns to base when a pin ends).
const baseRootPos = new THREE.Vector3();
const baseRootQuat = new THREE.Quaternion();
let time = 0;
let speed = 1;
let playing = false;
let loop = true;
let phaseCb: (info: ViewerPhaseInfo) => void = () => {};
let tickCb: (time: number, duration: number) => void = () => {};
let loopCb: () => void = () => {};
let lastPhaseIndex = -2;
let activeSegIndex = 0;
// `load()` briefly solves each real phase endpoint to seed any floor pin
// introduced by the following phase from the *fully solved* prior pose.
// Keep those internal solves out of callbacks, character/mocap state, and
// the canvas; they are deterministic anchor preparation, not visible frames.
let precomputingAnchors = false;
function refreshConstraintDiagnostics(
info: ReturnType<NonNullable<typeof timeline>["sample"]>,
): void {
if (precomputingAnchors) return;
const now = performance.now();
if (!constraintDiagnosticsDirty) {
if (!playing || now - lastConstraintDiagnosticsAt < CONSTRAINT_DIAGNOSTIC_INTERVAL_MS) return;
}
constraintDiagnostics = measureConstraintDiagnostics(
mannequin,
info.groundLock,
info.pins,
);
constraintDiagnosticsDirty = false;
lastConstraintDiagnosticsAt = now;
}
// Camera easing targets.
const desiredTarget = new THREE.Vector3(0, 0.9, 0);
const desiredPos = camera.position.clone();
let easeCamera = false;
function resize(): void {
const w = canvas.clientWidth || 1;
const h = canvas.clientHeight || 1;
if (canvas.width !== w || canvas.height !== h) {
renderer.setSize(w, h, false);
camera.aspect = w / h;
camera.updateProjectionMatrix();
}
}
function applyBaseRoot(): void {
const root = mannequin.root;
const base = timeline?.basePose.root;
root.position.set(...(base?.position ?? [0, 0, 0]));
const [rx, ry, rz] = base?.rotationDeg ?? [0, 0, 0];
root.rotation.set(rx * DEG, ry * DEG, rz * DEG);
root.updateMatrixWorld(true);
}
function captureGroundTargets(): void {
// "Ground-lock" means HOLD the effector where the grounded base pose placed
// it, not drag it to y=0. groundFigure() already set the floor contact.
groundTargets = new Map();
frameAnchorMap.clear(); // drop anchors for effectors no longer captured
for (const ids of Object.values(mannequin.effectors)) {
for (const id of ids) {
const node = mannequin.bones.get(id);
if (node) groundTargets.set(id, node.getWorldPosition(new THREE.Vector3()));
}
}
}
// Reused scratch for the per-frame facing rotation (yaw about world Y).
const WORLD_Y = new THREE.Vector3(0, 1, 0);
const YAW_Q = new THREE.Quaternion();
// Per-frame ground anchors: the captured load-time effector positions,
// carried along by the phase's yaw/travel so horizontal foot planting
// composes with choreography instead of fighting it. Values are mutated in
// place each frame; the map is rebuilt on load (captureGroundTargets).
const frameAnchorMap = new Map<string, THREE.Vector3>();
function frameAnchors(rootYaw: number, rootOffset: { x: number; z: number }): Map<string, THREE.Vector3> {
for (const [id, captured] of groundTargets) {
let v = frameAnchorMap.get(id);
if (!v) {
v = new THREE.Vector3();
frameAnchorMap.set(id, v);
}
v.copy(captured);
if (rootYaw !== 0) {
// Yaw spins the body about the vertical axis through the root, so the
// anchors must pivot with it (a quarter-turn carries the feet around).
v.sub(baseRootPos).applyAxisAngle(WORLD_Y, rootYaw).add(baseRootPos);
}
v.x += rootOffset.x;
v.z += rootOffset.z;
}
return frameAnchorMap;
}
/** Resolve a reach target name to a world point: floor / prop anchor / landmark. */
function resolveReachTarget(
target: string,
effectorName: string,
): THREE.Vector3 | null {
if (target === "floor") return floorTargetForEffector(mannequin, effectorName);
const anchor = propAnchors.get(target);
if (anchor) return anchor.clone();
const bone = mannequin.bones.get(target);
if (bone) return bone.getWorldPosition(new THREE.Vector3());
return null;
}
/**
* Reach-IK: drive each active effector to its world target with ROM-
* constrained CCD: the solved arm/leg obeys the same hard joint limits as
* authored angles, so an unreachable target yields the closest SAFE pose.
* Runs AFTER ground-lock so landmark/floor targets are resolved against the
* final root placement. The chain is the arm (hand) or the leg (foot); other
* joints keep their authored FK pose.
*/
function applyReaches(reaches: WeightedReachTarget[]): void {
reachResiduals = [];
reachResidualTargets = [];
for (const r of reaches) {
const effectorBone = effectorBoneId(r.effector);
const effector = mannequin.bones.get(effectorBone);
if (!effector) {
reachResiduals.push(
solveReachToPoint(mannequin, r.effector, r.target, new THREE.Vector3(), r.weight),
);
reachResidualTargets.push(null);
continue;
}
const target = resolveReachTarget(r.target, r.effector);
if (!target) {
reachResiduals.push(missingReachTarget(r.effector, r.target, r.weight));
reachResidualTargets.push(null);
continue;
}
reachResiduals.push(
solveReachToPoint(mannequin, r.effector, r.target, target, r.weight),
);
reachResidualTargets.push(
r.target === "floor"
? { kind: "floor", point: target.clone() }
: mannequin.bones.has(r.target)
? { kind: "landmark", boneId: r.target }
: { kind: "fixed", point: target.clone() },
);
}
}
/** Re-measure after later contacts/root grounding so diagnostics are final. */
function refreshReachResiduals(): void {
reachResiduals = reachResiduals.map((residual, index) => {
const targetRef = reachResidualTargets[index];
if (!targetRef || residual.distance === null) return residual;
const effector = mannequin.bones.get(effectorBoneId(residual.effector));
if (!effector) return residual;
// Body landmarks and contact surfaces can move during later root/contact
// reconciliation. Re-read their final geometry while preserving a floor
// contact's solved world-space X/Z anchor.
const point = effector.getWorldPosition(new THREE.Vector3());
let target: THREE.Vector3 | undefined;
if (targetRef.kind === "fixed") {
target = targetRef.point;
} else if (targetRef.kind === "landmark") {
target = mannequin.bones.get(targetRef.boneId)?.getWorldPosition(new THREE.Vector3());
} else {
const height = floorContactHeight(mannequin, residual.effector);
if (height !== null) target = targetRef.point.clone().setY(point.y - height);
}
if (!target) return residual;
const distance = point.distanceTo(target);
return { ...residual, distance, reached: distance <= REACH_TOLERANCE };
});
}
/**
* Contact pins: translate the WHOLE figure so each pinned effector sits on its
* anchor. Where ground-lock keeps a planted foot on the floor, a pin keeps a
* hand on the bar or a foot on the box while the body moves relative to it,
* so the figure hangs from a bar, pulls up toward it, rises onto a box, or
* lowers into a dip as the limb joints work. Applied after ground-lock (which
* pinned movements normally omit) and before reach-IK.
*/
function applyPins(pins: PinTarget[]): void {
if (pins.length === 0) return;
const dipBarPins = pins.filter((pin) => isDipBarGrip(pin.anchor));
prepareGripFrames(mannequin, dipBarPins);
const delta = new THREE.Vector3();
let n = 0;
// Stance-foot plants solved by leg IK after the body reaches its waypoint,
// rather than by translating the body onto the anchor (which cancels travel).
const stancePlants: { effector: string; anchor: THREE.Vector3 }[] = [];
for (const p of pins) {
const effectorBone = effectorBoneId(p.effector);
const effector = mannequin.bones.get(effectorBone);
if (!effector) continue;
let anchor: THREE.Vector3 | null = null;
if (p.anchor === "floor") {
const startPos = segmentStartEffectors[activeSegIndex]?.get(effectorBone);
if (startPos) {
anchor = startPos.clone();
anchor.y = floorTargetForEffector(mannequin, p.effector)?.y ?? 0;
} else {
anchor = resolveReachTarget(p.anchor, p.effector);
}
} else {
anchor = resolveReachTarget(p.anchor, p.effector);
}
if (!anchor) continue;
if (clipIsGait && p.anchor === "floor" && effectorBone.startsWith("ankle_")) {
stancePlants.push({ effector: p.effector, anchor });
continue;
}
delta.add(anchor.sub(effector.getWorldPosition(new THREE.Vector3())));
n++;
}
if (n > 0) {
mannequin.root.position.add(delta.multiplyScalar(1 / n));
mannequin.root.updateMatrixWorld(true);
}
// Keep each stance foot on its plant while the travelled root stays put: the
// leg reaches back to the fixed floor anchor, so the figure steps across the
// floor instead of marching in place.
for (const plant of stancePlants) {
solveReachToPoint(mannequin, plant.effector, "floor", plant.anchor, 1);
}
alignGripFrames(mannequin, dipBarPins);
}
/**
* Bar grips: unlike a pin (body translate only), a grip makes each hand hold
* the bar. (1) Translate the body by the average wrist→anchor delta — the
* authored elbow flex raises the wrists, so the body rises: the pull-up. (2)
* Per-hand arm IK drives each wrist exactly onto its own two-point anchor
* (`bar_left`/`bar_right`), so the hands grip shoulder-width and the arms angle
* naturally instead of pointing straight up. (3) Wrap the fingers round the bar.
*/
function applyGrips(grips: GripTarget[]): void {
if (grips.length === 0) return;
// Dip support begins from a deterministic untwisted forearm frame; doing
// this before translation/IK means the later wrist target remains exact.
prepareGripFrames(mannequin, grips);
const resolveGrip = (anchor: string, effectorName: string): THREE.Vector3 | null =>
resolveReachTarget(anchor, effectorName) ??
resolveReachTarget(anchor.replace(/_(left|right)$/, ""), effectorName);
// 1. Body translate (the vertical pull).
const delta = new THREE.Vector3();
let n = 0;
for (const g of grips) {
const effectorBone = effectorBoneId(g.effector);
const effector = mannequin.bones.get(effectorBone);
if (!effector) continue;
const target = resolveGrip(g.anchor, g.effector);
if (!target) continue;
delta.add(target.clone().sub(effector.getWorldPosition(new THREE.Vector3())));
n++;
}
if (n > 0) {
mannequin.root.position.add(delta.multiplyScalar(1 / n));
mannequin.root.updateMatrixWorld(true);
}
// 2. Per-hand arm IK onto each grip point (ROM-clamped via reachChain).
for (const g of grips) {
const effectorBone = effectorBoneId(g.effector);
const effector = mannequin.bones.get(effectorBone);
if (!effector) continue;
const target = resolveGrip(g.anchor, g.effector);
if (!target) continue;
const { joints, limits } = reachChain(mannequin, g.effector);
if (joints.length === 0) continue;
if (isDipBarGrip(g.anchor)) {
// Keep forearm twist stable while CCD positions the hand. Otherwise
// equally-valid axial solutions flip palms between/away from the rails.
for (let i = 0; i < joints.length; i++) {
if (!joints[i]!.name.startsWith("elbow_")) continue;
const limit = limits[i];
if (limit) limits[i] = { ...limit, y: [0, 0] };
}
}
solveCCD({ joints, limits, effector, target }, 12);
}
// 3. Stable contact frame followed by an anatomically signed finger wrap.
alignGripFrames(mannequin, grips);
wrapGrip(mannequin, grips);
}
/**
* L4.3 look-at: turn the head toward the action. Collects the world points of
* this phase's active grips/reaches (up at the bar, down at a floor reach) and
* aims the head at their average. Skipped when the document poses the head/neck.
*/
function applyLookAt(info: { grips: GripTarget[]; reaches: ReachTarget[] }): void {
if (authoredHead) return;
const pts: THREE.Vector3[] = [];
const collect = (effectorName: string, anchorName: string): void => {
const bone = effectorBoneId(effectorName);
const eff = mannequin.bones.get(bone);
if (!eff) return;
const t =
resolveReachTarget(anchorName, effectorName) ??
resolveReachTarget(anchorName.replace(/_(left|right)$/, ""), effectorName);
if (t) pts.push(t);
};
for (const g of info.grips) collect(g.effector, g.anchor);
for (const r of info.reaches) collect(r.effector, r.target);
if (pts.length === 0) return;
const focus = new THREE.Vector3();
for (const p of pts) focus.add(p);
aimHead(mannequin, focus.multiplyScalar(1 / pts.length));
}
/** Prop-contact exemptions for a phase: limbs pinned/gripped/reached to props. */
function contactExemptionsOf(info: {
pins?: readonly PinTarget[];
grips?: readonly GripTarget[];
reaches?: readonly ReachTarget[];
}): ReturnType<typeof propContactExemptions> {
return propContactExemptions([
...(info.pins ?? []),
...(info.grips ?? []),
...(info.reaches ?? []).map((r) => ({ effector: r.effector, anchor: r.target })),
]);
}
function frameCamera(): void {
// Auto-frame the figure: fit its bounding box, keep a pleasant angle.
// Include any scene prop too: a pull-up bar sits well above the figure's
// head, and framing on the mannequin alone left it cropped out of view.
const box = new THREE.Box3().setFromObject(mannequin.root);
if (propScene) box.union(new THREE.Box3().setFromObject(propScene.group));
if (box.isEmpty()) return;
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
// Frame against a ~1.8m standing height floor so short poses (squat,
// plank) don't zoom in awkwardly; fill most of the viewport. Traveling
// movements (turn/travel) roam across the floor, so widen the frame by the
// movement's travel extent to keep the figure in view the whole loop.
const travel = timeline?.travelExtent ?? 0;
const radius = Math.max(size.x, size.y, size.z, 1.8) * 0.5 + travel;
const dist = (radius / Math.sin((camera.fov * DEG) / 2)) * 1.15 + 0.3;
desiredTarget.copy(center);
desiredTarget.y = Math.max(center.y, 0.55);
desiredPos.set(
center.x + dist * 0.55,
Math.max(center.y + radius * 0.5, 1.0),
center.z + dist,
);
easeCamera = true;
}
function frame(): void {
let solvedInfo: ReturnType<NonNullable<typeof timeline>["sample"]> | null = null;
if (timeline) {
const info = timeline.sample(time, mannequin.bones);
solvedInfo = info;
activeSegIndex = info.phaseIndex >= 0 ? info.phaseIndex : 0;
// Life layer rides on wall-clock time (not timeline time) so the figure
// keeps breathing and blinking while paused or scrubbing.
if (!precomputingAnchors) applyLife(performance.now() / 1000);
// Recompute root contact from the grounded base each frame (no drift).
mannequin.root.position.copy(baseRootPos);
mannequin.root.quaternion.copy(baseRootQuat);
// Spatial choreography: layer the phase's facing (yaw about world Y) and
// ground travel (world X/Z) onto the base root BEFORE ground-lock. The
// feet-only ground-lock only corrects the root's Y, so it composes with
// travel (X/Z) and yaw without fighting them; the figure turns and steps
// across the floor while its feet still rest on it.
if (info.rootYaw !== 0) {
YAW_Q.setFromAxisAngle(WORLD_Y, info.rootYaw);
mannequin.root.quaternion.premultiply(YAW_Q);
}
mannequin.root.position.x += info.rootOffset.x;
mannequin.root.position.z += info.rootOffset.z;
mannequin.root.updateMatrixWorld(true);
// A semantic fist is geometry as well as an endpoint name. Close any
// unauthored digits before floor target/bounds resolution; authored curl
// remains untouched and survives the later wrist contact correction.
const fistSides = fistSidesOf(info.reaches, info.pins, info.groundLock);
const activeGripSides = gripSidesOf(info.grips);
const constrainedHandSides = contactHandSidesOf(
info.reaches,
info.pins,
info.grips,
info.groundLock,
);
const palmFloorSides = floorHandSidesOf(info.reaches, info.pins, info.groundLock);
formFists(mannequin, fistSides, authoredFingers);
// Finger surface shape is part of a floor target too. Flatten palms (and
// relax free hands) before measuring their subtree bounds; fist/grip
// sides are protected from this pass.
relaxHands(
mannequin,
unionHandSides(activeGripSides, fistSides),
authoredFingers,
palmFloorSides,
);
// Establish the intended palm/knuckle surface BEFORE any floor target is
// measured. The post-IK pass below restores the same frame after parent
// joints move, keeping contact-surface height consistent at both ends.
alignFloorContacts(mannequin, info.reaches, info.pins, info.groundLock);
// Self-collision: nudge limbs out of the body BEFORE contact solving so
// ground-lock and pins see the corrected pose (same order as load()).
depenetrate(mannequin);
applyGroundLockTo(mannequin, info.groundLock, frameAnchors(info.rootYaw, info.rootOffset));
applyPins(info.pins);
applyGrips(info.grips);
// Props are solid: after the root solvers place the body, push it back
// out of any prop face it crossed (wall-sit slides down the wall's
// surface, not through it) and bend swing legs clear of box edges.
// Before reach-IK so a later root push can't drag reached hands off
// their world targets. Limbs pinned/gripped to a prop anchor are that
// phase's declared support, exempt from clearing.
if (propScene) {
resolvePropContacts(mannequin, propScene.colliders, contactExemptionsOf(info));
}
// Reach-IK BEFORE the floor safety clamp. When authored FK pushes a
// reaching limb through the floor (cobra: prone + shoulders flex 50),
// the limb must bend to meet the floor. Running reaches after the clamp
// let the clamp "solve" the penetration first by hoisting the whole
// rigid body into the air — legs floating, the classic levitating-cobra
// bug. Ground-lock and pins have already fixed the root placement that
// floor/landmark targets resolve against.
applyReaches(info.reaches);
alignFloorContacts(mannequin, info.reaches, info.pins, info.groundLock);
// Plantigrade correction: keep planted soles flat to the floor so grounded
// lower-body poses (squat, lunge, deadlift) don't balance on the toes.
// Runs before the floor clamp so the leveled sole is what rests on y=0.
levelPlantedFeet(mannequin, info.groundLock);
// L4.2 aliveness: contralateral arm swing during locomotion (free arms only).
swingArms(mannequin, authoredShoulders, constrainedHandSides);
// L4.3 aliveness: turn the head toward the active contact (bar / floor reach).
applyLookAt(info);
// Final renderer-authored contact mutations stay inside strict terminal
// ROM (notably wrist and every ankle axis, including locked ankle Y/Z).
enforceContactRom(mannequin);
// A floor reach can change a limb after floating-root ground-lock has
// placed the existing supports. Reconcile once more in constraint order:
// replant the root support, then re-solve the independent limbs. Without
// this bounded refinement, the global floor safety clamp could rescue a
// reached knee/hand by lifting the declared planted foot several cm.
if (info.groundLock.length > 0 && info.reaches.length > 0) {
for (let refinement = 0; refinement < 3; refinement++) {
applyGroundLockTo(
mannequin,
info.groundLock,
frameAnchors(info.rootYaw, info.rootOffset),
);
applyReaches(info.reaches);
alignFloorContacts(mannequin, info.reaches, info.pins, info.groundLock);
enforceContactRom(mannequin);
}
}
// Safety net: reconcile the fully-solved pose with the floor.
//
// A ground-locked phase asserts its effectors (feet, and for a plank the
// forearms) are PLANTED, so its lowest mesh point must sit exactly on the
// floor — clamp the root BOTH ways. This is essential because
// levelPlantedFeet() rotates the ankle flat AFTER ground-lock dropped the
// body, which lifts the sole a couple centimetres; an up-only clamp could
// never recover it and the whole figure floated (squat, deadlift,
// good-morning, forward-fold, plank, …).
//
// Explicit elevated support is the opt-out: bar grips and non-floor pins
// (box/chair) preserve their solved height. Everything else remains
// floor-bound; airborne choreography should use a future explicit flight
// contact rather than arise accidentally from missing `ground-lock`.
mannequin.root.updateMatrixWorld(true);
const box = new THREE.Box3().setFromObject(mannequin.root);
// Unless an elevated prop/grip is carrying the body, the movement is
// floor-bound even when the author omitted `ground-lock`. This prevents
// ordinary curls, lunges, stretches, and transitions from inheriting a
// floating root when their FK pose raises the previous lowest point.
const floorBound = isFloorBound(info);