-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
803 lines (657 loc) · 28.6 KB
/
index.html
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
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title></title></head>
<style>canvas{ display:block; } body, html { padding:0px; margin:0px; width:100%; height:100%; }</style>
<body><script src="./import-map.js"></script><script type="module">
// #region IMPORTS
import useThreeWebGL2, { THREE, useDarkScene, useVisualDebug } from './_lib/useThreeWebGL2.js';
import MatrixSkinMaterial from './_lib/customSkinning/MatrixSkinMaterial.js';
import Gltf2 from '@Gltf2';
import {
Armature, TranMatrixSkin,
Pose, BoneMap, PoseAnimator, Clip, TrackVec3, TrackQuat,
Quat, Vec3, Transform,
IKRig, BoneAxes,
} from '@ossos';
// #endregion
// #region MAIN
let Debug;
let App = useDarkScene( useThreeWebGL2() );
let Ref = {};
window.addEventListener( 'load', async ()=>{
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Setup
App.sphericalLook( 45, 20, 4, [ 1.2, 0.8, 0 ] );
Debug = await useVisualDebug( App );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Load Character Mesh
Ref.char0 = await fetchCharacter( './_res/models/agora/alpha.json' );
Ref.char0.setOffsetPos( [1.2,0,0] );
App.scene.add( ...Ref.char0.models );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Load Animation for Retargetting
const gltf = await Gltf2.fetch( './_res/anim/mixamo/Catwalk.gltf' );
const arm = parseArmature( gltf );
const clip = loadAnimationClip( gltf, null, arm.bindPose );
const retarget = new IKBipedRetarget();
retarget
.setSourceTPose( arm.bindPose ) // TPose for the clip animation
.setPlacementReset( [0,0,1] ) // Animation uses Zup, clear XY
.setClip( clip ); // Set animation to retarget
Ref.retarget = retarget;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Test Frame Reargetting
Ref.retarget
.atFrame( 0 ) // Animate Frame + Gen IK Data
// .step( 0.1 ) // Move Animation by seconds
.debugBones( Debug ) // Visualize Bones
.debugIKPose( Debug ) // Visualize IK Data
.applyIkPoseToRig( Ref.char0.rig ); // Push IK data to target IK Rig
Ref.char0
.runIk()
.updateSkin()
.debugBones();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
App.createRenderLoop( onPreRender ).start();
// App.renderLoop();
});
function onPreRender( dt, et ){
Debug.reset();
Ref.retarget
.step( dt )
.debugBones( Debug )
.debugIKPose( Debug )
.applyIkPoseToRig( Ref.char0.rig );
Ref.char0
.runIk()
.updateSkin()
.debugBones();
}
// #endregion
// #region ARMATURE
// Turn GLTF Skeleton to an OSSOS Armature
function parseArmature( gltf, idx=0, minLen=0.1 ){
const skin = gltf.getSkin( idx );
const arm = new Armature();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Create Armature Skeleton
let b;
for( const j of skin.joints ){
b = arm.addBone( { name: j.name, parent: j.parentIndex } );
if( j.rotation ) b.local.rot.copy( j.rotation );
if( j.position ) b.local.pos.copy( j.position );
if( j.scale ) b.local.scl.copy( j.scale );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Set offset before binding, GLTF's inverseMatrices will
// include this in the bindpose which I think shouldnt
if( skin.position || skin.scale || skin.rotation ){
const pose = arm.bindPose;
if( skin.position ) pose.offset.pos.copy( skin.position );
if( skin.rotation ) pose.offset.rot.copy( skin.rotation );
if( skin.scale ) pose.offset.scl.copy( skin.scale );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Finalize bone & instialize one of the skinning algorithms
arm.bind( minLen );
arm.useSkin( TranMatrixSkin );
return arm;
}
function getAnimationPose( gltf, pose, name='TPose', frame=0 ){
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Find animation
let idx = -1;
if( gltf.json.animations ){
idx = gltf.json.animations.findIndex( e=>(e.name.toLowerCase() === 'tpose') );
}
if( idx === -1 ){ console.log( 'Animation not found with the name: ', name ); return false; }
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Parse Animation
const anim = gltf.getAnimation( idx );
if( anim.timestamps.length > 1 ) console.warn( 'Multiple timestamps in animation named: ', name );
for( let i of anim.tracks ){
switch( i.transform ){
case 0:
// TODO, frame value might need to be multiplied for use with .fromBuf
pose.bones[ i.jointIndex ].local.rot.fromBuf( i.keyframes.data, frame );
break;
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
pose.updateWorld();
return true;
}
function debugBones( ary, debug, offset=[0,0,0] ){ // flen=0.06, pntSize=0.9, doReset=false,
const flen = 0.06;
const pntSize = 0.9;
const doReset = false
const up = new Vec3();
const fwd = new Vec3();
const v = new Vec3();
const boneColor = 0x797979;
const jntColor = 0x909090;
if( doReset ){
debug.pnt.reset();
debug.ln.reset();
}
for( let b of ary ){
v .fromAdd( b.world.pos, offset );
up .fromQuat( b.world.rot, Vec3.UP )
// .scale( b.len * b.world.scl[1] )
.scale( b.len ) // No Scale, can't see bones when dealing with offset transforms that scale characters
.add( v );
fwd .fromQuat( b.world.rot, Vec3.FORWARD )
.scale( flen )
.add( v );
debug.pnt.add( v, jntColor, pntSize, 1 );
debug.ln.add( v, fwd, jntColor );
debug.ln.add( v, up, boneColor );
}
}
// #endregion
// #region ANIMATION
function loadAnimationClip( gltf, name, pose ){
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
const anim = gltf.getAnimation( name );
const clip = new Clip( anim.name );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let i;
for( i of anim.timestamps ){
if( i.data ) clip.timeStamps.push( new Float32Array( i.data ) ); // Clone TimeStamp Data so its not bound to GLTF's BIN
if( i.elementCnt > clip.frameCount ) clip.frameCount = i.elementCnt; // Find max frame counts
if( i?.boundMax[0] > clip.duration ) clip.duration = i.boundMax[0]; // Find full duration
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
let gTrack; // Gltf Track
let oTrack; // Ossos Track
let bName; // Bone Name
let reBoneFilter = new RegExp( /(root|hips?)/i ); // Only use Vec3 tracks for root or hip bone
for( gTrack of anim.tracks ){
// -------------------------------------------
if( !gTrack.keyframes.data ){
console.error( 'GLTF Animation Track has no keyframe data' );
continue;
}
// -------------------------------------------
oTrack = null;
switch( gTrack.transform ){
// Rotation
case 0: oTrack = new TrackQuat( gTrack.interpolation ); break;
// Translation
case 1:
bName = pose.bones[ gTrack.jointIndex ].name;
if( reBoneFilter.test( bName ) ){
oTrack = new TrackVec3( gTrack.interpolation ); break;
}
break;
// Scale
case 2: break;
}
// -------------------------------------------
if( !oTrack ) continue;
oTrack.setData( gTrack.keyframes.data );
oTrack.boneIndex = gTrack.jointIndex;
oTrack.timeIndex = gTrack.timeStampIndex;
clip.tracks.push( oTrack );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return clip;
}
// #endregion
// #region IK RIG
class IKBipedRig extends IKRig {
// #region MAIN
hipHeight = 0; // Track how far character stands off the ground + for IK Scaling
constructor( TPose, autoGen=true ){
super( TPose );
if( autoGen ){
const bMap = new BoneMap( this.pose );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Limbs
this.setLeftArm( bMap.getBoneNames( [ 'upperarm_l', 'forearm_l', 'hand_l' ] ) );
this.setRightArm( bMap.getBoneNames( [ 'upperarm_r', 'forearm_r', 'hand_r' ] ) );
this.setLeftLeg( bMap.getBoneNames( [ 'thigh_l', 'shin_l', 'foot_l' ] ) );
this.setRightLeg( bMap.getBoneNames( [ 'thigh_r', 'shin_r', 'foot_r' ] ) );
this.setLeftFoot( bMap.getBoneNames( [ 'foot_l' ] ) );
this.setRightFoot( bMap.getBoneNames( [ 'foot_r' ] ) );
this.setLeftHand( bMap.getBoneNames( [ 'hand_l' ] ) );
this.setRightHand( bMap.getBoneNames( [ 'hand_r' ] ) );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Others
this.setSpine( bMap.getBoneNames( [ 'spine' ] ) );
this.setHead( bMap.getBoneNames( [ 'head' ] ) );
this.setHip( bMap.getBoneNames( [ 'hip' ] ) );
}
}
// #endregion
// #region ARM CHAINS
get leftArm(){ return this.sets[ this.names[ 'arm_l' ] ]; }
setLeftArm( bones ){
if( bones ) this.addSet( { name: 'arm_l', solver: 'limb', bones: bones, axes: BoneAxes.RBD, order: 10 } );
return this;
}
get leftHand(){ return this.sets[ this.names[ 'hand_l' ] ]; }
setLeftHand( bones ){
if( bones ) this.addSet( { name: 'hand_l', solver: 'look', bones: bones, axes: BoneAxes.RBD, order: 11 } );
return this;
}
get rightArm(){ return this.sets[ this.names[ 'arm_r' ] ]; }
setRightArm( bones ){
if( bones ) this.addSet( { name: 'arm_r', solver: 'limb', bones: bones, axes: BoneAxes.LBU, order: 10 } );
return this;
}
get rightHand(){ return this.sets[ this.names[ 'hand_r' ] ]; }
setRightHand( bones ){
if( bones ) this.addSet( { name: 'hand_r', solver: 'look', bones: bones, axes: BoneAxes.LBU, order: 11 } );
return this;
}
// #endregion
// #region LEG CHAINS
// Note : Reserve 8 for Toes
get leftLeg(){ return this.sets[ this.names[ 'leg_l' ] ]; }
setLeftLeg( bones ){
if( bones ) this.addSet( { name: 'leg_l', solver: 'limb', bones: bones, axes: BoneAxes.DFR, order: 6 } );
return this;
}
get leftFoot(){ return this.sets[ this.names[ 'foot_l' ] ]; }
setLeftFoot( bones ){
if( bones ) this.addSet( { name: 'foot_l', solver: 'look', bones: bones, axes: BoneAxes.FUR, order:7 } );
return this;
}
get rightLeg(){ return this.sets[ this.names[ 'leg_r' ] ]; }
setRightLeg( bones ){
if( bones ) this.addSet( { name: 'leg_r', solver: 'limb', bones: bones, axes: BoneAxes.DFR, order: 6 } );
return this;
}
get rightFoot(){ return this.sets[ this.names[ 'foot_r' ] ]; }
setRightFoot( bones ){
if( bones ) this.addSet( { name: 'foot_r', solver: 'look', bones: bones, axes: BoneAxes.FUR, order: 7 } );
return this;
}
// #endregion
// #region CENTER LINE
get hip(){ return this.sets[ this.names[ 'hip' ] ]; }
setHip( bones ){
if( bones ){
this.addSet( { name: 'hip', solver: 'root', bones: bones, axes: BoneAxes.FUR, order: 1, } );
// Save Hip Height for use of scaling translations
const b = this.pose.bones[ this.hip.chain.firstLink.index ];
this.hipHeight = b.world.pos[ 1 ]; // Y can give us the hip height
}
return this;
}
get spine(){ return this.sets[ this.names[ 'spine' ] ]; }
setSpine( bones ){
if( bones ) this.addSet( { name: 'spine', solver: 'swingchain', bones: bones, axes: BoneAxes.UFR, order: 2, } );
return this;
}
get head(){ return this.sets[ this.names[ 'head' ] ]; }
setHead( bones ){
if( bones ) this.addSet( { name: 'head', solver: 'look', bones: bones, axes: BoneAxes.FUR, order: 3, } );
return this;
}
// #endregion
}
// #endregion
// #region COMPUTE IK DATA
class IKBipedRetarget {
// #region MAIN
animator = new PoseAnimator();
ikpose = new IKBipedPose();
rig = null;
// #endregion
// #region SETUP
setSourceTPose( tpose ){
this.rig = new IKBipedRig( tpose ); // IK Rig for Animation Skeleton
return this;
}
setPlacementReset( v ){ this.animator.usePlacementReset( v ); return this; }
setClip( clip ){
this.animator.setClip( clip );
this.animator.start();
return this;
}
// #endregion
// #region ANIMATE
atFrame( i ){
this.animator.atFrame( i ).updatePose( this.rig.pose );
this.#compute();
return this;
}
step( i ){
this.animator.step( i ).updatePose( this.rig.pose );
this.#compute();
return this;
}
// #endregion
// #region RETARGET
#compute(){
const rig = this.rig;
const ikp = this.ikpose;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Compute Limbs
this.#computeLimb( rig.leftArm.chain, ikp.armL );
this.#computeLimb( rig.rightArm.chain, ikp.armR );
this.#computeLimb( rig.leftLeg.chain, ikp.legL );
this.#computeLimb( rig.rightLeg.chain, ikp.legR );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Other
this.#computeSpine( rig.spine.chain, ikp.spine );
this.#computeSwingTwist( rig.head.chain, ikp.head );
this.#computeSwingTwist( rig.leftFoot.chain, ikp.footL );
this.#computeSwingTwist( rig.rightFoot.chain, ikp.footR );
this.#computeSwingTwist( rig.leftHand.chain, ikp.handL );
this.#computeSwingTwist( rig.rightHand.chain, ikp.handR );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HIP / ROOT
this.#computeSwingTwist( rig.hip.chain, ikp.hip );
this.#computeDeltaPos( rig.hip.chain, ikp.hip );
}
/** Data from Limb Solver */
#computeLimb( chain, out ){
const v = new Vec3();
const bones = this.rig.pose.bones;
const ikSwing = out.swing;
const ikTwist = out.twist;
let fLnk = chain.firstLink;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Get Bone ends of the chain
const a = bones[ fLnk.index ];
const b = bones[ chain.lastLink.index ];
// Compute Swing Direction & Effector Distance Scale
ikSwing.fromSub( b.world.pos, a.world.pos );
out.lenScale = ikSwing.len / chain.len;
ikSwing.norm();
// Compute Orthogonal Twist Direction
ikTwist.fromQuat( a.world.rot, fLnk.axes.twist ); // Get Twist dir of root bone
v.fromCross( ikTwist, ikSwing ); // Get orthogonal Direction...
ikTwist.fromCross( ikSwing, v ).norm(); // To align to Swing Dir
}
/** Only useful for spine data utilizing two axis rotation */
#computeSpine( chain, out ){
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Start Axes
let lnk = chain.firstLink;
let b = this.rig.pose.bones[ lnk.index ];
out.startSwing.fromQuat( b.world.rot, lnk.axes.swing ).norm();
out.startTwist.fromQuat( b.world.rot, lnk.axes.twist ).norm();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// End Axes
lnk = chain.lastLink;
b = this.rig.pose.bones[ lnk.index ];
out.endSwing.fromQuat( b.world.rot, lnk.axes.swing ).norm();
out.endTwist.fromQuat( b.world.rot, lnk.axes.twist ).norm();
}
/** Simple Axis Rotation : Head, Hips, Hands, Feet */
#computeSwingTwist( chain, out ){
let lnk = chain.firstLink;
let a = this.rig.pose.bones[ lnk.index ];
out.swing.fromQuat( a.world.rot, lnk.axes.swing ).norm();
out.twist.fromQuat( a.world.rot, lnk.axes.twist ).norm();
}
/** Used for HIP / ROOT Delta Translation */
#computeDeltaPos( chain, out ){
const lnk = chain.firstLink;
const b = this.rig.pose.bones[ lnk.index ]; // Get Current World Transform
const t = this.rig.pose
.getWorldTransform( lnk.pindex ) // Parent's current World Transform
.mul( lnk.bind ); // Add Bone's localspace bind pose to it
// Diff between current pose & where bone would be if not posed
out.deltaPos.fromSub( b.world.pos, t.pos );
// Save skeleton's hip height as a scalar for hip translations
out.bindHeight = this.rig.hipHeight;
}
// #endregion
// #region APPLY
applyIkPoseToRig( rig ){
const ikp = this.ikpose;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// CENTER LINE
rig.hip.target
.setDirections( ikp.hip.swing, ikp.hip.twist )
.setDeltaMove( ikp.hip.deltaPos, Math.abs( rig.hipHeight / ikp.hip.bindHeight ) );
rig.spine.target
.setDirections( ikp.spine.startSwing, ikp.spine.startTwist )
.setAltDirections( ikp.spine.endSwing, ikp.spine.endTwist );
rig.head.target.setDirections( ikp.head.swing, ikp.head.twist );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// LEGS
rig.leftLeg.target.setDirections( ikp.legL.swing, ikp.legL.twist, ikp.legL.lenScale );
rig.leftFoot.target.setDirections( ikp.footL.swing, ikp.footL.twist );
rig.rightLeg.target.setDirections( ikp.legR.swing, ikp.legR.twist, ikp.legR.lenScale );
rig.rightFoot.target.setDirections( ikp.footR.swing, ikp.footR.twist );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ARMS
rig.leftArm.target.setDirections( ikp.armL.swing, ikp.armL.twist, ikp.armL.lenScale );
rig.leftHand.target.setDirections( ikp.handL.swing, ikp.handL.twist );
rig.rightArm.target.setDirections( ikp.armR.swing, ikp.armR.twist, ikp.armR.lenScale );
rig.rightHand.target.setDirections( ikp.handR.swing, ikp.handR.twist );
return this;
}
// #endregion
// #region DEBUG
debugBones( debug, offset=[0,0,0] ){
const bones = this.rig.pose.bones;
const flen = 0.06;
const pntSize = 0.9;
const doReset = false
const up = new Vec3();
const fwd = new Vec3();
const v = new Vec3();
const boneColor = 0x797979;
const jntColor = 0x909090;
for( let b of bones ){
v .fromAdd( b.world.pos, offset );
up .fromQuat( b.world.rot, Vec3.UP )
// .scale( b.len * b.world.scl[1] )
.scale( b.len ) // No Scale, can't see bones when dealing with offset transforms that scale characters
.add( v );
fwd .fromQuat( b.world.rot, Vec3.FORWARD )
.scale( flen )
.add( v );
debug.pnt.add( v, jntColor, pntSize, 1 );
debug.ln.add( v, fwd, jntColor );
debug.ln.add( v, up, boneColor );
}
return this;
}
debugIKPose( debug ){
const rig = this.rig;
const ikp = this.ikpose;
const pose = rig.pose;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Render Limbs
this.#debugIKLimb( debug, rig.leftArm.chain, ikp.armL );
this.#debugIKLimb( debug, rig.rightArm.chain, ikp.armR );
this.#debugIKLimb( debug, rig.leftLeg.chain, ikp.legL );
this.#debugIKLimb( debug, rig.rightLeg.chain, ikp.legR );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Other
this.#debugIKEnds( debug, rig.spine.chain, ikp.spine );
this.#debugIKSwingTwist( debug, rig.head.chain, ikp.head, true );
this.#debugIKSwingTwist( debug, rig.leftFoot.chain, ikp.footL );
this.#debugIKSwingTwist( debug, rig.rightFoot.chain, ikp.footR );
this.#debugIKSwingTwist( debug, rig.leftHand.chain, ikp.handL );
this.#debugIKSwingTwist( debug, rig.rightHand.chain, ikp.handR );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HIP - ROOT
this.#debugIKSwingTwist( debug, rig.hip.chain, ikp.hip, true );
this.#debugIKDeltaPos( debug, rig.hip.chain, ikp.hip );
return this;
}
#debugIKLimb( debug, chain, ikp ){
const aCol = 0x00ffff;
const bCol = 0x00ff00;
const v = new Vec3();
const a = this.rig.pose.bones[ chain.firstLink.index ];
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Render End Points
debug.pnt.add( a.world.pos, aCol, 2, 7 );
v.fromScaleThenAdd( ikp.lenScale * chain.len, ikp.swing, a.world.pos );
debug.pnt.add( v, bCol, 2, 7 );
debug.ln.add( a.world.pos, v, aCol, bCol, true );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Draw Pole Direction ( Twist )
v.fromScaleThenAdd( 0.2, ikp.twist, a.world.pos );
debug.ln.add( a.world.pos, v, aCol );
debug.pnt.add( v, aCol, 1, 0 );
}
#debugIKEnds( debug, chain, ikp ){
const aCol = 0x00ffff;
const bCol = 0x00ff00;
const scl = 0.1;
const va = new Vec3();
const vb = new Vec3();
const aLnk = chain.firstLink;
const bLnk = chain.lastLink;
const a = this.rig.pose.bones[ aLnk.index ];
const b = this.rig.pose.bones[ bLnk.index ];
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// First Link
va.fromQuat( a.world.rot, aLnk.axes.swing ).norm().scale( scl ).add( a.world.pos );
vb.fromQuat( a.world.rot, aLnk.axes.twist ).norm().scale( scl ).add( a.world.pos );
Debug.pnt.add( a.world.pos, aCol, 2, 7 );
Debug.ln.add( a.world.pos, vb, aCol );
Debug.ln.add( a.world.pos, va, bCol );
Debug.pnt.add( vb, aCol, 1, 0 );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Last Link
va.fromQuat( b.world.rot, bLnk.axes.swing ).norm().scale( scl ).add( b.world.pos );
vb.fromQuat( b.world.rot, bLnk.axes.twist ).norm().scale( scl ).add( b.world.pos );
Debug.pnt.add( b.world.pos, aCol, 2, 7 );
Debug.ln.add( b.world.pos, vb, aCol );
Debug.ln.add( b.world.pos, va, bCol );
Debug.pnt.add( vb, aCol, 1, 0 );
}
#debugIKSwingTwist( debug, chain, ikp, showPose=false ){
const aCol = 0x00ffff;
const bCol = 0x00ff00;
const scl = 0.1;
const va = new Vec3();
const vb = new Vec3();
const aLnk = chain.firstLink;
const a = this.rig.pose.bones[ aLnk.index ];
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
va.fromQuat( a.world.rot, aLnk.axes.swing ).norm().scale( scl ).add( a.world.pos );
vb.fromQuat( a.world.rot, aLnk.axes.twist ).norm().scale( scl ).add( a.world.pos );
if( showPose ) debug.pnt.add( a.world.pos, aCol, 2, 7 );
debug.ln.add( a.world.pos, vb, aCol );
debug.ln.add( a.world.pos, va, bCol );
debug.pnt.add( vb, aCol, 1, 0 );
}
#debugIKDeltaPos( debug, chain, ikp ){
const lnk = chain.firstLink;
const b = this.rig.pose.bones[ lnk.index ]; // Get Current World Transform
const v = new Vec3();
const t = this.rig.pose
.getWorldTransform( lnk.pindex ) // Parent's current World Transform
.mul( lnk.bind ); // Add Bone's localspace bind pose to it
v.fromAdd( t.pos, ikp.deltaPos ); // Bind Pose + IK Offset
debug.pnt.add( t.pos, 0xffff00, 1, 1 );
debug.ln.add( t.pos, v, 0xffff00 );
}
// #endregion
}
class IKBipedPose {
hip = { swing:new Vec3(), twist:new Vec3(), deltaPos:new Vec3(), bindHeight:0 };
spine = { startSwing:new Vec3(), startTwist:new Vec3(), endSwing:new Vec3(), endTwist:new Vec3() };
head = { swing:new Vec3(), twist:new Vec3() };
armR = { swing:new Vec3(), twist:new Vec3(), lenScale:0 };
armL = { swing:new Vec3(), twist:new Vec3(), lenScale:0 };
legR = { swing:new Vec3(), twist:new Vec3(), lenScale:0 };
legL = { swing:new Vec3(), twist:new Vec3(), lenScale:0 };
footR = { swing:new Vec3(), twist:new Vec3() };
footL = { swing:new Vec3(), twist:new Vec3() };
handR = { swing:new Vec3(), twist:new Vec3() };
handL = { swing:new Vec3(), twist:new Vec3() };
constructor(){}
}
// #endregion
// #region CHARACTER LOADING
class Character {
// #region MAIN
name = ''; // Character Name
arm = null; // Armature
rig = null; // IK Rig
models = []; // Collection of skinned models that make character
constructor( name ){
if( name ) this.name = name;
}
// #endregion
// #region SETUP
setTPose( tpose, autoGen=true ){
this.arm = tpose.arm;
this.rig = new IKBipedRig( tpose, autoGen );
return this;
}
setOffsetPos( v ){ this.rig.pose.offset.pos.copy( v ); return this; }
// #endregion
// #region METHODS
runIk(){ this.rig.runSolvers(); return this; }
updateSkin(){ this.arm.skin.updateFromPose( this.rig.pose ); return this; }
debugBones( offset=[1,0,0] ){
debugBones( this.rig.pose.bones, Debug, offset );
return this;
}
// #endregion
}
async function fetchCharacter( url ){
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Load JSON Character File
const res = await fetch( url );
if( !res.ok ) throw new Error( `fetchCharacter: ${res.status} - ${res.statusText}` );
const json = await res.json();
if( !json.src || !json.src.includes( '.gltf' ) ) throw new Error( 'fetchCharacter: Src not GLTF' );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Download GLTF File
const path = url.substring( 0, url.lastIndexOf( '/' )+1 );
const gltf = await Gltf2.fetch( `${path}${json.src}` );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Parse skeleton & setup Ossos Armature
const arm = parseArmature( gltf, json.skinIndex || 0 );
// BindPose might be an APose, so TPose can be stored
// as a single frame animation
if( json.tpose && json.tpose.type === 'animation' ){
const tpose = arm.newPose( 'tpose' );
getAnimationPose( gltf, tpose, json.tpose.name, json.tpose.frame );
// arm.skin.updateFromPose( tpose );
}
const char = new Character( json.name )
.setTPose( arm.poses.tpose ?? arm.poses.bind );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Get all primitives to a gl mesh & create 3JS Meshes
const gmesh = gltf.getMesh( json.meshName );
if( !gmesh || gmesh.primitives.length == 0 ){
console.error( `No gltf mesh found: ${id}` );
return null;
}
for( const p of gmesh.primitives ){
// --------------------------
const gmat = gltf.getMaterial( p.materialName );
let col = 'gray';
if( gmat.baseTexture && gmat.baseTexture.uri ){
col = new THREE.TextureLoader().load( gltf.path + gmat.baseTexture.uri );
col.flipY = json.textureYFlip ?? true;
}else if( gmat.baseColor ) col = gmat.baseColor;
// --------------------------
const mat = MatrixSkinMaterial( col, arm.skin );
const geo = geoPrimitive( p );
const mesh = new THREE.Mesh( geo, mat );
char.models.push( mesh );
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return char;
}
function geoPrimitive( prim, useSkin=true ){
const geo = new THREE.BufferGeometry();
geo.setAttribute( 'position', new THREE.BufferAttribute( prim.position.data, prim.position.componentLen ) );
if( prim.indices ) geo.setIndex( new THREE.BufferAttribute( prim.indices.data, 1 ) );
if( prim.normal ) geo.setAttribute( 'normal', new THREE.BufferAttribute( prim.normal.data, prim.normal.componentLen ) );
if( prim.texcoord_0 ) geo.setAttribute( 'uv', new THREE.BufferAttribute( prim.texcoord_0.data, prim.texcoord_0.componentLen ) );
if( useSkin && prim.joints_0 && prim.weights_0 ){
geo.setAttribute( 'skinWeight', new THREE.BufferAttribute( prim.weights_0.data, prim.weights_0.componentLen ) );
geo.setAttribute( 'skinIndex', new THREE.BufferAttribute( prim.joints_0.data, prim.joints_0.componentLen ) );
}
return geo;
}
// #endregion
</script></body></html>