forked from sears2424/Source-PlusPlus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc_baseflex.cpp
2098 lines (1744 loc) · 60.6 KB
/
c_baseflex.cpp
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
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//===========================================================================//
#include "cbase.h"
#include "filesystem.h"
#include "sentence.h"
#include "hud_closecaption.h"
#include "engine/ivmodelinfo.h"
#include "engine/ivdebugoverlay.h"
#include "bone_setup.h"
#include "soundinfo.h"
#include "tools/bonelist.h"
#include "KeyValues.h"
#include "tier0/vprof.h"
#include "toolframework/itoolframework.h"
#include "choreoevent.h"
#include "choreoscene.h"
#include "choreoactor.h"
#include "toolframework_client.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
bool UseHWMorphVCDs();
ConVar g_CV_PhonemeDelay("phonemedelay", "0", 0, "Phoneme delay to account for sound system latency." );
ConVar g_CV_PhonemeFilter("phonemefilter", "0.08", 0, "Time duration of box filter to pass over phonemes." );
ConVar g_CV_FlexRules("flex_rules", "1", 0, "Allow flex animation rules to run." );
ConVar g_CV_BlinkDuration("blink_duration", "0.2", 0, "How many seconds an eye blink will last." );
ConVar g_CV_FlexSmooth("flex_smooth", "1", 0, "Applies smoothing/decay curve to flex animation controller changes." );
#if defined( CBaseFlex )
#undef CBaseFlex
#endif
IMPLEMENT_CLIENTCLASS_DT(C_BaseFlex, DT_BaseFlex, CBaseFlex)
RecvPropArray3( RECVINFO_ARRAY(m_flexWeight), RecvPropFloat(RECVINFO(m_flexWeight[0]))),
RecvPropInt(RECVINFO(m_blinktoggle)),
RecvPropVector(RECVINFO(m_viewtarget)),
#ifdef HL2_CLIENT_DLL
RecvPropFloat( RECVINFO(m_vecViewOffset[0]) ),
RecvPropFloat( RECVINFO(m_vecViewOffset[1]) ),
RecvPropFloat( RECVINFO(m_vecViewOffset[2]) ),
RecvPropVector(RECVINFO(m_vecLean)),
RecvPropVector(RECVINFO(m_vecShift)),
#endif
END_RECV_TABLE()
BEGIN_PREDICTION_DATA( C_BaseFlex )
/*
// DEFINE_FIELD( C_BaseFlex, m_viewtarget, FIELD_VECTOR ),
// DEFINE_ARRAY( C_BaseFlex, m_flexWeight, FIELD_FLOAT, 64 ),
// DEFINE_FIELD( C_BaseFlex, m_blinktoggle, FIELD_INTEGER ),
// DEFINE_FIELD( C_BaseFlex, m_blinktime, FIELD_FLOAT ),
// DEFINE_FIELD( C_BaseFlex, m_prevviewtarget, FIELD_VECTOR ),
// DEFINE_ARRAY( C_BaseFlex, m_prevflexWeight, FIELD_FLOAT, 64 ),
// DEFINE_FIELD( C_BaseFlex, m_prevblinktoggle, FIELD_INTEGER ),
// DEFINE_FIELD( C_BaseFlex, m_iBlink, FIELD_INTEGER ),
// DEFINE_FIELD( C_BaseFlex, m_iEyeUpdown, FIELD_INTEGER ),
// DEFINE_FIELD( C_BaseFlex, m_iEyeRightleft, FIELD_INTEGER ),
// DEFINE_FIELD( C_BaseFlex, m_FileList, CUtlVector < CFlexSceneFile * > ),
*/
END_PREDICTION_DATA()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool GetHWMExpressionFileName( const char *pFilename, char *pHWMFilename )
{
// Are we even using hardware morph?
if ( !UseHWMorphVCDs() )
return false;
// Do we have a valid filename?
if ( !( pFilename && pFilename[0] ) )
return false;
// Check to see if we already have an player/hwm/* filename.
if ( ( V_strstr( pFilename, "player/hwm" ) != NULL ) || ( V_strstr( pFilename, "player\\hwm" ) != NULL ) )
{
V_strcpy( pHWMFilename, pFilename );
return true;
}
// Find the hardware morph scene name and pass that along as well.
char szExpression[MAX_PATH];
V_strcpy( szExpression, pFilename );
char szExpressionHWM[MAX_PATH];
szExpressionHWM[0] = '\0';
char *pszToken = strtok( szExpression, "/\\" );
while ( pszToken != NULL )
{
V_strcat( szExpressionHWM, pszToken, sizeof( szExpressionHWM ) );
if ( !V_stricmp( pszToken, "player" ) )
{
V_strcat( szExpressionHWM, "\\hwm", sizeof( szExpressionHWM ) );
}
pszToken = strtok( NULL, "/\\" );
if ( pszToken != NULL )
{
V_strcat( szExpressionHWM, "\\", sizeof( szExpressionHWM ) );
}
}
V_strcpy( pHWMFilename, szExpressionHWM );
return true;
}
C_BaseFlex::C_BaseFlex() :
m_iv_viewtarget( "C_BaseFlex::m_iv_viewtarget" ),
m_iv_flexWeight("C_BaseFlex:m_iv_flexWeight" ),
#ifdef HL2_CLIENT_DLL
m_iv_vecLean("C_BaseFlex:m_iv_vecLean" ),
m_iv_vecShift("C_BaseFlex:m_iv_vecShift" ),
#endif
m_LocalToGlobal( 0, 0, FlexSettingLessFunc )
{
#ifdef _DEBUG
((Vector&)m_viewtarget).Init();
#endif
AddVar( &m_viewtarget, &m_iv_viewtarget, LATCH_ANIMATION_VAR | INTERPOLATE_LINEAR_ONLY );
AddVar( m_flexWeight, &m_iv_flexWeight, LATCH_ANIMATION_VAR );
// Fill in phoneme class lookup
SetupMappings( "phonemes" );
m_flFlexDelayedWeight = NULL;
m_cFlexDelayedWeight = 0;
/// Make sure size is correct
Assert( PHONEME_CLASS_STRONG + 1 == NUM_PHONEME_CLASSES );
#ifdef HL2_CLIENT_DLL
// Get general lean vector
AddVar( &m_vecLean, &m_iv_vecLean, LATCH_ANIMATION_VAR );
AddVar( &m_vecShift, &m_iv_vecShift, LATCH_ANIMATION_VAR );
#endif
}
C_BaseFlex::~C_BaseFlex()
{
delete[] m_flFlexDelayedWeight;
m_SceneEvents.RemoveAll();
m_LocalToGlobal.RemoveAll();
}
void C_BaseFlex::Spawn()
{
BaseClass::Spawn();
InitPhonemeMappings();
}
// TF Player overrides all of these with class specific files
void C_BaseFlex::InitPhonemeMappings()
{
SetupMappings( "phonemes" );
}
void C_BaseFlex::SetupMappings( char const *pchFileRoot )
{
// Fill in phoneme class lookup
memset( m_PhonemeClasses, 0, sizeof( m_PhonemeClasses ) );
Emphasized_Phoneme *normal = &m_PhonemeClasses[ PHONEME_CLASS_NORMAL ];
Q_snprintf( normal->classname, sizeof( normal->classname ), "%s", pchFileRoot );
normal->required = true;
Emphasized_Phoneme *weak = &m_PhonemeClasses[ PHONEME_CLASS_WEAK ];
Q_snprintf( weak->classname, sizeof( weak->classname ), "%s_weak", pchFileRoot );
Emphasized_Phoneme *strong = &m_PhonemeClasses[ PHONEME_CLASS_STRONG ];
Q_snprintf( strong->classname, sizeof( strong->classname ), "%s_strong", pchFileRoot );
}
//-----------------------------------------------------------------------------
// Purpose: initialize fast lookups when model changes
//-----------------------------------------------------------------------------
CStudioHdr *C_BaseFlex::OnNewModel()
{
CStudioHdr *hdr = BaseClass::OnNewModel();
// init to invalid setting
m_iBlink = -1;
m_iEyeUpdown = LocalFlexController_t(-1);
m_iEyeRightleft = LocalFlexController_t(-1);
m_bSearchedForEyeFlexes = false;
m_iMouthAttachment = 0;
delete[] m_flFlexDelayedWeight;
m_flFlexDelayedWeight = NULL;
m_cFlexDelayedWeight = 0;
if (hdr)
{
if (hdr->numflexdesc())
{
m_cFlexDelayedWeight = hdr->numflexdesc();
m_flFlexDelayedWeight = new float[ m_cFlexDelayedWeight ];
memset( m_flFlexDelayedWeight, 0, sizeof( float ) * m_cFlexDelayedWeight );
}
m_iv_flexWeight.SetMaxCount( hdr->numflexcontrollers() );
m_iMouthAttachment = LookupAttachment( "mouth" );
LinkToGlobalFlexControllers( hdr );
}
return hdr;
}
void C_BaseFlex::StandardBlendingRules( CStudioHdr *hdr, Vector pos[], Quaternion q[], float currentTime, int boneMask )
{
BaseClass::StandardBlendingRules( hdr, pos, q, currentTime, boneMask );
#ifdef HL2_CLIENT_DLL
// shift pelvis, rotate body
if (hdr->GetNumIKChains() != 0 && (m_vecShift.x != 0.0 || m_vecShift.y != 0.0))
{
//CIKContext auto_ik;
//auto_ik.Init( hdr, GetRenderAngles(), GetRenderOrigin(), currentTime, gpGlobals->framecount, boneMask );
//auto_ik.AddAllLocks( pos, q );
matrix3x4_t rootxform;
AngleMatrix( GetRenderAngles(), GetRenderOrigin(), rootxform );
Vector localShift;
VectorIRotate( m_vecShift, rootxform, localShift );
Vector localLean;
VectorIRotate( m_vecLean, rootxform, localLean );
Vector p0 = pos[0];
float length = VectorNormalize( p0 );
// shift the root bone, but keep the height off the origin the same
Vector shiftPos = pos[0] + localShift;
VectorNormalize( shiftPos );
Vector leanPos = pos[0] + localLean;
VectorNormalize( leanPos );
pos[0] = shiftPos * length;
// rotate the root bone based on how much it was "leaned"
Vector p1;
CrossProduct( p0, leanPos, p1 );
float sinAngle = VectorNormalize( p1 );
float cosAngle = DotProduct( p0, leanPos );
float angle = atan2( sinAngle, cosAngle ) * 180 / M_PI;
Quaternion q1;
angle = clamp( angle, -45, 45 );
AxisAngleQuaternion( p1, angle, q1 );
QuaternionMult( q1, q[0], q[0] );
QuaternionNormalize( q[0] );
// DevMsgRT( " (%.2f) %.2f %.2f %.2f\n", angle, p1.x, p1.y, p1.z );
// auto_ik.SolveAllLocks( pos, q );
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose: place "voice" sounds on mouth
//-----------------------------------------------------------------------------
bool C_BaseFlex::GetSoundSpatialization( SpatializationInfo_t& info )
{
bool bret = BaseClass::GetSoundSpatialization( info );
// Default things it's audible, put it at a better spot?
if ( bret )
{
if ((info.info.nChannel == CHAN_VOICE || info.info.nChannel == CHAN_VOICE2) && m_iMouthAttachment > 0)
{
Vector origin;
QAngle angles;
C_BaseAnimating::AutoAllowBoneAccess boneaccess( true, false );
if (GetAttachment( m_iMouthAttachment, origin, angles ))
{
if (info.pOrigin)
{
*info.pOrigin = origin;
}
if (info.pAngles)
{
*info.pAngles = angles;
}
}
}
}
return bret;
}
//-----------------------------------------------------------------------------
// Purpose: run the interpreted FAC's expressions, converting global flex_controller
// values into FAC weights
//-----------------------------------------------------------------------------
void C_BaseFlex::RunFlexRules( CStudioHdr *hdr, float *dest )
{
if ( !g_CV_FlexRules.GetInt() )
return;
if ( !hdr )
return;
/*
// 0 means run them all
int nFlexRulesToRun = 0;
const char *pszExpression = flex_expression.GetString();
if ( pszExpression )
{
nFlexRulesToRun = atoi(pszExpression); // 0 will be returned if not a numeric string
}
//*/
hdr->RunFlexRules( g_flexweight, dest );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CFlexSceneFileManager::Init()
{
// Trakcer 16692: Preload these at startup to avoid hitch first time we try to load them during actual gameplay
FindSceneFile( NULL, "phonemes", true );
FindSceneFile( NULL, "phonemes_weak", true );
FindSceneFile(NULL, "phonemes_strong", true );
#if defined( HL2_CLIENT_DLL )
FindSceneFile( NULL, "random", true );
FindSceneFile( NULL, "randomAlert", true );
#endif
#if defined( TF_CLIENT_DLL )
// HACK TO ALL TF TO HAVE PER CLASS OVERRIDES
char const *pTFClasses[] =
{
"scout",
"sniper",
"soldier",
"demo",
"medic",
"heavy",
"pyro",
"spy",
"engineer",
};
char fn[ MAX_PATH ];
for ( int i = 0; i < ARRAYSIZE( pTFClasses ); ++i )
{
Q_snprintf( fn, sizeof( fn ), "player/%s/phonemes/phonemes", pTFClasses[i] );
FindSceneFile( NULL, fn, true );
Q_snprintf( fn, sizeof( fn ), "player/%s/phonemes/phonemes_weak", pTFClasses[i] );
FindSceneFile( NULL, fn, true );
Q_snprintf( fn, sizeof( fn ), "player/%s/phonemes/phonemes_strong", pTFClasses[i] );
FindSceneFile( NULL, fn, true );
if ( !IsX360() )
{
Q_snprintf( fn, sizeof( fn ), "player/hwm/%s/phonemes/phonemes", pTFClasses[i] );
FindSceneFile( NULL, fn, true );
Q_snprintf( fn, sizeof( fn ), "player/hwm/%s/phonemes/phonemes_weak", pTFClasses[i] );
FindSceneFile( NULL, fn, true );
Q_snprintf( fn, sizeof( fn ), "player/hwm/%s/phonemes/phonemes_strong", pTFClasses[i] );
FindSceneFile( NULL, fn, true );
}
Q_snprintf( fn, sizeof( fn ), "player/%s/emotion/emotion", pTFClasses[i] );
FindSceneFile( NULL, fn, true );
if ( !IsX360() )
{
Q_snprintf( fn, sizeof( fn ), "player/hwm/%s/emotion/emotion", pTFClasses[i] );
FindSceneFile( NULL, fn, true );
}
}
#endif
return true;
}
//-----------------------------------------------------------------------------
// Tracker 14992: We used to load 18K of .vfes for every C_BaseFlex who lipsynced, but now we only load those files once globally.
// Note, we could wipe these between levels, but they don't ever load more than the weak/normal/strong phoneme classes that I can tell
// so I'll just leave them loaded forever for now
//-----------------------------------------------------------------------------
void CFlexSceneFileManager::Shutdown()
{
DeleteSceneFiles();
}
//-----------------------------------------------------------------------------
// Purpose: Sets up translations
// Input : *instance -
// *pSettinghdr -
// Output : void
//-----------------------------------------------------------------------------
void CFlexSceneFileManager::EnsureTranslations( IHasLocalToGlobalFlexSettings *instance, const flexsettinghdr_t *pSettinghdr )
{
// The only time instance is NULL is in Init() above, where we're just loading the .vfe files off of the hard disk.
if ( instance )
{
instance->EnsureTranslations( pSettinghdr );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void *CFlexSceneFileManager::FindSceneFile( IHasLocalToGlobalFlexSettings *instance, const char *filename, bool allowBlockingIO )
{
char szFilename[MAX_PATH];
Assert( V_strlen( filename ) < MAX_PATH );
V_strcpy( szFilename, filename );
#if defined( TF_CLIENT_DLL )
char szHWMFilename[MAX_PATH];
if ( GetHWMExpressionFileName( szFilename, szHWMFilename ) )
{
V_strcpy( szFilename, szHWMFilename );
}
#endif
Q_FixSlashes( szFilename );
// See if it's already loaded
int i;
for ( i = 0; i < m_FileList.Count(); i++ )
{
CFlexSceneFile *file = m_FileList[ i ];
if ( file && !Q_stricmp( file->filename, szFilename ) )
{
// Make sure translations (local to global flex controller) are set up for this instance
EnsureTranslations( instance, ( const flexsettinghdr_t * )file->buffer );
return file->buffer;
}
}
if ( !allowBlockingIO )
{
return NULL;
}
// Load file into memory
void *buffer = NULL;
int len = filesystem->ReadFileEx( VarArgs( "expressions/%s.vfe", szFilename ), "GAME", &buffer );
if ( !len )
return NULL;
// Create scene entry
CFlexSceneFile *pfile = new CFlexSceneFile;
// Remember filename
Q_strncpy( pfile->filename, szFilename, sizeof( pfile->filename ) );
// Remember data pointer
pfile->buffer = buffer;
// Add to list
m_FileList.AddToTail( pfile );
// Swap the entire file
if ( IsX360() )
{
CByteswap swap;
swap.ActivateByteSwapping( true );
byte *pData = (byte*)buffer;
flexsettinghdr_t *pHdr = (flexsettinghdr_t*)pData;
swap.SwapFieldsToTargetEndian( pHdr );
// Flex Settings
flexsetting_t *pFlexSetting = (flexsetting_t*)((byte*)pHdr + pHdr->flexsettingindex);
for ( int i = 0; i < pHdr->numflexsettings; ++i, ++pFlexSetting )
{
swap.SwapFieldsToTargetEndian( pFlexSetting );
flexweight_t *pWeight = (flexweight_t*)(((byte*)pFlexSetting) + pFlexSetting->settingindex );
for ( int j = 0; j < pFlexSetting->numsettings; ++j, ++pWeight )
{
swap.SwapFieldsToTargetEndian( pWeight );
}
}
// indexes
pData = (byte*)pHdr + pHdr->indexindex;
swap.SwapBufferToTargetEndian( (int*)pData, (int*)pData, pHdr->numindexes );
// keymappings
pData = (byte*)pHdr + pHdr->keymappingindex;
swap.SwapBufferToTargetEndian( (int*)pData, (int*)pData, pHdr->numkeys );
// keyname indices
pData = (byte*)pHdr + pHdr->keynameindex;
swap.SwapBufferToTargetEndian( (int*)pData, (int*)pData, pHdr->numkeys );
}
// Fill in translation table
EnsureTranslations( instance, ( const flexsettinghdr_t * )pfile->buffer );
// Return data
return pfile->buffer;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CFlexSceneFileManager::DeleteSceneFiles()
{
while ( m_FileList.Count() > 0 )
{
CFlexSceneFile *file = m_FileList[ 0 ];
m_FileList.Remove( 0 );
free( file->buffer );
delete file;
}
}
CFlexSceneFileManager g_FlexSceneFileManager;
//-----------------------------------------------------------------------------
// Purpose:
// Input : *filename -
//-----------------------------------------------------------------------------
void *C_BaseFlex::FindSceneFile( const char *filename )
{
return g_FlexSceneFileManager.FindSceneFile( this, filename, false );
}
//-----------------------------------------------------------------------------
// Purpose: make sure the eyes are within 30 degrees of forward
//-----------------------------------------------------------------------------
Vector C_BaseFlex::SetViewTarget( CStudioHdr *pStudioHdr )
{
if ( !pStudioHdr )
return Vector( 0, 0, 0);
// aim the eyes
Vector tmp = m_viewtarget;
if ( !m_bSearchedForEyeFlexes )
{
m_bSearchedForEyeFlexes = true;
m_iEyeUpdown = FindFlexController( "eyes_updown" );
m_iEyeRightleft = FindFlexController( "eyes_rightleft" );
if ( m_iEyeUpdown != LocalFlexController_t(-1) )
{
pStudioHdr->pFlexcontroller( m_iEyeUpdown )->localToGlobal = AddGlobalFlexController( "eyes_updown" );
}
if ( m_iEyeRightleft != LocalFlexController_t(-1) )
{
pStudioHdr->pFlexcontroller( m_iEyeRightleft )->localToGlobal = AddGlobalFlexController( "eyes_rightleft" );
}
}
if (m_iEyeAttachment > 0)
{
matrix3x4_t attToWorld;
if (!GetAttachment( m_iEyeAttachment, attToWorld ))
{
return Vector( 0, 0, 0);
}
Vector local;
VectorITransform( tmp, attToWorld, local );
// FIXME: clamp distance to something based on eyeball distance
if (local.x < 6)
{
local.x = 6;
}
float flDist = local.Length();
VectorNormalize( local );
// calculate animated eye deflection
Vector eyeDeflect;
QAngle eyeAng( 0, 0, 0 );
if ( m_iEyeUpdown != LocalFlexController_t(-1) )
{
mstudioflexcontroller_t *pflex = pStudioHdr->pFlexcontroller( m_iEyeUpdown );
eyeAng.x = g_flexweight[ pflex->localToGlobal ];
}
if ( m_iEyeRightleft != LocalFlexController_t(-1) )
{
mstudioflexcontroller_t *pflex = pStudioHdr->pFlexcontroller( m_iEyeRightleft );
eyeAng.y = g_flexweight[ pflex->localToGlobal ];
}
// debugoverlay->AddTextOverlay( GetAbsOrigin() + Vector( 0, 0, 64 ), 0, 0, "%5.3f %5.3f", eyeAng.x, eyeAng.y );
AngleVectors( eyeAng, &eyeDeflect );
eyeDeflect.x = 0;
// reduce deflection the more the eye is off center
// FIXME: this angles make no damn sense
eyeDeflect = eyeDeflect * (local.x * local.x);
local = local + eyeDeflect;
VectorNormalize( local );
// check to see if the eye is aiming outside the max eye deflection
float flMaxEyeDeflection = pStudioHdr->MaxEyeDeflection();
if ( local.x < flMaxEyeDeflection )
{
// if so, clamp it to 30 degrees offset
// debugoverlay->AddTextOverlay( GetAbsOrigin() + Vector( 0, 0, 64 ), 1, 0, "%5.3f %5.3f %5.3f", local.x, local.y, local.z );
local.x = 0;
float d = local.LengthSqr();
if ( d > 0.0f )
{
d = sqrtf( ( 1.0f - flMaxEyeDeflection * flMaxEyeDeflection ) / ( local.y*local.y + local.z*local.z ) );
local.x = flMaxEyeDeflection;
local.y = local.y * d;
local.z = local.z * d;
}
else
{
local.x = 1.0;
}
}
local = local * flDist;
VectorTransform( local, attToWorld, tmp );
}
modelrender->SetViewTarget( GetModelPtr(), GetBody(), tmp );
/*
debugoverlay->AddTextOverlay( GetAbsOrigin() + Vector( 0, 0, 64 ), 0, 0, "%.2f %.2f %.2f : %.2f %.2f %.2f",
m_viewtarget.x, m_viewtarget.y, m_viewtarget.z,
m_prevviewtarget.x, m_prevviewtarget.y, m_prevviewtarget.z );
*/
return tmp;
}
#define STRONG_CROSSFADE_START 0.60f
#define WEAK_CROSSFADE_START 0.40f
//-----------------------------------------------------------------------------
// Purpose:
// Here's the formula
// 0.5 is neutral 100 % of the default setting
// Crossfade starts at STRONG_CROSSFADE_START and is full at STRONG_CROSSFADE_END
// If there isn't a strong then the intensity of the underlying phoneme is fixed at 2 x STRONG_CROSSFADE_START
// so we don't get huge numbers
// Input : *classes -
// emphasis_intensity -
//-----------------------------------------------------------------------------
void C_BaseFlex::ComputeBlendedSetting( Emphasized_Phoneme *classes, float emphasis_intensity )
{
// See which blends are available for the current phoneme
bool has_weak = classes[ PHONEME_CLASS_WEAK ].valid;
bool has_strong = classes[ PHONEME_CLASS_STRONG ].valid;
// Better have phonemes in general
Assert( classes[ PHONEME_CLASS_NORMAL ].valid );
if ( emphasis_intensity > STRONG_CROSSFADE_START )
{
if ( has_strong )
{
// Blend in some of strong
float dist_remaining = 1.0f - emphasis_intensity;
float frac = dist_remaining / ( 1.0f - STRONG_CROSSFADE_START );
classes[ PHONEME_CLASS_NORMAL ].amount = (frac) * 2.0f * STRONG_CROSSFADE_START;
classes[ PHONEME_CLASS_STRONG ].amount = 1.0f - frac;
}
else
{
emphasis_intensity = MIN( emphasis_intensity, STRONG_CROSSFADE_START );
classes[ PHONEME_CLASS_NORMAL ].amount = 2.0f * emphasis_intensity;
}
}
else if ( emphasis_intensity < WEAK_CROSSFADE_START )
{
if ( has_weak )
{
// Blend in some weak
float dist_remaining = WEAK_CROSSFADE_START - emphasis_intensity;
float frac = dist_remaining / ( WEAK_CROSSFADE_START );
classes[ PHONEME_CLASS_NORMAL ].amount = (1.0f - frac) * 2.0f * WEAK_CROSSFADE_START;
classes[ PHONEME_CLASS_WEAK ].amount = frac;
}
else
{
emphasis_intensity = MAX( emphasis_intensity, WEAK_CROSSFADE_START );
classes[ PHONEME_CLASS_NORMAL ].amount = 2.0f * emphasis_intensity;
}
}
else
{
// Assume 0.5 (neutral) becomes a scaling of 1.0f
classes[ PHONEME_CLASS_NORMAL ].amount = 2.0f * emphasis_intensity;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *classes -
// phoneme -
// scale -
// newexpression -
//-----------------------------------------------------------------------------
void C_BaseFlex::AddViseme( Emphasized_Phoneme *classes, float emphasis_intensity, int phoneme, float scale, bool newexpression )
{
int type;
// Setup weights for any emphasis blends
bool skip = SetupEmphasisBlend( classes, phoneme );
// Uh-oh, missing or unknown phoneme???
if ( skip )
{
return;
}
// Compute blend weights
ComputeBlendedSetting( classes, emphasis_intensity );
for ( type = 0; type < NUM_PHONEME_CLASSES; type++ )
{
Emphasized_Phoneme *info = &classes[ type ];
if ( !info->valid || info->amount == 0.0f )
continue;
const flexsettinghdr_t *actual_flexsetting_header = info->base;
const flexsetting_t *pSetting = actual_flexsetting_header->pIndexedSetting( phoneme );
if (!pSetting)
{
continue;
}
flexweight_t *pWeights = NULL;
int truecount = pSetting->psetting( (byte *)actual_flexsetting_header, 0, &pWeights );
if ( pWeights )
{
for ( int i = 0; i < truecount; i++)
{
// Translate to global controller number
int j = FlexControllerLocalToGlobal( actual_flexsetting_header, pWeights->key );
// Add scaled weighting in
g_flexweight[j] += info->amount * scale * pWeights->weight;
// Go to next setting
pWeights++;
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose: A lot of the one time setup and also resets amount to 0.0f default
// for strong/weak/normal tracks
// Returning true == skip this phoneme
// Input : *classes -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool C_BaseFlex::SetupEmphasisBlend( Emphasized_Phoneme *classes, int phoneme )
{
int i;
bool skip = false;
for ( i = 0; i < NUM_PHONEME_CLASSES; i++ )
{
Emphasized_Phoneme *info = &classes[ i ];
// Assume it's bogus
info->valid = false;
info->amount = 0.0f;
// One time setup
if ( !info->basechecked )
{
info->basechecked = true;
info->base = (flexsettinghdr_t *)FindSceneFile( info->classname );
}
info->exp = NULL;
if ( info->base )
{
Assert( info->base->id == ('V' << 16) + ('F' << 8) + ('E') );
info->exp = info->base->pIndexedSetting( phoneme );
}
if ( info->required && ( !info->base || !info->exp ) )
{
skip = true;
break;
}
if ( info->exp )
{
info->valid = true;
}
}
return skip;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *classes -
// *sentence -
// t -
// dt -
// juststarted -
//-----------------------------------------------------------------------------
ConVar g_CV_PhonemeSnap("phonemesnap", "2", 0, "Lod at level at which visemes stops always considering two phonemes, regardless of duration." );
void C_BaseFlex::AddVisemesForSentence( Emphasized_Phoneme *classes, float emphasis_intensity, CSentence *sentence, float t, float dt, bool juststarted )
{
CStudioHdr *hdr = GetModelPtr();
if ( !hdr )
{
return;
}
int pcount = sentence->GetRuntimePhonemeCount();
for ( int k = 0; k < pcount; k++ )
{
const CBasePhonemeTag *phoneme = sentence->GetRuntimePhoneme( k );
if (t > phoneme->GetStartTime() && t < phoneme->GetEndTime())
{
bool bCrossfade = true;
if ((hdr->flags() & STUDIOHDR_FLAGS_FORCE_PHONEME_CROSSFADE) == 0)
{
if (m_iAccumulatedBoneMask & BONE_USED_BY_VERTEX_LOD0)
{
bCrossfade = (g_CV_PhonemeSnap.GetInt() > 0);
}
else if (m_iAccumulatedBoneMask & BONE_USED_BY_VERTEX_LOD1)
{
bCrossfade = (g_CV_PhonemeSnap.GetInt() > 1);
}
else if (m_iAccumulatedBoneMask & BONE_USED_BY_VERTEX_LOD2)
{
bCrossfade = (g_CV_PhonemeSnap.GetInt() > 2);
}
else if (m_iAccumulatedBoneMask & BONE_USED_BY_VERTEX_LOD3)
{
bCrossfade = (g_CV_PhonemeSnap.GetInt() > 3);
}
else
{
bCrossfade = false;
}
}
if (bCrossfade)
{
if (k < pcount-1)
{
const CBasePhonemeTag *next = sentence->GetRuntimePhoneme( k + 1 );
// if I have a neighbor
if ( next )
{
// and they're touching
if (next->GetStartTime() == phoneme->GetEndTime() )
{
// no gap, so increase the blend length to the end of the next phoneme, as long as it's not longer than the current phoneme
dt = MAX( dt, MIN( next->GetEndTime() - t, phoneme->GetEndTime() - phoneme->GetStartTime() ) );
}
else
{
// dead space, so increase the blend length to the start of the next phoneme, as long as it's not longer than the current phoneme
dt = MAX( dt, MIN( next->GetStartTime() - t, phoneme->GetEndTime() - phoneme->GetStartTime() ) );
}
}
else
{
// last phoneme in list, increase the blend length to the length of the current phoneme
dt = MAX( dt, phoneme->GetEndTime() - phoneme->GetStartTime() );
}
}
}
}
float t1 = ( phoneme->GetStartTime() - t) / dt;
float t2 = ( phoneme->GetEndTime() - t) / dt;
if (t1 < 1.0 && t2 > 0)
{
float scale;
// clamp
if (t2 > 1)
t2 = 1;
if (t1 < 0)
t1 = 0;
// FIXME: simple box filter. Should use something fancier
scale = (t2 - t1);
AddViseme( classes, emphasis_intensity, phoneme->GetPhonemeCode(), scale, juststarted );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *classes -
//-----------------------------------------------------------------------------
void C_BaseFlex::ProcessVisemes( Emphasized_Phoneme *classes )
{
// Any sounds being played?
if ( !MouthInfo().IsActive() )
return;
// Multiple phoneme tracks can overlap, look across all such tracks.
for ( int source = 0 ; source < MouthInfo().GetNumVoiceSources(); source++ )
{
CVoiceData *vd = MouthInfo().GetVoiceSource( source );
if ( !vd || vd->ShouldIgnorePhonemes() )
continue;
CSentence *sentence = engine->GetSentence( vd->GetSource() );
if ( !sentence )
continue;
float sentence_length = engine->GetSentenceLength( vd->GetSource() );
float timesincestart = vd->GetElapsedTime();
// This sound should be done...why hasn't it been removed yet???
if ( timesincestart >= ( sentence_length + 2.0f ) )
continue;
// Adjust actual time
float t = timesincestart - g_CV_PhonemeDelay.GetFloat();
// Get box filter duration
float dt = g_CV_PhonemeFilter.GetFloat();
// Streaming sounds get an additional delay...
/*
// Tracker 20534: Probably not needed any more with the async sound stuff that
// we now have (we don't have a disk i/o hitch on startup which might have been
// messing up the startup timing a bit )
bool streaming = engine->IsStreaming( vd->m_pAudioSource );
if ( streaming )
{
t -= g_CV_PhonemeDelayStreaming.GetFloat();
}
*/
// Assume sound has been playing for a while...
bool juststarted = false;
// Get intensity setting for this time (from spline)
float emphasis_intensity = sentence->GetIntensity( t, sentence_length );
// Blend and add visemes together
AddVisemesForSentence( classes, emphasis_intensity, sentence, t, dt, juststarted );
}
}
//-----------------------------------------------------------------------------
// Purpose: fill keyvalues message with flex state
// Input :
//-----------------------------------------------------------------------------
void C_BaseFlex::GetToolRecordingState( KeyValues *msg )
{
if ( !ToolsEnabled() )
return;
VPROF_BUDGET( "C_BaseFlex::GetToolRecordingState", VPROF_BUDGETGROUP_TOOLS );
BaseClass::GetToolRecordingState( msg );
CStudioHdr *hdr = GetModelPtr();
if ( !hdr )
return;
memset( g_flexweight, 0, sizeof( g_flexweight ) );
if ( hdr->numflexcontrollers() == 0 )
return;
LocalFlexController_t i;
ProcessSceneEvents( true );