Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6059 lines
167 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //===========================================================================//
  8. #include "tier0/dbg.h"
  9. #include "mathlib/mathlib.h"
  10. #include "bone_setup.h"
  11. #include <string.h>
  12. #include "collisionutils.h"
  13. #include "vstdlib/random.h"
  14. #include "tier0/vprof.h"
  15. #include "bone_accessor.h"
  16. #include "mathlib/ssequaternion.h"
  17. #include "bitvec.h"
  18. #include "datamanager.h"
  19. #include "convar.h"
  20. #include "tier0/tslist.h"
  21. #include "vphysics_interface.h"
  22. #ifdef CLIENT_DLL
  23. #include "posedebugger.h"
  24. #endif
  25. // memdbgon must be the last include file in a .cpp file!!!
  26. #include "tier0/memdbgon.h"
  27. class CBoneSetup
  28. {
  29. public:
  30. CBoneSetup( const CStudioHdr *pStudioHdr, int boneMask, const float poseParameter[], IPoseDebugger *pPoseDebugger = NULL );
  31. void InitPose( Vector pos[], Quaternion q[] );
  32. void AccumulatePose( Vector pos[], Quaternion q[], int sequence, float cycle, float flWeight, float flTime, CIKContext *pIKContext );
  33. void CalcAutoplaySequences( Vector pos[], Quaternion q[], float flRealTime, CIKContext *pIKContext );
  34. private:
  35. void AddSequenceLayers( Vector pos[], Quaternion q[], mstudioseqdesc_t &seqdesc, int sequence, float cycle, float flWeight, float flTime, CIKContext *pIKContext );
  36. void AddLocalLayers( Vector pos[], Quaternion q[], mstudioseqdesc_t &seqdesc, int sequence, float cycle, float flWeight, float flTime, CIKContext *pIKContext );
  37. public:
  38. const CStudioHdr *m_pStudioHdr;
  39. int m_boneMask;
  40. const float *m_flPoseParameter;
  41. IPoseDebugger *m_pPoseDebugger;
  42. };
  43. // -----------------------------------------------------------------
  44. template <typename T>
  45. class CBoneSetupMemoryPool
  46. {
  47. public:
  48. T *Alloc()
  49. {
  50. T *p = (T *)m_FreeBlocks.Pop();
  51. if ( !p )
  52. {
  53. p = new T[MAXSTUDIOBONES];
  54. if ( ((size_t)p) % TSLIST_NODE_ALIGNMENT != 0 )
  55. {
  56. DebuggerBreak();
  57. }
  58. }
  59. return p;
  60. }
  61. void Free( T *p )
  62. {
  63. m_FreeBlocks.Push( (TSLNodeBase_t *)p );
  64. }
  65. private:
  66. CTSListBase m_FreeBlocks;
  67. };
  68. CBoneSetupMemoryPool<Quaternion> g_QaternionPool;
  69. CBoneSetupMemoryPool<Vector> g_VectorPool;
  70. CBoneSetupMemoryPool<matrix3x4_t> g_MatrixPool;
  71. // -----------------------------------------------------------------
  72. CBoneCache *CBoneCache::CreateResource( const bonecacheparams_t &params )
  73. {
  74. short studioToCachedIndex[MAXSTUDIOBONES];
  75. short cachedToStudioIndex[MAXSTUDIOBONES];
  76. int cachedBoneCount = 0;
  77. for ( int i = 0; i < params.pStudioHdr->numbones(); i++ )
  78. {
  79. // skip bones that aren't part of the boneMask (and aren't the root bone)
  80. if (i != 0 && !(params.pStudioHdr->boneFlags(i) & params.boneMask))
  81. {
  82. studioToCachedIndex[i] = -1;
  83. continue;
  84. }
  85. studioToCachedIndex[i] = cachedBoneCount;
  86. cachedToStudioIndex[cachedBoneCount] = i;
  87. cachedBoneCount++;
  88. }
  89. int tableSizeStudio = sizeof(short) * params.pStudioHdr->numbones();
  90. int tableSizeCached = sizeof(short) * cachedBoneCount;
  91. int matrixSize = sizeof(matrix3x4_t) * cachedBoneCount;
  92. int size = ( sizeof(CBoneCache) + tableSizeStudio + tableSizeCached + matrixSize + 3 ) & ~3;
  93. CBoneCache *pMem = (CBoneCache *)malloc( size );
  94. Construct( pMem );
  95. pMem->Init( params, size, studioToCachedIndex, cachedToStudioIndex, cachedBoneCount );
  96. return pMem;
  97. }
  98. unsigned int CBoneCache::EstimatedSize( const bonecacheparams_t &params )
  99. {
  100. // conservative estimate - max size
  101. return ( params.pStudioHdr->numbones() * (sizeof(short) + sizeof(short) + sizeof(matrix3x4_t)) + 3 ) & ~3;
  102. }
  103. void CBoneCache::DestroyResource()
  104. {
  105. free( this );
  106. }
  107. CBoneCache::CBoneCache()
  108. {
  109. m_size = 0;
  110. m_cachedBoneCount = 0;
  111. }
  112. void CBoneCache::Init( const bonecacheparams_t &params, unsigned int size, short *pStudioToCached, short *pCachedToStudio, int cachedBoneCount )
  113. {
  114. m_cachedBoneCount = cachedBoneCount;
  115. m_size = size;
  116. m_timeValid = params.curtime;
  117. m_boneMask = params.boneMask;
  118. int studioTableSize = params.pStudioHdr->numbones() * sizeof(short);
  119. m_cachedToStudioOffset = studioTableSize;
  120. memcpy( StudioToCached(), pStudioToCached, studioTableSize );
  121. int cachedTableSize = cachedBoneCount * sizeof(short);
  122. memcpy( CachedToStudio(), pCachedToStudio, cachedTableSize );
  123. m_matrixOffset = ( m_cachedToStudioOffset + cachedTableSize + 3 ) & ~3;
  124. UpdateBones( params.pBoneToWorld, params.pStudioHdr->numbones(), params.curtime );
  125. }
  126. void CBoneCache::UpdateBones( const matrix3x4_t *pBoneToWorld, int numbones, float curtime )
  127. {
  128. matrix3x4_t *pBones = BoneArray();
  129. const short *pCachedToStudio = CachedToStudio();
  130. for ( int i = 0; i < m_cachedBoneCount; i++ )
  131. {
  132. int index = pCachedToStudio[i];
  133. MatrixCopy( pBoneToWorld[index], pBones[i] );
  134. }
  135. m_timeValid = curtime;
  136. }
  137. matrix3x4_t *CBoneCache::GetCachedBone( int studioIndex )
  138. {
  139. int cachedIndex = StudioToCached()[studioIndex];
  140. if ( cachedIndex >= 0 )
  141. {
  142. return BoneArray() + cachedIndex;
  143. }
  144. return NULL;
  145. }
  146. void CBoneCache::ReadCachedBones( matrix3x4_t *pBoneToWorld )
  147. {
  148. matrix3x4_t *pBones = BoneArray();
  149. const short *pCachedToStudio = CachedToStudio();
  150. for ( int i = 0; i < m_cachedBoneCount; i++ )
  151. {
  152. MatrixCopy( pBones[i], pBoneToWorld[pCachedToStudio[i]] );
  153. }
  154. }
  155. void CBoneCache::ReadCachedBonePointers( matrix3x4_t **bones, int numbones )
  156. {
  157. memset( bones, 0, sizeof(matrix3x4_t *) * numbones );
  158. matrix3x4_t *pBones = BoneArray();
  159. const short *pCachedToStudio = CachedToStudio();
  160. for ( int i = 0; i < m_cachedBoneCount; i++ )
  161. {
  162. bones[pCachedToStudio[i]] = pBones + i;
  163. }
  164. }
  165. bool CBoneCache::IsValid( float curtime, float dt )
  166. {
  167. if ( curtime - m_timeValid <= dt )
  168. return true;
  169. return false;
  170. }
  171. // private functions
  172. matrix3x4_t *CBoneCache::BoneArray()
  173. {
  174. return (matrix3x4_t *)( (char *)(this+1) + m_matrixOffset );
  175. }
  176. short *CBoneCache::StudioToCached()
  177. {
  178. return (short *)( (char *)(this+1) );
  179. }
  180. short *CBoneCache::CachedToStudio()
  181. {
  182. return (short *)( (char *)(this+1) + m_cachedToStudioOffset );
  183. }
  184. // Construct a singleton
  185. static CDataManager<CBoneCache, bonecacheparams_t, CBoneCache *, CThreadFastMutex> g_StudioBoneCache( 128 * 1024L );
  186. CBoneCache *Studio_GetBoneCache( memhandle_t cacheHandle )
  187. {
  188. AUTO_LOCK( g_StudioBoneCache.AccessMutex() );
  189. return g_StudioBoneCache.GetResource_NoLock( cacheHandle );
  190. }
  191. memhandle_t Studio_CreateBoneCache( bonecacheparams_t &params )
  192. {
  193. AUTO_LOCK( g_StudioBoneCache.AccessMutex() );
  194. return g_StudioBoneCache.CreateResource( params );
  195. }
  196. void Studio_DestroyBoneCache( memhandle_t cacheHandle )
  197. {
  198. AUTO_LOCK( g_StudioBoneCache.AccessMutex() );
  199. g_StudioBoneCache.DestroyResource( cacheHandle );
  200. }
  201. void Studio_InvalidateBoneCache( memhandle_t cacheHandle )
  202. {
  203. AUTO_LOCK( g_StudioBoneCache.AccessMutex() );
  204. CBoneCache *pCache = g_StudioBoneCache.GetResource_NoLock( cacheHandle );
  205. if ( pCache )
  206. {
  207. pCache->m_timeValid = -1.0f;
  208. }
  209. }
  210. //-----------------------------------------------------------------------------
  211. // Purpose:
  212. //-----------------------------------------------------------------------------
  213. void BuildBoneChain(
  214. const CStudioHdr *pStudioHdr,
  215. const matrix3x4_t &rootxform,
  216. const Vector pos[],
  217. const Quaternion q[],
  218. int iBone,
  219. matrix3x4_t *pBoneToWorld )
  220. {
  221. CBoneBitList boneComputed;
  222. BuildBoneChain( pStudioHdr, rootxform, pos, q, iBone, pBoneToWorld, boneComputed );
  223. return;
  224. }
  225. //-----------------------------------------------------------------------------
  226. // Purpose: return a sub frame rotation for a single bone
  227. //-----------------------------------------------------------------------------
  228. void ExtractAnimValue( int frame, mstudioanimvalue_t *panimvalue, float scale, float &v1, float &v2 )
  229. {
  230. if ( !panimvalue )
  231. {
  232. v1 = v2 = 0;
  233. return;
  234. }
  235. // Avoids a crash reading off the end of the data
  236. // There is probably a better long-term solution; Ken is going to look into it.
  237. if ( ( panimvalue->num.total == 1 ) && ( panimvalue->num.valid == 1 ) )
  238. {
  239. v1 = v2 = panimvalue[1].value * scale;
  240. return;
  241. }
  242. int k = frame;
  243. // find the data list that has the frame
  244. while (panimvalue->num.total <= k)
  245. {
  246. k -= panimvalue->num.total;
  247. panimvalue += panimvalue->num.valid + 1;
  248. if ( panimvalue->num.total == 0 )
  249. {
  250. Assert( 0 ); // running off the end of the animation stream is bad
  251. v1 = v2 = 0;
  252. return;
  253. }
  254. }
  255. if (panimvalue->num.valid > k)
  256. {
  257. // has valid animation data
  258. v1 = panimvalue[k+1].value * scale;
  259. if (panimvalue->num.valid > k + 1)
  260. {
  261. // has valid animation blend data
  262. v2 = panimvalue[k+2].value * scale;
  263. }
  264. else
  265. {
  266. if (panimvalue->num.total > k + 1)
  267. {
  268. // data repeats, no blend
  269. v2 = v1;
  270. }
  271. else
  272. {
  273. // pull blend from first data block in next list
  274. v2 = panimvalue[panimvalue->num.valid+2].value * scale;
  275. }
  276. }
  277. }
  278. else
  279. {
  280. // get last valid data block
  281. v1 = panimvalue[panimvalue->num.valid].value * scale;
  282. if (panimvalue->num.total > k + 1)
  283. {
  284. // data repeats, no blend
  285. v2 = v1;
  286. }
  287. else
  288. {
  289. // pull blend from first data block in next list
  290. v2 = panimvalue[panimvalue->num.valid + 2].value * scale;
  291. }
  292. }
  293. }
  294. void ExtractAnimValue( int frame, mstudioanimvalue_t *panimvalue, float scale, float &v1 )
  295. {
  296. if ( !panimvalue )
  297. {
  298. v1 = 0;
  299. return;
  300. }
  301. int k = frame;
  302. while (panimvalue->num.total <= k)
  303. {
  304. k -= panimvalue->num.total;
  305. panimvalue += panimvalue->num.valid + 1;
  306. if ( panimvalue->num.total == 0 )
  307. {
  308. Assert( 0 ); // running off the end of the animation stream is bad
  309. v1 = 0;
  310. return;
  311. }
  312. }
  313. if (panimvalue->num.valid > k)
  314. {
  315. v1 = panimvalue[k+1].value * scale;
  316. }
  317. else
  318. {
  319. // get last valid data block
  320. v1 = panimvalue[panimvalue->num.valid].value * scale;
  321. }
  322. }
  323. //-----------------------------------------------------------------------------
  324. // Purpose: return a sub frame rotation for a single bone
  325. //-----------------------------------------------------------------------------
  326. void CalcBoneQuaternion( int frame, float s,
  327. const Quaternion &baseQuat, const RadianEuler &baseRot, const Vector &baseRotScale,
  328. int iBaseFlags, const Quaternion &baseAlignment,
  329. const mstudioanim_t *panim, Quaternion &q )
  330. {
  331. if ( panim->flags & STUDIO_ANIM_RAWROT )
  332. {
  333. q = *(panim->pQuat48());
  334. Assert( q.IsValid() );
  335. return;
  336. }
  337. if ( panim->flags & STUDIO_ANIM_RAWROT2 )
  338. {
  339. q = *(panim->pQuat64());
  340. Assert( q.IsValid() );
  341. return;
  342. }
  343. if ( !(panim->flags & STUDIO_ANIM_ANIMROT) )
  344. {
  345. if (panim->flags & STUDIO_ANIM_DELTA)
  346. {
  347. q.Init( 0.0f, 0.0f, 0.0f, 1.0f );
  348. }
  349. else
  350. {
  351. q = baseQuat;
  352. }
  353. return;
  354. }
  355. mstudioanim_valueptr_t *pValuesPtr = panim->pRotV();
  356. if (s > 0.001f)
  357. {
  358. QuaternionAligned q1, q2;
  359. RadianEuler angle1, angle2;
  360. ExtractAnimValue( frame, pValuesPtr->pAnimvalue( 0 ), baseRotScale.x, angle1.x, angle2.x );
  361. ExtractAnimValue( frame, pValuesPtr->pAnimvalue( 1 ), baseRotScale.y, angle1.y, angle2.y );
  362. ExtractAnimValue( frame, pValuesPtr->pAnimvalue( 2 ), baseRotScale.z, angle1.z, angle2.z );
  363. if (!(panim->flags & STUDIO_ANIM_DELTA))
  364. {
  365. angle1.x = angle1.x + baseRot.x;
  366. angle1.y = angle1.y + baseRot.y;
  367. angle1.z = angle1.z + baseRot.z;
  368. angle2.x = angle2.x + baseRot.x;
  369. angle2.y = angle2.y + baseRot.y;
  370. angle2.z = angle2.z + baseRot.z;
  371. }
  372. Assert( angle1.IsValid() && angle2.IsValid() );
  373. if (angle1.x != angle2.x || angle1.y != angle2.y || angle1.z != angle2.z)
  374. {
  375. AngleQuaternion( angle1, q1 );
  376. AngleQuaternion( angle2, q2 );
  377. #ifdef _X360
  378. fltx4 q1simd, q2simd, qsimd;
  379. q1simd = LoadAlignedSIMD( q1 );
  380. q2simd = LoadAlignedSIMD( q2 );
  381. qsimd = QuaternionBlendSIMD( q1simd, q2simd, s );
  382. StoreUnalignedSIMD( q.Base(), qsimd );
  383. #else
  384. QuaternionBlend( q1, q2, s, q );
  385. #endif
  386. }
  387. else
  388. {
  389. AngleQuaternion( angle1, q );
  390. }
  391. }
  392. else
  393. {
  394. RadianEuler angle;
  395. ExtractAnimValue( frame, pValuesPtr->pAnimvalue( 0 ), baseRotScale.x, angle.x );
  396. ExtractAnimValue( frame, pValuesPtr->pAnimvalue( 1 ), baseRotScale.y, angle.y );
  397. ExtractAnimValue( frame, pValuesPtr->pAnimvalue( 2 ), baseRotScale.z, angle.z );
  398. if (!(panim->flags & STUDIO_ANIM_DELTA))
  399. {
  400. angle.x = angle.x + baseRot.x;
  401. angle.y = angle.y + baseRot.y;
  402. angle.z = angle.z + baseRot.z;
  403. }
  404. Assert( angle.IsValid() );
  405. AngleQuaternion( angle, q );
  406. }
  407. Assert( q.IsValid() );
  408. // align to unified bone
  409. if (!(panim->flags & STUDIO_ANIM_DELTA) && (iBaseFlags & BONE_FIXED_ALIGNMENT))
  410. {
  411. QuaternionAlign( baseAlignment, q, q );
  412. }
  413. }
  414. inline void CalcBoneQuaternion( int frame, float s,
  415. const mstudiobone_t *pBone,
  416. const mstudiolinearbone_t *pLinearBones,
  417. const mstudioanim_t *panim, Quaternion &q )
  418. {
  419. if (pLinearBones)
  420. {
  421. CalcBoneQuaternion( frame, s, pLinearBones->quat(panim->bone), pLinearBones->rot(panim->bone), pLinearBones->rotscale(panim->bone), pLinearBones->flags(panim->bone), pLinearBones->qalignment(panim->bone), panim, q );
  422. }
  423. else
  424. {
  425. CalcBoneQuaternion( frame, s, pBone->quat, pBone->rot, pBone->rotscale, pBone->flags, pBone->qAlignment, panim, q );
  426. }
  427. }
  428. //-----------------------------------------------------------------------------
  429. // Purpose: return a sub frame position for a single bone
  430. //-----------------------------------------------------------------------------
  431. void CalcBonePosition( int frame, float s,
  432. const Vector &basePos, const Vector &baseBoneScale,
  433. const mstudioanim_t *panim, Vector &pos )
  434. {
  435. if (panim->flags & STUDIO_ANIM_RAWPOS)
  436. {
  437. pos = *(panim->pPos());
  438. Assert( pos.IsValid() );
  439. return;
  440. }
  441. else if (!(panim->flags & STUDIO_ANIM_ANIMPOS))
  442. {
  443. if (panim->flags & STUDIO_ANIM_DELTA)
  444. {
  445. pos.Init( 0.0f, 0.0f, 0.0f );
  446. }
  447. else
  448. {
  449. pos = basePos;
  450. }
  451. return;
  452. }
  453. mstudioanim_valueptr_t *pPosV = panim->pPosV();
  454. int j;
  455. if (s > 0.001f)
  456. {
  457. float v1, v2;
  458. for (j = 0; j < 3; j++)
  459. {
  460. ExtractAnimValue( frame, pPosV->pAnimvalue( j ), baseBoneScale[j], v1, v2 );
  461. pos[j] = v1 * (1.0 - s) + v2 * s;
  462. }
  463. }
  464. else
  465. {
  466. for (j = 0; j < 3; j++)
  467. {
  468. ExtractAnimValue( frame, pPosV->pAnimvalue( j ), baseBoneScale[j], pos[j] );
  469. }
  470. }
  471. if (!(panim->flags & STUDIO_ANIM_DELTA))
  472. {
  473. pos.x = pos.x + basePos.x;
  474. pos.y = pos.y + basePos.y;
  475. pos.z = pos.z + basePos.z;
  476. }
  477. Assert( pos.IsValid() );
  478. }
  479. inline void CalcBonePosition( int frame, float s,
  480. const mstudiobone_t *pBone,
  481. const mstudiolinearbone_t *pLinearBones,
  482. const mstudioanim_t *panim, Vector &pos )
  483. {
  484. if (pLinearBones)
  485. {
  486. CalcBonePosition( frame, s, pLinearBones->pos(panim->bone), pLinearBones->posscale(panim->bone), panim, pos );
  487. }
  488. else
  489. {
  490. CalcBonePosition( frame, s, pBone->pos, pBone->posscale, panim, pos );
  491. }
  492. }
  493. void SetupSingleBoneMatrix(
  494. CStudioHdr *pOwnerHdr,
  495. int nSequence,
  496. int iFrame,
  497. int iBone,
  498. matrix3x4_t &mBoneLocal )
  499. {
  500. mstudioseqdesc_t &seqdesc = pOwnerHdr->pSeqdesc( nSequence );
  501. mstudioanimdesc_t &animdesc = pOwnerHdr->pAnimdesc( seqdesc.anim( 0, 0 ) );
  502. int iLocalFrame = iFrame;
  503. mstudioanim_t *panim = animdesc.pAnim( &iLocalFrame );
  504. float s = 0;
  505. mstudiobone_t *pbone = pOwnerHdr->pBone( iBone );
  506. Quaternion boneQuat;
  507. Vector bonePos;
  508. // search for bone
  509. while (panim && panim->bone != iBone)
  510. {
  511. panim = panim->pNext();
  512. }
  513. // look up animation if found, if not, initialize
  514. if (panim && seqdesc.weight(iBone) > 0)
  515. {
  516. CalcBoneQuaternion( iLocalFrame, s, pbone, NULL, panim, boneQuat );
  517. CalcBonePosition ( iLocalFrame, s, pbone, NULL, panim, bonePos );
  518. }
  519. else if (animdesc.flags & STUDIO_DELTA)
  520. {
  521. boneQuat.Init( 0.0f, 0.0f, 0.0f, 1.0f );
  522. bonePos.Init( 0.0f, 0.0f, 0.0f );
  523. }
  524. else
  525. {
  526. boneQuat = pbone->quat;
  527. bonePos = pbone->pos;
  528. }
  529. QuaternionMatrix( boneQuat, bonePos, mBoneLocal );
  530. }
  531. //-----------------------------------------------------------------------------
  532. // Purpose:
  533. //-----------------------------------------------------------------------------
  534. static void CalcDecompressedAnimation( const mstudiocompressedikerror_t *pCompressed, int iFrame, float fraq, Vector &pos, Quaternion &q )
  535. {
  536. if (fraq > 0.0001f)
  537. {
  538. Vector p1, p2;
  539. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 0 ), pCompressed->scale[0], p1.x, p2.x );
  540. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 1 ), pCompressed->scale[1], p1.y, p2.y );
  541. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 2 ), pCompressed->scale[2], p1.z, p2.z );
  542. pos = p1 * (1 - fraq) + p2 * fraq;
  543. Quaternion q1, q2;
  544. RadianEuler angle1, angle2;
  545. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 3 ), pCompressed->scale[3], angle1.x, angle2.x );
  546. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 4 ), pCompressed->scale[4], angle1.y, angle2.y );
  547. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 5 ), pCompressed->scale[5], angle1.z, angle2.z );
  548. if (angle1.x != angle2.x || angle1.y != angle2.y || angle1.z != angle2.z)
  549. {
  550. AngleQuaternion( angle1, q1 );
  551. AngleQuaternion( angle2, q2 );
  552. QuaternionBlend( q1, q2, fraq, q );
  553. }
  554. else
  555. {
  556. AngleQuaternion( angle1, q );
  557. }
  558. }
  559. else
  560. {
  561. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 0 ), pCompressed->scale[0], pos.x );
  562. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 1 ), pCompressed->scale[1], pos.y );
  563. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 2 ), pCompressed->scale[2], pos.z );
  564. RadianEuler angle;
  565. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 3 ), pCompressed->scale[3], angle.x );
  566. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 4 ), pCompressed->scale[4], angle.y );
  567. ExtractAnimValue( iFrame, pCompressed->pAnimvalue( 5 ), pCompressed->scale[5], angle.z );
  568. AngleQuaternion( angle, q );
  569. }
  570. }
  571. //-----------------------------------------------------------------------------
  572. // Purpose: translate animations done in a non-standard parent space
  573. //-----------------------------------------------------------------------------
  574. static void CalcLocalHierarchyAnimation(
  575. const CStudioHdr *pStudioHdr,
  576. matrix3x4_t *boneToWorld,
  577. CBoneBitList &boneComputed,
  578. Vector *pos,
  579. Quaternion *q,
  580. //const mstudioanimdesc_t &animdesc,
  581. const mstudiobone_t *pbone,
  582. mstudiolocalhierarchy_t *pHierarchy,
  583. int iBone,
  584. int iNewParent,
  585. float cycle,
  586. int iFrame,
  587. float flFraq,
  588. int boneMask
  589. )
  590. {
  591. #ifdef STAGING_ONLY
  592. Assert( iNewParent == -1 || (iNewParent >= 0 && iNewParent < MAXSTUDIOBONES) );
  593. Assert( iBone > 0 );
  594. Assert( iBone < MAXSTUDIOBONES );
  595. #endif // STAGING_ONLY
  596. Vector localPos;
  597. Quaternion localQ;
  598. // make fake root transform
  599. static ALIGN16 matrix3x4_t rootXform ALIGN16_POST ( 1.0f, 0, 0, 0, 0, 1.0f, 0, 0, 0, 0, 1.0f, 0 );
  600. // FIXME: missing check to see if seq has a weight for this bone
  601. float weight = 1.0f;
  602. // check to see if there's a ramp on the influence
  603. if ( pHierarchy->tail - pHierarchy->peak < 1.0f )
  604. {
  605. float index = cycle;
  606. if (pHierarchy->end > 1.0f && index < pHierarchy->start)
  607. index += 1.0f;
  608. if (index < pHierarchy->start)
  609. return;
  610. if (index >= pHierarchy->end)
  611. return;
  612. if (index < pHierarchy->peak && pHierarchy->start != pHierarchy->peak)
  613. {
  614. weight = (index - pHierarchy->start) / (pHierarchy->peak - pHierarchy->start);
  615. }
  616. else if (index > pHierarchy->tail && pHierarchy->end != pHierarchy->tail)
  617. {
  618. weight = (pHierarchy->end - index) / (pHierarchy->end - pHierarchy->tail);
  619. }
  620. weight = SimpleSpline( weight );
  621. }
  622. CalcDecompressedAnimation( pHierarchy->pLocalAnim(), iFrame - pHierarchy->iStart, flFraq, localPos, localQ );
  623. BuildBoneChain( pStudioHdr, rootXform, pos, q, iBone, boneToWorld, boneComputed );
  624. matrix3x4_t localXform;
  625. AngleMatrix( localQ, localPos, localXform );
  626. if ( iNewParent != -1 )
  627. {
  628. BuildBoneChain( pStudioHdr, rootXform, pos, q, iNewParent, boneToWorld, boneComputed );
  629. ConcatTransforms( boneToWorld[iNewParent], localXform, boneToWorld[iBone] );
  630. }
  631. else
  632. {
  633. boneToWorld[iBone] = localXform;
  634. }
  635. // back solve
  636. Vector p1;
  637. Quaternion q1;
  638. int n = pbone[iBone].parent;
  639. if (n == -1)
  640. {
  641. if (weight == 1.0f)
  642. {
  643. MatrixAngles( boneToWorld[iBone], q[iBone], pos[iBone] );
  644. }
  645. else
  646. {
  647. MatrixAngles( boneToWorld[iBone], q1, p1 );
  648. QuaternionSlerp( q[iBone], q1, weight, q[iBone] );
  649. pos[iBone] = Lerp( weight, p1, pos[iBone] );
  650. }
  651. }
  652. else
  653. {
  654. matrix3x4_t worldToBone;
  655. MatrixInvert( boneToWorld[n], worldToBone );
  656. matrix3x4_t local;
  657. ConcatTransforms( worldToBone, boneToWorld[iBone], local );
  658. if (weight == 1.0f)
  659. {
  660. MatrixAngles( local, q[iBone], pos[iBone] );
  661. }
  662. else
  663. {
  664. MatrixAngles( local, q1, p1 );
  665. QuaternionSlerp( q[iBone], q1, weight, q[iBone] );
  666. pos[iBone] = Lerp( weight, p1, pos[iBone] );
  667. }
  668. }
  669. }
  670. //-----------------------------------------------------------------------------
  671. // Purpose: Calc Zeroframe Data
  672. //-----------------------------------------------------------------------------
  673. static void CalcZeroframeData( const CStudioHdr *pStudioHdr, const studiohdr_t *pAnimStudioHdr, const virtualgroup_t *pAnimGroup, const mstudiobone_t *pAnimbone, mstudioanimdesc_t &animdesc, float fFrame, Vector *pos, Quaternion *q, int boneMask, float flWeight )
  674. {
  675. byte *pData = animdesc.pZeroFrameData();
  676. if (!pData)
  677. return;
  678. int i, j;
  679. // Msg("zeroframe %s\n", animdesc.pszName() );
  680. if (animdesc.zeroframecount == 1)
  681. {
  682. for (j = 0; j < pAnimStudioHdr->numbones; j++)
  683. {
  684. if (pAnimGroup)
  685. i = pAnimGroup->masterBone[j];
  686. else
  687. i = j;
  688. if (pAnimbone[j].flags & BONE_HAS_SAVEFRAME_POS)
  689. {
  690. if ((i >= 0) && (pStudioHdr->boneFlags(i) & boneMask))
  691. {
  692. Vector p = *(Vector48 *)pData;
  693. pos[i] = pos[i] * (1.0f - flWeight) + p * flWeight;
  694. Assert( pos[i].IsValid() );
  695. }
  696. pData += sizeof( Vector48 );
  697. }
  698. if (pAnimbone[j].flags & BONE_HAS_SAVEFRAME_ROT)
  699. {
  700. if ((i >= 0) && (pStudioHdr->boneFlags(i) & boneMask))
  701. {
  702. Quaternion q0 = *(Quaternion64 *)pData;
  703. QuaternionBlend( q[i], q0, flWeight, q[i] );
  704. Assert( q[i].IsValid() );
  705. }
  706. pData += sizeof( Quaternion64 );
  707. }
  708. }
  709. }
  710. else
  711. {
  712. float s1;
  713. int index = fFrame / animdesc.zeroframespan;
  714. if (index >= animdesc.zeroframecount - 1)
  715. {
  716. index = animdesc.zeroframecount - 2;
  717. s1 = 1.0f;
  718. }
  719. else
  720. {
  721. s1 = clamp( (fFrame - index * animdesc.zeroframespan) / animdesc.zeroframespan, 0.0f, 1.0f );
  722. }
  723. int i0 = max( index - 1, 0 );
  724. int i1 = index;
  725. int i2 = min( index + 1, animdesc.zeroframecount - 1 );
  726. for (j = 0; j < pAnimStudioHdr->numbones; j++)
  727. {
  728. if (pAnimGroup)
  729. i = pAnimGroup->masterBone[j];
  730. else
  731. i = j;
  732. if (pAnimbone[j].flags & BONE_HAS_SAVEFRAME_POS)
  733. {
  734. if ((i >= 0) && (pStudioHdr->boneFlags(i) & boneMask))
  735. {
  736. Vector p0 = *(((Vector48 *)pData) + i0);
  737. Vector p1 = *(((Vector48 *)pData) + i1);
  738. Vector p2 = *(((Vector48 *)pData) + i2);
  739. Vector p3;
  740. Hermite_Spline( p0, p1, p2, s1, p3 );
  741. pos[i] = pos[i] * (1.0f - flWeight) + p3 * flWeight;
  742. Assert( pos[i].IsValid() );
  743. }
  744. pData += sizeof( Vector48 ) * animdesc.zeroframecount;
  745. }
  746. if (pAnimbone[j].flags & BONE_HAS_SAVEFRAME_ROT)
  747. {
  748. if ((i >= 0) && (pStudioHdr->boneFlags(i) & boneMask))
  749. {
  750. Quaternion q0 = *(((Quaternion64 *)pData) + i0);
  751. Quaternion q1 = *(((Quaternion64 *)pData) + i1);
  752. Quaternion q2 = *(((Quaternion64 *)pData) + i2);
  753. if (flWeight == 1.0f)
  754. {
  755. Hermite_Spline( q0, q1, q2, s1, q[i] );
  756. }
  757. else
  758. {
  759. Quaternion q3;
  760. Hermite_Spline( q0, q1, q2, s1, q3 );
  761. QuaternionBlend( q[i], q3, flWeight, q[i] );
  762. }
  763. Assert( q[i].IsValid() );
  764. }
  765. pData += sizeof( Quaternion64 ) * animdesc.zeroframecount;
  766. }
  767. }
  768. }
  769. }
  770. //-----------------------------------------------------------------------------
  771. // Purpose: Find and decode a sub-frame of animation, remapping the skeleton bone indexes
  772. //-----------------------------------------------------------------------------
  773. static void CalcVirtualAnimation( virtualmodel_t *pVModel, const CStudioHdr *pStudioHdr, Vector *pos, Quaternion *q,
  774. mstudioseqdesc_t &seqdesc, int sequence, int animation,
  775. float cycle, int boneMask )
  776. {
  777. //int i, k;
  778. const mstudiobone_t *pbone;
  779. const virtualgroup_t *pSeqGroup;
  780. const studiohdr_t *pSeqStudioHdr;
  781. const mstudiolinearbone_t *pSeqLinearBones;
  782. const mstudiobone_t *pSeqbone;
  783. const mstudioanim_t *panim;
  784. const studiohdr_t *pAnimStudioHdr;
  785. const mstudiolinearbone_t *pAnimLinearBones;
  786. const mstudiobone_t *pAnimbone;
  787. const virtualgroup_t *pAnimGroup;
  788. pSeqGroup = pVModel->pSeqGroup( sequence );
  789. int baseanimation = pStudioHdr->iRelativeAnim( sequence, animation );
  790. mstudioanimdesc_t &animdesc = ((CStudioHdr *)pStudioHdr)->pAnimdesc( baseanimation );
  791. pSeqStudioHdr = ((CStudioHdr *)pStudioHdr)->pSeqStudioHdr( sequence );
  792. pSeqLinearBones = pSeqStudioHdr->pLinearBones();
  793. pSeqbone = pSeqStudioHdr->pBone( 0 );
  794. pAnimGroup = pVModel->pAnimGroup( baseanimation );
  795. pAnimStudioHdr = ((CStudioHdr *)pStudioHdr)->pAnimStudioHdr( baseanimation );
  796. pAnimLinearBones = pAnimStudioHdr->pLinearBones();
  797. pAnimbone = pAnimStudioHdr->pBone( 0 );
  798. int iFrame;
  799. float s;
  800. float fFrame = cycle * (animdesc.numframes - 1);
  801. iFrame = (int)fFrame;
  802. s = (fFrame - iFrame);
  803. int iLocalFrame = iFrame;
  804. float flStall;
  805. panim = animdesc.pAnim( &iLocalFrame, flStall );
  806. float *pweight = seqdesc.pBoneweight( 0 );
  807. pbone = pStudioHdr->pBone( 0 );
  808. for (int i = 0; i < pStudioHdr->numbones(); i++)
  809. {
  810. if (pStudioHdr->boneFlags(i) & boneMask)
  811. {
  812. int j = pSeqGroup->boneMap[i];
  813. if (j >= 0 && pweight[j] > 0.0f)
  814. {
  815. if (animdesc.flags & STUDIO_DELTA)
  816. {
  817. q[i].Init( 0.0f, 0.0f, 0.0f, 1.0f );
  818. pos[i].Init( 0.0f, 0.0f, 0.0f );
  819. }
  820. else if (pSeqLinearBones)
  821. {
  822. q[i] = pSeqLinearBones->quat(j);
  823. pos[i] = pSeqLinearBones->pos(j);
  824. }
  825. else
  826. {
  827. q[i] = pSeqbone[j].quat;
  828. pos[i] = pSeqbone[j].pos;
  829. }
  830. #ifdef STUDIO_ENABLE_PERF_COUNTERS
  831. pStudioHdr->m_nPerfUsedBones++;
  832. #endif
  833. }
  834. }
  835. }
  836. // if the animation isn't available, look for the zero frame cache
  837. if (!panim)
  838. {
  839. CalcZeroframeData( ((CStudioHdr *)pStudioHdr), pAnimStudioHdr, pAnimGroup, pAnimbone, animdesc, fFrame, pos, q, boneMask, 1.0 );
  840. return;
  841. }
  842. // FIXME: change encoding so that bone -1 is never the case
  843. while (panim && panim->bone < 255)
  844. {
  845. int j = pAnimGroup->masterBone[panim->bone];
  846. if ( j >= 0 && ( pStudioHdr->boneFlags(j) & boneMask ) )
  847. {
  848. int k = pSeqGroup->boneMap[j];
  849. if (k >= 0 && pweight[k] > 0.0f)
  850. {
  851. CalcBoneQuaternion( iLocalFrame, s, &pAnimbone[panim->bone], pAnimLinearBones, panim, q[j] );
  852. CalcBonePosition ( iLocalFrame, s, &pAnimbone[panim->bone], pAnimLinearBones, panim, pos[j] );
  853. #ifdef STUDIO_ENABLE_PERF_COUNTERS
  854. pStudioHdr->m_nPerfAnimatedBones++;
  855. #endif
  856. }
  857. }
  858. panim = panim->pNext();
  859. }
  860. // cross fade in previous zeroframe data
  861. if (flStall > 0.0f)
  862. {
  863. CalcZeroframeData( pStudioHdr, pAnimStudioHdr, pAnimGroup, pAnimbone, animdesc, fFrame, pos, q, boneMask, flStall );
  864. }
  865. // calculate a local hierarchy override
  866. if (animdesc.numlocalhierarchy)
  867. {
  868. matrix3x4_t *boneToWorld = g_MatrixPool.Alloc();
  869. CBoneBitList boneComputed;
  870. int i;
  871. for (i = 0; i < animdesc.numlocalhierarchy; i++)
  872. {
  873. mstudiolocalhierarchy_t *pHierarchy = animdesc.pHierarchy( i );
  874. if ( !pHierarchy )
  875. break;
  876. int iBone = pAnimGroup->masterBone[pHierarchy->iBone];
  877. if (iBone >= 0 && (pStudioHdr->boneFlags(iBone) & boneMask))
  878. {
  879. if ( pHierarchy->iNewParent != -1 )
  880. {
  881. int iNewParent = pAnimGroup->masterBone[pHierarchy->iNewParent];
  882. if (iNewParent >= 0 && (pStudioHdr->boneFlags(iNewParent) & boneMask))
  883. {
  884. CalcLocalHierarchyAnimation( pStudioHdr, boneToWorld, boneComputed, pos, q, pbone, pHierarchy, iBone, iNewParent, cycle, iFrame, s, boneMask );
  885. }
  886. }
  887. else
  888. {
  889. CalcLocalHierarchyAnimation( pStudioHdr, boneToWorld, boneComputed, pos, q, pbone, pHierarchy, iBone, -1, cycle, iFrame, s, boneMask );
  890. }
  891. }
  892. }
  893. g_MatrixPool.Free( boneToWorld );
  894. }
  895. }
  896. //-----------------------------------------------------------------------------
  897. // Purpose: Find and decode a sub-frame of animation
  898. //-----------------------------------------------------------------------------
  899. static void CalcAnimation( const CStudioHdr *pStudioHdr, Vector *pos, Quaternion *q,
  900. mstudioseqdesc_t &seqdesc,
  901. int sequence, int animation,
  902. float cycle, int boneMask )
  903. {
  904. #ifdef STUDIO_ENABLE_PERF_COUNTERS
  905. pStudioHdr->m_nPerfAnimationLayers++;
  906. #endif
  907. virtualmodel_t *pVModel = pStudioHdr->GetVirtualModel();
  908. if (pVModel)
  909. {
  910. CalcVirtualAnimation( pVModel, pStudioHdr, pos, q, seqdesc, sequence, animation, cycle, boneMask );
  911. return;
  912. }
  913. mstudioanimdesc_t &animdesc = ((CStudioHdr *)pStudioHdr)->pAnimdesc( animation );
  914. mstudiobone_t *pbone = pStudioHdr->pBone( 0 );
  915. const mstudiolinearbone_t *pLinearBones = pStudioHdr->pLinearBones();
  916. // int i;
  917. int iFrame;
  918. float s;
  919. float fFrame = cycle * (animdesc.numframes - 1);
  920. iFrame = (int)fFrame;
  921. s = (fFrame - iFrame);
  922. int iLocalFrame = iFrame;
  923. float flStall;
  924. mstudioanim_t *panim = animdesc.pAnim( &iLocalFrame, flStall );
  925. float *pweight = seqdesc.pBoneweight( 0 );
  926. // if the animation isn't available, look for the zero frame cache
  927. if (!panim)
  928. {
  929. // Msg("zeroframe %s\n", animdesc.pszName() );
  930. // pre initialize
  931. for (int i = 0; i < pStudioHdr->numbones(); i++, pbone++, pweight++)
  932. {
  933. if (*pweight > 0 && (pStudioHdr->boneFlags(i) & boneMask))
  934. {
  935. if (animdesc.flags & STUDIO_DELTA)
  936. {
  937. q[i].Init( 0.0f, 0.0f, 0.0f, 1.0f );
  938. pos[i].Init( 0.0f, 0.0f, 0.0f );
  939. }
  940. else
  941. {
  942. q[i] = pbone->quat;
  943. pos[i] = pbone->pos;
  944. }
  945. }
  946. }
  947. CalcZeroframeData( pStudioHdr, pStudioHdr->GetRenderHdr(), NULL, pStudioHdr->pBone( 0 ), animdesc, fFrame, pos, q, boneMask, 1.0 );
  948. return;
  949. }
  950. // BUGBUG: the sequence, the anim, and the model can have all different bone mappings.
  951. for (int i = 0; i < pStudioHdr->numbones(); i++, pbone++, pweight++)
  952. {
  953. if (panim && panim->bone == i)
  954. {
  955. if (*pweight > 0 && (pStudioHdr->boneFlags(i) & boneMask))
  956. {
  957. CalcBoneQuaternion( iLocalFrame, s, pbone, pLinearBones, panim, q[i] );
  958. CalcBonePosition ( iLocalFrame, s, pbone, pLinearBones, panim, pos[i] );
  959. #ifdef STUDIO_ENABLE_PERF_COUNTERS
  960. pStudioHdr->m_nPerfAnimatedBones++;
  961. pStudioHdr->m_nPerfUsedBones++;
  962. #endif
  963. }
  964. panim = panim->pNext();
  965. }
  966. else if (*pweight > 0 && (pStudioHdr->boneFlags(i) & boneMask))
  967. {
  968. if (animdesc.flags & STUDIO_DELTA)
  969. {
  970. q[i].Init( 0.0f, 0.0f, 0.0f, 1.0f );
  971. pos[i].Init( 0.0f, 0.0f, 0.0f );
  972. }
  973. else
  974. {
  975. q[i] = pbone->quat;
  976. pos[i] = pbone->pos;
  977. }
  978. #ifdef STUDIO_ENABLE_PERF_COUNTERS
  979. pStudioHdr->m_nPerfUsedBones++;
  980. #endif
  981. }
  982. }
  983. // cross fade in previous zeroframe data
  984. if (flStall > 0.0f)
  985. {
  986. CalcZeroframeData( pStudioHdr, pStudioHdr->GetRenderHdr(), NULL, pStudioHdr->pBone( 0 ), animdesc, fFrame, pos, q, boneMask, flStall );
  987. }
  988. if (animdesc.numlocalhierarchy)
  989. {
  990. matrix3x4_t *boneToWorld = g_MatrixPool.Alloc();
  991. CBoneBitList boneComputed;
  992. int i;
  993. for (i = 0; i < animdesc.numlocalhierarchy; i++)
  994. {
  995. mstudiolocalhierarchy_t *pHierarchy = animdesc.pHierarchy( i );
  996. if ( !pHierarchy )
  997. break;
  998. if (pStudioHdr->boneFlags(pHierarchy->iBone) & boneMask)
  999. {
  1000. if (pStudioHdr->boneFlags(pHierarchy->iNewParent) & boneMask)
  1001. {
  1002. CalcLocalHierarchyAnimation( pStudioHdr, boneToWorld, boneComputed, pos, q, pbone, pHierarchy, pHierarchy->iBone, pHierarchy->iNewParent, cycle, iFrame, s, boneMask );
  1003. }
  1004. }
  1005. }
  1006. g_MatrixPool.Free( boneToWorld );
  1007. }
  1008. }
  1009. //-----------------------------------------------------------------------------
  1010. // Purpose: qt = ( s * p ) * q
  1011. //-----------------------------------------------------------------------------
  1012. void QuaternionSM( float s, const Quaternion &p, const Quaternion &q, Quaternion &qt )
  1013. {
  1014. Quaternion p1, q1;
  1015. QuaternionScale( p, s, p1 );
  1016. QuaternionMult( p1, q, q1 );
  1017. QuaternionNormalize( q1 );
  1018. qt[0] = q1[0];
  1019. qt[1] = q1[1];
  1020. qt[2] = q1[2];
  1021. qt[3] = q1[3];
  1022. }
  1023. #if ALLOW_SIMD_QUATERNION_MATH
  1024. FORCEINLINE fltx4 QuaternionSMSIMD( float s, const fltx4 &p, const fltx4 &q )
  1025. {
  1026. fltx4 p1, q1, result;
  1027. p1 = QuaternionScaleSIMD( p, s );
  1028. q1 = QuaternionMultSIMD( p1, q );
  1029. result = QuaternionNormalizeSIMD( q1 );
  1030. return result;
  1031. }
  1032. #endif
  1033. //-----------------------------------------------------------------------------
  1034. // Purpose: qt = p * ( s * q )
  1035. //-----------------------------------------------------------------------------
  1036. void QuaternionMA( const Quaternion &p, float s, const Quaternion &q, Quaternion &qt )
  1037. {
  1038. Quaternion p1, q1;
  1039. QuaternionScale( q, s, q1 );
  1040. QuaternionMult( p, q1, p1 );
  1041. QuaternionNormalize( p1 );
  1042. qt[0] = p1[0];
  1043. qt[1] = p1[1];
  1044. qt[2] = p1[2];
  1045. qt[3] = p1[3];
  1046. }
  1047. #if ALLOW_SIMD_QUATERNION_MATH
  1048. FORCEINLINE fltx4 QuaternionMASIMD( const fltx4 &p, float s, const fltx4 &q )
  1049. {
  1050. fltx4 p1, q1, result;
  1051. q1 = QuaternionScaleSIMD( q, s );
  1052. p1 = QuaternionMultSIMD( p, q1 );
  1053. result = QuaternionNormalizeSIMD( p1 );
  1054. return result;
  1055. }
  1056. #endif
  1057. //-----------------------------------------------------------------------------
  1058. // Purpose: qt = p + s * q
  1059. //-----------------------------------------------------------------------------
  1060. void QuaternionAccumulate( const Quaternion &p, float s, const Quaternion &q, Quaternion &qt )
  1061. {
  1062. Quaternion q2;
  1063. QuaternionAlign( p, q, q2 );
  1064. qt[0] = p[0] + s * q2[0];
  1065. qt[1] = p[1] + s * q2[1];
  1066. qt[2] = p[2] + s * q2[2];
  1067. qt[3] = p[3] + s * q2[3];
  1068. }
  1069. #if ALLOW_SIMD_QUATERNION_MATH
  1070. FORCEINLINE fltx4 QuaternionAccumulateSIMD( const fltx4 &p, float s, const fltx4 &q )
  1071. {
  1072. fltx4 q2, s4, result;
  1073. q2 = QuaternionAlignSIMD( p, q );
  1074. s4 = ReplicateX4( s );
  1075. result = MaddSIMD( s4, q2, p );
  1076. return result;
  1077. }
  1078. #endif
  1079. //-----------------------------------------------------------------------------
  1080. // Purpose: blend together in world space q1,pos1 with q2,pos2. Return result in q1,pos1.
  1081. // 0 returns q1, pos1. 1 returns q2, pos2
  1082. //-----------------------------------------------------------------------------
  1083. void WorldSpaceSlerp(
  1084. const CStudioHdr *pStudioHdr,
  1085. Quaternion q1[MAXSTUDIOBONES],
  1086. Vector pos1[MAXSTUDIOBONES],
  1087. mstudioseqdesc_t &seqdesc,
  1088. int sequence,
  1089. const Quaternion q2[MAXSTUDIOBONES],
  1090. const Vector pos2[MAXSTUDIOBONES],
  1091. float s,
  1092. int boneMask )
  1093. {
  1094. int i, j;
  1095. float s1; // weight of parent for q2, pos2
  1096. float s2; // weight for q2, pos2
  1097. // make fake root transform
  1098. matrix3x4_t rootXform;
  1099. SetIdentityMatrix( rootXform );
  1100. // matrices for q2, pos2
  1101. matrix3x4_t *srcBoneToWorld = g_MatrixPool.Alloc();
  1102. CBoneBitList srcBoneComputed;
  1103. matrix3x4_t *destBoneToWorld = g_MatrixPool.Alloc();
  1104. CBoneBitList destBoneComputed;
  1105. matrix3x4_t *targetBoneToWorld = g_MatrixPool.Alloc();
  1106. CBoneBitList targetBoneComputed;
  1107. virtualmodel_t *pVModel = pStudioHdr->GetVirtualModel();
  1108. const virtualgroup_t *pSeqGroup = NULL;
  1109. if (pVModel)
  1110. {
  1111. pSeqGroup = pVModel->pSeqGroup( sequence );
  1112. }
  1113. mstudiobone_t *pbone = pStudioHdr->pBone( 0 );
  1114. for (i = 0; i < pStudioHdr->numbones(); i++)
  1115. {
  1116. // skip unused bones
  1117. if (!(pStudioHdr->boneFlags(i) & boneMask))
  1118. {
  1119. continue;
  1120. }
  1121. int n = pbone[i].parent;
  1122. s1 = 0.0;
  1123. if (pSeqGroup)
  1124. {
  1125. j = pSeqGroup->boneMap[i];
  1126. if (j >= 0)
  1127. {
  1128. s2 = s * seqdesc.weight( j ); // blend in based on this bones weight
  1129. if (n != -1)
  1130. {
  1131. s1 = s * seqdesc.weight( pSeqGroup->boneMap[n] );
  1132. }
  1133. }
  1134. else
  1135. {
  1136. s2 = 0.0;
  1137. }
  1138. }
  1139. else
  1140. {
  1141. s2 = s * seqdesc.weight( i ); // blend in based on this bones weight
  1142. if (n != -1)
  1143. {
  1144. s1 = s * seqdesc.weight( n );
  1145. }
  1146. }
  1147. if (s1 == 1.0 && s2 == 1.0)
  1148. {
  1149. pos1[i] = pos2[i];
  1150. q1[i] = q2[i];
  1151. }
  1152. else if (s2 > 0.0)
  1153. {
  1154. Quaternion srcQ, destQ;
  1155. Vector srcPos, destPos;
  1156. Quaternion targetQ;
  1157. Vector targetPos;
  1158. Vector tmp;
  1159. BuildBoneChain( pStudioHdr, rootXform, pos1, q1, i, destBoneToWorld, destBoneComputed );
  1160. BuildBoneChain( pStudioHdr, rootXform, pos2, q2, i, srcBoneToWorld, srcBoneComputed );
  1161. MatrixAngles( destBoneToWorld[i], destQ, destPos );
  1162. MatrixAngles( srcBoneToWorld[i], srcQ, srcPos );
  1163. QuaternionSlerp( destQ, srcQ, s2, targetQ );
  1164. AngleMatrix( targetQ, destPos, targetBoneToWorld[i] );
  1165. // back solve
  1166. if (n == -1)
  1167. {
  1168. MatrixAngles( targetBoneToWorld[i], q1[i], tmp );
  1169. }
  1170. else
  1171. {
  1172. matrix3x4_t worldToBone;
  1173. MatrixInvert( targetBoneToWorld[n], worldToBone );
  1174. matrix3x4_t local;
  1175. ConcatTransforms( worldToBone, targetBoneToWorld[i], local );
  1176. MatrixAngles( local, q1[i], tmp );
  1177. // blend bone lengths (local space)
  1178. pos1[i] = Lerp( s2, pos1[i], pos2[i] );
  1179. }
  1180. }
  1181. }
  1182. g_MatrixPool.Free( srcBoneToWorld );
  1183. g_MatrixPool.Free( destBoneToWorld );
  1184. g_MatrixPool.Free( targetBoneToWorld );
  1185. }
  1186. //-----------------------------------------------------------------------------
  1187. // Purpose: blend together q1,pos1 with q2,pos2. Return result in q1,pos1.
  1188. // 0 returns q1, pos1. 1 returns q2, pos2
  1189. //-----------------------------------------------------------------------------
  1190. void SlerpBones(
  1191. const CStudioHdr *pStudioHdr,
  1192. Quaternion q1[MAXSTUDIOBONES],
  1193. Vector pos1[MAXSTUDIOBONES],
  1194. mstudioseqdesc_t &seqdesc, // source of q2 and pos2
  1195. int sequence,
  1196. const QuaternionAligned q2[MAXSTUDIOBONES],
  1197. const Vector pos2[MAXSTUDIOBONES],
  1198. float s,
  1199. int boneMask )
  1200. {
  1201. if (s <= 0.0f)
  1202. return;
  1203. if (s > 1.0f)
  1204. {
  1205. s = 1.0f;
  1206. }
  1207. if (seqdesc.flags & STUDIO_WORLD)
  1208. {
  1209. WorldSpaceSlerp( pStudioHdr, q1, pos1, seqdesc, sequence, q2, pos2, s, boneMask );
  1210. return;
  1211. }
  1212. int i, j;
  1213. virtualmodel_t *pVModel = pStudioHdr->GetVirtualModel();
  1214. const virtualgroup_t *pSeqGroup = NULL;
  1215. if (pVModel)
  1216. {
  1217. pSeqGroup = pVModel->pSeqGroup( sequence );
  1218. }
  1219. // Build weightlist for all bones
  1220. int nBoneCount = pStudioHdr->numbones();
  1221. float *pS2 = (float*)stackalloc( nBoneCount * sizeof(float) );
  1222. for (i = 0; i < nBoneCount; i++)
  1223. {
  1224. // skip unused bones
  1225. if (!(pStudioHdr->boneFlags(i) & boneMask))
  1226. {
  1227. pS2[i] = 0.0f;
  1228. continue;
  1229. }
  1230. if ( !pSeqGroup )
  1231. {
  1232. pS2[i] = s * seqdesc.weight( i ); // blend in based on this bones weight
  1233. continue;
  1234. }
  1235. j = pSeqGroup->boneMap[i];
  1236. if ( j >= 0 )
  1237. {
  1238. pS2[i] = s * seqdesc.weight( j ); // blend in based on this bones weight
  1239. }
  1240. else
  1241. {
  1242. pS2[i] = 0.0;
  1243. }
  1244. }
  1245. float s1, s2;
  1246. if ( seqdesc.flags & STUDIO_DELTA )
  1247. {
  1248. for ( i = 0; i < nBoneCount; i++ )
  1249. {
  1250. s2 = pS2[i];
  1251. if ( s2 <= 0.0f )
  1252. continue;
  1253. if ( seqdesc.flags & STUDIO_POST )
  1254. {
  1255. #ifndef _X360
  1256. QuaternionMA( q1[i], s2, q2[i], q1[i] );
  1257. #else
  1258. fltx4 q1simd = LoadUnalignedSIMD( q1[i].Base() );
  1259. fltx4 q2simd = LoadAlignedSIMD( q2[i] );
  1260. fltx4 result = QuaternionMASIMD( q1simd, s2, q2simd );
  1261. StoreUnalignedSIMD( q1[i].Base(), result );
  1262. #endif
  1263. // FIXME: are these correct?
  1264. pos1[i][0] = pos1[i][0] + pos2[i][0] * s2;
  1265. pos1[i][1] = pos1[i][1] + pos2[i][1] * s2;
  1266. pos1[i][2] = pos1[i][2] + pos2[i][2] * s2;
  1267. }
  1268. else
  1269. {
  1270. #ifndef _X360
  1271. QuaternionSM( s2, q2[i], q1[i], q1[i] );
  1272. #else
  1273. fltx4 q1simd = LoadUnalignedSIMD( q1[i].Base() );
  1274. fltx4 q2simd = LoadAlignedSIMD( q2[i] );
  1275. fltx4 result = QuaternionSMSIMD( s2, q2simd, q1simd );
  1276. StoreUnalignedSIMD( q1[i].Base(), result );
  1277. #endif
  1278. // FIXME: are these correct?
  1279. pos1[i][0] = pos1[i][0] + pos2[i][0] * s2;
  1280. pos1[i][1] = pos1[i][1] + pos2[i][1] * s2;
  1281. pos1[i][2] = pos1[i][2] + pos2[i][2] * s2;
  1282. }
  1283. }
  1284. return;
  1285. }
  1286. QuaternionAligned q3;
  1287. for (i = 0; i < nBoneCount; i++)
  1288. {
  1289. s2 = pS2[i];
  1290. if ( s2 <= 0.0f )
  1291. continue;
  1292. s1 = 1.0 - s2;
  1293. #ifdef _X360
  1294. fltx4 q1simd, q2simd, result;
  1295. q1simd = LoadUnalignedSIMD( q1[i].Base() );
  1296. q2simd = LoadAlignedSIMD( q2[i] );
  1297. #endif
  1298. if ( pStudioHdr->boneFlags(i) & BONE_FIXED_ALIGNMENT )
  1299. {
  1300. #ifndef _X360
  1301. QuaternionSlerpNoAlign( q2[i], q1[i], s1, q3 );
  1302. #else
  1303. result = QuaternionSlerpNoAlignSIMD( q2simd, q1simd, s1 );
  1304. #endif
  1305. }
  1306. else
  1307. {
  1308. #ifndef _X360
  1309. QuaternionSlerp( q2[i], q1[i], s1, q3 );
  1310. #else
  1311. result = QuaternionSlerpSIMD( q2simd, q1simd, s1 );
  1312. #endif
  1313. }
  1314. #ifndef _X360
  1315. q1[i][0] = q3[0];
  1316. q1[i][1] = q3[1];
  1317. q1[i][2] = q3[2];
  1318. q1[i][3] = q3[3];
  1319. #else
  1320. StoreUnalignedSIMD( q1[i].Base(), result );
  1321. #endif
  1322. pos1[i][0] = pos1[i][0] * s1 + pos2[i][0] * s2;
  1323. pos1[i][1] = pos1[i][1] * s1 + pos2[i][1] * s2;
  1324. pos1[i][2] = pos1[i][2] * s1 + pos2[i][2] * s2;
  1325. }
  1326. }
  1327. //-----------------------------------------------------------------------------
  1328. // Purpose: Inter-animation blend. Assumes both types are identical.
  1329. // blend together q1,pos1 with q2,pos2. Return result in q1,pos1.
  1330. // 0 returns q1, pos1. 1 returns q2, pos2
  1331. //-----------------------------------------------------------------------------
  1332. void BlendBones(
  1333. const CStudioHdr *pStudioHdr,
  1334. Quaternion q1[MAXSTUDIOBONES],
  1335. Vector pos1[MAXSTUDIOBONES],
  1336. mstudioseqdesc_t &seqdesc,
  1337. int sequence,
  1338. const Quaternion q2[MAXSTUDIOBONES],
  1339. const Vector pos2[MAXSTUDIOBONES],
  1340. float s,
  1341. int boneMask )
  1342. {
  1343. int i, j;
  1344. Quaternion q3;
  1345. virtualmodel_t *pVModel = pStudioHdr->GetVirtualModel();
  1346. const virtualgroup_t *pSeqGroup = NULL;
  1347. if (pVModel)
  1348. {
  1349. pSeqGroup = pVModel->pSeqGroup( sequence );
  1350. }
  1351. if (s <= 0)
  1352. {
  1353. Assert(0); // shouldn't have been called
  1354. return;
  1355. }
  1356. else if (s >= 1.0)
  1357. {
  1358. Assert(0); // shouldn't have been called
  1359. for (i = 0; i < pStudioHdr->numbones(); i++)
  1360. {
  1361. // skip unused bones
  1362. if (!(pStudioHdr->boneFlags(i) & boneMask))
  1363. {
  1364. continue;
  1365. }
  1366. if (pSeqGroup)
  1367. {
  1368. j = pSeqGroup->boneMap[i];
  1369. }
  1370. else
  1371. {
  1372. j = i;
  1373. }
  1374. if (j >= 0 && seqdesc.weight( j ) > 0.0)
  1375. {
  1376. q1[i] = q2[i];
  1377. pos1[i] = pos2[i];
  1378. }
  1379. }
  1380. return;
  1381. }
  1382. float s2 = s;
  1383. float s1 = 1.0 - s2;
  1384. for (i = 0; i < pStudioHdr->numbones(); i++)
  1385. {
  1386. // skip unused bones
  1387. if (!(pStudioHdr->boneFlags(i) & boneMask))
  1388. {
  1389. continue;
  1390. }
  1391. if (pSeqGroup)
  1392. {
  1393. j = pSeqGroup->boneMap[i];
  1394. }
  1395. else
  1396. {
  1397. j = i;
  1398. }
  1399. if (j >= 0 && seqdesc.weight( j ) > 0.0)
  1400. {
  1401. if (pStudioHdr->boneFlags(i) & BONE_FIXED_ALIGNMENT)
  1402. {
  1403. QuaternionBlendNoAlign( q2[i], q1[i], s1, q3 );
  1404. }
  1405. else
  1406. {
  1407. QuaternionBlend( q2[i], q1[i], s1, q3 );
  1408. }
  1409. q1[i][0] = q3[0];
  1410. q1[i][1] = q3[1];
  1411. q1[i][2] = q3[2];
  1412. q1[i][3] = q3[3];
  1413. pos1[i][0] = pos1[i][0] * s1 + pos2[i][0] * s2;
  1414. pos1[i][1] = pos1[i][1] * s1 + pos2[i][1] * s2;
  1415. pos1[i][2] = pos1[i][2] * s1 + pos2[i][2] * s2;
  1416. }
  1417. }
  1418. }
  1419. //-----------------------------------------------------------------------------
  1420. // Purpose: Scale a set of bones. Must be of type delta
  1421. //-----------------------------------------------------------------------------
  1422. void ScaleBones(
  1423. const CStudioHdr *pStudioHdr,
  1424. Quaternion q1[MAXSTUDIOBONES],
  1425. Vector pos1[MAXSTUDIOBONES],
  1426. int sequence,
  1427. float s,
  1428. int boneMask )
  1429. {
  1430. int i, j;
  1431. Quaternion q3;
  1432. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( sequence );
  1433. virtualmodel_t *pVModel = pStudioHdr->GetVirtualModel();
  1434. const virtualgroup_t *pSeqGroup = NULL;
  1435. if (pVModel)
  1436. {
  1437. pSeqGroup = pVModel->pSeqGroup( sequence );
  1438. }
  1439. float s2 = s;
  1440. float s1 = 1.0 - s2;
  1441. for (i = 0; i < pStudioHdr->numbones(); i++)
  1442. {
  1443. // skip unused bones
  1444. if (!(pStudioHdr->boneFlags(i) & boneMask))
  1445. {
  1446. continue;
  1447. }
  1448. if (pSeqGroup)
  1449. {
  1450. j = pSeqGroup->boneMap[i];
  1451. }
  1452. else
  1453. {
  1454. j = i;
  1455. }
  1456. if (j >= 0 && seqdesc.weight( j ) > 0.0)
  1457. {
  1458. QuaternionIdentityBlend( q1[i], s1, q1[i] );
  1459. VectorScale( pos1[i], s2, pos1[i] );
  1460. }
  1461. }
  1462. }
  1463. //-----------------------------------------------------------------------------
  1464. // Purpose: resolve a global pose parameter to the specific setting for this sequence
  1465. //-----------------------------------------------------------------------------
  1466. void Studio_LocalPoseParameter( const CStudioHdr *pStudioHdr, const float poseParameter[], mstudioseqdesc_t &seqdesc, int iSequence, int iLocalIndex, float &flSetting, int &index )
  1467. {
  1468. if (!pStudioHdr)
  1469. {
  1470. flSetting = 0;
  1471. index = 0;
  1472. return;
  1473. }
  1474. int iPose = pStudioHdr->GetSharedPoseParameter( iSequence, seqdesc.paramindex[iLocalIndex] );
  1475. if (iPose == -1)
  1476. {
  1477. flSetting = 0;
  1478. index = 0;
  1479. return;
  1480. }
  1481. const mstudioposeparamdesc_t &Pose = ((CStudioHdr *)pStudioHdr)->pPoseParameter( iPose );
  1482. float flValue = poseParameter[iPose];
  1483. if (Pose.loop)
  1484. {
  1485. float wrap = (Pose.start + Pose.end) / 2.0 + Pose.loop / 2.0;
  1486. float shift = Pose.loop - wrap;
  1487. flValue = flValue - Pose.loop * floor((flValue + shift) / Pose.loop);
  1488. }
  1489. if (seqdesc.posekeyindex == 0)
  1490. {
  1491. float flLocalStart = ((float)seqdesc.paramstart[iLocalIndex] - Pose.start) / (Pose.end - Pose.start);
  1492. float flLocalEnd = ((float)seqdesc.paramend[iLocalIndex] - Pose.start) / (Pose.end - Pose.start);
  1493. // convert into local range
  1494. flSetting = (flValue - flLocalStart) / (flLocalEnd - flLocalStart);
  1495. // clamp. This shouldn't ever need to happen if it's looping.
  1496. if (flSetting < 0)
  1497. flSetting = 0;
  1498. if (flSetting > 1)
  1499. flSetting = 1;
  1500. index = 0;
  1501. if (seqdesc.groupsize[iLocalIndex] > 2 )
  1502. {
  1503. // estimate index
  1504. index = (int)(flSetting * (seqdesc.groupsize[iLocalIndex] - 1));
  1505. if (index == seqdesc.groupsize[iLocalIndex] - 1) index = seqdesc.groupsize[iLocalIndex] - 2;
  1506. flSetting = flSetting * (seqdesc.groupsize[iLocalIndex] - 1) - index;
  1507. }
  1508. }
  1509. else
  1510. {
  1511. flValue = flValue * (Pose.end - Pose.start) + Pose.start;
  1512. index = 0;
  1513. // FIXME: this needs to be 2D
  1514. // FIXME: this shouldn't be a linear search
  1515. while (1)
  1516. {
  1517. flSetting = (flValue - seqdesc.poseKey( iLocalIndex, index )) / (seqdesc.poseKey( iLocalIndex, index + 1 ) - seqdesc.poseKey( iLocalIndex, index ));
  1518. /*
  1519. if (index > 0 && flSetting < 0.0)
  1520. {
  1521. index--;
  1522. continue;
  1523. }
  1524. else
  1525. */
  1526. if (index < seqdesc.groupsize[iLocalIndex] - 2 && flSetting > 1.0)
  1527. {
  1528. index++;
  1529. continue;
  1530. }
  1531. break;
  1532. }
  1533. // clamp.
  1534. if (flSetting < 0.0f)
  1535. flSetting = 0.0f;
  1536. if (flSetting > 1.0f)
  1537. flSetting = 1.0f;
  1538. }
  1539. }
  1540. void Studio_CalcBoneToBoneTransform( const CStudioHdr *pStudioHdr, int inputBoneIndex, int outputBoneIndex, matrix3x4_t& matrixOut )
  1541. {
  1542. mstudiobone_t *pbone = pStudioHdr->pBone( inputBoneIndex );
  1543. matrix3x4_t inputToPose;
  1544. MatrixInvert( pbone->poseToBone, inputToPose );
  1545. ConcatTransforms( pStudioHdr->pBone( outputBoneIndex )->poseToBone, inputToPose, matrixOut );
  1546. }
  1547. //-----------------------------------------------------------------------------
  1548. // Purpose: calculate a pose for a single sequence
  1549. //-----------------------------------------------------------------------------
  1550. void InitPose(
  1551. const CStudioHdr *pStudioHdr,
  1552. Vector pos[],
  1553. Quaternion q[],
  1554. int boneMask
  1555. )
  1556. {
  1557. if (!pStudioHdr->pLinearBones())
  1558. {
  1559. for (int i = 0; i < pStudioHdr->numbones(); i++)
  1560. {
  1561. if (pStudioHdr->boneFlags( i ) & boneMask )
  1562. {
  1563. mstudiobone_t *pbone = pStudioHdr->pBone( i );
  1564. pos[i] = pbone->pos;
  1565. q[i] = pbone->quat;
  1566. }
  1567. }
  1568. }
  1569. else
  1570. {
  1571. mstudiolinearbone_t *pLinearBones = pStudioHdr->pLinearBones();
  1572. for (int i = 0; i < pStudioHdr->numbones(); i++)
  1573. {
  1574. if (pStudioHdr->boneFlags( i ) & boneMask )
  1575. {
  1576. pos[i] = pLinearBones->pos(i);
  1577. q[i] = pLinearBones->quat(i);
  1578. }
  1579. }
  1580. }
  1581. }
  1582. inline bool PoseIsAllZeros(
  1583. const CStudioHdr *pStudioHdr,
  1584. int sequence,
  1585. mstudioseqdesc_t &seqdesc,
  1586. int i0,
  1587. int i1
  1588. )
  1589. {
  1590. int baseanim;
  1591. // remove "zero" positional blends
  1592. baseanim = pStudioHdr->iRelativeAnim( sequence, seqdesc.anim(i0 ,i1 ) );
  1593. mstudioanimdesc_t &anim = ((CStudioHdr *)pStudioHdr)->pAnimdesc( baseanim );
  1594. return (anim.flags & STUDIO_ALLZEROS) != 0;
  1595. }
  1596. //-----------------------------------------------------------------------------
  1597. // Purpose: turn a 2x2 blend into a 3 way triangle blend
  1598. // Returns: returns the animination indices and barycentric coordinates of a triangle
  1599. // the triangle is a right triangle, and the diagonal is between elements [0] and [2]
  1600. //-----------------------------------------------------------------------------
  1601. static ConVar anim_3wayblend( "anim_3wayblend", "1", FCVAR_REPLICATED, "Toggle the 3-way animation blending code." );
  1602. void Calc3WayBlendIndices( int i0, int i1, float s0, float s1, const mstudioseqdesc_t &seqdesc, int *pAnimIndices, float *pWeight )
  1603. {
  1604. // Figure out which bi-section direction we are using to make triangles.
  1605. bool bEven = ( ( ( i0 + i1 ) & 0x1 ) == 0 );
  1606. int x1, y1;
  1607. int x2, y2;
  1608. int x3, y3;
  1609. // diagonal is between elements 1 & 3
  1610. // TL to BR
  1611. if ( bEven )
  1612. {
  1613. if ( s0 > s1 )
  1614. {
  1615. // B
  1616. x1 = 0; y1 = 0;
  1617. x2 = 1; y2 = 0;
  1618. x3 = 1; y3 = 1;
  1619. pWeight[0] = (1.0f - s0);
  1620. pWeight[1] = s0 - s1;
  1621. }
  1622. else
  1623. {
  1624. // C
  1625. x1 = 1; y1 = 1;
  1626. x2 = 0; y2 = 1;
  1627. x3 = 0; y3 = 0;
  1628. pWeight[0] = s0;
  1629. pWeight[1] = s1 - s0;
  1630. }
  1631. }
  1632. // BL to TR
  1633. else
  1634. {
  1635. float flTotal = s0 + s1;
  1636. if( flTotal > 1.0f )
  1637. {
  1638. // D
  1639. x1 = 1; y1 = 0;
  1640. x2 = 1; y2 = 1;
  1641. x3 = 0; y3 = 1;
  1642. pWeight[0] = (1.0f - s1);
  1643. pWeight[1] = s0 - 1.0f + s1;
  1644. }
  1645. else
  1646. {
  1647. // A
  1648. x1 = 0; y1 = 1;
  1649. x2 = 0; y2 = 0;
  1650. x3 = 1; y3 = 0;
  1651. pWeight[0] = s1;
  1652. pWeight[1] = 1.0f - s0 - s1;
  1653. }
  1654. }
  1655. pAnimIndices[0] = seqdesc.anim( i0 + x1, i1 + y1 );
  1656. pAnimIndices[1] = seqdesc.anim( i0 + x2, i1 + y2 );
  1657. pAnimIndices[2] = seqdesc.anim( i0 + x3, i1 + y3 );
  1658. /*
  1659. float w0 = ((x2-x3)*(y3-s1) - (x3-s0)*(y2-y3)) / ((x1-x3)*(y2-y3) - (x2-x3)*(y1-y3));
  1660. float w1 = ((x1-x3)*(y3-s1) - (x3-s0)*(y1-y3)) / ((x2-x3)*(y1-y3) - (x1-x3)*(y2-y3));
  1661. Assert( pWeight[0] == w0 && pWeight[1] == w1 );
  1662. */
  1663. // clamp the diagonal
  1664. if (pWeight[1] < 0.001f)
  1665. pWeight[1] = 0.0f;
  1666. pWeight[2] = 1.0f - pWeight[0] - pWeight[1];
  1667. Assert( pWeight[0] >= 0.0f && pWeight[0] <= 1.0f );
  1668. Assert( pWeight[1] >= 0.0f && pWeight[1] <= 1.0f );
  1669. Assert( pWeight[2] >= 0.0f && pWeight[2] <= 1.0f );
  1670. }
  1671. //-----------------------------------------------------------------------------
  1672. // Purpose: calculate a pose for a single sequence
  1673. //-----------------------------------------------------------------------------
  1674. bool CalcPoseSingle(
  1675. const CStudioHdr *pStudioHdr,
  1676. Vector pos[],
  1677. Quaternion q[],
  1678. mstudioseqdesc_t &seqdesc,
  1679. int sequence,
  1680. float cycle,
  1681. const float poseParameter[],
  1682. int boneMask,
  1683. float flTime
  1684. )
  1685. {
  1686. bool bResult = true;
  1687. Vector *pos2 = g_VectorPool.Alloc();
  1688. Quaternion *q2 = g_QaternionPool.Alloc();
  1689. Vector *pos3= g_VectorPool.Alloc();
  1690. Quaternion *q3 = g_QaternionPool.Alloc();
  1691. if (sequence >= pStudioHdr->GetNumSeq())
  1692. {
  1693. sequence = 0;
  1694. seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( sequence );
  1695. }
  1696. int i0 = 0, i1 = 0;
  1697. float s0 = 0, s1 = 0;
  1698. Studio_LocalPoseParameter( pStudioHdr, poseParameter, seqdesc, sequence, 0, s0, i0 );
  1699. Studio_LocalPoseParameter( pStudioHdr, poseParameter, seqdesc, sequence, 1, s1, i1 );
  1700. if (seqdesc.flags & STUDIO_REALTIME)
  1701. {
  1702. float cps = Studio_CPS( pStudioHdr, seqdesc, sequence, poseParameter );
  1703. cycle = flTime * cps;
  1704. cycle = cycle - (int)cycle;
  1705. }
  1706. else if (seqdesc.flags & STUDIO_CYCLEPOSE)
  1707. {
  1708. int iPose = pStudioHdr->GetSharedPoseParameter( sequence, seqdesc.cycleposeindex );
  1709. if (iPose != -1)
  1710. {
  1711. /*
  1712. const mstudioposeparamdesc_t &Pose = ((CStudioHdr *)pStudioHdr)->pPoseParameter( iPose );
  1713. cycle = poseParameter[ iPose ] * (Pose.end - Pose.start) + Pose.start;
  1714. */
  1715. cycle = poseParameter[ iPose ];
  1716. }
  1717. else
  1718. {
  1719. cycle = 0.0f;
  1720. }
  1721. }
  1722. else if (cycle < 0 || cycle >= 1)
  1723. {
  1724. if (seqdesc.flags & STUDIO_LOOPING)
  1725. {
  1726. cycle = cycle - (int)cycle;
  1727. if (cycle < 0) cycle += 1;
  1728. }
  1729. else
  1730. {
  1731. cycle = clamp( cycle, 0.0f, 1.0f );
  1732. }
  1733. }
  1734. if (s0 < 0.001)
  1735. {
  1736. if (s1 < 0.001)
  1737. {
  1738. if (PoseIsAllZeros( pStudioHdr, sequence, seqdesc, i0, i1 ))
  1739. {
  1740. bResult = false;
  1741. }
  1742. else
  1743. {
  1744. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0 , i1 ), cycle, boneMask );
  1745. }
  1746. }
  1747. else if (s1 > 0.999)
  1748. {
  1749. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0 , i1+1 ), cycle, boneMask );
  1750. }
  1751. else
  1752. {
  1753. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0 , i1 ), cycle, boneMask );
  1754. CalcAnimation( pStudioHdr, pos2, q2, seqdesc, sequence, seqdesc.anim( i0 , i1+1 ), cycle, boneMask );
  1755. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, s1, boneMask );
  1756. }
  1757. }
  1758. else if (s0 > 0.999)
  1759. {
  1760. if (s1 < 0.001)
  1761. {
  1762. if (PoseIsAllZeros( pStudioHdr, sequence, seqdesc, i0+1, i1 ))
  1763. {
  1764. bResult = false;
  1765. }
  1766. else
  1767. {
  1768. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0+1, i1 ), cycle, boneMask );
  1769. }
  1770. }
  1771. else if (s1 > 0.999)
  1772. {
  1773. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0+1, i1+1 ), cycle, boneMask );
  1774. }
  1775. else
  1776. {
  1777. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0+1, i1 ), cycle, boneMask );
  1778. CalcAnimation( pStudioHdr, pos2, q2, seqdesc, sequence, seqdesc.anim( i0+1, i1+1 ), cycle, boneMask );
  1779. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, s1, boneMask );
  1780. }
  1781. }
  1782. else
  1783. {
  1784. if (s1 < 0.001)
  1785. {
  1786. if (PoseIsAllZeros( pStudioHdr, sequence, seqdesc, i0+1, i1 ))
  1787. {
  1788. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0 ,i1 ), cycle, boneMask );
  1789. ScaleBones( pStudioHdr, q, pos, sequence, 1.0 - s0, boneMask );
  1790. }
  1791. else if (PoseIsAllZeros( pStudioHdr, sequence, seqdesc, i0, i1 ))
  1792. {
  1793. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0+1 ,i1 ), cycle, boneMask );
  1794. ScaleBones( pStudioHdr, q, pos, sequence, s0, boneMask );
  1795. }
  1796. else
  1797. {
  1798. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0 ,i1 ), cycle, boneMask );
  1799. CalcAnimation( pStudioHdr, pos2, q2, seqdesc, sequence, seqdesc.anim( i0+1,i1 ), cycle, boneMask );
  1800. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, s0, boneMask );
  1801. }
  1802. }
  1803. else if (s1 > 0.999)
  1804. {
  1805. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0 ,i1+1 ), cycle, boneMask );
  1806. CalcAnimation( pStudioHdr, pos2, q2, seqdesc, sequence, seqdesc.anim( i0+1,i1+1 ), cycle, boneMask );
  1807. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, s0, boneMask );
  1808. }
  1809. else if ( !anim_3wayblend.GetBool() )
  1810. {
  1811. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, seqdesc.anim( i0 ,i1 ), cycle, boneMask );
  1812. CalcAnimation( pStudioHdr, pos2, q2, seqdesc, sequence, seqdesc.anim( i0+1,i1 ), cycle, boneMask );
  1813. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, s0, boneMask );
  1814. CalcAnimation( pStudioHdr, pos2, q2, seqdesc, sequence, seqdesc.anim( i0 , i1+1), cycle, boneMask );
  1815. CalcAnimation( pStudioHdr, pos3, q3, seqdesc, sequence, seqdesc.anim( i0+1, i1+1), cycle, boneMask );
  1816. BlendBones( pStudioHdr, q2, pos2, seqdesc, sequence, q3, pos3, s0, boneMask );
  1817. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, s1, boneMask );
  1818. }
  1819. else
  1820. {
  1821. int iAnimIndices[3];
  1822. float weight[3];
  1823. Calc3WayBlendIndices( i0, i1, s0, s1, seqdesc, iAnimIndices, weight );
  1824. /*
  1825. char buf[256];
  1826. sprintf( buf, "%d %6.2f %d %6.2f : %6.2f %6.2f %6.2f\n", i0, s0, i1, s1, weight[0], weight[1], weight[2] );
  1827. OutputDebugString( buf );
  1828. */
  1829. if (weight[1] < 0.001)
  1830. {
  1831. // on diagonal
  1832. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, iAnimIndices[0], cycle, boneMask );
  1833. CalcAnimation( pStudioHdr, pos2, q2, seqdesc, sequence, iAnimIndices[2], cycle, boneMask );
  1834. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, weight[2] / (weight[0] + weight[2]), boneMask );
  1835. }
  1836. else
  1837. {
  1838. CalcAnimation( pStudioHdr, pos, q, seqdesc, sequence, iAnimIndices[0], cycle, boneMask );
  1839. CalcAnimation( pStudioHdr, pos2, q2, seqdesc, sequence, iAnimIndices[1], cycle, boneMask );
  1840. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, weight[1] / (weight[0] + weight[1]), boneMask );
  1841. CalcAnimation( pStudioHdr, pos3, q3, seqdesc, sequence, iAnimIndices[2], cycle, boneMask );
  1842. BlendBones( pStudioHdr, q, pos, seqdesc, sequence, q3, pos3, weight[2], boneMask );
  1843. }
  1844. }
  1845. }
  1846. g_VectorPool.Free( pos2 );
  1847. g_QaternionPool.Free( q2 );
  1848. g_VectorPool.Free( pos3 );
  1849. g_QaternionPool.Free( q3 );
  1850. return bResult;
  1851. }
  1852. //-----------------------------------------------------------------------------
  1853. // Purpose: calculate a pose for a single sequence
  1854. // adds autolayers, runs local ik rukes
  1855. //-----------------------------------------------------------------------------
  1856. void CBoneSetup::AddSequenceLayers(
  1857. Vector pos[],
  1858. Quaternion q[],
  1859. mstudioseqdesc_t &seqdesc,
  1860. int sequence,
  1861. float cycle,
  1862. float flWeight,
  1863. float flTime,
  1864. CIKContext *pIKContext
  1865. )
  1866. {
  1867. for (int i = 0; i < seqdesc.numautolayers; i++)
  1868. {
  1869. mstudioautolayer_t *pLayer = seqdesc.pAutolayer( i );
  1870. if (pLayer->flags & STUDIO_AL_LOCAL)
  1871. continue;
  1872. float layerCycle = cycle;
  1873. float layerWeight = flWeight;
  1874. if (pLayer->start != pLayer->end)
  1875. {
  1876. float s = 1.0;
  1877. float index;
  1878. if (!(pLayer->flags & STUDIO_AL_POSE))
  1879. {
  1880. index = cycle;
  1881. }
  1882. else
  1883. {
  1884. int iSequence = m_pStudioHdr->iRelativeSeq( sequence, pLayer->iSequence );
  1885. int iPose = m_pStudioHdr->GetSharedPoseParameter( iSequence, pLayer->iPose );
  1886. if (iPose != -1)
  1887. {
  1888. const mstudioposeparamdesc_t &Pose = ((CStudioHdr *)m_pStudioHdr)->pPoseParameter( iPose );
  1889. index = m_flPoseParameter[ iPose ] * (Pose.end - Pose.start) + Pose.start;
  1890. }
  1891. else
  1892. {
  1893. index = 0;
  1894. }
  1895. }
  1896. if (index < pLayer->start)
  1897. continue;
  1898. if (index >= pLayer->end)
  1899. continue;
  1900. if (index < pLayer->peak && pLayer->start != pLayer->peak)
  1901. {
  1902. s = (index - pLayer->start) / (pLayer->peak - pLayer->start);
  1903. }
  1904. else if (index > pLayer->tail && pLayer->end != pLayer->tail)
  1905. {
  1906. s = (pLayer->end - index) / (pLayer->end - pLayer->tail);
  1907. }
  1908. if (pLayer->flags & STUDIO_AL_SPLINE)
  1909. {
  1910. s = SimpleSpline( s );
  1911. }
  1912. if ((pLayer->flags & STUDIO_AL_XFADE) && (index > pLayer->tail))
  1913. {
  1914. layerWeight = ( s * flWeight ) / ( 1 - flWeight + s * flWeight );
  1915. }
  1916. else if (pLayer->flags & STUDIO_AL_NOBLEND)
  1917. {
  1918. layerWeight = s;
  1919. }
  1920. else
  1921. {
  1922. layerWeight = flWeight * s;
  1923. }
  1924. if (!(pLayer->flags & STUDIO_AL_POSE))
  1925. {
  1926. layerCycle = (cycle - pLayer->start) / (pLayer->end - pLayer->start);
  1927. }
  1928. }
  1929. int iSequence = m_pStudioHdr->iRelativeSeq( sequence, pLayer->iSequence );
  1930. AccumulatePose( pos, q, iSequence, layerCycle, layerWeight, flTime, pIKContext );
  1931. }
  1932. }
  1933. //-----------------------------------------------------------------------------
  1934. // Purpose: calculate a pose for a single sequence
  1935. // adds autolayers, runs local ik rukes
  1936. //-----------------------------------------------------------------------------
  1937. void CBoneSetup::AddLocalLayers(
  1938. Vector pos[],
  1939. Quaternion q[],
  1940. mstudioseqdesc_t &seqdesc,
  1941. int sequence,
  1942. float cycle,
  1943. float flWeight,
  1944. float flTime,
  1945. CIKContext *pIKContext
  1946. )
  1947. {
  1948. if (!(seqdesc.flags & STUDIO_LOCAL))
  1949. {
  1950. return;
  1951. }
  1952. for (int i = 0; i < seqdesc.numautolayers; i++)
  1953. {
  1954. mstudioautolayer_t *pLayer = seqdesc.pAutolayer( i );
  1955. if (!(pLayer->flags & STUDIO_AL_LOCAL))
  1956. continue;
  1957. float layerCycle = cycle;
  1958. float layerWeight = flWeight;
  1959. if (pLayer->start != pLayer->end)
  1960. {
  1961. float s = 1.0;
  1962. if (cycle < pLayer->start)
  1963. continue;
  1964. if (cycle >= pLayer->end)
  1965. continue;
  1966. if (cycle < pLayer->peak && pLayer->start != pLayer->peak)
  1967. {
  1968. s = (cycle - pLayer->start) / (pLayer->peak - pLayer->start);
  1969. }
  1970. else if (cycle > pLayer->tail && pLayer->end != pLayer->tail)
  1971. {
  1972. s = (pLayer->end - cycle) / (pLayer->end - pLayer->tail);
  1973. }
  1974. if (pLayer->flags & STUDIO_AL_SPLINE)
  1975. {
  1976. s = SimpleSpline( s );
  1977. }
  1978. if ((pLayer->flags & STUDIO_AL_XFADE) && (cycle > pLayer->tail))
  1979. {
  1980. layerWeight = ( s * flWeight ) / ( 1 - flWeight + s * flWeight );
  1981. }
  1982. else if (pLayer->flags & STUDIO_AL_NOBLEND)
  1983. {
  1984. layerWeight = s;
  1985. }
  1986. else
  1987. {
  1988. layerWeight = flWeight * s;
  1989. }
  1990. layerCycle = (cycle - pLayer->start) / (pLayer->end - pLayer->start);
  1991. }
  1992. int iSequence = m_pStudioHdr->iRelativeSeq( sequence, pLayer->iSequence );
  1993. AccumulatePose( pos, q, iSequence, layerCycle, layerWeight, flTime, pIKContext );
  1994. }
  1995. }
  1996. //-----------------------------------------------------------------------------
  1997. // Purpose: my sleezy attempt at an interface only class
  1998. //-----------------------------------------------------------------------------
  1999. IBoneSetup::IBoneSetup( const CStudioHdr *pStudioHdr, int boneMask, const float poseParameter[], IPoseDebugger *pPoseDebugger )
  2000. {
  2001. m_pBoneSetup = new CBoneSetup( pStudioHdr, boneMask, poseParameter, pPoseDebugger );
  2002. }
  2003. IBoneSetup::~IBoneSetup( void )
  2004. {
  2005. if ( m_pBoneSetup )
  2006. {
  2007. delete m_pBoneSetup;
  2008. }
  2009. }
  2010. void IBoneSetup::InitPose( Vector pos[], Quaternion q[] )
  2011. {
  2012. ::InitPose( m_pBoneSetup->m_pStudioHdr, pos, q, m_pBoneSetup->m_boneMask );
  2013. }
  2014. void IBoneSetup::AccumulatePose( Vector pos[], Quaternion q[], int sequence, float cycle, float flWeight, float flTime, CIKContext *pIKContext )
  2015. {
  2016. m_pBoneSetup->AccumulatePose( pos, q, sequence, cycle, flWeight, flTime, pIKContext );
  2017. }
  2018. void IBoneSetup::CalcAutoplaySequences( Vector pos[], Quaternion q[], float flRealTime, CIKContext *pIKContext )
  2019. {
  2020. m_pBoneSetup->CalcAutoplaySequences( pos, q, flRealTime, pIKContext );
  2021. }
  2022. void CalcBoneAdj( const CStudioHdr *pStudioHdr, Vector pos[], Quaternion q[], const float controllers[], int boneMask );
  2023. // takes a "controllers[]" array normalized to 0..1 and adds in the adjustments to pos[], and q[].
  2024. void IBoneSetup::CalcBoneAdj( Vector pos[], Quaternion q[], const float controllers[] )
  2025. {
  2026. ::CalcBoneAdj( m_pBoneSetup->m_pStudioHdr, pos, q, controllers, m_pBoneSetup->m_boneMask );
  2027. }
  2028. CStudioHdr *IBoneSetup::GetStudioHdr()
  2029. {
  2030. return (CStudioHdr *)m_pBoneSetup->m_pStudioHdr;
  2031. }
  2032. CBoneSetup::CBoneSetup( const CStudioHdr *pStudioHdr, int boneMask, const float poseParameter[], IPoseDebugger *pPoseDebugger )
  2033. {
  2034. m_pStudioHdr = pStudioHdr;
  2035. m_boneMask = boneMask;
  2036. m_flPoseParameter = poseParameter;
  2037. m_pPoseDebugger = pPoseDebugger;
  2038. }
  2039. #if 0
  2040. //-----------------------------------------------------------------------------
  2041. // Purpose: calculate a pose for a single sequence
  2042. // adds autolayers, runs local ik rukes
  2043. //-----------------------------------------------------------------------------
  2044. void CalcPose(
  2045. const CStudioHdr *pStudioHdr,
  2046. CIKContext *pIKContext,
  2047. Vector pos[],
  2048. Quaternion q[],
  2049. int sequence,
  2050. float cycle,
  2051. const float poseParameter[],
  2052. int boneMask,
  2053. float flWeight,
  2054. float flTime
  2055. )
  2056. {
  2057. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( sequence );
  2058. Assert( flWeight >= 0.0f && flWeight <= 1.0f );
  2059. // This shouldn't be necessary, but the Assert should help us catch whoever is screwing this up
  2060. flWeight = clamp( flWeight, 0.0f, 1.0f );
  2061. // add any IK locks to prevent numautolayers from moving extremities
  2062. CIKContext seq_ik;
  2063. if (seqdesc.numiklocks)
  2064. {
  2065. seq_ik.Init( pStudioHdr, vec3_angle, vec3_origin, 0.0, 0, boneMask ); // local space relative so absolute position doesn't mater
  2066. seq_ik.AddSequenceLocks( seqdesc, pos, q );
  2067. }
  2068. CalcPoseSingle( pStudioHdr, pos, q, seqdesc, sequence, cycle, poseParameter, boneMask, flTime );
  2069. if ( pIKContext )
  2070. {
  2071. pIKContext->AddDependencies( seqdesc, sequence, cycle, poseParameter, flWeight );
  2072. }
  2073. AddSequenceLayers( pStudioHdr, pIKContext, pos, q, seqdesc, sequence, cycle, poseParameter, boneMask, flWeight, flTime );
  2074. if (seqdesc.numiklocks)
  2075. {
  2076. seq_ik.SolveSequenceLocks( seqdesc, pos, q );
  2077. }
  2078. }
  2079. #endif
  2080. //-----------------------------------------------------------------------------
  2081. // Purpose: accumulate a pose for a single sequence on top of existing animation
  2082. // adds autolayers, runs local ik rukes
  2083. //-----------------------------------------------------------------------------
  2084. void CBoneSetup::AccumulatePose(
  2085. Vector pos[],
  2086. Quaternion q[],
  2087. int sequence,
  2088. float cycle,
  2089. float flWeight,
  2090. float flTime,
  2091. CIKContext *pIKContext
  2092. )
  2093. {
  2094. Vector pos2[MAXSTUDIOBONES];
  2095. QuaternionAligned q2[MAXSTUDIOBONES];
  2096. Assert( flWeight >= 0.0f && flWeight <= 1.0f );
  2097. // This shouldn't be necessary, but the Assert should help us catch whoever is screwing this up
  2098. flWeight = clamp( flWeight, 0.0f, 1.0f );
  2099. if ( sequence < 0 )
  2100. return;
  2101. #ifdef CLIENT_DLL
  2102. // Trigger pose debugger
  2103. if (m_pPoseDebugger)
  2104. {
  2105. m_pPoseDebugger->AccumulatePose( m_pStudioHdr, pIKContext, pos, q, sequence, cycle, m_flPoseParameter, m_boneMask, flWeight, flTime );
  2106. }
  2107. #endif
  2108. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)m_pStudioHdr)->pSeqdesc( sequence );
  2109. // add any IK locks to prevent extremities from moving
  2110. CIKContext seq_ik;
  2111. if (seqdesc.numiklocks)
  2112. {
  2113. seq_ik.Init( m_pStudioHdr, vec3_angle, vec3_origin, 0.0, 0, m_boneMask ); // local space relative so absolute position doesn't mater
  2114. seq_ik.AddSequenceLocks( seqdesc, pos, q );
  2115. }
  2116. if (seqdesc.flags & STUDIO_LOCAL)
  2117. {
  2118. ::InitPose( m_pStudioHdr, pos2, q2, m_boneMask );
  2119. }
  2120. if (CalcPoseSingle( m_pStudioHdr, pos2, q2, seqdesc, sequence, cycle, m_flPoseParameter, m_boneMask, flTime ))
  2121. {
  2122. // this weight is wrong, the IK rules won't composite at the correct intensity
  2123. AddLocalLayers( pos2, q2, seqdesc, sequence, cycle, 1.0, flTime, pIKContext );
  2124. SlerpBones( m_pStudioHdr, q, pos, seqdesc, sequence, q2, pos2, flWeight, m_boneMask );
  2125. }
  2126. if ( pIKContext )
  2127. {
  2128. pIKContext->AddDependencies( seqdesc, sequence, cycle, m_flPoseParameter, flWeight );
  2129. }
  2130. AddSequenceLayers( pos, q, seqdesc, sequence, cycle, flWeight, flTime, pIKContext );
  2131. if (seqdesc.numiklocks)
  2132. {
  2133. seq_ik.SolveSequenceLocks( seqdesc, pos, q );
  2134. }
  2135. }
  2136. //-----------------------------------------------------------------------------
  2137. // Purpose: blend together q1,pos1 with q2,pos2. Return result in q1,pos1.
  2138. // 0 returns q1, pos1. 1 returns q2, pos2
  2139. //-----------------------------------------------------------------------------
  2140. void CalcBoneAdj(
  2141. const CStudioHdr *pStudioHdr,
  2142. Vector pos[],
  2143. Quaternion q[],
  2144. const float controllers[],
  2145. int boneMask
  2146. )
  2147. {
  2148. int i, j, k;
  2149. float value;
  2150. mstudiobonecontroller_t *pbonecontroller;
  2151. Vector p0;
  2152. RadianEuler a0;
  2153. Quaternion q0;
  2154. for (j = 0; j < pStudioHdr->numbonecontrollers(); j++)
  2155. {
  2156. pbonecontroller = pStudioHdr->pBonecontroller( j );
  2157. k = pbonecontroller->bone;
  2158. if (pStudioHdr->boneFlags( k ) & boneMask)
  2159. {
  2160. i = pbonecontroller->inputfield;
  2161. value = controllers[i];
  2162. if (value < 0) value = 0;
  2163. if (value > 1.0) value = 1.0;
  2164. value = (1.0 - value) * pbonecontroller->start + value * pbonecontroller->end;
  2165. switch(pbonecontroller->type & STUDIO_TYPES)
  2166. {
  2167. case STUDIO_XR:
  2168. a0.Init( value * (M_PI / 180.0), 0, 0 );
  2169. AngleQuaternion( a0, q0 );
  2170. QuaternionSM( 1.0, q0, q[k], q[k] );
  2171. break;
  2172. case STUDIO_YR:
  2173. a0.Init( 0, value * (M_PI / 180.0), 0 );
  2174. AngleQuaternion( a0, q0 );
  2175. QuaternionSM( 1.0, q0, q[k], q[k] );
  2176. break;
  2177. case STUDIO_ZR:
  2178. a0.Init( 0, 0, value * (M_PI / 180.0) );
  2179. AngleQuaternion( a0, q0 );
  2180. QuaternionSM( 1.0, q0, q[k], q[k] );
  2181. break;
  2182. case STUDIO_X:
  2183. pos[k].x += value;
  2184. break;
  2185. case STUDIO_Y:
  2186. pos[k].y += value;
  2187. break;
  2188. case STUDIO_Z:
  2189. pos[k].z += value;
  2190. break;
  2191. }
  2192. }
  2193. }
  2194. }
  2195. void CalcBoneDerivatives( Vector &velocity, AngularImpulse &angVel, const matrix3x4_t &prev, const matrix3x4_t &current, float dt )
  2196. {
  2197. float scale = 1.0;
  2198. if ( dt > 0 )
  2199. {
  2200. scale = 1.0 / dt;
  2201. }
  2202. Vector endPosition, startPosition, deltaAxis;
  2203. QAngle endAngles, startAngles;
  2204. float deltaAngle;
  2205. MatrixAngles( prev, startAngles, startPosition );
  2206. MatrixAngles( current, endAngles, endPosition );
  2207. velocity.x = (endPosition.x - startPosition.x) * scale;
  2208. velocity.y = (endPosition.y - startPosition.y) * scale;
  2209. velocity.z = (endPosition.z - startPosition.z) * scale;
  2210. RotationDeltaAxisAngle( startAngles, endAngles, deltaAxis, deltaAngle );
  2211. VectorScale( deltaAxis, (deltaAngle * scale), angVel );
  2212. }
  2213. void CalcBoneVelocityFromDerivative( const QAngle &vecAngles, Vector &velocity, AngularImpulse &angVel, const matrix3x4_t &current )
  2214. {
  2215. Vector vecLocalVelocity;
  2216. AngularImpulse LocalAngVel;
  2217. Quaternion q;
  2218. float angle;
  2219. MatrixAngles( current, q, vecLocalVelocity );
  2220. QuaternionAxisAngle( q, LocalAngVel, angle );
  2221. LocalAngVel *= angle;
  2222. matrix3x4_t matAngles;
  2223. AngleMatrix( vecAngles, matAngles );
  2224. VectorTransform( vecLocalVelocity, matAngles, velocity );
  2225. VectorTransform( LocalAngVel, matAngles, angVel );
  2226. }
  2227. class CIKSolver
  2228. {
  2229. public:
  2230. //-------- SOLVE TWO LINK INVERSE KINEMATICS -------------
  2231. // Author: Ken Perlin
  2232. //
  2233. // Given a two link joint from [0,0,0] to end effector position P,
  2234. // let link lengths be a and b, and let norm |P| = c. Clearly a+b <= c.
  2235. //
  2236. // Problem: find a "knee" position Q such that |Q| = a and |P-Q| = b.
  2237. //
  2238. // In the case of a point on the x axis R = [c,0,0], there is a
  2239. // closed form solution S = [d,e,0], where |S| = a and |R-S| = b:
  2240. //
  2241. // d2+e2 = a2 -- because |S| = a
  2242. // (c-d)2+e2 = b2 -- because |R-S| = b
  2243. //
  2244. // c2-2cd+d2+e2 = b2 -- combine the two equations
  2245. // c2-2cd = b2 - a2
  2246. // c-2d = (b2-a2)/c
  2247. // d - c/2 = (a2-b2)/c / 2
  2248. //
  2249. // d = (c + (a2-b2/c) / 2 -- to solve for d and e.
  2250. // e = sqrt(a2-d2)
  2251. static float findD(float a, float b, float c) {
  2252. return (c + (a*a-b*b)/c) / 2;
  2253. }
  2254. static float findE(float a, float d) { return sqrt(a*a-d*d); }
  2255. // This leads to a solution to the more general problem:
  2256. //
  2257. // (1) R = Mfwd(P) -- rotate P onto the x axis
  2258. // (2) Solve for S
  2259. // (3) Q = Minv(S) -- rotate back again
  2260. float Mfwd[3][3];
  2261. float Minv[3][3];
  2262. bool solve(float A, float B, float const P[], float const D[], float Q[]) {
  2263. float R[3];
  2264. defineM(P,D);
  2265. rot(Minv,P,R);
  2266. float r = length(R);
  2267. float d = findD(A,B,r);
  2268. float e = findE(A,d);
  2269. float S[3] = {d,e,0};
  2270. rot(Mfwd,S,Q);
  2271. return d > (r - B) && d < A;
  2272. }
  2273. // If "knee" position Q needs to be as close as possible to some point D,
  2274. // then choose M such that M(D) is in the y>0 half of the z=0 plane.
  2275. //
  2276. // Given that constraint, define the forward and inverse of M as follows:
  2277. void defineM(float const P[], float const D[]) {
  2278. float *X = Minv[0], *Y = Minv[1], *Z = Minv[2];
  2279. // Minv defines a coordinate system whose x axis contains P, so X = unit(P).
  2280. int i;
  2281. for (i = 0 ; i < 3 ; i++)
  2282. X[i] = P[i];
  2283. normalize(X);
  2284. // Its y axis is perpendicular to P, so Y = unit( E - X(E�X) ).
  2285. float dDOTx = dot(D,X);
  2286. for (i = 0 ; i < 3 ; i++)
  2287. Y[i] = D[i] - dDOTx * X[i];
  2288. normalize(Y);
  2289. // Its z axis is perpendicular to both X and Y, so Z = X�Y.
  2290. cross(X,Y,Z);
  2291. // Mfwd = (Minv)T, since transposing inverts a rotation matrix.
  2292. for (i = 0 ; i < 3 ; i++) {
  2293. Mfwd[i][0] = Minv[0][i];
  2294. Mfwd[i][1] = Minv[1][i];
  2295. Mfwd[i][2] = Minv[2][i];
  2296. }
  2297. }
  2298. //------------ GENERAL VECTOR MATH SUPPORT -----------
  2299. static float dot(float const a[], float const b[]) { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]; }
  2300. static float length(float const v[]) { return sqrt( dot(v,v) ); }
  2301. static void normalize(float v[]) {
  2302. float norm = length(v);
  2303. for (int i = 0 ; i < 3 ; i++)
  2304. v[i] /= norm;
  2305. }
  2306. static void cross(float const a[], float const b[], float c[]) {
  2307. c[0] = a[1] * b[2] - a[2] * b[1];
  2308. c[1] = a[2] * b[0] - a[0] * b[2];
  2309. c[2] = a[0] * b[1] - a[1] * b[0];
  2310. }
  2311. static void rot(float const M[3][3], float const src[], float dst[]) {
  2312. for (int i = 0 ; i < 3 ; i++)
  2313. dst[i] = dot(M[i],src);
  2314. }
  2315. };
  2316. //-----------------------------------------------------------------------------
  2317. // Purpose: visual debugging code
  2318. //-----------------------------------------------------------------------------
  2319. #if 1
  2320. inline void debugLine(const Vector& origin, const Vector& dest, int r, int g, int b, bool noDepthTest, float duration) { };
  2321. #else
  2322. extern void drawLine( const Vector &p1, const Vector &p2, int r = 0, int g = 0, int b = 1, bool noDepthTest = true, float duration = 0.1 );
  2323. void debugLine(const Vector& origin, const Vector& dest, int r, int g, int b, bool noDepthTest, float duration)
  2324. {
  2325. drawLine( origin, dest, r, g, b, noDepthTest, duration );
  2326. }
  2327. #endif
  2328. //-----------------------------------------------------------------------------
  2329. // Purpose: for a 2 bone chain, find the IK solution and reset the matrices
  2330. //-----------------------------------------------------------------------------
  2331. bool Studio_SolveIK( mstudioikchain_t *pikchain, Vector &targetFoot, matrix3x4_t *pBoneToWorld )
  2332. {
  2333. if (pikchain->pLink(0)->kneeDir.LengthSqr() > 0.0)
  2334. {
  2335. Vector targetKneeDir, targetKneePos;
  2336. // FIXME: knee length should be as long as the legs
  2337. Vector tmp = pikchain->pLink( 0 )->kneeDir;
  2338. VectorRotate( tmp, pBoneToWorld[ pikchain->pLink( 0 )->bone ], targetKneeDir );
  2339. MatrixPosition( pBoneToWorld[ pikchain->pLink( 1 )->bone ], targetKneePos );
  2340. return Studio_SolveIK( pikchain->pLink( 0 )->bone, pikchain->pLink( 1 )->bone, pikchain->pLink( 2 )->bone, targetFoot, targetKneePos, targetKneeDir, pBoneToWorld );
  2341. }
  2342. else
  2343. {
  2344. return Studio_SolveIK( pikchain->pLink( 0 )->bone, pikchain->pLink( 1 )->bone, pikchain->pLink( 2 )->bone, targetFoot, pBoneToWorld );
  2345. }
  2346. }
  2347. #define KNEEMAX_EPSILON 0.9998 // (0.9998 is about 1 degree)
  2348. //-----------------------------------------------------------------------------
  2349. // Purpose: Solve Knee position for a known hip and foot location, but no specific knee direction preference
  2350. //-----------------------------------------------------------------------------
  2351. bool Studio_SolveIK( int iThigh, int iKnee, int iFoot, Vector &targetFoot, matrix3x4_t *pBoneToWorld )
  2352. {
  2353. Vector worldFoot, worldKnee, worldThigh;
  2354. MatrixPosition( pBoneToWorld[ iThigh ], worldThigh );
  2355. MatrixPosition( pBoneToWorld[ iKnee ], worldKnee );
  2356. MatrixPosition( pBoneToWorld[ iFoot ], worldFoot );
  2357. //debugLine( worldThigh, worldKnee, 0, 0, 255, true, 0 );
  2358. //debugLine( worldKnee, worldFoot, 0, 0, 255, true, 0 );
  2359. Vector ikFoot, ikKnee;
  2360. ikFoot = targetFoot - worldThigh;
  2361. ikKnee = worldKnee - worldThigh;
  2362. float l1 = (worldKnee-worldThigh).Length();
  2363. float l2 = (worldFoot-worldKnee).Length();
  2364. float l3 = (worldFoot-worldThigh).Length();
  2365. // leg too straight to figure out knee?
  2366. if (l3 > (l1 + l2) * KNEEMAX_EPSILON)
  2367. {
  2368. return false;
  2369. }
  2370. Vector ikHalf = (worldFoot-worldThigh) * (l1 / l3);
  2371. // FIXME: what to do when the knee completely straight?
  2372. Vector ikKneeDir = ikKnee - ikHalf;
  2373. VectorNormalize( ikKneeDir );
  2374. return Studio_SolveIK( iThigh, iKnee, iFoot, targetFoot, worldKnee, ikKneeDir, pBoneToWorld );
  2375. }
  2376. //-----------------------------------------------------------------------------
  2377. // Purpose: Realign the matrix so that its X axis points along the desired axis.
  2378. //-----------------------------------------------------------------------------
  2379. void Studio_AlignIKMatrix( matrix3x4_t &mMat, const Vector &vAlignTo )
  2380. {
  2381. Vector tmp1, tmp2, tmp3;
  2382. // Column 0 (X) becomes the vector.
  2383. tmp1 = vAlignTo;
  2384. VectorNormalize( tmp1 );
  2385. MatrixSetColumn( tmp1, 0, mMat );
  2386. // Column 1 (Y) is the cross of the vector and column 2 (Z).
  2387. MatrixGetColumn( mMat, 2, tmp3 );
  2388. tmp2 = tmp3.Cross( tmp1 );
  2389. VectorNormalize( tmp2 );
  2390. // FIXME: check for X being too near to Z
  2391. MatrixSetColumn( tmp2, 1, mMat );
  2392. // Column 2 (Z) is the cross of columns 0 (X) and 1 (Y).
  2393. tmp3 = tmp1.Cross( tmp2 );
  2394. MatrixSetColumn( tmp3, 2, mMat );
  2395. }
  2396. //-----------------------------------------------------------------------------
  2397. // Purpose: Solve Knee position for a known hip and foot location, and a known knee direction
  2398. //-----------------------------------------------------------------------------
  2399. bool Studio_SolveIK( int iThigh, int iKnee, int iFoot, Vector &targetFoot, Vector &targetKneePos, Vector &targetKneeDir, matrix3x4_t *pBoneToWorld )
  2400. {
  2401. Vector worldFoot, worldKnee, worldThigh;
  2402. MatrixPosition( pBoneToWorld[ iThigh ], worldThigh );
  2403. MatrixPosition( pBoneToWorld[ iKnee ], worldKnee );
  2404. MatrixPosition( pBoneToWorld[ iFoot ], worldFoot );
  2405. //debugLine( worldThigh, worldKnee, 0, 0, 255, true, 0 );
  2406. //debugLine( worldThigh, worldThigh + targetKneeDir, 0, 0, 255, true, 0 );
  2407. // debugLine( worldKnee, targetKnee, 0, 0, 255, true, 0 );
  2408. Vector ikFoot, ikTargetKnee, ikKnee;
  2409. ikFoot = targetFoot - worldThigh;
  2410. ikKnee = targetKneePos - worldThigh;
  2411. float l1 = (worldKnee-worldThigh).Length();
  2412. float l2 = (worldFoot-worldKnee).Length();
  2413. // exaggerate knee targets for legs that are nearly straight
  2414. // FIXME: should be configurable, and the ikKnee should be from the original animation, not modifed
  2415. float d = (targetFoot-worldThigh).Length() - min( l1, l2 );
  2416. d = max( l1 + l2, d );
  2417. // FIXME: too short knee directions cause trouble
  2418. d = d * 100;
  2419. ikTargetKnee = ikKnee + targetKneeDir * d;
  2420. // debugLine( worldKnee, worldThigh + ikTargetKnee, 0, 0, 255, true, 0 );
  2421. int color[3] = { 0, 255, 0 };
  2422. // too far away? (0.9998 is about 1 degree)
  2423. if (ikFoot.Length() > (l1 + l2) * KNEEMAX_EPSILON)
  2424. {
  2425. VectorNormalize( ikFoot );
  2426. VectorScale( ikFoot, (l1 + l2) * KNEEMAX_EPSILON, ikFoot );
  2427. color[0] = 255; color[1] = 0; color[2] = 0;
  2428. }
  2429. // too close?
  2430. // limit distance to about an 80 degree knee bend
  2431. float minDist = max( fabs(l1 - l2) * 1.15, min( l1, l2 ) * 0.15 );
  2432. if (ikFoot.Length() < minDist)
  2433. {
  2434. // too close to get an accurate vector, just use original vector
  2435. ikFoot = (worldFoot - worldThigh);
  2436. VectorNormalize( ikFoot );
  2437. VectorScale( ikFoot, minDist, ikFoot );
  2438. }
  2439. CIKSolver ik;
  2440. if (ik.solve( l1, l2, ikFoot.Base(), ikTargetKnee.Base(), ikKnee.Base() ))
  2441. {
  2442. matrix3x4_t& mWorldThigh = pBoneToWorld[ iThigh ];
  2443. matrix3x4_t& mWorldKnee = pBoneToWorld[ iKnee ];
  2444. matrix3x4_t& mWorldFoot = pBoneToWorld[ iFoot ];
  2445. //debugLine( worldThigh, ikKnee + worldThigh, 255, 0, 0, true, 0 );
  2446. //debugLine( ikKnee + worldThigh, ikFoot + worldThigh, 255, 0, 0, true,0 );
  2447. // debugLine( worldThigh, ikKnee + worldThigh, color[0], color[1], color[2], true, 0 );
  2448. // debugLine( ikKnee + worldThigh, ikFoot + worldThigh, color[0], color[1], color[2], true,0 );
  2449. // build transformation matrix for thigh
  2450. Studio_AlignIKMatrix( mWorldThigh, ikKnee );
  2451. Studio_AlignIKMatrix( mWorldKnee, ikFoot - ikKnee );
  2452. mWorldKnee[0][3] = ikKnee.x + worldThigh.x;
  2453. mWorldKnee[1][3] = ikKnee.y + worldThigh.y;
  2454. mWorldKnee[2][3] = ikKnee.z + worldThigh.z;
  2455. mWorldFoot[0][3] = ikFoot.x + worldThigh.x;
  2456. mWorldFoot[1][3] = ikFoot.y + worldThigh.y;
  2457. mWorldFoot[2][3] = ikFoot.z + worldThigh.z;
  2458. return true;
  2459. }
  2460. else
  2461. {
  2462. /*
  2463. debugLine( worldThigh, worldThigh + ikKnee, 255, 0, 0, true, 0 );
  2464. debugLine( worldThigh + ikKnee, worldThigh + ikFoot, 255, 0, 0, true, 0 );
  2465. debugLine( worldThigh + ikFoot, worldThigh, 255, 0, 0, true, 0 );
  2466. debugLine( worldThigh + ikKnee, worldThigh + ikTargetKnee, 255, 0, 0, true, 0 );
  2467. */
  2468. return false;
  2469. }
  2470. }
  2471. //-----------------------------------------------------------------------------
  2472. // Purpose:
  2473. //-----------------------------------------------------------------------------
  2474. float Studio_IKRuleWeight( mstudioikrule_t &ikRule, const mstudioanimdesc_t *panim, float flCycle, int &iFrame, float &fraq )
  2475. {
  2476. if (ikRule.end > 1.0f && flCycle < ikRule.start)
  2477. {
  2478. flCycle = flCycle + 1.0f;
  2479. }
  2480. float value = 0.0f;
  2481. fraq = (panim->numframes - 1) * (flCycle - ikRule.start) + ikRule.iStart;
  2482. iFrame = (int)fraq;
  2483. fraq = fraq - iFrame;
  2484. if (flCycle < ikRule.start)
  2485. {
  2486. iFrame = ikRule.iStart;
  2487. fraq = 0.0f;
  2488. return 0.0f;
  2489. }
  2490. else if (flCycle < ikRule.peak )
  2491. {
  2492. value = (flCycle - ikRule.start) / (ikRule.peak - ikRule.start);
  2493. }
  2494. else if (flCycle < ikRule.tail )
  2495. {
  2496. return 1.0f;
  2497. }
  2498. else if (flCycle < ikRule.end )
  2499. {
  2500. value = 1.0f - ((flCycle - ikRule.tail) / (ikRule.end - ikRule.tail));
  2501. }
  2502. else
  2503. {
  2504. fraq = (panim->numframes - 1) * (ikRule.end - ikRule.start) + ikRule.iStart;
  2505. iFrame = (int)fraq;
  2506. fraq = fraq - iFrame;
  2507. }
  2508. return SimpleSpline( value );
  2509. }
  2510. float Studio_IKRuleWeight( ikcontextikrule_t &ikRule, float flCycle )
  2511. {
  2512. if (ikRule.end > 1.0f && flCycle < ikRule.start)
  2513. {
  2514. flCycle = flCycle + 1.0f;
  2515. }
  2516. float value = 0.0f;
  2517. if (flCycle < ikRule.start)
  2518. {
  2519. return 0.0f;
  2520. }
  2521. else if (flCycle < ikRule.peak )
  2522. {
  2523. value = (flCycle - ikRule.start) / (ikRule.peak - ikRule.start);
  2524. }
  2525. else if (flCycle < ikRule.tail )
  2526. {
  2527. return 1.0f;
  2528. }
  2529. else if (flCycle < ikRule.end )
  2530. {
  2531. value = 1.0f - ((flCycle - ikRule.tail) / (ikRule.end - ikRule.tail));
  2532. }
  2533. return 3.0f * value * value - 2.0f * value * value * value;
  2534. }
  2535. //-----------------------------------------------------------------------------
  2536. // Purpose:
  2537. //-----------------------------------------------------------------------------
  2538. bool Studio_IKShouldLatch( ikcontextikrule_t &ikRule, float flCycle )
  2539. {
  2540. if (ikRule.end > 1.0f && flCycle < ikRule.start)
  2541. {
  2542. flCycle = flCycle + 1.0f;
  2543. }
  2544. if (flCycle < ikRule.peak )
  2545. {
  2546. return false;
  2547. }
  2548. else if (flCycle < ikRule.end )
  2549. {
  2550. return true;
  2551. }
  2552. return false;
  2553. }
  2554. //-----------------------------------------------------------------------------
  2555. // Purpose:
  2556. //-----------------------------------------------------------------------------
  2557. float Studio_IKTail( ikcontextikrule_t &ikRule, float flCycle )
  2558. {
  2559. if (ikRule.end > 1.0f && flCycle < ikRule.start)
  2560. {
  2561. flCycle = flCycle + 1.0f;
  2562. }
  2563. if (flCycle <= ikRule.tail )
  2564. {
  2565. return 0.0f;
  2566. }
  2567. else if (flCycle < ikRule.end )
  2568. {
  2569. return ((flCycle - ikRule.tail) / (ikRule.end - ikRule.tail));
  2570. }
  2571. return 0.0;
  2572. }
  2573. //-----------------------------------------------------------------------------
  2574. // Purpose:
  2575. //-----------------------------------------------------------------------------
  2576. bool Studio_IKAnimationError( const CStudioHdr *pStudioHdr, mstudioikrule_t *pRule, const mstudioanimdesc_t *panim, float flCycle, Vector &pos, Quaternion &q, float &flWeight )
  2577. {
  2578. float fraq;
  2579. int iFrame;
  2580. flWeight = Studio_IKRuleWeight( *pRule, panim, flCycle, iFrame, fraq );
  2581. Assert( fraq >= 0.0 && fraq < 1.0 );
  2582. Assert( flWeight >= 0.0f && flWeight <= 1.0f );
  2583. // This shouldn't be necessary, but the Assert should help us catch whoever is screwing this up
  2584. flWeight = clamp( flWeight, 0.0f, 1.0f );
  2585. if (pRule->type != IK_GROUND && flWeight < 0.0001)
  2586. return false;
  2587. mstudioikerror_t *pError = pRule->pError( iFrame );
  2588. if (pError != NULL)
  2589. {
  2590. if (fraq < 0.001)
  2591. {
  2592. q = pError[0].q;
  2593. pos = pError[0].pos;
  2594. }
  2595. else
  2596. {
  2597. QuaternionBlend( pError[0].q, pError[1].q, fraq, q );
  2598. pos = pError[0].pos * (1.0f - fraq) + pError[1].pos * fraq;
  2599. }
  2600. return true;
  2601. }
  2602. mstudiocompressedikerror_t *pCompressed = pRule->pCompressedError();
  2603. if (pCompressed != NULL)
  2604. {
  2605. CalcDecompressedAnimation( pCompressed, iFrame - pRule->iStart, fraq, pos, q );
  2606. return true;
  2607. }
  2608. // no data, disable IK rule
  2609. Assert( 0 );
  2610. flWeight = 0.0f;
  2611. return false;
  2612. }
  2613. //-----------------------------------------------------------------------------
  2614. // Purpose: For a specific sequence:rule, find where it starts, stops, and what
  2615. // the estimated offset from the connection point is.
  2616. // return true if the rule is within bounds.
  2617. //-----------------------------------------------------------------------------
  2618. bool Studio_IKSequenceError( const CStudioHdr *pStudioHdr, mstudioseqdesc_t &seqdesc, int iSequence, float flCycle, int iRule, const float poseParameter[], mstudioanimdesc_t *panim[4], float weight[4], ikcontextikrule_t &ikRule )
  2619. {
  2620. int i;
  2621. memset( &ikRule, 0, sizeof(ikRule) );
  2622. ikRule.start = ikRule.peak = ikRule.tail = ikRule.end = 0;
  2623. mstudioikrule_t *prevRule = NULL;
  2624. // find overall influence
  2625. for (i = 0; i < 4; i++)
  2626. {
  2627. if (weight[i])
  2628. {
  2629. if (iRule >= panim[i]->numikrules || panim[i]->numikrules != panim[0]->numikrules)
  2630. {
  2631. Assert( 0 );
  2632. return false;
  2633. }
  2634. mstudioikrule_t *pRule = panim[i]->pIKRule( iRule );
  2635. if (pRule == NULL)
  2636. return false;
  2637. float dt = 0.0;
  2638. if (prevRule != NULL)
  2639. {
  2640. if (pRule->start - prevRule->start > 0.5)
  2641. {
  2642. dt = -1.0;
  2643. }
  2644. else if (pRule->start - prevRule->start < -0.5)
  2645. {
  2646. dt = 1.0;
  2647. }
  2648. }
  2649. else
  2650. {
  2651. prevRule = pRule;
  2652. }
  2653. ikRule.start += (pRule->start + dt) * weight[i];
  2654. ikRule.peak += (pRule->peak + dt) * weight[i];
  2655. ikRule.tail += (pRule->tail + dt) * weight[i];
  2656. ikRule.end += (pRule->end + dt) * weight[i];
  2657. }
  2658. }
  2659. if (ikRule.start > 1.0)
  2660. {
  2661. ikRule.start -= 1.0;
  2662. ikRule.peak -= 1.0;
  2663. ikRule.tail -= 1.0;
  2664. ikRule.end -= 1.0;
  2665. }
  2666. else if (ikRule.start < 0.0)
  2667. {
  2668. ikRule.start += 1.0;
  2669. ikRule.peak += 1.0;
  2670. ikRule.tail += 1.0;
  2671. ikRule.end += 1.0;
  2672. }
  2673. ikRule.flWeight = Studio_IKRuleWeight( ikRule, flCycle );
  2674. if (ikRule.flWeight <= 0.001f)
  2675. {
  2676. // go ahead and allow IK_GROUND rules a virtual looping section
  2677. if ( panim[0]->pIKRule( iRule ) == NULL )
  2678. return false;
  2679. if ((panim[0]->flags & STUDIO_LOOPING) && panim[0]->pIKRule( iRule )->type == IK_GROUND && ikRule.end - ikRule.start > 0.75 )
  2680. {
  2681. ikRule.flWeight = 0.001;
  2682. flCycle = ikRule.end - 0.001;
  2683. }
  2684. else
  2685. {
  2686. return false;
  2687. }
  2688. }
  2689. Assert( ikRule.flWeight > 0.0f );
  2690. ikRule.pos.Init();
  2691. ikRule.q.Init();
  2692. // find target error
  2693. float total = 0.0f;
  2694. for (i = 0; i < 4; i++)
  2695. {
  2696. if (weight[i])
  2697. {
  2698. Vector pos1;
  2699. Quaternion q1;
  2700. float w;
  2701. mstudioikrule_t *pRule = panim[i]->pIKRule( iRule );
  2702. if (pRule == NULL)
  2703. return false;
  2704. ikRule.chain = pRule->chain; // FIXME: this is anim local
  2705. ikRule.bone = pRule->bone; // FIXME: this is anim local
  2706. ikRule.type = pRule->type;
  2707. ikRule.slot = pRule->slot;
  2708. ikRule.height += pRule->height * weight[i];
  2709. ikRule.floor += pRule->floor * weight[i];
  2710. ikRule.radius += pRule->radius * weight[i];
  2711. ikRule.drop += pRule->drop * weight[i];
  2712. ikRule.top += pRule->top * weight[i];
  2713. // keep track of tail condition
  2714. ikRule.release += Studio_IKTail( ikRule, flCycle ) * weight[i];
  2715. // only check rules with error values
  2716. switch( ikRule.type )
  2717. {
  2718. case IK_SELF:
  2719. case IK_WORLD:
  2720. case IK_GROUND:
  2721. case IK_ATTACHMENT:
  2722. {
  2723. int bResult = Studio_IKAnimationError( pStudioHdr, pRule, panim[i], flCycle, pos1, q1, w );
  2724. if (bResult)
  2725. {
  2726. ikRule.pos = ikRule.pos + pos1 * weight[i];
  2727. QuaternionAccumulate( ikRule.q, weight[i], q1, ikRule.q );
  2728. total += weight[i];
  2729. }
  2730. }
  2731. break;
  2732. default:
  2733. total += weight[i];
  2734. break;
  2735. }
  2736. ikRule.latched = Studio_IKShouldLatch( ikRule, flCycle ) * ikRule.flWeight;
  2737. if (ikRule.type == IK_ATTACHMENT)
  2738. {
  2739. ikRule.szLabel = pRule->pszAttachment();
  2740. }
  2741. }
  2742. }
  2743. if (total <= 0.0001f)
  2744. {
  2745. return false;
  2746. }
  2747. if (total < 0.999f)
  2748. {
  2749. VectorScale( ikRule.pos, 1.0f / total, ikRule.pos );
  2750. QuaternionScale( ikRule.q, 1.0f / total, ikRule.q );
  2751. }
  2752. if (ikRule.type == IK_SELF && ikRule.bone != -1)
  2753. {
  2754. // FIXME: this is anim local, not seq local!
  2755. ikRule.bone = pStudioHdr->RemapSeqBone( iSequence, ikRule.bone );
  2756. if (ikRule.bone == -1)
  2757. return false;
  2758. }
  2759. QuaternionNormalize( ikRule.q );
  2760. return true;
  2761. }
  2762. //-----------------------------------------------------------------------------
  2763. // Purpose:
  2764. //-----------------------------------------------------------------------------
  2765. CIKContext::CIKContext()
  2766. {
  2767. m_target.EnsureCapacity( 12 ); // FIXME: this sucks, shouldn't it be grown?
  2768. m_iFramecounter = -1;
  2769. m_pStudioHdr = NULL;
  2770. m_flTime = -1.0f;
  2771. m_target.SetSize( 0 );
  2772. }
  2773. void CIKContext::Init( const CStudioHdr *pStudioHdr, const QAngle &angles, const Vector &pos, float flTime, int iFramecounter, int boneMask )
  2774. {
  2775. m_pStudioHdr = pStudioHdr;
  2776. m_ikChainRule.RemoveAll(); // m_numikrules = 0;
  2777. if (pStudioHdr->numikchains())
  2778. {
  2779. m_ikChainRule.SetSize( pStudioHdr->numikchains() );
  2780. // FIXME: Brutal hackery to prevent a crash
  2781. if (m_target.Count() == 0)
  2782. {
  2783. m_target.SetSize(12);
  2784. memset( m_target.Base(), 0, sizeof(m_target[0])*m_target.Count() );
  2785. ClearTargets();
  2786. }
  2787. }
  2788. else
  2789. {
  2790. m_target.SetSize( 0 );
  2791. }
  2792. AngleMatrix( angles, pos, m_rootxform );
  2793. m_iFramecounter = iFramecounter;
  2794. m_flTime = flTime;
  2795. m_boneMask = boneMask;
  2796. }
  2797. void CIKContext::AddDependencies( mstudioseqdesc_t &seqdesc, int iSequence, float flCycle, const float poseParameters[], float flWeight )
  2798. {
  2799. int i;
  2800. if ( m_pStudioHdr->numikchains() == 0)
  2801. return;
  2802. if (seqdesc.numikrules == 0)
  2803. return;
  2804. ikcontextikrule_t ikrule;
  2805. Assert( flWeight >= 0.0f && flWeight <= 1.0f );
  2806. // This shouldn't be necessary, but the Assert should help us catch whoever is screwing this up
  2807. flWeight = clamp( flWeight, 0.0f, 1.0f );
  2808. // unify this
  2809. if (seqdesc.flags & STUDIO_REALTIME)
  2810. {
  2811. float cps = Studio_CPS( m_pStudioHdr, seqdesc, iSequence, poseParameters );
  2812. flCycle = m_flTime * cps;
  2813. flCycle = flCycle - (int)flCycle;
  2814. }
  2815. else if (flCycle < 0 || flCycle >= 1)
  2816. {
  2817. if (seqdesc.flags & STUDIO_LOOPING)
  2818. {
  2819. flCycle = flCycle - (int)flCycle;
  2820. if (flCycle < 0) flCycle += 1;
  2821. }
  2822. else
  2823. {
  2824. flCycle = max( 0.f, min( flCycle, 0.9999f ) );
  2825. }
  2826. }
  2827. mstudioanimdesc_t *panim[4];
  2828. float weight[4];
  2829. Studio_SeqAnims( m_pStudioHdr, seqdesc, iSequence, poseParameters, panim, weight );
  2830. // FIXME: add proper number of rules!!!
  2831. for (i = 0; i < seqdesc.numikrules; i++)
  2832. {
  2833. if ( !Studio_IKSequenceError( m_pStudioHdr, seqdesc, iSequence, flCycle, i, poseParameters, panim, weight, ikrule ) )
  2834. continue;
  2835. // don't add rule if the bone isn't going to be calculated
  2836. int bone = m_pStudioHdr->pIKChain( ikrule.chain )->pLink( 2 )->bone;
  2837. if ( !(m_pStudioHdr->boneFlags( bone ) & m_boneMask))
  2838. continue;
  2839. // or if its relative bone isn't going to be calculated
  2840. if ( ikrule.bone >= 0 && !(m_pStudioHdr->boneFlags( ikrule.bone ) & m_boneMask))
  2841. continue;
  2842. // FIXME: Brutal hackery to prevent a crash
  2843. if (m_target.Count() == 0)
  2844. {
  2845. m_target.SetSize(12);
  2846. memset( m_target.Base(), 0, sizeof(m_target[0])*m_target.Count() );
  2847. ClearTargets();
  2848. }
  2849. ikrule.flRuleWeight = flWeight;
  2850. if (ikrule.flRuleWeight * ikrule.flWeight > 0.999)
  2851. {
  2852. if ( ikrule.type != IK_UNLATCH)
  2853. {
  2854. // clear out chain if rule is 100%
  2855. m_ikChainRule.Element( ikrule.chain ).RemoveAll( );
  2856. if ( ikrule.type == IK_RELEASE)
  2857. {
  2858. continue;
  2859. }
  2860. }
  2861. }
  2862. int nIndex = m_ikChainRule.Element( ikrule.chain ).AddToTail( );
  2863. m_ikChainRule.Element( ikrule.chain ).Element( nIndex ) = ikrule;
  2864. }
  2865. }
  2866. //-----------------------------------------------------------------------------
  2867. // Purpose:
  2868. //-----------------------------------------------------------------------------
  2869. void CIKContext::AddAutoplayLocks( Vector pos[], Quaternion q[] )
  2870. {
  2871. // skip all array access if no autoplay locks.
  2872. if (m_pStudioHdr->GetNumIKAutoplayLocks() == 0)
  2873. {
  2874. return;
  2875. }
  2876. matrix3x4_t *boneToWorld = g_MatrixPool.Alloc();
  2877. CBoneBitList boneComputed;
  2878. int ikOffset = m_ikLock.AddMultipleToTail( m_pStudioHdr->GetNumIKAutoplayLocks() );
  2879. memset( &m_ikLock[ikOffset], 0, sizeof(ikcontextikrule_t)*m_pStudioHdr->GetNumIKAutoplayLocks() );
  2880. for (int i = 0; i < m_pStudioHdr->GetNumIKAutoplayLocks(); i++)
  2881. {
  2882. const mstudioiklock_t &lock = ((CStudioHdr *)m_pStudioHdr)->pIKAutoplayLock( i );
  2883. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( lock.chain );
  2884. int bone = pchain->pLink( 2 )->bone;
  2885. // don't bother with iklock if the bone isn't going to be calculated
  2886. if ( !(m_pStudioHdr->boneFlags( bone ) & m_boneMask))
  2887. continue;
  2888. // eval current ik'd bone
  2889. BuildBoneChain( pos, q, bone, boneToWorld, boneComputed );
  2890. ikcontextikrule_t &ikrule = m_ikLock[ i + ikOffset ];
  2891. ikrule.chain = lock.chain;
  2892. ikrule.slot = i;
  2893. ikrule.type = IK_WORLD;
  2894. MatrixAngles( boneToWorld[bone], ikrule.q, ikrule.pos );
  2895. // save off current knee direction
  2896. if (pchain->pLink(0)->kneeDir.LengthSqr() > 0.0)
  2897. {
  2898. Vector tmp = pchain->pLink( 0 )->kneeDir;
  2899. VectorRotate( pchain->pLink( 0 )->kneeDir, boneToWorld[ pchain->pLink( 0 )->bone ], ikrule.kneeDir );
  2900. MatrixPosition( boneToWorld[ pchain->pLink( 1 )->bone ], ikrule.kneePos );
  2901. }
  2902. else
  2903. {
  2904. ikrule.kneeDir.Init( );
  2905. }
  2906. }
  2907. g_MatrixPool.Free( boneToWorld );
  2908. }
  2909. //-----------------------------------------------------------------------------
  2910. // Purpose:
  2911. //-----------------------------------------------------------------------------
  2912. void CIKContext::AddSequenceLocks( mstudioseqdesc_t &seqdesc, Vector pos[], Quaternion q[] )
  2913. {
  2914. if ( m_pStudioHdr->numikchains() == 0)
  2915. {
  2916. return;
  2917. }
  2918. if ( seqdesc.numiklocks == 0 )
  2919. {
  2920. return;
  2921. }
  2922. matrix3x4_t *boneToWorld = g_MatrixPool.Alloc();
  2923. CBoneBitList boneComputed;
  2924. int ikOffset = m_ikLock.AddMultipleToTail( seqdesc.numiklocks );
  2925. memset( &m_ikLock[ikOffset], 0, sizeof(ikcontextikrule_t) * seqdesc.numiklocks );
  2926. for (int i = 0; i < seqdesc.numiklocks; i++)
  2927. {
  2928. mstudioiklock_t *plock = seqdesc.pIKLock( i );
  2929. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( plock->chain );
  2930. int bone = pchain->pLink( 2 )->bone;
  2931. // don't bother with iklock if the bone isn't going to be calculated
  2932. if ( !(m_pStudioHdr->boneFlags( bone ) & m_boneMask))
  2933. continue;
  2934. // eval current ik'd bone
  2935. BuildBoneChain( pos, q, bone, boneToWorld, boneComputed );
  2936. ikcontextikrule_t &ikrule = m_ikLock[i+ikOffset];
  2937. ikrule.chain = i;
  2938. ikrule.slot = i;
  2939. ikrule.type = IK_WORLD;
  2940. MatrixAngles( boneToWorld[bone], ikrule.q, ikrule.pos );
  2941. // save off current knee direction
  2942. if (pchain->pLink(0)->kneeDir.LengthSqr() > 0.0)
  2943. {
  2944. VectorRotate( pchain->pLink( 0 )->kneeDir, boneToWorld[ pchain->pLink( 0 )->bone ], ikrule.kneeDir );
  2945. }
  2946. else
  2947. {
  2948. ikrule.kneeDir.Init( );
  2949. }
  2950. }
  2951. g_MatrixPool.Free( boneToWorld );
  2952. }
  2953. //-----------------------------------------------------------------------------
  2954. // Purpose: build boneToWorld transforms for a specific bone
  2955. //-----------------------------------------------------------------------------
  2956. void CIKContext::BuildBoneChain(
  2957. const Vector pos[],
  2958. const Quaternion q[],
  2959. int iBone,
  2960. matrix3x4_t *pBoneToWorld,
  2961. CBoneBitList &boneComputed )
  2962. {
  2963. Assert( m_pStudioHdr->boneFlags( iBone ) & m_boneMask );
  2964. ::BuildBoneChain( m_pStudioHdr, m_rootxform, pos, q, iBone, pBoneToWorld, boneComputed );
  2965. }
  2966. //-----------------------------------------------------------------------------
  2967. // Purpose: build boneToWorld transforms for a specific bone
  2968. //-----------------------------------------------------------------------------
  2969. void BuildBoneChain(
  2970. const CStudioHdr *pStudioHdr,
  2971. const matrix3x4_t &rootxform,
  2972. const Vector pos[],
  2973. const Quaternion q[],
  2974. int iBone,
  2975. matrix3x4_t *pBoneToWorld,
  2976. CBoneBitList &boneComputed )
  2977. {
  2978. if ( boneComputed.IsBoneMarked(iBone) )
  2979. return;
  2980. matrix3x4_t bonematrix;
  2981. QuaternionMatrix( q[iBone], pos[iBone], bonematrix );
  2982. int parent = pStudioHdr->boneParent( iBone );
  2983. if (parent == -1)
  2984. {
  2985. ConcatTransforms( rootxform, bonematrix, pBoneToWorld[iBone] );
  2986. }
  2987. else
  2988. {
  2989. // evil recursive!!!
  2990. BuildBoneChain( pStudioHdr, rootxform, pos, q, parent, pBoneToWorld, boneComputed );
  2991. ConcatTransforms( pBoneToWorld[parent], bonematrix, pBoneToWorld[iBone]);
  2992. }
  2993. boneComputed.MarkBone(iBone);
  2994. }
  2995. //-----------------------------------------------------------------------------
  2996. // Purpose: turn a specific bones boneToWorld transform into a pos and q in parents bonespace
  2997. //-----------------------------------------------------------------------------
  2998. void SolveBone(
  2999. const CStudioHdr *pStudioHdr,
  3000. int iBone,
  3001. matrix3x4_t *pBoneToWorld,
  3002. Vector pos[],
  3003. Quaternion q[]
  3004. )
  3005. {
  3006. int iParent = pStudioHdr->boneParent( iBone );
  3007. matrix3x4_t worldToBone;
  3008. MatrixInvert( pBoneToWorld[iParent], worldToBone );
  3009. matrix3x4_t local;
  3010. ConcatTransforms( worldToBone, pBoneToWorld[iBone], local );
  3011. MatrixAngles( local, q[iBone], pos[iBone] );
  3012. }
  3013. //-----------------------------------------------------------------------------
  3014. // Purpose:
  3015. //-----------------------------------------------------------------------------
  3016. void CIKTarget::SetOwner( int entindex, const Vector &pos, const QAngle &angles )
  3017. {
  3018. latched.owner = entindex;
  3019. latched.absOrigin = pos;
  3020. latched.absAngles = angles;
  3021. }
  3022. //-----------------------------------------------------------------------------
  3023. // Purpose:
  3024. //-----------------------------------------------------------------------------
  3025. void CIKTarget::ClearOwner( void )
  3026. {
  3027. latched.owner = -1;
  3028. }
  3029. //-----------------------------------------------------------------------------
  3030. // Purpose:
  3031. //-----------------------------------------------------------------------------
  3032. int CIKTarget::GetOwner( void )
  3033. {
  3034. return latched.owner;
  3035. }
  3036. //-----------------------------------------------------------------------------
  3037. // Purpose: update the latched IK values that are in a moving frame of reference
  3038. //-----------------------------------------------------------------------------
  3039. void CIKTarget::UpdateOwner( int entindex, const Vector &pos, const QAngle &angles )
  3040. {
  3041. if (pos == latched.absOrigin && angles == latched.absAngles)
  3042. return;
  3043. matrix3x4_t in, out;
  3044. AngleMatrix( angles, pos, in );
  3045. AngleIMatrix( latched.absAngles, latched.absOrigin, out );
  3046. matrix3x4_t tmp1, tmp2;
  3047. QuaternionMatrix( latched.q, latched.pos, tmp1 );
  3048. ConcatTransforms( out, tmp1, tmp2 );
  3049. ConcatTransforms( in, tmp2, tmp1 );
  3050. MatrixAngles( tmp1, latched.q, latched.pos );
  3051. }
  3052. //-----------------------------------------------------------------------------
  3053. // Purpose: sets the ground position of an ik target
  3054. //-----------------------------------------------------------------------------
  3055. void CIKTarget::SetPos( const Vector &pos )
  3056. {
  3057. est.pos = pos;
  3058. }
  3059. //-----------------------------------------------------------------------------
  3060. // Purpose: sets the ground "identity" orientation of an ik target
  3061. //-----------------------------------------------------------------------------
  3062. void CIKTarget::SetAngles( const QAngle &angles )
  3063. {
  3064. AngleQuaternion( angles, est.q );
  3065. }
  3066. //-----------------------------------------------------------------------------
  3067. // Purpose: sets the ground "identity" orientation of an ik target
  3068. //-----------------------------------------------------------------------------
  3069. void CIKTarget::SetQuaternion( const Quaternion &q )
  3070. {
  3071. est.q = q;
  3072. }
  3073. //-----------------------------------------------------------------------------
  3074. // Purpose: calculates a ground "identity" orientation based on the surface
  3075. // normal of the ground and the desired ground identity orientation
  3076. //-----------------------------------------------------------------------------
  3077. void CIKTarget::SetNormal( const Vector &normal )
  3078. {
  3079. // recalculate foot angle based on slope of surface
  3080. matrix3x4_t m1;
  3081. Vector forward, right;
  3082. QuaternionMatrix( est.q, m1 );
  3083. MatrixGetColumn( m1, 1, right );
  3084. forward = CrossProduct( right, normal );
  3085. right = CrossProduct( normal, forward );
  3086. MatrixSetColumn( forward, 0, m1 );
  3087. MatrixSetColumn( right, 1, m1 );
  3088. MatrixSetColumn( normal, 2, m1 );
  3089. QAngle a1;
  3090. Vector p1;
  3091. MatrixAngles( m1, est.q, p1 );
  3092. }
  3093. //-----------------------------------------------------------------------------
  3094. // Purpose: estimates the ground impact at the center location assuming a the edge of
  3095. // an Z axis aligned disc collided with it the surface.
  3096. //-----------------------------------------------------------------------------
  3097. void CIKTarget::SetPosWithNormalOffset( const Vector &pos, const Vector &normal )
  3098. {
  3099. // assume it's a disc edge intersecting with the floor, so try to estimate the z location of the center
  3100. est.pos = pos;
  3101. if (normal.z > 0.9999)
  3102. {
  3103. return;
  3104. }
  3105. // clamp at 45 degrees
  3106. else if (normal.z > 0.707)
  3107. {
  3108. // tan == sin / cos
  3109. float tan = sqrt( 1 - normal.z * normal.z ) / normal.z;
  3110. est.pos.z = est.pos.z - est.radius * tan;
  3111. }
  3112. else
  3113. {
  3114. est.pos.z = est.pos.z - est.radius;
  3115. }
  3116. }
  3117. //-----------------------------------------------------------------------------
  3118. // Purpose:
  3119. //-----------------------------------------------------------------------------
  3120. void CIKTarget::SetOnWorld( bool bOnWorld )
  3121. {
  3122. est.onWorld = bOnWorld;
  3123. }
  3124. //-----------------------------------------------------------------------------
  3125. // Purpose:
  3126. //-----------------------------------------------------------------------------
  3127. bool CIKTarget::IsActive()
  3128. {
  3129. return (est.flWeight > 0.0f);
  3130. }
  3131. //-----------------------------------------------------------------------------
  3132. // Purpose:
  3133. //-----------------------------------------------------------------------------
  3134. void CIKTarget::IKFailed( void )
  3135. {
  3136. latched.deltaPos.Init();
  3137. latched.deltaQ.Init();
  3138. latched.pos = ideal.pos;
  3139. latched.q = ideal.q;
  3140. est.latched = 0.0;
  3141. est.flWeight = 0.0;
  3142. est.onWorld = false;
  3143. }
  3144. //-----------------------------------------------------------------------------
  3145. // Purpose:
  3146. //-----------------------------------------------------------------------------
  3147. void CIKTarget::MoveReferenceFrame( Vector &deltaPos, QAngle &deltaAngles )
  3148. {
  3149. est.pos -= deltaPos;
  3150. latched.pos -= deltaPos;
  3151. offset.pos -= deltaPos;
  3152. ideal.pos -= deltaPos;
  3153. }
  3154. //-----------------------------------------------------------------------------
  3155. // Purpose: Invalidate any IK locks.
  3156. //-----------------------------------------------------------------------------
  3157. void CIKContext::ClearTargets( void )
  3158. {
  3159. int i;
  3160. for (i = 0; i < m_target.Count(); i++)
  3161. {
  3162. m_target[i].latched.iFramecounter = -9999;
  3163. }
  3164. }
  3165. //-----------------------------------------------------------------------------
  3166. // Purpose: Run through the rules that survived and turn a specific bones boneToWorld
  3167. // transform into a pos and q in parents bonespace
  3168. //-----------------------------------------------------------------------------
  3169. void CIKContext::UpdateTargets( Vector pos[], Quaternion q[], matrix3x4_t boneToWorld[], CBoneBitList &boneComputed )
  3170. {
  3171. int i, j;
  3172. for (i = 0; i < m_target.Count(); i++)
  3173. {
  3174. m_target[i].est.flWeight = 0.0f;
  3175. m_target[i].est.latched = 1.0f;
  3176. m_target[i].est.release = 1.0f;
  3177. m_target[i].est.height = 0.0f;
  3178. m_target[i].est.floor = 0.0f;
  3179. m_target[i].est.radius = 0.0f;
  3180. m_target[i].offset.pos.Init();
  3181. m_target[i].offset.q.Init();
  3182. }
  3183. AutoIKRelease( );
  3184. for (j = 0; j < m_ikChainRule.Count(); j++)
  3185. {
  3186. for (i = 0; i < m_ikChainRule.Element( j ).Count(); i++)
  3187. {
  3188. ikcontextikrule_t *pRule = &m_ikChainRule.Element( j ).Element( i );
  3189. // ikchainresult_t *pChainRule = &chainRule[ m_ikRule[i].chain ];
  3190. switch( pRule->type )
  3191. {
  3192. case IK_ATTACHMENT:
  3193. case IK_GROUND:
  3194. // case IK_SELF:
  3195. {
  3196. matrix3x4_t footTarget;
  3197. CIKTarget *pTarget = &m_target[pRule->slot];
  3198. pTarget->chain = pRule->chain;
  3199. pTarget->type = pRule->type;
  3200. if (pRule->type == IK_ATTACHMENT)
  3201. {
  3202. pTarget->offset.pAttachmentName = pRule->szLabel;
  3203. }
  3204. else
  3205. {
  3206. pTarget->offset.pAttachmentName = NULL;
  3207. }
  3208. if (pRule->flRuleWeight == 1.0f || pTarget->est.flWeight == 0.0f)
  3209. {
  3210. pTarget->offset.q = pRule->q;
  3211. pTarget->offset.pos = pRule->pos;
  3212. pTarget->est.height = pRule->height;
  3213. pTarget->est.floor = pRule->floor;
  3214. pTarget->est.radius = pRule->radius;
  3215. pTarget->est.latched = pRule->latched * pRule->flRuleWeight;
  3216. pTarget->est.release = pRule->release;
  3217. pTarget->est.flWeight = pRule->flWeight * pRule->flRuleWeight;
  3218. }
  3219. else
  3220. {
  3221. QuaternionSlerp( pTarget->offset.q, pRule->q, pRule->flRuleWeight, pTarget->offset.q );
  3222. pTarget->offset.pos = Lerp( pRule->flRuleWeight, pTarget->offset.pos, pRule->pos );
  3223. pTarget->est.height = Lerp( pRule->flRuleWeight, pTarget->est.height, pRule->height );
  3224. pTarget->est.floor = Lerp( pRule->flRuleWeight, pTarget->est.floor, pRule->floor );
  3225. pTarget->est.radius = Lerp( pRule->flRuleWeight, pTarget->est.radius, pRule->radius );
  3226. //pTarget->est.latched = Lerp( pRule->flRuleWeight, pTarget->est.latched, pRule->latched );
  3227. pTarget->est.latched = min( pTarget->est.latched, pRule->latched );
  3228. pTarget->est.release = Lerp( pRule->flRuleWeight, pTarget->est.release, pRule->release );
  3229. pTarget->est.flWeight = Lerp( pRule->flRuleWeight, pTarget->est.flWeight, pRule->flWeight );
  3230. }
  3231. if ( pRule->type == IK_GROUND )
  3232. {
  3233. pTarget->latched.deltaPos.z = 0;
  3234. pTarget->est.pos.z = pTarget->est.floor + m_rootxform[2][3];
  3235. }
  3236. }
  3237. break;
  3238. case IK_UNLATCH:
  3239. {
  3240. CIKTarget *pTarget = &m_target[pRule->slot];
  3241. if (pRule->latched > 0.0)
  3242. pTarget->est.latched = 0.0;
  3243. else
  3244. pTarget->est.latched = min( pTarget->est.latched, 1.0f - pRule->flWeight );
  3245. }
  3246. break;
  3247. case IK_RELEASE:
  3248. {
  3249. CIKTarget *pTarget = &m_target[pRule->slot];
  3250. if (pRule->latched > 0.0)
  3251. pTarget->est.latched = 0.0;
  3252. else
  3253. pTarget->est.latched = min( pTarget->est.latched, 1.0f - pRule->flWeight );
  3254. pTarget->est.flWeight = (pTarget->est.flWeight) * (1 - pRule->flWeight * pRule->flRuleWeight);
  3255. }
  3256. break;
  3257. }
  3258. }
  3259. }
  3260. for (i = 0; i < m_target.Count(); i++)
  3261. {
  3262. CIKTarget *pTarget = &m_target[i];
  3263. if (pTarget->est.flWeight > 0.0)
  3264. {
  3265. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( pTarget->chain );
  3266. // ikchainresult_t *pChainRule = &chainRule[ i ];
  3267. int bone = pchain->pLink( 2 )->bone;
  3268. // eval current ik'd bone
  3269. BuildBoneChain( pos, q, bone, boneToWorld, boneComputed );
  3270. // xform IK target error into world space
  3271. matrix3x4_t local;
  3272. matrix3x4_t worldFootpad;
  3273. QuaternionMatrix( pTarget->offset.q, pTarget->offset.pos, local );
  3274. MatrixInvert( local, local );
  3275. ConcatTransforms( boneToWorld[bone], local, worldFootpad );
  3276. if (pTarget->est.latched == 1.0)
  3277. {
  3278. pTarget->latched.bNeedsLatch = true;
  3279. }
  3280. else
  3281. {
  3282. pTarget->latched.bNeedsLatch = false;
  3283. }
  3284. // disable latched position if it looks invalid
  3285. if (m_iFramecounter < 0 || pTarget->latched.iFramecounter < m_iFramecounter - 1 || pTarget->latched.iFramecounter > m_iFramecounter)
  3286. {
  3287. pTarget->latched.bHasLatch = false;
  3288. pTarget->latched.influence = 0.0;
  3289. }
  3290. pTarget->latched.iFramecounter = m_iFramecounter;
  3291. // find ideal contact position
  3292. MatrixAngles( worldFootpad, pTarget->ideal.q, pTarget->ideal.pos );
  3293. pTarget->est.q = pTarget->ideal.q;
  3294. pTarget->est.pos = pTarget->ideal.pos;
  3295. float latched = pTarget->est.latched;
  3296. if (pTarget->latched.bHasLatch)
  3297. {
  3298. if (pTarget->est.latched == 1.0)
  3299. {
  3300. // keep track of latch position error from ideal contact position
  3301. pTarget->latched.deltaPos = pTarget->latched.pos - pTarget->est.pos;
  3302. QuaternionSM( -1, pTarget->est.q, pTarget->latched.q, pTarget->latched.deltaQ );
  3303. pTarget->est.q = pTarget->latched.q;
  3304. pTarget->est.pos = pTarget->latched.pos;
  3305. }
  3306. else if (pTarget->est.latched > 0.0)
  3307. {
  3308. // ramp out latch differences during decay phase of rule
  3309. if (latched > 0 && latched < pTarget->latched.influence)
  3310. {
  3311. // latching has decreased
  3312. float dt = pTarget->latched.influence - latched;
  3313. if (pTarget->latched.influence > 0.0)
  3314. dt = dt / pTarget->latched.influence;
  3315. VectorScale( pTarget->latched.deltaPos, (1-dt), pTarget->latched.deltaPos );
  3316. QuaternionScale( pTarget->latched.deltaQ, (1-dt), pTarget->latched.deltaQ );
  3317. }
  3318. // move ideal contact position by latched error factor
  3319. pTarget->est.pos = pTarget->est.pos + pTarget->latched.deltaPos;
  3320. QuaternionMA( pTarget->est.q, 1, pTarget->latched.deltaQ, pTarget->est.q );
  3321. pTarget->latched.q = pTarget->est.q;
  3322. pTarget->latched.pos = pTarget->est.pos;
  3323. }
  3324. else
  3325. {
  3326. pTarget->latched.bHasLatch = false;
  3327. pTarget->latched.q = pTarget->est.q;
  3328. pTarget->latched.pos = pTarget->est.pos;
  3329. pTarget->latched.deltaPos.Init();
  3330. pTarget->latched.deltaQ.Init();
  3331. }
  3332. pTarget->latched.influence = latched;
  3333. }
  3334. // check for illegal requests
  3335. Vector p1, p2, p3;
  3336. MatrixPosition( boneToWorld[pchain->pLink( 0 )->bone], p1 ); // hip
  3337. MatrixPosition( boneToWorld[pchain->pLink( 1 )->bone], p2 ); // knee
  3338. MatrixPosition( boneToWorld[pchain->pLink( 2 )->bone], p3 ); // foot
  3339. float d1 = (p2 - p1).Length();
  3340. float d2 = (p3 - p2).Length();
  3341. if (pTarget->latched.bHasLatch)
  3342. {
  3343. //float d3 = (p3 - p1).Length();
  3344. float d4 = (p3 + pTarget->latched.deltaPos - p1).Length();
  3345. // unstick feet when distance is too great
  3346. if ((d4 < fabs( d1 - d2 ) || d4 * 0.95 > d1 + d2) && pTarget->est.latched > 0.2)
  3347. {
  3348. pTarget->error.flTime = m_flTime;
  3349. }
  3350. // unstick feet when angle is too great
  3351. if (pTarget->est.latched > 0.2)
  3352. {
  3353. float d = fabs( pTarget->latched.deltaQ.w ) * 2.0f - 1.0f; // QuaternionDotProduct( pTarget->latched.q, pTarget->est.q );
  3354. // FIXME: cos(45), make property of chain
  3355. if (d < 0.707)
  3356. {
  3357. pTarget->error.flTime = m_flTime;
  3358. }
  3359. }
  3360. }
  3361. Vector dt = pTarget->est.pos - p1;
  3362. pTarget->trace.hipToFoot = VectorNormalize( dt );
  3363. pTarget->trace.hipToKnee = d1;
  3364. pTarget->trace.kneeToFoot = d2;
  3365. pTarget->trace.hip = p1;
  3366. pTarget->trace.knee = p2;
  3367. pTarget->trace.closest = p1 + dt * (fabs( d1 - d2 ) * 1.01);
  3368. pTarget->trace.farthest = p1 + dt * (d1 + d2) * 0.99;
  3369. pTarget->trace.lowest = p1 + Vector( 0, 0, -1 ) * (d1 + d2) * 0.99;
  3370. // pTarget->trace.endpos = pTarget->est.pos;
  3371. }
  3372. }
  3373. }
  3374. //-----------------------------------------------------------------------------
  3375. // Purpose: insert release rules if the ik rules were in error
  3376. //-----------------------------------------------------------------------------
  3377. void CIKContext::AutoIKRelease( void )
  3378. {
  3379. int i;
  3380. for (i = 0; i < m_target.Count(); i++)
  3381. {
  3382. CIKTarget *pTarget = &m_target[i];
  3383. float dt = m_flTime - pTarget->error.flTime;
  3384. if (pTarget->error.bInError || dt < 0.5)
  3385. {
  3386. if (!pTarget->error.bInError)
  3387. {
  3388. pTarget->error.ramp = 0.0;
  3389. pTarget->error.flErrorTime = pTarget->error.flTime;
  3390. pTarget->error.bInError = true;
  3391. }
  3392. float ft = m_flTime - pTarget->error.flErrorTime;
  3393. if (dt < 0.25)
  3394. {
  3395. pTarget->error.ramp = min( pTarget->error.ramp + ft * 4.0, 1.0 );
  3396. }
  3397. else
  3398. {
  3399. pTarget->error.ramp = max( pTarget->error.ramp - ft * 4.0, 0.0 );
  3400. }
  3401. if (pTarget->error.ramp > 0.0)
  3402. {
  3403. ikcontextikrule_t ikrule;
  3404. ikrule.chain = pTarget->chain;
  3405. ikrule.bone = 0;
  3406. ikrule.type = IK_RELEASE;
  3407. ikrule.slot = i;
  3408. ikrule.flWeight = SimpleSpline( pTarget->error.ramp );
  3409. ikrule.flRuleWeight = 1.0;
  3410. ikrule.latched = dt < 0.25 ? 0.0 : ikrule.flWeight;
  3411. // don't bother with AutoIKRelease if the bone isn't going to be calculated
  3412. // this code is crashing for some unknown reason.
  3413. if ( pTarget->chain >= 0 && pTarget->chain < m_pStudioHdr->numikchains())
  3414. {
  3415. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( pTarget->chain );
  3416. if (pchain != NULL)
  3417. {
  3418. int bone = pchain->pLink( 2 )->bone;
  3419. if (bone >= 0 && bone < m_pStudioHdr->numbones())
  3420. {
  3421. mstudiobone_t *pBone = m_pStudioHdr->pBone( bone );
  3422. if (pBone != NULL)
  3423. {
  3424. if ( !(m_pStudioHdr->boneFlags( bone ) & m_boneMask))
  3425. {
  3426. pTarget->error.bInError = false;
  3427. continue;
  3428. }
  3429. /*
  3430. char buf[256];
  3431. sprintf( buf, "dt %.4f ft %.4f weight %.4f latched %.4f\n", dt, ft, ikrule.flWeight, ikrule.latched );
  3432. OutputDebugString( buf );
  3433. */
  3434. int nIndex = m_ikChainRule.Element( ikrule.chain ).AddToTail( );
  3435. m_ikChainRule.Element( ikrule.chain ).Element( nIndex ) = ikrule;
  3436. }
  3437. else
  3438. {
  3439. DevWarning( 1, "AutoIKRelease (%s) got a NULL pBone %d\n", m_pStudioHdr->pszName(), bone );
  3440. }
  3441. }
  3442. else
  3443. {
  3444. DevWarning( 1, "AutoIKRelease (%s) got an out of range bone %d (%d)\n", m_pStudioHdr->pszName(), bone, m_pStudioHdr->numbones() );
  3445. }
  3446. }
  3447. else
  3448. {
  3449. DevWarning( 1, "AutoIKRelease (%s) got a NULL pchain %d\n", m_pStudioHdr->pszName(), pTarget->chain );
  3450. }
  3451. }
  3452. else
  3453. {
  3454. DevWarning( 1, "AutoIKRelease (%s) got an out of range chain %d (%d)\n", m_pStudioHdr->pszName(), pTarget->chain, m_pStudioHdr->numikchains());
  3455. }
  3456. }
  3457. else
  3458. {
  3459. pTarget->error.bInError = false;
  3460. }
  3461. pTarget->error.flErrorTime = m_flTime;
  3462. }
  3463. }
  3464. }
  3465. void CIKContext::SolveDependencies( Vector pos[], Quaternion q[], matrix3x4_t boneToWorld[], CBoneBitList &boneComputed )
  3466. {
  3467. // ASSERT_NO_REENTRY();
  3468. matrix3x4_t worldTarget;
  3469. int i, j;
  3470. ikchainresult_t chainResult[32]; // allocate!!!
  3471. // init chain rules
  3472. for (i = 0; i < m_pStudioHdr->numikchains(); i++)
  3473. {
  3474. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( i );
  3475. ikchainresult_t *pChainResult = &chainResult[ i ];
  3476. int bone = pchain->pLink( 2 )->bone;
  3477. pChainResult->target = -1;
  3478. pChainResult->flWeight = 0.0;
  3479. // don't bother with chain if the bone isn't going to be calculated
  3480. if ( !(m_pStudioHdr->boneFlags( bone ) & m_boneMask))
  3481. continue;
  3482. // eval current ik'd bone
  3483. BuildBoneChain( pos, q, bone, boneToWorld, boneComputed );
  3484. MatrixAngles( boneToWorld[bone], pChainResult->q, pChainResult->pos );
  3485. }
  3486. for (j = 0; j < m_ikChainRule.Count(); j++)
  3487. {
  3488. for (i = 0; i < m_ikChainRule.Element( j ).Count(); i++)
  3489. {
  3490. ikcontextikrule_t *pRule = &m_ikChainRule.Element( j ).Element( i );
  3491. ikchainresult_t *pChainResult = &chainResult[ pRule->chain ];
  3492. pChainResult->target = -1;
  3493. switch( pRule->type )
  3494. {
  3495. case IK_SELF:
  3496. {
  3497. // xform IK target error into world space
  3498. matrix3x4_t local;
  3499. QuaternionMatrix( pRule->q, pRule->pos, local );
  3500. // eval target bone space
  3501. if (pRule->bone != -1)
  3502. {
  3503. BuildBoneChain( pos, q, pRule->bone, boneToWorld, boneComputed );
  3504. ConcatTransforms( boneToWorld[pRule->bone], local, worldTarget );
  3505. }
  3506. else
  3507. {
  3508. ConcatTransforms( m_rootxform, local, worldTarget );
  3509. }
  3510. float flWeight = pRule->flWeight * pRule->flRuleWeight;
  3511. pChainResult->flWeight = pChainResult->flWeight * (1 - flWeight) + flWeight;
  3512. Vector p2;
  3513. Quaternion q2;
  3514. // target p and q
  3515. MatrixAngles( worldTarget, q2, p2 );
  3516. // debugLine( pChainResult->pos, p2, 0, 0, 255, true, 0.1 );
  3517. // blend in position and angles
  3518. pChainResult->pos = pChainResult->pos * (1.0 - flWeight) + p2 * flWeight;
  3519. QuaternionSlerp( pChainResult->q, q2, flWeight, pChainResult->q );
  3520. }
  3521. break;
  3522. case IK_WORLD:
  3523. Assert( 0 );
  3524. break;
  3525. case IK_ATTACHMENT:
  3526. break;
  3527. case IK_GROUND:
  3528. break;
  3529. case IK_RELEASE:
  3530. {
  3531. // move target back towards original location
  3532. float flWeight = pRule->flWeight * pRule->flRuleWeight;
  3533. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( pRule->chain );
  3534. int bone = pchain->pLink( 2 )->bone;
  3535. Vector p2;
  3536. Quaternion q2;
  3537. BuildBoneChain( pos, q, bone, boneToWorld, boneComputed );
  3538. MatrixAngles( boneToWorld[bone], q2, p2 );
  3539. // blend in position and angles
  3540. pChainResult->pos = pChainResult->pos * (1.0 - flWeight) + p2 * flWeight;
  3541. QuaternionSlerp( pChainResult->q, q2, flWeight, pChainResult->q );
  3542. }
  3543. break;
  3544. case IK_UNLATCH:
  3545. {
  3546. /*
  3547. pChainResult->flWeight = pChainResult->flWeight * (1 - pRule->flWeight) + pRule->flWeight;
  3548. pChainResult->pos = pChainResult->pos * (1.0 - pRule->flWeight ) + pChainResult->local.pos * pRule->flWeight;
  3549. QuaternionSlerp( pChainResult->q, pChainResult->local.q, pRule->flWeight, pChainResult->q );
  3550. */
  3551. }
  3552. break;
  3553. }
  3554. }
  3555. }
  3556. for (i = 0; i < m_target.Count(); i++)
  3557. {
  3558. CIKTarget *pTarget = &m_target[i];
  3559. if (m_target[i].est.flWeight > 0.0)
  3560. {
  3561. matrix3x4_t worldFootpad;
  3562. matrix3x4_t local;
  3563. //mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( m_target[i].chain );
  3564. ikchainresult_t *pChainResult = &chainResult[ pTarget->chain ];
  3565. AngleMatrix(pTarget->offset.q, pTarget->offset.pos, local );
  3566. AngleMatrix( pTarget->est.q, pTarget->est.pos, worldFootpad );
  3567. ConcatTransforms( worldFootpad, local, worldTarget );
  3568. Vector p2;
  3569. Quaternion q2;
  3570. // target p and q
  3571. MatrixAngles( worldTarget, q2, p2 );
  3572. // MatrixAngles( worldTarget, pChainResult->q, pChainResult->pos );
  3573. // blend in position and angles
  3574. pChainResult->flWeight = pTarget->est.flWeight;
  3575. pChainResult->pos = pChainResult->pos * (1.0 - pChainResult->flWeight ) + p2 * pChainResult->flWeight;
  3576. QuaternionSlerp( pChainResult->q, q2, pChainResult->flWeight, pChainResult->q );
  3577. }
  3578. if (pTarget->latched.bNeedsLatch)
  3579. {
  3580. // keep track of latch position
  3581. pTarget->latched.bHasLatch = true;
  3582. pTarget->latched.q = pTarget->est.q;
  3583. pTarget->latched.pos = pTarget->est.pos;
  3584. }
  3585. }
  3586. for (i = 0; i < m_pStudioHdr->numikchains(); i++)
  3587. {
  3588. ikchainresult_t *pChainResult = &chainResult[ i ];
  3589. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( i );
  3590. if (pChainResult->flWeight > 0.0)
  3591. {
  3592. Vector tmp;
  3593. MatrixPosition( boneToWorld[pchain->pLink( 2 )->bone], tmp );
  3594. // debugLine( pChainResult->pos, tmp, 255, 255, 255, true, 0.1 );
  3595. // do exact IK solution
  3596. // FIXME: once per link!
  3597. if (Studio_SolveIK(pchain, pChainResult->pos, boneToWorld ))
  3598. {
  3599. Vector p3;
  3600. MatrixGetColumn( boneToWorld[pchain->pLink( 2 )->bone], 3, p3 );
  3601. QuaternionMatrix( pChainResult->q, p3, boneToWorld[pchain->pLink( 2 )->bone] );
  3602. // rebuild chain
  3603. // FIXME: is this needed if everyone past this uses the boneToWorld array?
  3604. SolveBone( m_pStudioHdr, pchain->pLink( 2 )->bone, boneToWorld, pos, q );
  3605. SolveBone( m_pStudioHdr, pchain->pLink( 1 )->bone, boneToWorld, pos, q );
  3606. SolveBone( m_pStudioHdr, pchain->pLink( 0 )->bone, boneToWorld, pos, q );
  3607. }
  3608. else
  3609. {
  3610. // FIXME: need to invalidate the targets that forced this...
  3611. if (pChainResult->target != -1)
  3612. {
  3613. CIKTarget *pTarget = &m_target[pChainResult->target];
  3614. VectorScale( pTarget->latched.deltaPos, 0.8, pTarget->latched.deltaPos );
  3615. QuaternionScale( pTarget->latched.deltaQ, 0.8, pTarget->latched.deltaQ );
  3616. }
  3617. }
  3618. }
  3619. }
  3620. #if 0
  3621. Vector p1, p2, p3;
  3622. Quaternion q1, q2, q3;
  3623. // current p and q
  3624. MatrixAngles( boneToWorld[bone], q1, p1 );
  3625. // target p and q
  3626. MatrixAngles( worldTarget, q2, p2 );
  3627. // blend in position and angles
  3628. p3 = p1 * (1.0 - m_ikRule[i].flWeight ) + p2 * m_ikRule[i].flWeight;
  3629. // do exact IK solution
  3630. // FIXME: once per link!
  3631. Studio_SolveIK(pchain, p3, boneToWorld );
  3632. // force angle (bad?)
  3633. QuaternionSlerp( q1, q2, m_ikRule[i].flWeight, q3 );
  3634. MatrixGetColumn( boneToWorld[bone], 3, p3 );
  3635. QuaternionMatrix( q3, p3, boneToWorld[bone] );
  3636. // rebuild chain
  3637. SolveBone( m_pStudioHdr, pchain->pLink( 2 )->bone, boneToWorld, pos, q );
  3638. SolveBone( m_pStudioHdr, pchain->pLink( 1 )->bone, boneToWorld, pos, q );
  3639. SolveBone( m_pStudioHdr, pchain->pLink( 0 )->bone, boneToWorld, pos, q );
  3640. #endif
  3641. }
  3642. //-----------------------------------------------------------------------------
  3643. // Purpose:
  3644. //-----------------------------------------------------------------------------
  3645. void CIKContext::SolveAutoplayLocks(
  3646. Vector pos[],
  3647. Quaternion q[]
  3648. )
  3649. {
  3650. matrix3x4_t *boneToWorld = g_MatrixPool.Alloc();
  3651. CBoneBitList boneComputed;
  3652. int i;
  3653. for (i = 0; i < m_ikLock.Count(); i++)
  3654. {
  3655. const mstudioiklock_t &lock = ((CStudioHdr *)m_pStudioHdr)->pIKAutoplayLock( i );
  3656. SolveLock( &lock, i, pos, q, boneToWorld, boneComputed );
  3657. }
  3658. g_MatrixPool.Free( boneToWorld );
  3659. }
  3660. //-----------------------------------------------------------------------------
  3661. // Purpose:
  3662. //-----------------------------------------------------------------------------
  3663. void CIKContext::SolveSequenceLocks(
  3664. mstudioseqdesc_t &seqdesc,
  3665. Vector pos[],
  3666. Quaternion q[]
  3667. )
  3668. {
  3669. matrix3x4_t *boneToWorld = g_MatrixPool.Alloc();
  3670. CBoneBitList boneComputed;
  3671. int i;
  3672. for (i = 0; i < m_ikLock.Count(); i++)
  3673. {
  3674. mstudioiklock_t *plock = seqdesc.pIKLock( i );
  3675. SolveLock( plock, i, pos, q, boneToWorld, boneComputed );
  3676. }
  3677. g_MatrixPool.Free( boneToWorld );
  3678. }
  3679. //-----------------------------------------------------------------------------
  3680. // Purpose:
  3681. //-----------------------------------------------------------------------------
  3682. void CIKContext::AddAllLocks( Vector pos[], Quaternion q[] )
  3683. {
  3684. // skip all array access if no autoplay locks.
  3685. if (m_pStudioHdr->GetNumIKChains() == 0)
  3686. {
  3687. return;
  3688. }
  3689. matrix3x4_t *boneToWorld = g_MatrixPool.Alloc();
  3690. CBoneBitList boneComputed;
  3691. int ikOffset = m_ikLock.AddMultipleToTail( m_pStudioHdr->GetNumIKChains() );
  3692. memset( &m_ikLock[ikOffset], 0, sizeof(ikcontextikrule_t)*m_pStudioHdr->GetNumIKChains() );
  3693. for (int i = 0; i < m_pStudioHdr->GetNumIKChains(); i++)
  3694. {
  3695. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( i );
  3696. int bone = pchain->pLink( 2 )->bone;
  3697. // don't bother with iklock if the bone isn't going to be calculated
  3698. if ( !(m_pStudioHdr->boneFlags( bone ) & m_boneMask))
  3699. continue;
  3700. // eval current ik'd bone
  3701. BuildBoneChain( pos, q, bone, boneToWorld, boneComputed );
  3702. ikcontextikrule_t &ikrule = m_ikLock[ i + ikOffset ];
  3703. ikrule.chain = i;
  3704. ikrule.slot = i;
  3705. ikrule.type = IK_WORLD;
  3706. MatrixAngles( boneToWorld[bone], ikrule.q, ikrule.pos );
  3707. // save off current knee direction
  3708. if (pchain->pLink(0)->kneeDir.LengthSqr() > 0.0)
  3709. {
  3710. Vector tmp = pchain->pLink( 0 )->kneeDir;
  3711. VectorRotate( pchain->pLink( 0 )->kneeDir, boneToWorld[ pchain->pLink( 0 )->bone ], ikrule.kneeDir );
  3712. MatrixPosition( boneToWorld[ pchain->pLink( 1 )->bone ], ikrule.kneePos );
  3713. }
  3714. else
  3715. {
  3716. ikrule.kneeDir.Init( );
  3717. }
  3718. }
  3719. g_MatrixPool.Free( boneToWorld );
  3720. }
  3721. //-----------------------------------------------------------------------------
  3722. // Purpose:
  3723. //-----------------------------------------------------------------------------
  3724. void CIKContext::SolveAllLocks(
  3725. Vector pos[],
  3726. Quaternion q[]
  3727. )
  3728. {
  3729. matrix3x4_t *boneToWorld = g_MatrixPool.Alloc();
  3730. CBoneBitList boneComputed;
  3731. int i;
  3732. mstudioiklock_t lock;
  3733. for (i = 0; i < m_ikLock.Count(); i++)
  3734. {
  3735. lock.chain = i;
  3736. lock.flPosWeight = 1.0;
  3737. lock.flLocalQWeight = 0.0;
  3738. lock.flags = 0;
  3739. SolveLock( &lock, i, pos, q, boneToWorld, boneComputed );
  3740. }
  3741. g_MatrixPool.Free( boneToWorld );
  3742. }
  3743. //-----------------------------------------------------------------------------
  3744. // Purpose:
  3745. //-----------------------------------------------------------------------------
  3746. void CIKContext::SolveLock(
  3747. const mstudioiklock_t *plock,
  3748. int i,
  3749. Vector pos[],
  3750. Quaternion q[],
  3751. matrix3x4_t boneToWorld[],
  3752. CBoneBitList &boneComputed
  3753. )
  3754. {
  3755. mstudioikchain_t *pchain = m_pStudioHdr->pIKChain( plock->chain );
  3756. int bone = pchain->pLink( 2 )->bone;
  3757. // don't bother with iklock if the bone isn't going to be calculated
  3758. if ( !(m_pStudioHdr->boneFlags( bone ) & m_boneMask))
  3759. return;
  3760. // eval current ik'd bone
  3761. BuildBoneChain( pos, q, bone, boneToWorld, boneComputed );
  3762. Vector p1, p2, p3;
  3763. Quaternion q2, q3;
  3764. // current p and q
  3765. MatrixPosition( boneToWorld[bone], p1 );
  3766. // blend in position
  3767. p3 = p1 * (1.0 - plock->flPosWeight ) + m_ikLock[i].pos * plock->flPosWeight;
  3768. // do exact IK solution
  3769. if (m_ikLock[i].kneeDir.LengthSqr() > 0)
  3770. {
  3771. Studio_SolveIK(pchain->pLink( 0 )->bone, pchain->pLink( 1 )->bone, pchain->pLink( 2 )->bone, p3, m_ikLock[i].kneePos, m_ikLock[i].kneeDir, boneToWorld );
  3772. }
  3773. else
  3774. {
  3775. Studio_SolveIK(pchain, p3, boneToWorld );
  3776. }
  3777. // slam orientation
  3778. MatrixPosition( boneToWorld[bone], p3 );
  3779. QuaternionMatrix( m_ikLock[i].q, p3, boneToWorld[bone] );
  3780. // rebuild chain
  3781. q2 = q[ bone ];
  3782. SolveBone( m_pStudioHdr, pchain->pLink( 2 )->bone, boneToWorld, pos, q );
  3783. QuaternionSlerp( q[bone], q2, plock->flLocalQWeight, q[bone] );
  3784. SolveBone( m_pStudioHdr, pchain->pLink( 1 )->bone, boneToWorld, pos, q );
  3785. SolveBone( m_pStudioHdr, pchain->pLink( 0 )->bone, boneToWorld, pos, q );
  3786. }
  3787. //-----------------------------------------------------------------------------
  3788. // Purpose: run all animations that automatically play and are driven off of poseParameters
  3789. //-----------------------------------------------------------------------------
  3790. void CBoneSetup::CalcAutoplaySequences(
  3791. Vector pos[],
  3792. Quaternion q[],
  3793. float flRealTime,
  3794. CIKContext *pIKContext
  3795. )
  3796. {
  3797. // ASSERT_NO_REENTRY();
  3798. int i;
  3799. if ( pIKContext )
  3800. {
  3801. pIKContext->AddAutoplayLocks( pos, q );
  3802. }
  3803. unsigned short *pList = NULL;
  3804. int count = m_pStudioHdr->GetAutoplayList( &pList );
  3805. for (i = 0; i < count; i++)
  3806. {
  3807. int sequenceIndex = pList[i];
  3808. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)m_pStudioHdr)->pSeqdesc( sequenceIndex );
  3809. if (seqdesc.flags & STUDIO_AUTOPLAY)
  3810. {
  3811. float cycle = 0;
  3812. float cps = Studio_CPS( m_pStudioHdr, seqdesc, sequenceIndex, m_flPoseParameter );
  3813. cycle = flRealTime * cps;
  3814. cycle = cycle - (int)cycle;
  3815. AccumulatePose( pos, q, sequenceIndex, cycle, 1.0, flRealTime, pIKContext );
  3816. }
  3817. }
  3818. if ( pIKContext )
  3819. {
  3820. pIKContext->SolveAutoplayLocks( pos, q );
  3821. }
  3822. }
  3823. //-----------------------------------------------------------------------------
  3824. // Purpose:
  3825. //-----------------------------------------------------------------------------
  3826. void Studio_BuildMatrices(
  3827. const CStudioHdr *pStudioHdr,
  3828. const QAngle& angles,
  3829. const Vector& origin,
  3830. const Vector pos[],
  3831. const Quaternion q[],
  3832. int iBone,
  3833. float flScale,
  3834. matrix3x4_t bonetoworld[MAXSTUDIOBONES],
  3835. int boneMask
  3836. )
  3837. {
  3838. int i, j;
  3839. int chain[MAXSTUDIOBONES] = {};
  3840. int chainlength = 0;
  3841. if (iBone < -1 || iBone >= pStudioHdr->numbones())
  3842. iBone = 0;
  3843. // build list of what bones to use
  3844. if (iBone == -1)
  3845. {
  3846. // all bones
  3847. chainlength = pStudioHdr->numbones();
  3848. for (i = 0; i < pStudioHdr->numbones(); i++)
  3849. {
  3850. chain[chainlength - i - 1] = i;
  3851. }
  3852. }
  3853. else
  3854. {
  3855. // only the parent bones
  3856. i = iBone;
  3857. while (i != -1)
  3858. {
  3859. chain[chainlength++] = i;
  3860. i = pStudioHdr->boneParent( i );
  3861. }
  3862. }
  3863. matrix3x4_t bonematrix;
  3864. matrix3x4_t rotationmatrix; // model to world transformation
  3865. AngleMatrix( angles, origin, rotationmatrix );
  3866. // Account for a change in scale
  3867. if ( flScale < 1.0f-FLT_EPSILON || flScale > 1.0f+FLT_EPSILON )
  3868. {
  3869. Vector vecOffset;
  3870. MatrixGetColumn( rotationmatrix, 3, vecOffset );
  3871. vecOffset -= origin;
  3872. vecOffset *= flScale;
  3873. vecOffset += origin;
  3874. MatrixSetColumn( vecOffset, 3, rotationmatrix );
  3875. // Scale it uniformly
  3876. VectorScale( rotationmatrix[0], flScale, rotationmatrix[0] );
  3877. VectorScale( rotationmatrix[1], flScale, rotationmatrix[1] );
  3878. VectorScale( rotationmatrix[2], flScale, rotationmatrix[2] );
  3879. }
  3880. for (j = chainlength - 1; j >= 0; j--)
  3881. {
  3882. i = chain[j];
  3883. if (pStudioHdr->boneFlags(i) & boneMask)
  3884. {
  3885. QuaternionMatrix( q[i], pos[i], bonematrix );
  3886. if (pStudioHdr->boneParent(i) == -1)
  3887. {
  3888. ConcatTransforms (rotationmatrix, bonematrix, bonetoworld[i]);
  3889. }
  3890. else
  3891. {
  3892. ConcatTransforms (bonetoworld[pStudioHdr->boneParent(i)], bonematrix, bonetoworld[i]);
  3893. }
  3894. }
  3895. }
  3896. }
  3897. //-----------------------------------------------------------------------------
  3898. // Purpose: look at single column vector of another bones local transformation
  3899. // and generate a procedural transformation based on how that column
  3900. // points down the 6 cardinal axis (all negative weights are clamped to 0).
  3901. //-----------------------------------------------------------------------------
  3902. void DoAxisInterpBone(
  3903. mstudiobone_t *pbones,
  3904. int ibone,
  3905. CBoneAccessor &bonetoworld
  3906. )
  3907. {
  3908. matrix3x4_t bonematrix;
  3909. Vector control;
  3910. mstudioaxisinterpbone_t *pProc = (mstudioaxisinterpbone_t *)pbones[ibone].pProcedure( );
  3911. const matrix3x4_t &controlBone = bonetoworld.GetBone( pProc->control );
  3912. if (pProc && pbones[pProc->control].parent != -1)
  3913. {
  3914. Vector tmp;
  3915. // pull out the control column
  3916. tmp.x = controlBone[0][pProc->axis];
  3917. tmp.y = controlBone[1][pProc->axis];
  3918. tmp.z = controlBone[2][pProc->axis];
  3919. // invert it back into parent's space.
  3920. VectorIRotate( tmp, bonetoworld.GetBone( pbones[pProc->control].parent ), control );
  3921. #if 0
  3922. matrix3x4_t tmpmatrix;
  3923. matrix3x4_t controlmatrix;
  3924. MatrixInvert( bonetoworld.GetBone( pbones[pProc->control].parent ), tmpmatrix );
  3925. ConcatTransforms( tmpmatrix, bonetoworld.GetBone( pProc->control ), controlmatrix );
  3926. // pull out the control column
  3927. control.x = controlmatrix[0][pProc->axis];
  3928. control.y = controlmatrix[1][pProc->axis];
  3929. control.z = controlmatrix[2][pProc->axis];
  3930. #endif
  3931. }
  3932. else
  3933. {
  3934. // pull out the control column
  3935. control.x = controlBone[0][pProc->axis];
  3936. control.y = controlBone[1][pProc->axis];
  3937. control.z = controlBone[2][pProc->axis];
  3938. }
  3939. Quaternion *q1, *q2, *q3;
  3940. Vector *p1, *p2, *p3;
  3941. // find axial control inputs
  3942. float a1 = control.x;
  3943. float a2 = control.y;
  3944. float a3 = control.z;
  3945. if (a1 >= 0)
  3946. {
  3947. q1 = &pProc->quat[0];
  3948. p1 = &pProc->pos[0];
  3949. }
  3950. else
  3951. {
  3952. a1 = -a1;
  3953. q1 = &pProc->quat[1];
  3954. p1 = &pProc->pos[1];
  3955. }
  3956. if (a2 >= 0)
  3957. {
  3958. q2 = &pProc->quat[2];
  3959. p2 = &pProc->pos[2];
  3960. }
  3961. else
  3962. {
  3963. a2 = -a2;
  3964. q2 = &pProc->quat[3];
  3965. p2 = &pProc->pos[3];
  3966. }
  3967. if (a3 >= 0)
  3968. {
  3969. q3 = &pProc->quat[4];
  3970. p3 = &pProc->pos[4];
  3971. }
  3972. else
  3973. {
  3974. a3 = -a3;
  3975. q3 = &pProc->quat[5];
  3976. p3 = &pProc->pos[5];
  3977. }
  3978. // do a three-way blend
  3979. Vector p;
  3980. Quaternion v, tmp;
  3981. if (a1 + a2 > 0)
  3982. {
  3983. float t = 1.0 / (a1 + a2 + a3);
  3984. // FIXME: do a proper 3-way Quat blend!
  3985. QuaternionSlerp( *q2, *q1, a1 / (a1 + a2), tmp );
  3986. QuaternionSlerp( tmp, *q3, a3 * t, v );
  3987. VectorScale( *p1, a1 * t, p );
  3988. VectorMA( p, a2 * t, *p2, p );
  3989. VectorMA( p, a3 * t, *p3, p );
  3990. }
  3991. else
  3992. {
  3993. QuaternionSlerp( *q3, *q3, 0, v ); // ??? no quat copy?
  3994. p = *p3;
  3995. }
  3996. QuaternionMatrix( v, p, bonematrix );
  3997. ConcatTransforms (bonetoworld.GetBone( pbones[ibone].parent ), bonematrix, bonetoworld.GetBoneForWrite( ibone ));
  3998. }
  3999. //-----------------------------------------------------------------------------
  4000. // Purpose: Generate a procedural transformation based on how that another bones
  4001. // local transformation matches a set of target orientations.
  4002. //-----------------------------------------------------------------------------
  4003. void DoQuatInterpBone(
  4004. mstudiobone_t *pbones,
  4005. int ibone,
  4006. CBoneAccessor &bonetoworld
  4007. )
  4008. {
  4009. matrix3x4_t bonematrix;
  4010. Vector control;
  4011. mstudioquatinterpbone_t *pProc = (mstudioquatinterpbone_t *)pbones[ibone].pProcedure( );
  4012. if (pProc && pbones[pProc->control].parent != -1)
  4013. {
  4014. Quaternion src;
  4015. float weight[32];
  4016. float scale = 0.0;
  4017. Quaternion quat;
  4018. Vector pos;
  4019. matrix3x4_t tmpmatrix;
  4020. matrix3x4_t controlmatrix;
  4021. MatrixInvert( bonetoworld.GetBone( pbones[pProc->control].parent), tmpmatrix );
  4022. ConcatTransforms( tmpmatrix, bonetoworld.GetBone( pProc->control ), controlmatrix );
  4023. MatrixAngles( controlmatrix, src, pos ); // FIXME: make a version without pos
  4024. int i;
  4025. for (i = 0; i < pProc->numtriggers; i++)
  4026. {
  4027. float dot = fabs( QuaternionDotProduct( pProc->pTrigger( i )->trigger, src ) );
  4028. // FIXME: a fast acos should be acceptable
  4029. dot = clamp( dot, -1.f, 1.f );
  4030. weight[i] = 1 - (2 * acos( dot ) * pProc->pTrigger( i )->inv_tolerance );
  4031. weight[i] = max( 0.f, weight[i] );
  4032. scale += weight[i];
  4033. }
  4034. if (scale <= 0.001) // EPSILON?
  4035. {
  4036. AngleMatrix( pProc->pTrigger( 0 )->quat, pProc->pTrigger( 0 )->pos, bonematrix );
  4037. ConcatTransforms ( bonetoworld.GetBone( pbones[ibone].parent ), bonematrix, bonetoworld.GetBoneForWrite( ibone ) );
  4038. return;
  4039. }
  4040. scale = 1.0 / scale;
  4041. quat.Init( 0, 0, 0, 0);
  4042. pos.Init( );
  4043. for (i = 0; i < pProc->numtriggers; i++)
  4044. {
  4045. if (weight[i])
  4046. {
  4047. float s = weight[i] * scale;
  4048. mstudioquatinterpinfo_t *pTrigger = pProc->pTrigger( i );
  4049. QuaternionAlign( pTrigger->quat, quat, quat );
  4050. quat.x = quat.x + s * pTrigger->quat.x;
  4051. quat.y = quat.y + s * pTrigger->quat.y;
  4052. quat.z = quat.z + s * pTrigger->quat.z;
  4053. quat.w = quat.w + s * pTrigger->quat.w;
  4054. pos.x = pos.x + s * pTrigger->pos.x;
  4055. pos.y = pos.y + s * pTrigger->pos.y;
  4056. pos.z = pos.z + s * pTrigger->pos.z;
  4057. }
  4058. }
  4059. Assert( QuaternionNormalize( quat ) != 0);
  4060. QuaternionMatrix( quat, pos, bonematrix );
  4061. }
  4062. ConcatTransforms (bonetoworld.GetBone( pbones[ibone].parent ), bonematrix, bonetoworld.GetBoneForWrite( ibone ));
  4063. }
  4064. /*
  4065. * This is for DoAimAtBone below, was just for testing, not needed in general
  4066. * but to turn it back on, uncomment this and the section in DoAimAtBone() below
  4067. *
  4068. static ConVar aim_constraint( "aim_constraint", "1", FCVAR_REPLICATED, "Toggle <aimconstraint> Helper Bones" );
  4069. */
  4070. //-----------------------------------------------------------------------------
  4071. // Purpose: Generate a procedural transformation so that one bone points at
  4072. // another point on the model
  4073. //-----------------------------------------------------------------------------
  4074. void DoAimAtBone(
  4075. mstudiobone_t *pBones,
  4076. int iBone,
  4077. CBoneAccessor &bonetoworld,
  4078. const CStudioHdr *pStudioHdr
  4079. )
  4080. {
  4081. mstudioaimatbone_t *pProc = (mstudioaimatbone_t *)pBones[iBone].pProcedure();
  4082. if ( !pProc )
  4083. {
  4084. return;
  4085. }
  4086. /*
  4087. * Uncomment this if the ConVar above is uncommented
  4088. *
  4089. if ( !aim_constraint.GetBool() )
  4090. {
  4091. // If the aim constraint is turned off then just copy the parent transform
  4092. // plus the offset value
  4093. matrix3x4_t boneToWorldSpace;
  4094. MatrixCopy ( bonetoworld.GetBone( pProc->parent ), boneToWorldSpace );
  4095. Vector boneWorldPosition;
  4096. VectorTransform( pProc->basepos, boneToWorldSpace, boneWorldPosition );
  4097. MatrixSetColumn( boneWorldPosition, 3, boneToWorldSpace );
  4098. MatrixCopy( boneToWorldSpace, bonetoworld.GetBoneForWrite( iBone ) );
  4099. return;
  4100. }
  4101. */
  4102. // The world matrix of the bone to change
  4103. matrix3x4_t boneMatrix;
  4104. // Guaranteed to be unit length
  4105. const Vector &userAimVector( pProc->aimvector );
  4106. // Guaranteed to be unit length
  4107. const Vector &userUpVector( pProc->upvector );
  4108. // Get to get position of bone but also for up reference
  4109. matrix3x4_t parentSpace;
  4110. MatrixCopy ( bonetoworld.GetBone( pProc->parent ), parentSpace );
  4111. // World space position of the bone to aim
  4112. Vector aimWorldPosition;
  4113. VectorTransform( pProc->basepos, parentSpace, aimWorldPosition );
  4114. // The worldspace matrix of the bone to aim at
  4115. matrix3x4_t aimAtSpace;
  4116. if ( pStudioHdr )
  4117. {
  4118. // This means it's AIMATATTACH
  4119. const mstudioattachment_t &attachment( ((CStudioHdr *)pStudioHdr)->pAttachment( pProc->aim ) );
  4120. ConcatTransforms(
  4121. bonetoworld.GetBone( attachment.localbone ),
  4122. attachment.local,
  4123. aimAtSpace );
  4124. }
  4125. else
  4126. {
  4127. MatrixCopy( bonetoworld.GetBone( pProc->aim ), aimAtSpace );
  4128. }
  4129. Vector aimAtWorldPosition;
  4130. MatrixGetColumn( aimAtSpace, 3, aimAtWorldPosition );
  4131. // make sure the redundant parent info is correct
  4132. Assert( pProc->parent == pBones[iBone].parent );
  4133. // make sure the redundant position info is correct
  4134. Assert( pProc->basepos.DistToSqr( pBones[iBone].pos ) < 0.1 );
  4135. // The aim and up data is relative to this bone, not the parent bone
  4136. matrix3x4_t bonematrix, boneLocalToWorld;
  4137. AngleMatrix( pBones[iBone].quat, pProc->basepos, bonematrix );
  4138. ConcatTransforms( bonetoworld.GetBone( pProc->parent ), bonematrix, boneLocalToWorld );
  4139. Vector aimVector;
  4140. VectorSubtract( aimAtWorldPosition, aimWorldPosition, aimVector );
  4141. VectorNormalizeFast( aimVector );
  4142. Vector axis;
  4143. CrossProduct( userAimVector, aimVector, axis );
  4144. VectorNormalizeFast( axis );
  4145. Assert( 1.0f - fabs( DotProduct( userAimVector, aimVector ) ) > FLT_EPSILON );
  4146. float angle( acosf( DotProduct( userAimVector, aimVector ) ) );
  4147. Quaternion aimRotation;
  4148. AxisAngleQuaternion( axis, RAD2DEG( angle ), aimRotation );
  4149. if ( ( 1.0f - fabs( DotProduct( userUpVector, userAimVector ) ) ) > FLT_EPSILON )
  4150. {
  4151. matrix3x4_t aimRotationMatrix;
  4152. QuaternionMatrix( aimRotation, aimRotationMatrix );
  4153. Vector tmpV;
  4154. Vector tmp_pUp;
  4155. VectorRotate( userUpVector, aimRotationMatrix, tmp_pUp );
  4156. VectorScale( aimVector, DotProduct( aimVector, tmp_pUp ), tmpV );
  4157. Vector pUp;
  4158. VectorSubtract( tmp_pUp, tmpV, pUp );
  4159. VectorNormalizeFast( pUp );
  4160. Vector tmp_pParentUp;
  4161. VectorRotate( userUpVector, boneLocalToWorld, tmp_pParentUp );
  4162. VectorScale( aimVector, DotProduct( aimVector, tmp_pParentUp ), tmpV );
  4163. Vector pParentUp;
  4164. VectorSubtract( tmp_pParentUp, tmpV, pParentUp );
  4165. VectorNormalizeFast( pParentUp );
  4166. Quaternion upRotation;
  4167. //Assert( 1.0f - fabs( DotProduct( pUp, pParentUp ) ) > FLT_EPSILON );
  4168. if( 1.0f - fabs( DotProduct( pUp, pParentUp ) ) > FLT_EPSILON )
  4169. {
  4170. angle = acos( DotProduct( pUp, pParentUp ) );
  4171. CrossProduct( pUp, pParentUp, axis );
  4172. }
  4173. else
  4174. {
  4175. angle = 0;
  4176. axis = pUp;
  4177. }
  4178. VectorNormalizeFast( axis );
  4179. AxisAngleQuaternion( axis, RAD2DEG( angle ), upRotation );
  4180. Quaternion boneRotation;
  4181. QuaternionMult( upRotation, aimRotation, boneRotation );
  4182. QuaternionMatrix( boneRotation, aimWorldPosition, boneMatrix );
  4183. }
  4184. else
  4185. {
  4186. QuaternionMatrix( aimRotation, aimWorldPosition, boneMatrix );
  4187. }
  4188. MatrixCopy( boneMatrix, bonetoworld.GetBoneForWrite( iBone ) );
  4189. }
  4190. //-----------------------------------------------------------------------------
  4191. // Purpose:
  4192. //-----------------------------------------------------------------------------
  4193. bool CalcProceduralBone(
  4194. const CStudioHdr *pStudioHdr,
  4195. int iBone,
  4196. CBoneAccessor &bonetoworld
  4197. )
  4198. {
  4199. mstudiobone_t *pbones = pStudioHdr->pBone( 0 );
  4200. if ( pStudioHdr->boneFlags(iBone) & BONE_ALWAYS_PROCEDURAL )
  4201. {
  4202. switch( pbones[iBone].proctype )
  4203. {
  4204. case STUDIO_PROC_AXISINTERP:
  4205. DoAxisInterpBone( pbones, iBone, bonetoworld );
  4206. return true;
  4207. case STUDIO_PROC_QUATINTERP:
  4208. DoQuatInterpBone( pbones, iBone, bonetoworld );
  4209. return true;
  4210. case STUDIO_PROC_AIMATBONE:
  4211. DoAimAtBone( pbones, iBone, bonetoworld, NULL );
  4212. return true;
  4213. case STUDIO_PROC_AIMATATTACH:
  4214. DoAimAtBone( pbones, iBone, bonetoworld, pStudioHdr );
  4215. return true;
  4216. default:
  4217. return false;
  4218. }
  4219. }
  4220. return false;
  4221. }
  4222. //-----------------------------------------------------------------------------
  4223. // Purpose: Lookup a bone controller
  4224. //-----------------------------------------------------------------------------
  4225. static mstudiobonecontroller_t* FindController( const CStudioHdr *pStudioHdr, int iController)
  4226. {
  4227. // find first controller that matches the index
  4228. for (int i = 0; i < pStudioHdr->numbonecontrollers(); i++)
  4229. {
  4230. if (pStudioHdr->pBonecontroller( i )->inputfield == iController)
  4231. return pStudioHdr->pBonecontroller( i );
  4232. }
  4233. return NULL;
  4234. }
  4235. //-----------------------------------------------------------------------------
  4236. // Purpose: converts a ranged bone controller value into a 0..1 encoded value
  4237. // Output: ctlValue contains 0..1 encoding.
  4238. // returns clamped ranged value
  4239. //-----------------------------------------------------------------------------
  4240. float Studio_SetController( const CStudioHdr *pStudioHdr, int iController, float flValue, float &ctlValue )
  4241. {
  4242. if (! pStudioHdr)
  4243. return flValue;
  4244. mstudiobonecontroller_t *pbonecontroller = FindController(pStudioHdr, iController);
  4245. if(!pbonecontroller)
  4246. {
  4247. ctlValue = 0;
  4248. return flValue;
  4249. }
  4250. // wrap 0..360 if it's a rotational controller
  4251. if (pbonecontroller->type & (STUDIO_XR | STUDIO_YR | STUDIO_ZR))
  4252. {
  4253. // ugly hack, invert value if end < start
  4254. if (pbonecontroller->end < pbonecontroller->start)
  4255. flValue = -flValue;
  4256. // does the controller not wrap?
  4257. if (pbonecontroller->start + 359.0 >= pbonecontroller->end)
  4258. {
  4259. if (flValue > ((pbonecontroller->start + pbonecontroller->end) / 2.0) + 180)
  4260. flValue = flValue - 360;
  4261. if (flValue < ((pbonecontroller->start + pbonecontroller->end) / 2.0) - 180)
  4262. flValue = flValue + 360;
  4263. }
  4264. else
  4265. {
  4266. if (flValue > 360)
  4267. flValue = flValue - (int)(flValue / 360.0) * 360.0;
  4268. else if (flValue < 0)
  4269. flValue = flValue + (int)((flValue / -360.0) + 1) * 360.0;
  4270. }
  4271. }
  4272. ctlValue = (flValue - pbonecontroller->start) / (pbonecontroller->end - pbonecontroller->start);
  4273. if (ctlValue < 0) ctlValue = 0;
  4274. if (ctlValue > 1) ctlValue = 1;
  4275. float flReturnVal = ((1.0 - ctlValue)*pbonecontroller->start + ctlValue *pbonecontroller->end);
  4276. // ugly hack, invert value if a rotational controller and end < start
  4277. if (pbonecontroller->type & (STUDIO_XR | STUDIO_YR | STUDIO_ZR) &&
  4278. pbonecontroller->end < pbonecontroller->start )
  4279. {
  4280. flReturnVal *= -1;
  4281. }
  4282. return flReturnVal;
  4283. }
  4284. //-----------------------------------------------------------------------------
  4285. // Purpose: converts a 0..1 encoded bone controller value into a ranged value
  4286. // Output: returns ranged value
  4287. //-----------------------------------------------------------------------------
  4288. float Studio_GetController( const CStudioHdr *pStudioHdr, int iController, float ctlValue )
  4289. {
  4290. if (!pStudioHdr)
  4291. return 0.0;
  4292. mstudiobonecontroller_t *pbonecontroller = FindController(pStudioHdr, iController);
  4293. if(!pbonecontroller)
  4294. return 0;
  4295. return ctlValue * (pbonecontroller->end - pbonecontroller->start) + pbonecontroller->start;
  4296. }
  4297. //-----------------------------------------------------------------------------
  4298. // Purpose: Calculates default values for the pose parameters
  4299. // Output: fills in an array
  4300. //-----------------------------------------------------------------------------
  4301. void Studio_CalcDefaultPoseParameters( const CStudioHdr *pStudioHdr, float flPoseParameter[], int nCount )
  4302. {
  4303. int nPoseCount = pStudioHdr->GetNumPoseParameters();
  4304. int nNumParams = MIN( nCount, MAXSTUDIOPOSEPARAM );
  4305. for ( int i = 0; i < nNumParams; ++i )
  4306. {
  4307. // Default to middle of the pose parameter range
  4308. flPoseParameter[ i ] = 0.5f;
  4309. if ( i < nPoseCount )
  4310. {
  4311. const mstudioposeparamdesc_t &Pose = ((CStudioHdr *)pStudioHdr)->pPoseParameter( i );
  4312. // Want to try for a zero state. If one doesn't exist set it to .5 by default.
  4313. if ( Pose.start < 0.0f && Pose.end > 0.0f )
  4314. {
  4315. float flPoseDelta = Pose.end - Pose.start;
  4316. flPoseParameter[i] = -Pose.start / flPoseDelta;
  4317. }
  4318. }
  4319. }
  4320. }
  4321. //-----------------------------------------------------------------------------
  4322. // Purpose: converts a ranged pose parameter value into a 0..1 encoded value
  4323. // Output: ctlValue contains 0..1 encoding.
  4324. // returns clamped ranged value
  4325. //-----------------------------------------------------------------------------
  4326. float Studio_SetPoseParameter( const CStudioHdr *pStudioHdr, int iParameter, float flValue, float &ctlValue )
  4327. {
  4328. if (iParameter < 0 || iParameter >= pStudioHdr->GetNumPoseParameters())
  4329. {
  4330. return 0;
  4331. }
  4332. const mstudioposeparamdesc_t &PoseParam = ((CStudioHdr *)pStudioHdr)->pPoseParameter( iParameter );
  4333. Assert( IsFinite( flValue ) );
  4334. if (PoseParam.loop)
  4335. {
  4336. float wrap = (PoseParam.start + PoseParam.end) / 2.0 + PoseParam.loop / 2.0;
  4337. float shift = PoseParam.loop - wrap;
  4338. flValue = flValue - PoseParam.loop * floor((flValue + shift) / PoseParam.loop);
  4339. }
  4340. ctlValue = (flValue - PoseParam.start) / (PoseParam.end - PoseParam.start);
  4341. if (ctlValue < 0) ctlValue = 0;
  4342. if (ctlValue > 1) ctlValue = 1;
  4343. Assert( IsFinite( ctlValue ) );
  4344. return ctlValue * (PoseParam.end - PoseParam.start) + PoseParam.start;
  4345. }
  4346. //-----------------------------------------------------------------------------
  4347. // Purpose: converts a 0..1 encoded pose parameter value into a ranged value
  4348. // Output: returns ranged value
  4349. //-----------------------------------------------------------------------------
  4350. float Studio_GetPoseParameter( const CStudioHdr *pStudioHdr, int iParameter, float ctlValue )
  4351. {
  4352. if (iParameter < 0 || iParameter >= pStudioHdr->GetNumPoseParameters())
  4353. {
  4354. return 0;
  4355. }
  4356. const mstudioposeparamdesc_t &PoseParam = ((CStudioHdr *)pStudioHdr)->pPoseParameter( iParameter );
  4357. return ctlValue * (PoseParam.end - PoseParam.start) + PoseParam.start;
  4358. }
  4359. #pragma warning (disable : 4701)
  4360. //-----------------------------------------------------------------------------
  4361. // Purpose:
  4362. //-----------------------------------------------------------------------------
  4363. static int ClipRayToHitbox( const Ray_t &ray, mstudiobbox_t *pbox, matrix3x4_t& matrix, trace_t &tr )
  4364. {
  4365. const float flProjEpsilon = 0.01f;
  4366. // scale by current t so hits shorten the ray and increase the likelihood of early outs
  4367. Vector delta2;
  4368. VectorScale( ray.m_Delta, (0.5f * tr.fraction), delta2 );
  4369. // OPTIMIZE: Store this in the box instead of computing it here
  4370. // compute center in local space
  4371. Vector boxextents;
  4372. boxextents.x = (pbox->bbmin.x + pbox->bbmax.x) * 0.5;
  4373. boxextents.y = (pbox->bbmin.y + pbox->bbmax.y) * 0.5;
  4374. boxextents.z = (pbox->bbmin.z + pbox->bbmax.z) * 0.5;
  4375. Vector boxCenter;
  4376. // transform to world space
  4377. VectorTransform( boxextents, matrix, boxCenter );
  4378. // calc extents from local center
  4379. boxextents.x = pbox->bbmax.x - boxextents.x;
  4380. boxextents.y = pbox->bbmax.y - boxextents.y;
  4381. boxextents.z = pbox->bbmax.z - boxextents.z;
  4382. // OPTIMIZE: This is optimized for world space. If the transform is fast enough, it may make more
  4383. // sense to just xform and call UTIL_ClipToBox() instead. MEASURE THIS.
  4384. // save the extents of the ray along
  4385. Vector extent, uextent;
  4386. Vector segmentCenter;
  4387. segmentCenter.x = ray.m_Start.x + delta2.x - boxCenter.x;
  4388. segmentCenter.y = ray.m_Start.y + delta2.y - boxCenter.y;
  4389. segmentCenter.z = ray.m_Start.z + delta2.z - boxCenter.z;
  4390. extent.Init();
  4391. // check box axes for separation
  4392. for ( int j = 0; j < 3; j++ )
  4393. {
  4394. extent[j] = delta2.x * matrix[0][j] + delta2.y * matrix[1][j] + delta2.z * matrix[2][j];
  4395. uextent[j] = fabsf(extent[j]);
  4396. float coord = segmentCenter.x * matrix[0][j] + segmentCenter.y * matrix[1][j] + segmentCenter.z * matrix[2][j];
  4397. coord = fabsf(coord);
  4398. if ( coord > (boxextents[j] + uextent[j]) )
  4399. return -1;
  4400. }
  4401. // now check cross axes for separation
  4402. float tmp, tmpfix, cextent;
  4403. Vector cross;
  4404. CrossProduct( delta2, segmentCenter, cross );
  4405. cextent = cross.x * matrix[0][0] + cross.y * matrix[1][0] + cross.z * matrix[2][0];
  4406. cextent = fabsf(cextent);
  4407. tmp = boxextents[1]*uextent[2] + boxextents[2]*uextent[1];
  4408. tmpfix = MAX(tmp, flProjEpsilon);
  4409. if ( cextent > tmpfix )
  4410. return -1;
  4411. // if ( cextent > tmp && cextent <= tmpfix )
  4412. // DevWarning( "ClipRayToHitbox trace precision error case\n" );
  4413. cextent = cross.x * matrix[0][1] + cross.y * matrix[1][1] + cross.z * matrix[2][1];
  4414. cextent = fabsf(cextent);
  4415. tmp = boxextents[0]*uextent[2] + boxextents[2]*uextent[0];
  4416. tmpfix = MAX(tmp, flProjEpsilon);
  4417. if ( cextent > tmpfix )
  4418. return -1;
  4419. // if ( cextent > tmp && cextent <= tmpfix )
  4420. // DevWarning( "ClipRayToHitbox trace precision error case\n" );
  4421. cextent = cross.x * matrix[0][2] + cross.y * matrix[1][2] + cross.z * matrix[2][2];
  4422. cextent = fabsf(cextent);
  4423. tmp = boxextents[0]*uextent[1] + boxextents[1]*uextent[0];
  4424. tmpfix = MAX(tmp, flProjEpsilon);
  4425. if ( cextent > tmpfix )
  4426. return -1;
  4427. // if ( cextent > tmp && cextent <= tmpfix )
  4428. // DevWarning( "ClipRayToHitbox trace precision error case\n" );
  4429. // !!! We hit this box !!! compute intersection point and return
  4430. Vector start;
  4431. // Compute ray start in bone space
  4432. VectorITransform( ray.m_Start, matrix, start );
  4433. // extent is delta2 in bone space, recompute delta in bone space
  4434. VectorScale( extent, 2, extent );
  4435. // delta was prescaled by the current t, so no need to see if this intersection
  4436. // is closer
  4437. trace_t boxTrace;
  4438. if ( !IntersectRayWithBox( start, extent, pbox->bbmin, pbox->bbmax, 0.0f, &boxTrace ) )
  4439. return -1;
  4440. Assert( IsFinite(boxTrace.fraction) );
  4441. tr.fraction *= boxTrace.fraction;
  4442. tr.startsolid = boxTrace.startsolid;
  4443. int hitside = boxTrace.plane.type;
  4444. if ( boxTrace.plane.normal[hitside] >= 0 )
  4445. {
  4446. hitside += 3;
  4447. }
  4448. return hitside;
  4449. }
  4450. #pragma warning (default : 4701)
  4451. //-----------------------------------------------------------------------------
  4452. // Purpose:
  4453. //-----------------------------------------------------------------------------
  4454. bool SweepBoxToStudio( IPhysicsSurfaceProps *pProps, const Ray_t& ray, CStudioHdr *pStudioHdr, mstudiohitboxset_t *set,
  4455. matrix3x4_t **hitboxbones, int fContentsMask, trace_t &tr )
  4456. {
  4457. tr.fraction = 1.0;
  4458. tr.startsolid = false;
  4459. // OPTIMIZE: Partition these?
  4460. Ray_t clippedRay = ray;
  4461. int hitbox = -1;
  4462. for ( int i = 0; i < set->numhitboxes; i++ )
  4463. {
  4464. mstudiobbox_t *pbox = set->pHitbox(i);
  4465. // Filter based on contents mask
  4466. int fBoneContents = pStudioHdr->pBone( pbox->bone )->contents;
  4467. if ( ( fBoneContents & fContentsMask ) == 0 )
  4468. continue;
  4469. //FIXME: Won't work with scaling!
  4470. trace_t obbTrace;
  4471. if ( IntersectRayWithOBB( clippedRay, *hitboxbones[pbox->bone], pbox->bbmin, pbox->bbmax, 0.0f, &obbTrace ) )
  4472. {
  4473. tr.startpos = obbTrace.startpos;
  4474. tr.endpos = obbTrace.endpos;
  4475. tr.plane = obbTrace.plane;
  4476. tr.startsolid = obbTrace.startsolid;
  4477. tr.allsolid = obbTrace.allsolid;
  4478. // This logic here is to shorten the ray each time to get more early outs
  4479. tr.fraction *= obbTrace.fraction;
  4480. clippedRay.m_Delta *= obbTrace.fraction;
  4481. hitbox = i;
  4482. if (tr.startsolid)
  4483. break;
  4484. }
  4485. }
  4486. if ( hitbox >= 0 )
  4487. {
  4488. tr.hitgroup = set->pHitbox(hitbox)->group;
  4489. tr.hitbox = hitbox;
  4490. const mstudiobone_t *pBone = pStudioHdr->pBone( set->pHitbox(hitbox)->bone );
  4491. tr.contents = pBone->contents | CONTENTS_HITBOX;
  4492. tr.physicsbone = pBone->physicsbone;
  4493. tr.surface.name = "**studio**";
  4494. tr.surface.flags = SURF_HITBOX;
  4495. tr.surface.surfaceProps = pProps->GetSurfaceIndex( pBone->pszSurfaceProp() );
  4496. Assert( tr.physicsbone >= 0 );
  4497. return true;
  4498. }
  4499. return false;
  4500. }
  4501. //-----------------------------------------------------------------------------
  4502. // Purpose:
  4503. //-----------------------------------------------------------------------------
  4504. bool TraceToStudio( IPhysicsSurfaceProps *pProps, const Ray_t& ray, CStudioHdr *pStudioHdr, mstudiohitboxset_t *set,
  4505. matrix3x4_t **hitboxbones, int fContentsMask, const Vector &vecOrigin, float flScale, trace_t &tr )
  4506. {
  4507. if ( !ray.m_IsRay )
  4508. {
  4509. return SweepBoxToStudio( pProps, ray, pStudioHdr, set, hitboxbones, fContentsMask, tr );
  4510. }
  4511. tr.fraction = 1.0;
  4512. tr.startsolid = false;
  4513. // no hit yet
  4514. int hitbox = -1;
  4515. int hitside = -1;
  4516. // OPTIMIZE: Partition these?
  4517. for ( int i = 0; i < set->numhitboxes; i++ )
  4518. {
  4519. mstudiobbox_t *pbox = set->pHitbox(i);
  4520. // Filter based on contents mask
  4521. int fBoneContents = pStudioHdr->pBone( pbox->bone )->contents;
  4522. if ( ( fBoneContents & fContentsMask ) == 0 )
  4523. continue;
  4524. // columns are axes of the bones in world space, translation is in world space
  4525. matrix3x4_t& matrix = *hitboxbones[pbox->bone];
  4526. // Because we're sending in a matrix with scale data, and because the matrix inversion in the hitbox
  4527. // code does not handle that case, we pre-scale the bones and ray down here and do our collision checks
  4528. // in unscaled space. We can then rescale the results afterwards.
  4529. int side = -1;
  4530. if ( flScale < 1.0f-FLT_EPSILON || flScale > 1.0f+FLT_EPSILON )
  4531. {
  4532. matrix3x4_t matScaled;
  4533. MatrixCopy( matrix, matScaled );
  4534. float invScale = 1.0f / flScale;
  4535. Vector vecBoneOrigin;
  4536. MatrixGetColumn( matScaled, 3, vecBoneOrigin );
  4537. // Pre-scale the origin down
  4538. Vector vecNewOrigin = vecBoneOrigin - vecOrigin;
  4539. vecNewOrigin *= invScale;
  4540. vecNewOrigin += vecOrigin;
  4541. MatrixSetColumn( vecNewOrigin, 3, matScaled );
  4542. // Scale it uniformly
  4543. VectorScale( matScaled[0], invScale, matScaled[0] );
  4544. VectorScale( matScaled[1], invScale, matScaled[1] );
  4545. VectorScale( matScaled[2], invScale, matScaled[2] );
  4546. // Pre-scale our ray as well
  4547. Vector vecRayStart = ray.m_Start - vecOrigin;
  4548. vecRayStart *= invScale;
  4549. vecRayStart += vecOrigin;
  4550. Vector vecRayDelta = ray.m_Delta * invScale;
  4551. Ray_t newRay;
  4552. newRay.Init( vecRayStart, vecRayStart + vecRayDelta );
  4553. side = ClipRayToHitbox( newRay, pbox, matScaled, tr );
  4554. }
  4555. else
  4556. {
  4557. side = ClipRayToHitbox( ray, pbox, matrix, tr );
  4558. }
  4559. if ( side >= 0 )
  4560. {
  4561. hitbox = i;
  4562. hitside = side;
  4563. }
  4564. }
  4565. if ( hitbox >= 0 )
  4566. {
  4567. mstudiobbox_t *pbox = set->pHitbox(hitbox);
  4568. VectorMA( ray.m_Start, tr.fraction, ray.m_Delta, tr.endpos );
  4569. tr.hitgroup = set->pHitbox(hitbox)->group;
  4570. tr.hitbox = hitbox;
  4571. const mstudiobone_t *pBone = pStudioHdr->pBone( pbox->bone );
  4572. tr.contents = pBone->contents | CONTENTS_HITBOX;
  4573. tr.physicsbone = pBone->physicsbone;
  4574. tr.surface.name = "**studio**";
  4575. tr.surface.flags = SURF_HITBOX;
  4576. tr.surface.surfaceProps = pProps->GetSurfaceIndex( pBone->pszSurfaceProp() );
  4577. Assert( tr.physicsbone >= 0 );
  4578. matrix3x4_t& matrix = *hitboxbones[pbox->bone];
  4579. if ( hitside >= 3 )
  4580. {
  4581. hitside -= 3;
  4582. tr.plane.normal[0] = matrix[0][hitside];
  4583. tr.plane.normal[1] = matrix[1][hitside];
  4584. tr.plane.normal[2] = matrix[2][hitside];
  4585. //tr.plane.dist = DotProduct( tr.plane.normal, Vector(matrix[0][3], matrix[1][3], matrix[2][3] ) ) + pbox->bbmax[hitside];
  4586. }
  4587. else
  4588. {
  4589. tr.plane.normal[0] = -matrix[0][hitside];
  4590. tr.plane.normal[1] = -matrix[1][hitside];
  4591. tr.plane.normal[2] = -matrix[2][hitside];
  4592. //tr.plane.dist = DotProduct( tr.plane.normal, Vector(matrix[0][3], matrix[1][3], matrix[2][3] ) ) - pbox->bbmin[hitside];
  4593. }
  4594. // simpler plane constant equation
  4595. tr.plane.dist = DotProduct( tr.endpos, tr.plane.normal );
  4596. tr.plane.type = 3;
  4597. return true;
  4598. }
  4599. return false;
  4600. }
  4601. //-----------------------------------------------------------------------------
  4602. // Purpose: returns array of animations and weightings for a sequence based on current pose parameters
  4603. //-----------------------------------------------------------------------------
  4604. void Studio_SeqAnims( const CStudioHdr *pStudioHdr, mstudioseqdesc_t &seqdesc, int iSequence, const float poseParameter[], mstudioanimdesc_t *panim[4], float *weight )
  4605. {
  4606. #if _DEBUG
  4607. VPROF_INCREMENT_COUNTER("SEQ_ANIMS",1);
  4608. #endif
  4609. if (!pStudioHdr || iSequence >= pStudioHdr->GetNumSeq())
  4610. {
  4611. weight[0] = weight[1] = weight[2] = weight[3] = 0.0;
  4612. return;
  4613. }
  4614. int i0 = 0, i1 = 0;
  4615. float s0 = 0, s1 = 0;
  4616. Studio_LocalPoseParameter( pStudioHdr, poseParameter, seqdesc, iSequence, 0, s0, i0 );
  4617. Studio_LocalPoseParameter( pStudioHdr, poseParameter, seqdesc, iSequence, 1, s1, i1 );
  4618. panim[0] = &((CStudioHdr *)pStudioHdr)->pAnimdesc( pStudioHdr->iRelativeAnim( iSequence, seqdesc.anim( i0 , i1 ) ) );
  4619. weight[0] = (1 - s0) * (1 - s1);
  4620. panim[1] = &((CStudioHdr *)pStudioHdr)->pAnimdesc( pStudioHdr->iRelativeAnim( iSequence, seqdesc.anim( i0+1, i1 ) ) );
  4621. weight[1] = (s0) * (1 - s1);
  4622. panim[2] = &((CStudioHdr *)pStudioHdr)->pAnimdesc( pStudioHdr->iRelativeAnim( iSequence, seqdesc.anim( i0 , i1+1 ) ) );
  4623. weight[2] = (1 - s0) * (s1);
  4624. panim[3] = &((CStudioHdr *)pStudioHdr)->pAnimdesc( pStudioHdr->iRelativeAnim( iSequence, seqdesc.anim( i0+1, i1+1 ) ) );
  4625. weight[3] = (s0) * (s1);
  4626. Assert( weight[0] >= 0.0f && weight[1] >= 0.0f && weight[2] >= 0.0f && weight[3] >= 0.0f );
  4627. }
  4628. //-----------------------------------------------------------------------------
  4629. // Purpose: returns max frame number for a sequence
  4630. //-----------------------------------------------------------------------------
  4631. int Studio_MaxFrame( const CStudioHdr *pStudioHdr, int iSequence, const float poseParameter[] )
  4632. {
  4633. mstudioanimdesc_t *panim[4];
  4634. float weight[4];
  4635. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( iSequence );
  4636. Studio_SeqAnims( pStudioHdr, seqdesc, iSequence, poseParameter, panim, weight );
  4637. float maxFrame = 0;
  4638. for (int i = 0; i < 4; i++)
  4639. {
  4640. if (weight[i] > 0)
  4641. {
  4642. maxFrame += panim[i]->numframes * weight[i];
  4643. }
  4644. }
  4645. if ( maxFrame > 1 )
  4646. maxFrame -= 1;
  4647. // FIXME: why does the weights sometimes not exactly add it 1.0 and this sometimes rounds down?
  4648. return (maxFrame + 0.01);
  4649. }
  4650. //-----------------------------------------------------------------------------
  4651. // Purpose: returns frames per second of a sequence
  4652. //-----------------------------------------------------------------------------
  4653. float Studio_FPS( const CStudioHdr *pStudioHdr, int iSequence, const float poseParameter[] )
  4654. {
  4655. mstudioanimdesc_t *panim[4];
  4656. float weight[4];
  4657. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( iSequence );
  4658. Studio_SeqAnims( pStudioHdr, seqdesc, iSequence, poseParameter, panim, weight );
  4659. float t = 0;
  4660. for (int i = 0; i < 4; i++)
  4661. {
  4662. if (weight[i] > 0)
  4663. {
  4664. t += panim[i]->fps * weight[i];
  4665. }
  4666. }
  4667. return t;
  4668. }
  4669. //-----------------------------------------------------------------------------
  4670. // Purpose: returns cycles per second of a sequence (cycles/second)
  4671. //-----------------------------------------------------------------------------
  4672. float Studio_CPS( const CStudioHdr *pStudioHdr, mstudioseqdesc_t &seqdesc, int iSequence, const float poseParameter[] )
  4673. {
  4674. mstudioanimdesc_t *panim[4];
  4675. float weight[4];
  4676. Studio_SeqAnims( pStudioHdr, seqdesc, iSequence, poseParameter, panim, weight );
  4677. float t = 0;
  4678. for (int i = 0; i < 4; i++)
  4679. {
  4680. if (weight[i] > 0 && panim[i]->numframes > 1)
  4681. {
  4682. t += (panim[i]->fps / (panim[i]->numframes - 1)) * weight[i];
  4683. }
  4684. }
  4685. return t;
  4686. }
  4687. //-----------------------------------------------------------------------------
  4688. // Purpose: returns length (in seconds) of a sequence (seconds/cycle)
  4689. //-----------------------------------------------------------------------------
  4690. float Studio_Duration( const CStudioHdr *pStudioHdr, int iSequence, const float poseParameter[] )
  4691. {
  4692. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( iSequence );
  4693. float cps = Studio_CPS( pStudioHdr, seqdesc, iSequence, poseParameter );
  4694. if( cps == 0 )
  4695. return 0.0f;
  4696. return 1.0f/cps;
  4697. }
  4698. //-----------------------------------------------------------------------------
  4699. // Purpose: calculate changes in position and angle relative to the start of an animations cycle
  4700. // Output: updated position and angle, relative to the origin
  4701. // returns false if animation is not a movement animation
  4702. //-----------------------------------------------------------------------------
  4703. bool Studio_AnimPosition( mstudioanimdesc_t *panim, float flCycle, Vector &vecPos, QAngle &vecAngle )
  4704. {
  4705. float prevframe = 0;
  4706. vecPos.Init( );
  4707. vecAngle.Init( );
  4708. if (panim->nummovements == 0)
  4709. return false;
  4710. int iLoops = 0;
  4711. if (flCycle > 1.0)
  4712. {
  4713. iLoops = (int)flCycle;
  4714. }
  4715. else if (flCycle < 0.0)
  4716. {
  4717. iLoops = (int)flCycle - 1;
  4718. }
  4719. flCycle = flCycle - iLoops;
  4720. float flFrame = flCycle * (panim->numframes - 1);
  4721. for (int i = 0; i < panim->nummovements; i++)
  4722. {
  4723. mstudiomovement_t *pmove = panim->pMovement( i );
  4724. if (pmove->endframe >= flFrame)
  4725. {
  4726. float f = (flFrame - prevframe) / (pmove->endframe - prevframe);
  4727. float d = pmove->v0 * f + 0.5 * (pmove->v1 - pmove->v0) * f * f;
  4728. vecPos = vecPos + d * pmove->vector;
  4729. vecAngle.y = vecAngle.y * (1 - f) + pmove->angle * f;
  4730. if (iLoops != 0)
  4731. {
  4732. mstudiomovement_t *pmoveAnim = panim->pMovement( panim->nummovements - 1 );
  4733. vecPos = vecPos + iLoops * pmoveAnim->position;
  4734. vecAngle.y = vecAngle.y + iLoops * pmoveAnim->angle;
  4735. }
  4736. return true;
  4737. }
  4738. else
  4739. {
  4740. prevframe = pmove->endframe;
  4741. vecPos = pmove->position;
  4742. vecAngle.y = pmove->angle;
  4743. }
  4744. }
  4745. return false;
  4746. }
  4747. //-----------------------------------------------------------------------------
  4748. // Purpose: calculate instantaneous velocity in ips at a given point
  4749. // in the animations cycle
  4750. // Output: velocity vector, relative to identity orientation
  4751. // returns false if animation is not a movement animation
  4752. //-----------------------------------------------------------------------------
  4753. bool Studio_AnimVelocity( mstudioanimdesc_t *panim, float flCycle, Vector &vecVelocity )
  4754. {
  4755. float prevframe = 0;
  4756. float flFrame = flCycle * (panim->numframes - 1);
  4757. flFrame = flFrame - (int)(flFrame / (panim->numframes - 1));
  4758. for (int i = 0; i < panim->nummovements; i++)
  4759. {
  4760. mstudiomovement_t *pmove = panim->pMovement( i );
  4761. if (pmove->endframe >= flFrame)
  4762. {
  4763. float f = (flFrame - prevframe) / (pmove->endframe - prevframe);
  4764. float vel = pmove->v0 * (1 - f) + pmove->v1 * f;
  4765. // scale from per block to per sec velocity
  4766. vel = vel * panim->fps / (pmove->endframe - prevframe);
  4767. vecVelocity = pmove->vector * vel;
  4768. return true;
  4769. }
  4770. else
  4771. {
  4772. prevframe = pmove->endframe;
  4773. }
  4774. }
  4775. return false;
  4776. }
  4777. //-----------------------------------------------------------------------------
  4778. // Purpose: calculate changes in position and angle between two points in an animation cycle
  4779. // Output: updated position and angle, relative to CycleFrom being at the origin
  4780. // returns false if animation is not a movement animation
  4781. //-----------------------------------------------------------------------------
  4782. bool Studio_AnimMovement( mstudioanimdesc_t *panim, float flCycleFrom, float flCycleTo, Vector &deltaPos, QAngle &deltaAngle )
  4783. {
  4784. if (panim->nummovements == 0)
  4785. return false;
  4786. Vector startPos;
  4787. QAngle startA;
  4788. Studio_AnimPosition( panim, flCycleFrom, startPos, startA );
  4789. Vector endPos;
  4790. QAngle endA;
  4791. Studio_AnimPosition( panim, flCycleTo, endPos, endA );
  4792. Vector tmp = endPos - startPos;
  4793. deltaAngle.y = endA.y - startA.y;
  4794. VectorYawRotate( tmp, -startA.y, deltaPos );
  4795. return true;
  4796. }
  4797. //-----------------------------------------------------------------------------
  4798. // Purpose: finds how much of an animation to play to move given linear distance
  4799. //-----------------------------------------------------------------------------
  4800. float Studio_FindAnimDistance( mstudioanimdesc_t *panim, float flDist )
  4801. {
  4802. float prevframe = 0;
  4803. if (flDist <= 0)
  4804. return 0.0;
  4805. for (int i = 0; i < panim->nummovements; i++)
  4806. {
  4807. mstudiomovement_t *pmove = panim->pMovement( i );
  4808. float flMove = (pmove->v0 + pmove->v1) * 0.5;
  4809. if (flMove >= flDist)
  4810. {
  4811. float root1, root2;
  4812. // d = V0 * t + 1/2 (V1-V0) * t^2
  4813. if (SolveQuadratic( 0.5 * (pmove->v1 - pmove->v0), pmove->v0, -flDist, root1, root2 ))
  4814. {
  4815. float cpf = 1.0 / (panim->numframes - 1); // cycles per frame
  4816. return (prevframe + root1 * (pmove->endframe - prevframe)) * cpf;
  4817. }
  4818. return 0.0;
  4819. }
  4820. else
  4821. {
  4822. flDist -= flMove;
  4823. prevframe = pmove->endframe;
  4824. }
  4825. }
  4826. return 1.0;
  4827. }
  4828. //-----------------------------------------------------------------------------
  4829. // Purpose: calculate changes in position and angle between two points in a sequences cycle
  4830. // Output: updated position and angle, relative to CycleFrom being at the origin
  4831. // returns false if sequence is not a movement sequence
  4832. //-----------------------------------------------------------------------------
  4833. bool Studio_SeqMovement( const CStudioHdr *pStudioHdr, int iSequence, float flCycleFrom, float flCycleTo, const float poseParameter[], Vector &deltaPos, QAngle &deltaAngles )
  4834. {
  4835. mstudioanimdesc_t *panim[4];
  4836. float weight[4];
  4837. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( iSequence );
  4838. Studio_SeqAnims( pStudioHdr, seqdesc, iSequence, poseParameter, panim, weight );
  4839. deltaPos.Init( );
  4840. deltaAngles.Init( );
  4841. bool found = false;
  4842. for (int i = 0; i < 4; i++)
  4843. {
  4844. if (weight[i])
  4845. {
  4846. Vector localPos;
  4847. QAngle localAngles;
  4848. localPos.Init();
  4849. localAngles.Init();
  4850. if (Studio_AnimMovement( panim[i], flCycleFrom, flCycleTo, localPos, localAngles ))
  4851. {
  4852. found = true;
  4853. deltaPos = deltaPos + localPos * weight[i];
  4854. // FIXME: this makes no sense
  4855. deltaAngles = deltaAngles + localAngles * weight[i];
  4856. }
  4857. else if (!(panim[i]->flags & STUDIO_DELTA) && panim[i]->nummovements == 0 && seqdesc.weight(0) > 0.0)
  4858. {
  4859. found = true;
  4860. }
  4861. }
  4862. }
  4863. return found;
  4864. }
  4865. //-----------------------------------------------------------------------------
  4866. // Purpose: calculate instantaneous velocity in ips at a given point in the sequence's cycle
  4867. // Output: velocity vector, relative to identity orientation
  4868. // returns false if sequence is not a movement sequence
  4869. //-----------------------------------------------------------------------------
  4870. bool Studio_SeqVelocity( const CStudioHdr *pStudioHdr, int iSequence, float flCycle, const float poseParameter[], Vector &vecVelocity )
  4871. {
  4872. mstudioanimdesc_t *panim[4];
  4873. float weight[4];
  4874. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( iSequence );
  4875. Studio_SeqAnims( pStudioHdr, seqdesc, iSequence, poseParameter, panim, weight );
  4876. vecVelocity.Init( );
  4877. bool found = false;
  4878. for (int i = 0; i < 4; i++)
  4879. {
  4880. if (weight[i])
  4881. {
  4882. Vector vecLocalVelocity;
  4883. if (Studio_AnimVelocity( panim[i], flCycle, vecLocalVelocity ))
  4884. {
  4885. vecVelocity = vecVelocity + vecLocalVelocity * weight[i];
  4886. found = true;
  4887. }
  4888. }
  4889. }
  4890. return found;
  4891. }
  4892. //-----------------------------------------------------------------------------
  4893. // Purpose: finds how much of an sequence to play to move given linear distance
  4894. //-----------------------------------------------------------------------------
  4895. float Studio_FindSeqDistance( const CStudioHdr *pStudioHdr, int iSequence, const float poseParameter[], float flDist )
  4896. {
  4897. mstudioanimdesc_t *panim[4];
  4898. float weight[4];
  4899. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( iSequence );
  4900. Studio_SeqAnims( pStudioHdr, seqdesc, iSequence, poseParameter, panim, weight );
  4901. float flCycle = 0;
  4902. for (int i = 0; i < 4; i++)
  4903. {
  4904. if (weight[i])
  4905. {
  4906. float flLocalCycle = Studio_FindAnimDistance( panim[i], flDist );
  4907. flCycle = flCycle + flLocalCycle * weight[i];
  4908. }
  4909. }
  4910. return flCycle;
  4911. }
  4912. //-----------------------------------------------------------------------------
  4913. // Purpose: lookup attachment by name
  4914. //-----------------------------------------------------------------------------
  4915. int Studio_FindAttachment( const CStudioHdr *pStudioHdr, const char *pAttachmentName )
  4916. {
  4917. if ( pStudioHdr && pStudioHdr->SequencesAvailable() )
  4918. {
  4919. // Extract the bone index from the name
  4920. for (int i = 0; i < pStudioHdr->GetNumAttachments(); i++)
  4921. {
  4922. if (!V_stricmp(pAttachmentName,((CStudioHdr *)pStudioHdr)->pAttachment(i).pszName( )))
  4923. {
  4924. return i;
  4925. }
  4926. }
  4927. }
  4928. return -1;
  4929. }
  4930. //-----------------------------------------------------------------------------
  4931. // Purpose: lookup attachments by substring. Randomly return one of the matching attachments.
  4932. //-----------------------------------------------------------------------------
  4933. int Studio_FindRandomAttachment( const CStudioHdr *pStudioHdr, const char *pAttachmentName )
  4934. {
  4935. if ( pStudioHdr )
  4936. {
  4937. // First move them all matching attachments into a list
  4938. CUtlVector<int> matchingAttachments;
  4939. // Extract the bone index from the name
  4940. for (int i = 0; i < pStudioHdr->GetNumAttachments(); i++)
  4941. {
  4942. if ( strstr( ((CStudioHdr *)pStudioHdr)->pAttachment(i).pszName(), pAttachmentName ) )
  4943. {
  4944. matchingAttachments.AddToTail(i);
  4945. }
  4946. }
  4947. // Then randomly return one of the attachments
  4948. if ( matchingAttachments.Size() > 0 )
  4949. return matchingAttachments[ RandomInt( 0, matchingAttachments.Size()-1 ) ];
  4950. }
  4951. return -1;
  4952. }
  4953. //-----------------------------------------------------------------------------
  4954. // Purpose: lookup bone by name
  4955. //-----------------------------------------------------------------------------
  4956. int Studio_BoneIndexByName( const CStudioHdr *pStudioHdr, const char *pName )
  4957. {
  4958. if ( pStudioHdr )
  4959. {
  4960. // binary search for the bone matching pName
  4961. int start = 0, end = pStudioHdr->numbones()-1;
  4962. const byte *pBoneTable = pStudioHdr->GetBoneTableSortedByName();
  4963. mstudiobone_t *pbones = pStudioHdr->pBone( 0 );
  4964. while (start <= end)
  4965. {
  4966. int mid = (start + end) >> 1;
  4967. int cmp = Q_stricmp( pbones[pBoneTable[mid]].pszName(), pName );
  4968. if ( cmp < 0 )
  4969. {
  4970. start = mid + 1;
  4971. }
  4972. else if ( cmp > 0 )
  4973. {
  4974. end = mid - 1;
  4975. }
  4976. else
  4977. {
  4978. return pBoneTable[mid];
  4979. }
  4980. }
  4981. }
  4982. return -1;
  4983. }
  4984. const char *Studio_GetDefaultSurfaceProps( CStudioHdr *pstudiohdr )
  4985. {
  4986. return pstudiohdr->pszSurfaceProp();
  4987. }
  4988. float Studio_GetMass( CStudioHdr *pstudiohdr )
  4989. {
  4990. return pstudiohdr->mass();
  4991. }
  4992. //-----------------------------------------------------------------------------
  4993. // Purpose: return pointer to sequence key value buffer
  4994. //-----------------------------------------------------------------------------
  4995. const char *Studio_GetKeyValueText( const CStudioHdr *pStudioHdr, int iSequence )
  4996. {
  4997. if (pStudioHdr && pStudioHdr->SequencesAvailable())
  4998. {
  4999. if (iSequence >= 0 && iSequence < pStudioHdr->GetNumSeq())
  5000. {
  5001. return ((CStudioHdr *)pStudioHdr)->pSeqdesc( iSequence ).KeyValueText();
  5002. }
  5003. }
  5004. return NULL;
  5005. }
  5006. bool Studio_PrefetchSequence( const CStudioHdr *pStudioHdr, int iSequence )
  5007. {
  5008. bool pendingload = false;
  5009. mstudioseqdesc_t &seqdesc = ((CStudioHdr *)pStudioHdr)->pSeqdesc( iSequence );
  5010. int size0 = seqdesc.groupsize[ 0 ];
  5011. int size1 = seqdesc.groupsize[ 1 ];
  5012. for ( int i = 0; i < size0; ++i )
  5013. {
  5014. for ( int j = 0; j < size1; ++j )
  5015. {
  5016. mstudioanimdesc_t &animdesc = ((CStudioHdr *)pStudioHdr)->pAnimdesc( seqdesc.anim( i, j ) );
  5017. int iFrame = 0;
  5018. mstudioanim_t *panim = animdesc.pAnim( &iFrame );
  5019. if ( !panim )
  5020. {
  5021. pendingload = true;
  5022. }
  5023. }
  5024. }
  5025. // Everything for this sequence is resident?
  5026. return !pendingload;
  5027. }
  5028. //-----------------------------------------------------------------------------
  5029. // Purpose: Drive a flex controller from a component of a bone
  5030. //-----------------------------------------------------------------------------
  5031. void Studio_RunBoneFlexDrivers( float *pflFlexControllerWeights, const CStudioHdr *pStudioHdr, const Vector *pvPositions, const matrix3x4_t *pBoneToWorld, const matrix3x4_t &mRootToWorld )
  5032. {
  5033. bool bRootToWorldInvComputed = false;
  5034. matrix3x4_t mRootToWorldInv;
  5035. matrix3x4_t mParentInv;
  5036. matrix3x4_t mBoneLocal;
  5037. const int nBoneFlexDriverCount = pStudioHdr->BoneFlexDriverCount();
  5038. for ( int i = 0; i < nBoneFlexDriverCount; ++i )
  5039. {
  5040. const mstudioboneflexdriver_t *pBoneFlexDriver = pStudioHdr->BoneFlexDriver( i );
  5041. const mstudiobone_t *pStudioBone = pStudioHdr->pBone( pBoneFlexDriver->m_nBoneIndex );
  5042. const int nControllerCount = pBoneFlexDriver->m_nControlCount;
  5043. if ( pStudioBone->flags & BONE_USED_BY_BONE_MERGE )
  5044. {
  5045. // The local space version of the bone is not available if this is a bonemerged bone
  5046. // so do the slow computation of the local version of the bone from boneToWorld
  5047. if ( pStudioBone->parent < 0 )
  5048. {
  5049. if ( !bRootToWorldInvComputed )
  5050. {
  5051. MatrixInvert( mRootToWorld, mRootToWorldInv );
  5052. bRootToWorldInvComputed = true;
  5053. }
  5054. MatrixMultiply( mRootToWorldInv, pBoneToWorld[ pBoneFlexDriver->m_nBoneIndex ], mBoneLocal );
  5055. }
  5056. else
  5057. {
  5058. MatrixInvert( pBoneToWorld[ pStudioBone->parent ], mParentInv );
  5059. MatrixMultiply( mParentInv, pBoneToWorld[ pBoneFlexDriver->m_nBoneIndex ], mBoneLocal );
  5060. }
  5061. for ( int j = 0; j < nControllerCount; ++j )
  5062. {
  5063. const mstudioboneflexdrivercontrol_t *pController = pBoneFlexDriver->pBoneFlexDriverControl( j );
  5064. const mstudioflexcontroller_t *pFlexController = pStudioHdr->pFlexcontroller( static_cast< LocalFlexController_t >( pController->m_nFlexControllerIndex ) );
  5065. if ( pFlexController->localToGlobal < 0 )
  5066. continue;
  5067. Assert( pController->m_nFlexControllerIndex >= 0 && pController->m_nFlexControllerIndex < pStudioHdr->numflexcontrollers() );
  5068. Assert( pController->m_nBoneComponent >= 0 && pController->m_nBoneComponent <= 2 );
  5069. pflFlexControllerWeights[pFlexController->localToGlobal] =
  5070. RemapValClamped( mBoneLocal[pController->m_nBoneComponent][3], pController->m_flMin, pController->m_flMax, 0.0f, 1.0f );
  5071. }
  5072. }
  5073. else
  5074. {
  5075. // Use the local space version of the bone directly for non-bonemerged bones
  5076. const Vector &position = pvPositions[ pBoneFlexDriver->m_nBoneIndex ];
  5077. for ( int j = 0; j < nControllerCount; ++j )
  5078. {
  5079. const mstudioboneflexdrivercontrol_t *pController = pBoneFlexDriver->pBoneFlexDriverControl( j );
  5080. const mstudioflexcontroller_t *pFlexController = pStudioHdr->pFlexcontroller( static_cast< LocalFlexController_t >( pController->m_nFlexControllerIndex ) );
  5081. if ( pFlexController->localToGlobal < 0 )
  5082. continue;
  5083. Assert( pController->m_nFlexControllerIndex >= 0 && pController->m_nFlexControllerIndex < pStudioHdr->numflexcontrollers() );
  5084. Assert( pController->m_nBoneComponent >= 0 && pController->m_nBoneComponent <= 2 );
  5085. pflFlexControllerWeights[pFlexController->localToGlobal] =
  5086. RemapValClamped( position[pController->m_nBoneComponent], pController->m_flMin, pController->m_flMax, 0.0f, 1.0f );
  5087. }
  5088. }
  5089. }
  5090. }