forked from gildor2/UEViewer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSkelMeshInstance.cpp
More file actions
1324 lines (1149 loc) · 35.5 KB
/
Copy pathSkelMeshInstance.cpp
File metadata and controls
1324 lines (1149 loc) · 35.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
#include "Core.h"
#include "UnrealClasses.h"
#if RENDERING
#include "SkeletalMesh.h"
#include "MeshInstance.h"
#include "GlWindow.h"
#include "UnMathTools.h"
// debugging
//#define SHOW_INFLUENCES 1
#define SHOW_TANGENTS 1
//#define SHOW_ANIM 1
#define SHOW_BONE_UPDATES 1
//#define PROFILE_MESH 1
//#define TICK_SECTIONS 1
#define SORT_BY_OPACITY 1
#if TICK_SECTIONS
#undef SORT_BY_OPACITY // to not obfuscate section indices
#endif
struct CMeshBoneData
{
// static data (computed after mesh loading)
int BoneMap; // index of bone in animation tracks
CCoords RefCoords; // coordinates of bone in reference pose (unused!!)
CCoords RefCoordsInv; // inverse of RefCoords
int SubtreeSize; // count of all children bones (0 for leaf bone)
// dynamic data
// skeleton configuration
float Scale; // bone scale; 1=unscaled
int FirstChannel; // first animation channel, affecting this bone
// current pose
CCoords Coords; // current coordinates of bone, model-space
CCoords Transform; // used to transform vertex from reference pose to current pose
#if USE_SSE
CCoords4 Transform4; // SSE version
#endif
// data for tweening; bone-space
CVec3 Pos; // current position of bone
CQuat Quat; // current orientation quaternion
};
// transformed vertex (cutoff version of CSkelMeshVertex)
struct CSkinVert
{
CVecT Position;
CVecT Normal, Tangent, Binormal;
};
#define MAX_MESHMATERIALS 256
/*-----------------------------------------------------------------------------
Interface
-----------------------------------------------------------------------------*/
int CSkelMeshInstance::GetAnimCount() const
{
if (!Animation) return 0;
return Animation->Sequences.Num();
}
const char *CSkelMeshInstance::GetAnimName(int Index) const
{
guard(CSkelMeshInstance::GetAnimName);
if (Index < 0) return "None";
assert(Animation);
return Animation->Sequences[Index].Name;
unguard;
}
/*-----------------------------------------------------------------------------
Create/destroy
-----------------------------------------------------------------------------*/
CSkelMeshInstance::CSkelMeshInstance()
: LodNum(0)
, UVIndex(0)
, RotationMode(EARO_AnimSet)
, LastLodNum(-2) // differs from LodNum and from all other values
, MaxAnimChannel(-1)
, Animation(NULL)
, DataBlock(NULL)
, BoneData(NULL)
, Skinned(NULL)
, InfColors(NULL)
{
ClearSkelAnims();
}
CSkelMeshInstance::~CSkelMeshInstance()
{
if (DataBlock) appFree(DataBlock);
if (InfColors) delete[] InfColors;
}
void CSkelMeshInstance::ClearSkelAnims()
{
// init 1st animation channel with default pose
for (int i = 0; i < MAX_SKELANIMCHANNELS; i++)
{
Channels[i].Anim1 = NULL;
Channels[i].Anim2 = NULL;
Channels[i].SecondaryBlend = 0;
Channels[i].BlendAlpha = 1;
Channels[i].RootBone = 0;
}
}
//!! CSkeletalMesh has SortBones() method now!
/* Iterate bone (sub)tree and do following:
* - find all direct childs of bone 'Index', check sort order; bones should be
* sorted in hierarchy order (1st child and its children first, other childs next)
* Example of tree:
* Bone1
* +- Bone11
* | +- Bone111
* +- Bone12
* | +- Bone121
* | +- Bone122
* +- Bone13
* Sorted order: Bone1, Bone11, Bone111, Bone12, Bone121, Bone122, Bone13
* Note: it seems, Unreal already have sorted bone list (assumed in other code,
* verified by 'assert(currIndex == Index)')
* - compute subtree sizes ('Sizes' array)
* - compute bone hierarchy depth ('Depth' array, for debugging only)
*/
static int CheckBoneTree(const TArray<CSkelMeshBone> &Bones, int Index,
int *Sizes, int *Depth, int &numIndices, int maxIndices)
{
assert(numIndices < maxIndices);
static int depth = 0;
// remember curerent index, increment for recustion
int currIndex = numIndices++;
// find children of Bone[Index]
int treeSize = 0;
for (int i = Index + 1; i < Bones.Num(); i++)
if (Bones[i].ParentIndex == Index)
{
// recurse
depth++;
treeSize += CheckBoneTree(Bones, i, Sizes, Depth, numIndices, maxIndices);
depth--;
}
// store gathered information
// assert(currIndex == Index); //??
if (currIndex != Index) appNotify("Strange skeleton, check childs of bone %d (%s)", currIndex, *Bones[currIndex].Name);
Sizes[currIndex] = treeSize;
Depth[currIndex] = depth;
return treeSize + 1;
}
void CSkelMeshInstance::SetMesh(CSkeletalMesh *Mesh)
{
guard(CSkelMeshInstance::SetMesh);
int i;
pMesh = Mesh;
// orientation
SetAxis(pMesh->RotOrigin, BaseTransform.axis);
BaseTransform.origin[0] = pMesh->MeshOrigin[0] * pMesh->MeshScale[0];
BaseTransform.origin[1] = pMesh->MeshOrigin[1] * pMesh->MeshScale[1];
BaseTransform.origin[2] = pMesh->MeshOrigin[2] * pMesh->MeshScale[2];
BaseTransformScaled.axis = BaseTransform.axis;
CVec3 tmp;
tmp[0] = 1.0f / pMesh->MeshScale[0];
tmp[1] = 1.0f / pMesh->MeshScale[1];
tmp[2] = 1.0f / pMesh->MeshScale[2];
BaseTransformScaled.axis.PrescaleSource(tmp);
BaseTransformScaled.origin = Mesh->MeshOrigin;
int NumBones = pMesh->RefSkeleton.Num();
int NumVerts = 0;
for (i = 0; i < pMesh->Lods.Num(); i++)
if (pMesh->Lods[i].NumVerts > NumVerts)
NumVerts = pMesh->Lods[i].NumVerts;
// free old data
if (DataBlock) appFree(DataBlock);
if (InfColors)
{
delete[] InfColors;
InfColors = NULL;
}
// allocate data arrays in a single block
int DataSize = sizeof(CMeshBoneData) * NumBones + sizeof(CSkinVert) * NumVerts;
DataBlock = appMalloc(DataSize, 16);
BoneData = (CMeshBoneData*)DataBlock;
Skinned = (CSkinVert*)(BoneData + NumBones);
LastLodNum = -2;
CMeshBoneData *data;
for (i = 0, data = BoneData; i < NumBones; i++, data++)
{
const CSkelMeshBone &B = Mesh->RefSkeleton[i];
// NOTE: assumed, that parent bones goes first
assert(B.ParentIndex <= i);
// reset animation bone map (will be set by SetAnim())
data->BoneMap = INDEX_NONE;
// compute reference bone coords
CVec3 BP;
CQuat BO;
// get default pose
BP = B.Position;
BO = B.Orientation;
if (!i) BO.Conjugate();
CCoords &BC = data->RefCoords;
BC.origin = BP;
BO.ToAxis(BC.axis);
// move bone position to global coordinate space
if (i) // do not rotate root bone
BoneData[B.ParentIndex].RefCoords.UnTransformCoords(BC, BC);
// store inverted transformation too
InvertCoords(data->RefCoords, data->RefCoordsInv);
#if 0
//!!
if (i == 32 || i == 34)
{
appNotify("Bone %d (%8.3f %8.3f %8.3f) - (%8.3f %8.3f %8.3f %8.3f)", i, VECTOR_ARG(BP), QUAT_ARG(BO));
#define C data->RefCoords
appNotify("REF : o=%8.3f %8.3f %8.3f", VECTOR_ARG(C.origin ));
appNotify(" 0=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[0]));
appNotify(" 1=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[1]));
appNotify(" 2=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[2]));
#undef C
#define C data->RefCoordsInv
appNotify("REFIN : o=%8.3f %8.3f %8.3f", VECTOR_ARG(C.origin ));
appNotify(" 0=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[0]));
appNotify(" 1=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[1]));
appNotify(" 2=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[2]));
#undef C
}
#endif
// initialize skeleton configuration
data->Scale = 1.0f; // default bone scale
}
// check bones tree
if (NumBones)
{
//!! should be done in CSkeletalMesh
guard(VerifySkeleton);
int treeSizes[MAX_MESHBONES], depth[MAX_MESHBONES];
int numIndices = 0;
CheckBoneTree(Mesh->RefSkeleton, 0, treeSizes, depth, numIndices, MAX_MESHBONES);
assert(numIndices == NumBones);
for (i = 0; i < numIndices; i++)
BoneData[i].SubtreeSize = treeSizes[i]; // remember subtree size
unguard;
}
PlayAnim(NULL);
unguard;
}
void CSkelMeshInstance::SetAnim(const CAnimSet *Anim)
{
if (!pMesh) return; // mesh is not set yet
Animation = Anim;
int i;
CMeshBoneData *data;
for (i = 0, data = BoneData; i < pMesh->RefSkeleton.Num(); i++, data++)
{
const CSkelMeshBone &B = pMesh->RefSkeleton[i];
// find reference bone in animation track
data->BoneMap = INDEX_NONE; // in a case when bone has no corresponding animation track
if (Animation)
{
for (int j = 0; j < Animation->TrackBoneNames.Num(); j++)
if (!stricmp(B.Name, Animation->TrackBoneNames[j]))
{
data->BoneMap = j;
break;
}
}
}
ClearSkelAnims();
PlayAnim(NULL);
}
void CSkelMeshInstance::DumpBones()
{
#if 1
int treeSizes[MAX_MESHBONES], depth[MAX_MESHBONES];
int numIndices = 0;
CheckBoneTree(pMesh->RefSkeleton, 0, treeSizes, depth, numIndices, MAX_MESHBONES);
//?? dump tree; separate function (requires depth information)
for (int i = 0; i < numIndices; i++)
{
const CSkelMeshBone &B = pMesh->RefSkeleton[i];
int parent = B.ParentIndex;
appPrintf("bone#%3d (parent %3d); tree size: %3d ", i, parent, treeSizes[i]);
#if 1
for (int j = 0; j < depth[i]; j++)
{
#if 0
// simple picture
appPrintf("| ");
#else
// graph-like picture
bool found = false;
for (int n = i+1; n < numIndices; n++)
{
if (depth[n] > j+1) continue;
if (depth[n] == j+1) found = true;
break;
}
#if _WIN32
// pseudographics
if (j == depth[i]-1)
appPrintf(found ? "\xC3\xC4\xC4" : "\xC0\xC4\xC4"); // [+--] : [\--]
else
appPrintf(found ? "\xB3 " : " "); // [| ] : [ ]
#else
// ASCII
if (j == depth[i]-1)
appPrintf(found ? "+--" : "\\--");
else
appPrintf(found ? "| " : " ");
#endif
#endif
}
appPrintf("%s\n", *B.Name);
#else
appPrintf("%s {%g %g %g} {%g %g %g %g}\n", *B.Name, FVECTOR_ARG(B.BonePos.Position), FQUAT_ARG(B.BonePos.Orientation));
#endif
}
#endif
}
/*-----------------------------------------------------------------------------
Miscellaneous
-----------------------------------------------------------------------------*/
int CSkelMeshInstance::FindBone(const char *BoneName) const
{
for (int i = 0; i < pMesh->RefSkeleton.Num(); i++)
if (!strcmp(pMesh->RefSkeleton[i].Name, BoneName))
return i;
return INDEX_NONE;
}
const CAnimSequence *CSkelMeshInstance::FindAnim(const char *AnimName) const
{
if (!Animation || !AnimName)
return NULL;
for (int i = 0; i < Animation->Sequences.Num(); i++)
{
const CAnimSequence &Seq = Animation->Sequences[i];
if (!stricmp(Seq.Name, AnimName))
return &Seq;
}
return NULL;
}
void CSkelMeshInstance::SetBoneScale(const char *BoneName, float scale)
{
int BoneIndex = FindBone(BoneName);
if (BoneIndex == INDEX_NONE) return;
BoneData[BoneIndex].Scale = scale;
}
CVec3 CSkelMeshInstance::GetMeshOrigin() const
{
if (!BoneData)
return nullVec3;
// find first animated bone
int BoneIndex = pMesh->GetRootBone(); //?? cache this value
if (BoneIndex < 0)
BoneIndex = 0;
// appPrintf("Focus on bone %d (%s)\n", BoneIndex, *pMesh->RefSkeleton[BoneIndex].Name);
return BoneData[BoneIndex].Coords.origin;
}
/*-----------------------------------------------------------------------------
Skeletal animation itself
-----------------------------------------------------------------------------*/
#if SHOW_BONE_UPDATES
static int BoneUpdateCounts[MAX_MESHBONES];
#endif
void CSkelMeshInstance::UpdateSkeleton()
{
guard(CSkelMeshInstance::UpdateSkeleton);
// process all animation channels
assert(MaxAnimChannel < MAX_SKELANIMCHANNELS);
int Stage;
CAnimChan *Chn;
#if SHOW_BONE_UPDATES
memset(BoneUpdateCounts, 0, sizeof(BoneUpdateCounts));
#endif
for (Stage = 0, Chn = Channels; Stage <= MaxAnimChannel; Stage++, Chn++)
{
if (Stage > 0 && (Chn->Anim1 == NULL || Chn->BlendAlpha <= 0))
continue;
const CAnimSequence *AnimSeq1 = Chn->Anim1;
const CAnimSequence *AnimSeq2 = NULL;
float Time2;
if (AnimSeq1)
{
if (Chn->Anim2 && Chn->SecondaryBlend)
{
AnimSeq2 = Chn->Anim2;
// compute time for secondary channel; always in sync with primary channel
Time2 = Chn->Time / AnimSeq1->NumFrames * AnimSeq2->NumFrames;
}
}
// compute bone range, affected by specified animation bone
int firstBone = Chn->RootBone;
int lastBone = firstBone + BoneData[firstBone].SubtreeSize;
assert(lastBone < pMesh->RefSkeleton.Num());
int i;
CMeshBoneData *data;
for (i = firstBone, data = BoneData + firstBone; i <= lastBone; i++, data++)
{
if (Stage < data->FirstChannel)
{
// this bone position will be overrided in following channel(s); all
// subhierarchy bones should be overrided too; skip whole subtree
int skip = data->SubtreeSize;
// note: 'skip' equals to subtree size; current bone is excluded - it
// will be skipped by 'for' operator (after 'continue')
i += skip;
data += skip;
continue;
}
CVec3 BP;
CQuat BO;
const CSkelMeshBone &Bone = pMesh->RefSkeleton[i];
BP = Bone.Position; // default position - from bind pose
BO = Bone.Orientation; // ...
int BoneIndex = data->BoneMap;
// compute bone orientation
if (AnimSeq1 && BoneIndex != INDEX_NONE)
{
// get bone position from track
if (!AnimSeq2 || Chn->SecondaryBlend != 1.0f)
{
AnimSeq1->Tracks[BoneIndex].GetBonePosition(Chn->Time, AnimSeq1->NumFrames, Chn->Looped, BP, BO);
//const char *bname = *Bone.Name;
//CQuat BOO = BO;
//if (!strcmp(bname, "b_MF_UpperArm_L")) { BO.Set(-0.225, -0.387, -0.310, 0.839); }
#if SHOW_ANIM
//if (i == 6 || i == 8 || i == 10 || i == 11 || i == 29) //??
DrawTextLeft("%s%d Bone (%s) : P{ %8.3f %8.3f %8.3f } Q{ %6.3f %6.3f %6.3f %6.3f }",
AnimSeq1->Tracks[BoneIndex].HasKeys() ? S_GREEN : S_BLUE,
i, *Bone.Name, VECTOR_ARG(BP), QUAT_ARG(BO));
//if (!strcmp(bname, "b_MF_UpperArm_L")) DrawTextLeft("%g %g %g %g [%g %g]", BO.x-BOO.x,BO.y-BOO.y,BO.z-BOO.z,BO.w-BOO.w, BO.w, BOO.w);
#endif
//BO.Normalize();
#if SHOW_BONE_UPDATES
if (AnimSeq1->Tracks[BoneIndex].HasKeys())
BoneUpdateCounts[i]++;
#endif
}
// blend secondary animation
if (AnimSeq2)
{
CVec3 BP2;
CQuat BO2;
BP2 = Bone.Position; // default position - from bind pose
BO2 = Bone.Orientation; // ...
AnimSeq2->Tracks[BoneIndex].GetBonePosition(Time2, AnimSeq2->NumFrames, Chn->Looped, BP2, BO2);
if (Chn->SecondaryBlend == 1.0f)
{
BO = BO2;
BP = BP2;
}
else
{
Lerp (BP, BP2, Chn->SecondaryBlend, BP);
Slerp(BO, BO2, Chn->SecondaryBlend, BO);
}
#if SHOW_BONE_UPDATES
BoneUpdateCounts[i]++;
#endif
}
// process AnimRotationOnly
if (!Animation->ShouldAnimateTranslation(BoneIndex, (EAnimRotationOnly)RotationMode))
BP = Bone.Position;
}
else
{
// get default bone position
// BP = Bone.Position; -- already set above
// BO = Bone.Orientation;
#if SHOW_ANIM
DrawTextLeft(S_YELLOW"%d Bone (%s) : P{ %8.3f %8.3f %8.3f } Q{ %6.3f %6.3f %6.3f %6.3f }",
i, *Bone.Name, VECTOR_ARG(BP), QUAT_ARG(BO));
#endif
}
if (!i) BO.Conjugate();
// tweening
if (Chn->TweenTime > 0)
{
// interpolate orientation using AnimTweenStep
// current orientation -> {BP,BO}
Lerp (data->Pos, BP, Chn->TweenStep, BP);
Slerp(data->Quat, BO, Chn->TweenStep, BO);
}
// blending with previous channels
if (Chn->BlendAlpha < 1.0f)
{
Lerp (data->Pos, BP, Chn->BlendAlpha, BP);
Slerp(data->Quat, BO, Chn->BlendAlpha, BO);
}
data->Quat = BO;
data->Pos = BP;
}
}
// transform bones using skeleton hierarchy
int i;
CMeshBoneData *data;
for (i = 0, data = BoneData; i < pMesh->RefSkeleton.Num(); i++, data++)
{
CCoords &BC = data->Coords;
BC.origin = data->Pos;
data->Quat.ToAxis(BC.axis);
// move bone position to global coordinate space
if (!i)
{
// root bone - use BaseTransform
// can use inverted BaseTransformScaled to avoid 'slow' operation
BaseTransformScaled.TransformCoordsSlow(BC, BC);
}
else
{
// other bones - rotate around parent bone
BoneData[pMesh->RefSkeleton[i].ParentIndex].Coords.UnTransformCoords(BC, BC);
}
// deform skeleton according to external settings
if (data->Scale != 1.0f)
{
BC.axis[0].Scale(data->Scale);
BC.axis[1].Scale(data->Scale);
BC.axis[2].Scale(data->Scale);
}
// compute transformation of world-space model vertices from reference
// pose to desired pose
BC.UnTransformCoords(data->RefCoordsInv, data->Transform);
#if USE_SSE
data->Transform4.Set(data->Transform);
#endif
#if 0
//!!
if (i == 32 || i == 34)
{
#define C BC
DrawTextLeft("[%2d] : o=%8.3f %8.3f %8.3f", i, VECTOR_ARG(C.origin ));
DrawTextLeft(" 0=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[0]));
DrawTextLeft(" 1=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[1]));
DrawTextLeft(" 2=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[2]));
#undef C
#define C data->Transform
DrawTextLeft("TRN : o=%8.3f %8.3f %8.3f", VECTOR_ARG(C.origin ));
DrawTextLeft(" 0=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[0]));
DrawTextLeft(" 1=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[1]));
DrawTextLeft(" 2=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[2]));
#undef C
#define C data->RefCoordsInv
DrawTextLeft("REF : o=%8.3f %8.3f %8.3f", VECTOR_ARG(C.origin ));
DrawTextLeft(" 0=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[0]));
DrawTextLeft(" 1=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[1]));
DrawTextLeft(" 2=%8.3f %8.3f %8.3f", VECTOR_ARG(C.axis[2]));
#undef C
}
#endif
}
unguard;
}
void CSkelMeshInstance::UpdateAnimation(float TimeDelta)
{
if (!pMesh->RefSkeleton.Num()) return; // just in case
// prepare bone-to-channel map
//?? optimize: update when animation changed only
for (int i = 0; i < pMesh->RefSkeleton.Num(); i++)
BoneData[i].FirstChannel = 0;
assert(MaxAnimChannel < MAX_SKELANIMCHANNELS);
int Stage;
CAnimChan *Chn;
for (Stage = 0, Chn = Channels; Stage <= MaxAnimChannel; Stage++, Chn++)
{
if (Stage > 0 && Chn->Anim1 == NULL)
continue;
// update tweening
if (Chn->TweenTime)
{
Chn->TweenStep = TimeDelta / Chn->TweenTime;
Chn->TweenTime -= TimeDelta;
if (Chn->TweenTime < 0)
{
// stop tweening, start animation
TimeDelta = -Chn->TweenTime;
Chn->TweenTime = 0;
}
assert(Chn->Time == 0);
}
// note: TweenTime may be changed now, check again
if (!Chn->TweenTime && Chn->Anim1)
{
// update animation time
const CAnimSequence *Seq1 = Chn->Anim1;
const CAnimSequence *Seq2 = Chn->Anim2;
if (!Chn->SecondaryBlend) Seq2 = NULL;
float Rate1 = Chn->Rate * Seq1->Rate;
if (Seq2)
{
// if blending 2 channels, should adjust animation rate
Rate1 = Lerp(Seq1->Rate / Seq1->NumFrames, Seq2->Rate / Seq2->NumFrames, Chn->SecondaryBlend)
* Seq1->NumFrames;
}
Chn->Time += TimeDelta * Rate1;
if (Chn->Looped)
{
if (Chn->Time >= Seq1->NumFrames)
{
// wrap time
int numSkip = appFloor(Chn->Time / Seq1->NumFrames);
Chn->Time -= numSkip * Seq1->NumFrames;
}
}
else
{
if (Chn->Time >= Seq1->NumFrames-1)
{
// clamp time
Chn->Time = Seq1->NumFrames-1;
if (Chn->Time < 0)
Chn->Time = 0;
}
}
}
// assign bones to channel
if (Chn->BlendAlpha >= 1.0f && Stage > 0) // stage 0 already set
{
// whole subtree will be skipped in UpdateSkeleton(), so - mark root bone only
BoneData[Chn->RootBone].FirstChannel = Stage;
}
}
UpdateSkeleton();
}
/*-----------------------------------------------------------------------------
Animation setup
-----------------------------------------------------------------------------*/
void CSkelMeshInstance::PlayAnimInternal(const char *AnimName, float Rate, float TweenTime, int Channel, bool Looped)
{
guard(CSkelMeshInstance::PlayAnimInternal);
CAnimChan &Chn = GetStage(Channel);
if (Channel > MaxAnimChannel)
MaxAnimChannel = Channel;
const CAnimSequence *NewAnim = FindAnim(AnimName);
if (!NewAnim)
{
// show default pose
Chn.Anim1 = NULL;
Chn.Anim2 = NULL;
Chn.Time = 0;
Chn.Rate = 0;
Chn.Looped = false;
Chn.TweenTime = TweenTime;
Chn.SecondaryBlend = 0;
return;
}
Chn.Rate = Rate;
Chn.Looped = Looped;
if (NewAnim == Chn.Anim1 && Looped)
{
// animation not changed, just set some flags (above)
return;
}
Chn.Anim1 = NewAnim;
Chn.Anim2 = NULL;
Chn.Time = 0;
Chn.SecondaryBlend = 0;
Chn.TweenTime = TweenTime;
unguard;
}
void CSkelMeshInstance::SetBlendParams(int Channel, float BlendAlpha, const char *BoneName)
{
guard(CSkelMeshInstance::SetBlendParams);
CAnimChan &Chn = GetStage(Channel);
Chn.BlendAlpha = BlendAlpha;
if (Channel == 0)
Chn.BlendAlpha = 1; // force full animation for 1st stage
Chn.RootBone = 0;
if (BoneName)
{
Chn.RootBone = FindBone(BoneName);
if (Chn.RootBone == INDEX_NONE) // bone not found -- ignore animation
Chn.BlendAlpha = 0;
}
unguard;
}
void CSkelMeshInstance::SetSecondaryAnim(int Channel, const char *AnimName)
{
guard(CSkelMeshInstance::SetSecondaryAnim);
CAnimChan &Chn = GetStage(Channel);
Chn.Anim2 = FindAnim(AnimName);
Chn.SecondaryBlend = 0;
unguard;
}
void CSkelMeshInstance::FreezeAnimAt(float Time, int Channel)
{
guard(CSkelMeshInstance::FreezeAnimAt);
CAnimChan &Chn = GetStage(Channel);
Chn.Time = Time;
Chn.Rate = 0;
unguard;
}
void CSkelMeshInstance::GetAnimParams(int Channel, const char *&AnimName, float &Frame, float &NumFrames, float &Rate) const
{
guard(CSkelMeshInstance::GetAnimParams);
const CAnimChan &Chn = GetStage(Channel);
if (!Animation || !Chn.Anim1 || Channel > MaxAnimChannel)
{
AnimName = "None";
Frame = 0;
NumFrames = 0;
Rate = 0;
return;
}
const CAnimSequence *Seq = Chn.Anim1;
AnimName = Seq->Name;
Frame = Chn.Time;
NumFrames = Seq->NumFrames;
Rate = Seq->Rate * Chn.Rate;
unguard;
}
/*-----------------------------------------------------------------------------
Drawing
-----------------------------------------------------------------------------*/
static void GetBoneInfColor(int BoneIndex, float *Color)
{
// most of this code is targetted to make maximal color combinations
// which are maximally different for adjancent BoneIndex values
static const float table[] = { 0.9f, 0.3f, 0.6f, 0.0f };
static const int table2[] = { 0, 1, 2, 4, 7, 3, 5, 6 };
BoneIndex = (BoneIndex & 0xFFF8) | table2[BoneIndex & 7] ^ 7;
#if 0
// this version produces similar colors for adjacent indices - less contrast picture
Color[0] = table[BoneIndex & 3];
Color[1] = table[(BoneIndex >> 2) & 3];
Color[2] = table[(BoneIndex >> 4) & 3];
#else
// this version produces more color contrast between adjacent indices
#define C(x) ( (x) & 1 ) | ( ((x) >> 2) & 2 )
Color[0] = table[C(BoneIndex)];
Color[1] = table[C(BoneIndex >> 1)];
Color[2] = table[C(BoneIndex >> 2)];
#undef C
#endif
}
void CSkelMeshInstance::DrawSkeleton(bool ShowLabels, bool ColorizeBones)
{
guard(CSkelMeshInstance::DrawSkeleton);
glDisable(GL_LIGHTING);
BindDefaultMaterial(true);
glLineWidth(3);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBegin(GL_LINES);
for (int i = 0; i < pMesh->RefSkeleton.Num(); i++)
{
const CSkelMeshBone &B = pMesh->RefSkeleton[i];
const CCoords &BC = BoneData[i].Coords;
CVec3 v1;
float Color[4];
unsigned TextColor;
Color[3] = 0.5f;
if (i > 0)
{
// Color.Set(1,1,0.3);
#if SHOW_BONE_UPDATES
int t = BoneUpdateCounts[i];
Color[0] = t & 1;
Color[1] = (t >> 1) & 1;
Color[2] = (t >> 2) & 1;
#endif
v1 = BoneData[B.ParentIndex].Coords.origin;
}
else
{
Color[0] = 1; Color[1] = 0; Color[2] = 1;
v1.Zero();
}
TextColor = RGBA(1,1,0,0.7);
if (ColorizeBones)
{
GetBoneInfColor(i, Color);
TextColor = RGBAS(Color[0], Color[1], Color[2], 0.7);
}
glColor4fv(Color);
glVertex3fv(v1.v);
glVertex3fv(BC.origin.v);
if (ShowLabels)
{
// show bone label
v1.Add(BC.origin);
v1.Scale(0.5f);
DrawText3D(v1, TextColor, "(%d)%s", i, *B.Name);
}
}
glColor3f(1,1,1);
glEnd();
glLineWidth(1);
glDisable(GL_BLEND);
glDisable(GL_LINE_SMOOTH);
glEnable(GL_DEPTH_TEST);
unguard;
}
void CSkelMeshInstance::DrawAttachments()
{
guard(CSkelMeshInstance::DrawAttachments);
if (!pMesh->Sockets.Num()) return;
BindDefaultMaterial(true);
glBegin(GL_LINES);
for (int i = 0; i < pMesh->Sockets.Num(); i++)
{
const CSkelMeshSocket &S = pMesh->Sockets[i];
const char *BoneName = S.Bone;
int BoneIndex = FindBone(BoneName);
if (BoneIndex == INDEX_NONE) continue; // should not happen
CCoords AC;
BoneData[BoneIndex].Coords.UnTransformCoords(S.Transform, AC);
for (int j = 0; j < 3; j++)
{
float color[3];
CVec3 point0, point1;
color[0] = color[1] = color[2] = 0.1f; color[j] = 1.0f;
point0.Set(0, 0, 0); point0[j] = 10;
AC.UnTransformPoint(point0, point1);
glColor3fv(color);
glVertex3fv(AC.origin.v);
glVertex3fv(point1.v);
}
// show attachment label
CVec3 labelOrigin;
static const CVec3 origin0 = { 4, 4, 4 };
AC.UnTransformPoint(origin0, labelOrigin);
DrawText3D(labelOrigin, RGB(0,1,0), "%s\n(%s)", *S.Name, BoneName);
}
glColor3f(1,1,1);
glEnd();
unguard;
}
// Software skinning
void CSkelMeshInstance::TransformMesh()
{
guard(CSkelMeshInstance::TransformMesh);
const CSkelMeshLod& Mesh = pMesh->Lods[LodNum];
int NumVerts = Mesh.NumVerts;
memset(Skinned, 0, sizeof(CSkinVert) * NumVerts);
for (int i = 0; i < NumVerts; i++)
{
const CSkelMeshVertex &V = Mesh.Verts[i];
CSkinVert &D = Skinned[i];
// compute weighted transform from all influenced bones
// take a 1st influence
#if !USE_SSE
CCoords transform;
transform = BoneData[V.Bone[0]].Transform;
transform.Scale(V.Weight[0]);
#else
const CCoords4 &transform = BoneData[V.Bone[0]].Transform4;
__m128 x1, x2, x3, x4, x5, x6, x7, x8;
x1 = transform.mm[0]; // bone transform
x2 = transform.mm[1];
x3 = transform.mm[2];
x4 = transform.mm[3];
x5 = _mm_load1_ps(&V.Weight[0]); // Weight
x1 = _mm_mul_ps(x1, x5); // Transform * Weight
x2 = _mm_mul_ps(x2, x5);
x3 = _mm_mul_ps(x3, x5);
x4 = _mm_mul_ps(x4, x5);
#endif // USE_SSE
// add remaining influences
for (int j = 1; j < NUM_INFLUENCES; j++)
{
int iBone = V.Bone[j];
if (iBone < 0) break;
assert(iBone < pMesh->RefSkeleton.Num()); // validate bone index
const CMeshBoneData &data = BoneData[iBone];
#if !USE_SSE
CoordsMA(transform, V.Weight[j], data.Transform);
#else
x5 = _mm_load1_ps(&V.Weight[j]); // Weight
// x1..x4 += data.Transform * Weight
x6 = _mm_mul_ps(data.Transform4.mm[0], x5);
x1 = _mm_add_ps(x1, x6);
x6 = _mm_mul_ps(data.Transform4.mm[1], x5);
x2 = _mm_add_ps(x2, x6);
x6 = _mm_mul_ps(data.Transform4.mm[2], x5);
x3 = _mm_add_ps(x3, x6);
x6 = _mm_mul_ps(data.Transform4.mm[3], x5);
x4 = _mm_add_ps(x4, x6);