Counter Strike : Global Offensive Source Code
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.

5013 lines
164 KiB

  1. //===== Copyright � 1996-2008, Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose: Loads mesh data from dmx files
  4. //
  5. // $NoKeywords: $
  6. //
  7. //===========================================================================//
  8. // Valve includes
  9. #include "bspflags.h"
  10. #include "movieobjects/dmeattributereference.h"
  11. #include "movieobjects/dmeconnectionoperator.h"
  12. #include "movieobjects/dmemodel.h"
  13. #include "movieobjects/dmemesh.h"
  14. #include "movieobjects/dmefaceset.h"
  15. #include "movieobjects/dmematerial.h"
  16. #include "movieobjects/dmeclip.h"
  17. #include "movieobjects/dmechannel.h"
  18. #include "movieobjects/dmeattachment.h"
  19. #include "movieobjects/dmeanimationlist.h"
  20. #include "movieobjects/dmecombinationoperator.h"
  21. #include "movieobjects/dmerigconstraintoperators.h"
  22. #include "mdlobjects/dmebbox.h"
  23. #include "mdlobjects/dmelod.h"
  24. #include "mdlobjects/dmelodlist.h"
  25. #include "mdlobjects/dmebodygroup.h"
  26. #include "mdlobjects/dmebodygrouplist.h"
  27. #include "mdlobjects/dmehitbox.h"
  28. #include "mdlobjects/dmehitboxset.h"
  29. #include "mdlobjects/dmehitboxsetlist.h"
  30. #include "mdlobjects/dmesequence.h"
  31. #include "mdlobjects/dmesequencelist.h"
  32. #include "mdlobjects/dmecollisionmodel.h"
  33. #include "mdlobjects/dmecollisionjoints.h"
  34. #include "mdlobjects/dmeincludemodellist.h"
  35. #include "mdlobjects/dmedefinebone.h"
  36. #include "mdlobjects/dmedefinebonelist.h"
  37. #include "mdlobjects/dmematerialgroup.h"
  38. #include "mdlobjects/dmematerialgrouplist.h"
  39. #include "mdlobjects/dmeeyeball.h"
  40. #include "mdlobjects/dmeeyeballglobals.h"
  41. #include "mdlobjects/dmeeyelid.h"
  42. #include "mdlobjects/dmeboneweight.h"
  43. #include "mdlobjects/dmebonemask.h"
  44. #include "mdlobjects/dmebonemasklist.h"
  45. #include "mdlobjects/dmeik.h"
  46. #include "mdlobjects/dmeanimcmd.h"
  47. #include "mdlobjects/dmemotioncontrol.h"
  48. #include "mdlobjects/dmeposeparameter.h"
  49. #include "mdlobjects/dmeposeparameterlist.h"
  50. #include "mdlobjects/dmeanimblocksize.h"
  51. #include "mdlobjects/dmeboneflexdriver.h"
  52. #include "mdlobjects/dmejigglebone.h"
  53. #include "mdlobjects/dmemouth.h"
  54. #include "fbxutils/dmfbxserializer.h"
  55. #include "mdlobjects/mpp_utils.h"
  56. // Local includes
  57. #include "studiomdl.h"
  58. #include "collisionmodel.h"
  59. #include "tier1/fmtstr.h"
  60. // memdbgon must be the last include file in a .cpp file!!!
  61. #include "tier0/memdbgon.h"
  62. //-----------------------------------------------------------------------------
  63. // The current model being loaded...
  64. //-----------------------------------------------------------------------------
  65. s_model_t *g_pCurrentModel = NULL;
  66. void UnifyIndices( s_source_t *psource );
  67. //-----------------------------------------------------------------------------
  68. // Mapping of bone transforms
  69. //-----------------------------------------------------------------------------
  70. struct BoneTransformMap_t
  71. {
  72. // Number of bones
  73. int m_nBoneCount;
  74. // The order in which transforms appear in this list specifies their bone indices
  75. CDmeTransform *m_ppTransforms[MAXSTUDIOSRCBONES];
  76. // m_pnDmeModelToMdl[bone index in DmeModel] == bone index in studiomdl
  77. int m_pnDmeModelToMdl[MAXSTUDIOSRCBONES];
  78. // m_pnMdlToDmeModel[bone index in studiomdl] == bone index in DmeModel
  79. int m_pnMdlToDmeModel[MAXSTUDIOSRCBONES];
  80. };
  81. //-----------------------------------------------------------------------------
  82. // Index into an s_node_t array for the default root node
  83. //-----------------------------------------------------------------------------
  84. static int s_nDefaultRootNode;
  85. //-----------------------------------------------------------------------------
  86. // Balance/speed data
  87. //-----------------------------------------------------------------------------
  88. static CUtlVector<float> s_Balance;
  89. static CUtlVector<float> s_Speed;
  90. //-----------------------------------------------------------------------------
  91. // List of unique vertices
  92. //-----------------------------------------------------------------------------
  93. struct VertIndices_t
  94. {
  95. int v;
  96. int n;
  97. int t[MAXSTUDIOTEXCOORDS];
  98. int balance;
  99. int speed;
  100. };
  101. static CUtlVector< VertIndices_t > s_UniqueVertices; // A list of the unique vertices in the mesh
  102. // Given the non-unique vertex index, return the unique vertex index
  103. // The indices are absolute indices into s_UniqueVertices
  104. // But as both arrays contain information for all meshes in the DMX
  105. // The proper offset for the desired mesh must be added to the lookup
  106. // into the map but the value returned has the offset already built in
  107. static CUtlVector< int > s_UniqueVerticesMap;
  108. //-----------------------------------------------------------------------------
  109. // Delta state intermediate data [used for positions, normals, etc.]
  110. //-----------------------------------------------------------------------------
  111. struct DeltaIndex_t
  112. {
  113. DeltaIndex_t() : m_nPositionIndex(-1), m_nNormalIndex(-1), m_nNextDelta(-1), m_nWrinkleIndex(-1), m_bInList(false) {}
  114. int m_nPositionIndex; // Index into DeltaState_t::m_PositionDeltas
  115. int m_nNormalIndex; // Index into DeltaState_t::m_NormalDeltas
  116. int m_nWrinkleIndex; // Index into DeltaState_t::m_WrinkleDeltas
  117. int m_nNextDelta; // Index into DeltaState_t::m_DeltaIndices;
  118. bool m_bInList;
  119. };
  120. struct DeltaState_t
  121. {
  122. DeltaState_t() : m_nDeltaCount( 0 ), m_nFirstDelta( -1 ) {}
  123. CUtlString m_Name;
  124. CUtlVector< Vector > m_PositionDeltas;
  125. CUtlVector< Vector > m_NormalDeltas;
  126. CUtlVector< float > m_WrinkleDeltas;
  127. CUtlVector< DeltaIndex_t > m_DeltaIndices;
  128. int m_nDeltaCount;
  129. int m_nFirstDelta;
  130. };
  131. // NOTE: This is a temporary which loses its state once Load_DMX is exited.
  132. static CUtlVector<DeltaState_t> s_DeltaStates;
  133. // Finds or adds delta states. These pointers are invalidated by calling FindOrAddDeltaState again
  134. //-----------------------------------------------------------------------------
  135. static DeltaState_t* FindOrAddDeltaState( const char *pDeltaStateName, int nBaseStateVertexCount )
  136. {
  137. int nCount = s_DeltaStates.Count();
  138. for ( int i = 0; i < nCount; ++i )
  139. {
  140. if ( !Q_stricmp( s_DeltaStates[i].m_Name, pDeltaStateName ) )
  141. {
  142. MdlWarning( "Unsupported duplicate delta state named \"%s\" in DMX file\n", pDeltaStateName );
  143. s_DeltaStates[i].m_DeltaIndices.EnsureCount( nBaseStateVertexCount );
  144. return &s_DeltaStates[i];
  145. }
  146. }
  147. int j = s_DeltaStates.AddToTail();
  148. s_DeltaStates[j].m_Name = pDeltaStateName;
  149. s_DeltaStates[j].m_DeltaIndices.SetCount( nBaseStateVertexCount );
  150. return &s_DeltaStates[j];
  151. }
  152. struct VertexLookup_t
  153. {
  154. int v, n, t;
  155. int index;
  156. };
  157. static bool VertexLookup_CompareFunc( VertexLookup_t const &a, VertexLookup_t const &b )
  158. {
  159. return ( ( a.v == b.v ) && ( a.n == b.n ) && ( a.t == b.t ) );
  160. }
  161. static unsigned int VertexLookup_KeyFunc( VertexLookup_t const &a )
  162. {
  163. return Hash12( &a );
  164. }
  165. //-----------------------------------------------------------------------------
  166. // Loads the vertices from the model
  167. //-----------------------------------------------------------------------------
  168. static bool DefineUniqueVertices( CDmeVertexData *pBindState )
  169. {
  170. const CUtlVector<int> &positionIndices = pBindState->GetVertexIndexData( CDmeVertexData::FIELD_POSITION );
  171. const CUtlVector<int> &normalIndices = pBindState->GetVertexIndexData( CDmeVertexData::FIELD_NORMAL );
  172. const CUtlVector<int> &texcoordIndices = pBindState->GetVertexIndexData( CDmeVertexData::FIELD_TEXCOORD );
  173. const CUtlVector<int> &balanceIndices = pBindState->GetVertexIndexData( CDmeVertexData::FIELD_BALANCE );
  174. const CUtlVector<int> &speedIndices = pBindState->GetVertexIndexData( CDmeVertexData::FIELD_MORPH_SPEED );
  175. int nPositionCount = positionIndices.Count();
  176. int nNormalCount = normalIndices.Count();
  177. int nTexcoordCount = texcoordIndices.Count();
  178. int nBalanceCount = balanceIndices.Count();
  179. int nSpeedCount = speedIndices.Count();
  180. int nExtraTexcoordCount[MAXSTUDIOTEXCOORDS-1];
  181. const CUtlVector<int> * extraTexcoordIndices[MAXSTUDIOTEXCOORDS - 1];
  182. for (int i = 1; i < MAXSTUDIOTEXCOORDS; ++i)
  183. {
  184. FieldIndex_t nExtra = pBindState->FindFieldIndex(CFmtStr("texcoord$%d", i).Get());
  185. if (nExtra != -1)
  186. {
  187. extraTexcoordIndices[i-1] = &pBindState->GetVertexIndexData(nExtra);
  188. nExtraTexcoordCount[i-1] = extraTexcoordIndices[i-1]->Count();
  189. if (nPositionCount != nExtraTexcoordCount[i-1])
  190. {
  191. MdlError("Encountered a mesh with invalid geometry (different number of indices for various data fields)\n");
  192. return false;
  193. }
  194. }
  195. else
  196. {
  197. extraTexcoordIndices[i-1] = NULL;
  198. nExtraTexcoordCount[i-1] = 0;
  199. }
  200. }
  201. if ( nNormalCount && nPositionCount != nNormalCount )
  202. {
  203. MdlError( "Encountered a mesh with invalid geometry (different number of indices for various data fields)\n" );
  204. return false;
  205. }
  206. if ( nTexcoordCount && nPositionCount != nTexcoordCount )
  207. {
  208. MdlError( "Encountered a mesh with invalid geometry (different number of indices for various data fields)\n" );
  209. return false;
  210. }
  211. if ( nBalanceCount && nPositionCount != nBalanceCount )
  212. {
  213. MdlError( "Encountered a mesh with invalid geometry (different number of indices for various data fields)\n" );
  214. return false;
  215. }
  216. if ( nSpeedCount && nPositionCount != nSpeedCount )
  217. {
  218. MdlError( "Encountered a mesh with invalid geometry (different number of indices for various data fields)\n" );
  219. return false;
  220. }
  221. // Make a hash table to speed up this de-duplication process:
  222. CUtlHash< VertexLookup_t > vertexLookupHash( nPositionCount, 0, 0, VertexLookup_CompareFunc, VertexLookup_KeyFunc );
  223. // Only add unique vertices to the list as in UnifyIndices
  224. for ( int i = 0; i < nPositionCount; ++i )
  225. {
  226. VertIndices_t vert;
  227. vert.v = g_numverts + positionIndices[i];
  228. vert.n = ( nNormalCount > 0 ) ? g_numnormals + normalIndices[i] : -1;
  229. vert.t[0] = ( nTexcoordCount > 0 ) ? g_numtexcoords[0] + texcoordIndices[i] : -1;
  230. vert.balance = s_Balance.Count() + ( ( nBalanceCount > 0 ) ? balanceIndices[i] : 0 );
  231. vert.speed = s_Speed.Count() + ( ( nSpeedCount > 0 ) ? speedIndices[i] : 0 );
  232. for (int j = 1; j < MAXSTUDIOTEXCOORDS; ++j)
  233. {
  234. vert.t[j] = (nExtraTexcoordCount[j-1] > 0) ? g_numtexcoords[j] + extraTexcoordIndices[j-1]->Element(i) : -1;
  235. }
  236. VertexLookup_t vertexLookup = { vert.v, vert.n, vert.t[0], -1 };
  237. UtlHashHandle_t vertexHandle = vertexLookupHash.Find( vertexLookup );
  238. if ( vertexHandle == vertexLookupHash.InvalidHandle() )
  239. {
  240. // Unique
  241. int k = s_UniqueVertices.AddToTail();
  242. s_UniqueVertices[k] = vert;
  243. s_UniqueVerticesMap.AddToTail( k );
  244. vertexLookup.index = k;
  245. vertexLookupHash.Insert( vertexLookup );
  246. }
  247. else
  248. {
  249. // Not unique
  250. VertexLookup_t &equivalentVertex = vertexLookupHash.Element( vertexHandle );
  251. s_UniqueVerticesMap.AddToTail( equivalentVertex.index );
  252. }
  253. }
  254. return true;
  255. }
  256. //-----------------------------------------------------------------------------
  257. // Loads the vertices from the model
  258. //-----------------------------------------------------------------------------
  259. static bool LoadVertices( CDmeDag *pDmeDag, CDmeVertexData *pBindState, const matrix3x4_t& mat, float flScale, int nBoneAssign, int *pBoneRemap, s_source_t *pSource )
  260. {
  261. // nBoneAssign is only used if the mesh has no skinning information
  262. // It's the DMX bone index, but it might be < 0, in which case
  263. // no bone has been defined yet. There are two options, use the
  264. // default root bone which is always defined and at the origin
  265. // or try and use the DmeDag's bone that was created when the mesh was
  266. // loaded
  267. if ( nBoneAssign < 0 )
  268. {
  269. nBoneAssign = s_nDefaultRootNode;
  270. }
  271. else
  272. {
  273. nBoneAssign = pBoneRemap[ nBoneAssign ];
  274. if ( nBoneAssign < 0 )
  275. {
  276. nBoneAssign = s_nDefaultRootNode;
  277. }
  278. }
  279. // Used by the morphing system to set up delta states
  280. DefineUniqueVertices( pBindState );
  281. matrix3x4_t normalMat;
  282. MatrixInverseTranspose( mat, normalMat );
  283. const CUtlVector<Vector> &positions = pBindState->GetPositionData( );
  284. const CUtlVector<Vector> &normals = pBindState->GetNormalData( );
  285. const CUtlVector<Vector2D> &texcoords = pBindState->GetTextureCoordData( );
  286. const CUtlVector<float> &balances = pBindState->GetBalanceData( );
  287. const CUtlVector<float> &speeds = pBindState->GetMorphSpeedData( );
  288. int nCount = positions.Count();
  289. int nJointCount = pBindState->HasSkinningData() ? pBindState->JointCount() : 0;
  290. if ( nJointCount > MAXSTUDIOBONEWEIGHTS )
  291. {
  292. MdlError( "Too many bone influences per vertex!\n" );
  293. return false;
  294. }
  295. if ( nJointCount <= 0 && nBoneAssign == s_nDefaultRootNode && pDmeDag )
  296. {
  297. // Use the bone created for the DmeDag node of the DmeMesh
  298. for ( int i = 0; i < pSource->numbones; ++i )
  299. {
  300. if ( !Q_strcmp( pDmeDag->GetName(), pSource->localBone[ i ].name ) )
  301. {
  302. nBoneAssign = i;
  303. break;
  304. }
  305. }
  306. }
  307. bool pbWarnmap[ MAXSTUDIOBONES ];
  308. Q_memset( pbWarnmap, 0, MAXSTUDIOBONES * sizeof( bool ) );
  309. float *pWeightBuf = (float *)malloc( nJointCount * sizeof( float ) );
  310. int *pIndexBuf = (int *)malloc( nJointCount * sizeof( int ) );
  311. // Copy positions + bone info
  312. for ( int i = 0; i < nCount; ++i )
  313. {
  314. // NOTE: The transform transforms the positions into the bind space
  315. VectorTransform( positions[i], mat, g_vertex[g_numverts] );
  316. g_vertex[g_numverts] *= flScale;
  317. if ( nJointCount == 0 )
  318. {
  319. g_bone[g_numverts].numbones = 1;
  320. g_bone[g_numverts].bone[0] = nBoneAssign;
  321. g_bone[g_numverts].weight[0] = 1.0;
  322. }
  323. else
  324. {
  325. const float *pJointWeights = pBindState->GetJointWeightData( i );
  326. const int *pJointIndices = pBindState->GetJointIndexData( i );
  327. memcpy( pWeightBuf, pJointWeights, nJointCount * sizeof(float) );
  328. memcpy( pIndexBuf, pJointIndices, nJointCount * sizeof(int) );
  329. int nBoneCount = SortAndBalanceBones( nJointCount, MAXSTUDIOBONEWEIGHTS, pIndexBuf, pWeightBuf );
  330. int nBoneIndex = -1;
  331. g_bone[g_numverts].numbones = nBoneCount;
  332. for ( int j = 0; j < nBoneCount; ++j )
  333. {
  334. nBoneIndex = pBoneRemap[ pIndexBuf[j] ];
  335. if ( nBoneIndex < 0 )
  336. {
  337. if ( pIndexBuf[j] < MAXSTUDIOBONES && !pbWarnmap[ pIndexBuf[j] ] )
  338. {
  339. MdlWarning( "DmeMesh[%s] Verts Assigned To DmeModel.jointList[%d] Which Isn't Mapped To The Dag Hierarchy\n",
  340. pDmeDag->GetName(), pIndexBuf[j] );
  341. pbWarnmap[ pIndexBuf[j] ] = true;
  342. }
  343. g_bone[g_numverts].bone[j] = nBoneAssign;
  344. }
  345. else
  346. {
  347. g_bone[g_numverts].bone[j] = nBoneIndex;
  348. }
  349. g_bone[g_numverts].weight[j] = pWeightBuf[j];
  350. }
  351. }
  352. ++g_numverts;
  353. }
  354. free( pWeightBuf );
  355. free( pIndexBuf );
  356. // Copy normals
  357. Vector vNormal;
  358. nCount = normals.Count();
  359. for ( int i = 0; i < nCount; ++i )
  360. {
  361. VectorCopy( normals[i], vNormal );
  362. VectorNormalize( vNormal );
  363. if ( fabs( VectorLength( vNormal ) - 1.0f ) > 0.01 )
  364. {
  365. MdlWarning( "Non-Unit Length Normal [%d] < %8.6f %8.6f %8.6f >\n", i, vNormal.x, vNormal.y, vNormal.z );
  366. }
  367. VectorRotate( vNormal, normalMat, g_normal[g_numnormals] );
  368. ++g_numnormals;
  369. }
  370. // Copy texcoords
  371. nCount = texcoords.Count();
  372. bool bFlipVCoordinate = pBindState->IsVCoordinateFlipped();
  373. for ( int i = 0; i < nCount; ++i )
  374. {
  375. g_texcoord[0][g_numtexcoords[0]].x = texcoords[i].x;
  376. g_texcoord[0][g_numtexcoords[0]].y = bFlipVCoordinate ? 1.0f - texcoords[i].y : texcoords[i].y;
  377. ++g_numtexcoords[0];
  378. }
  379. // Check for additional texcoords
  380. for (int i = 1; i < MAXSTUDIOTEXCOORDS; ++i)
  381. {
  382. g_numtexcoords[i] = 0;
  383. FieldIndex_t nFieldIndex = pBindState->FindFieldIndex(CFmtStr("texcoord$%d", i).Get());
  384. if (nFieldIndex > -1)
  385. {
  386. CDmrArrayConst<Vector2D> vertexData = pBindState->GetVertexData(nFieldIndex);
  387. const CUtlVector<Vector2D> &extraTexcoords = vertexData.Get();
  388. nCount = extraTexcoords.Count();
  389. for (int j = 0; j < nCount; ++j)
  390. {
  391. g_texcoord[i][g_numtexcoords[i]].x = extraTexcoords[j].x;
  392. g_texcoord[i][g_numtexcoords[i]].y = bFlipVCoordinate ? 1.0f - extraTexcoords[j].y : extraTexcoords[j].y;
  393. ++g_numtexcoords[i];
  394. }
  395. }
  396. else
  397. {
  398. break;
  399. }
  400. }
  401. // In the event of no speed or balance map, use the same value of 1 for all vertices
  402. if ( balances.Count() )
  403. {
  404. s_Balance.AddMultipleToTail( balances.Count(), balances.Base() );
  405. }
  406. else
  407. {
  408. s_Balance.AddToTail( 1.0f );
  409. }
  410. if ( speeds.Count() )
  411. {
  412. s_Speed.AddMultipleToTail( speeds.Count(), speeds.Base() );
  413. }
  414. else
  415. {
  416. s_Speed.AddToTail( 1.0f );
  417. }
  418. return true;
  419. }
  420. //-----------------------------------------------------------------------------
  421. // Hook delta into delta list
  422. //-----------------------------------------------------------------------------
  423. static void AddToDeltaList( DeltaState_t *pDeltaStateData, int nUniqueVertex )
  424. {
  425. DeltaIndex_t &index = pDeltaStateData->m_DeltaIndices[ nUniqueVertex ];
  426. if ( !index.m_bInList )
  427. {
  428. index.m_nNextDelta = pDeltaStateData->m_nFirstDelta;
  429. pDeltaStateData->m_nFirstDelta = nUniqueVertex;
  430. pDeltaStateData->m_nDeltaCount++;
  431. index.m_bInList = true;
  432. }
  433. }
  434. //-----------------------------------------------------------------------------
  435. // Loads the vertices from the delta state
  436. //-----------------------------------------------------------------------------
  437. static bool LoadDeltaState(
  438. CDmeVertexDeltaData *pDeltaState,
  439. CDmeVertexData *pBindState,
  440. const matrix3x4_t& mat,
  441. float flScale,
  442. int nStartingUniqueVertex,
  443. int nStartingUniqueVertexMap )
  444. {
  445. DeltaState_t *pDeltaStateData = FindOrAddDeltaState( pDeltaState->GetName(), nStartingUniqueVertex + pBindState->VertexCount() );
  446. matrix3x4_t normalMat;
  447. MatrixInverseTranspose( mat, normalMat );
  448. const CUtlVector<Vector> &positions = pDeltaState->GetPositionData( );
  449. const CUtlVector<int> &positionIndices = pDeltaState->GetVertexIndexData( CDmeVertexDataBase::FIELD_POSITION );
  450. const CUtlVector<Vector> &normals = pDeltaState->GetNormalData( );
  451. const CUtlVector<int> &normalIndices = pDeltaState->GetVertexIndexData( CDmeVertexDataBase::FIELD_NORMAL );
  452. const CUtlVector<float> &wrinkle = pDeltaState->GetWrinkleData( );
  453. const CUtlVector<int> &wrinkleIndices = pDeltaState->GetVertexIndexData( CDmeVertexDataBase::FIELD_WRINKLE );
  454. if ( positions.Count() != positionIndices.Count() )
  455. {
  456. MdlError( "DeltaState %s contains a different number of positions + position indices!\n", pDeltaState->GetName() );
  457. return false;
  458. }
  459. if ( normals.Count() != normalIndices.Count() )
  460. {
  461. MdlError( "DeltaState %s contains a different number of normals + normal indices!\n", pDeltaState->GetName() );
  462. return false;
  463. }
  464. if ( wrinkle.Count() != wrinkleIndices.Count() )
  465. {
  466. MdlError( "DeltaState %s contains a different number of wrinkles + wrinkle indices!\n", pDeltaState->GetName() );
  467. return false;
  468. }
  469. // Copy position delta
  470. int nCount = positions.Count();
  471. for ( int i = 0; i < nCount; ++i )
  472. {
  473. Vector vecDelta;
  474. // NOTE NOTE!!: This is VectorRotate, *not* VectorTransform. This is because
  475. // we're transforming a delta, which is basically a direction vector. To
  476. // move it into the new space, we must rotate it
  477. VectorRotate( positions[i], mat, vecDelta );
  478. vecDelta *= flScale;
  479. int nPositionIndex = pDeltaStateData->m_PositionDeltas.AddToTail( vecDelta );
  480. // Indices
  481. const CUtlVector< int > &baseVerts = pBindState->FindVertexIndicesFromDataIndex( CDmeVertexData::FIELD_POSITION, positionIndices[i] );
  482. int nBaseVertCount = baseVerts.Count();
  483. for ( int k = 0; k < nBaseVertCount; ++k )
  484. {
  485. int nUniqueVertexIndex = s_UniqueVerticesMap[ nStartingUniqueVertexMap + baseVerts[k] ];
  486. AddToDeltaList( pDeltaStateData, nUniqueVertexIndex );
  487. DeltaIndex_t &index = pDeltaStateData->m_DeltaIndices[ nUniqueVertexIndex ];
  488. index.m_nPositionIndex = nPositionIndex;
  489. }
  490. }
  491. // Copy normals
  492. nCount = normals.Count();
  493. for ( int i = 0; i < nCount; ++i )
  494. {
  495. Vector vecDelta;
  496. VectorRotate( normals[i], normalMat, vecDelta );
  497. int nNormalIndex = pDeltaStateData->m_NormalDeltas.AddToTail( vecDelta );
  498. // Indices
  499. const CUtlVector< int > &baseVerts = pBindState->FindVertexIndicesFromDataIndex( CDmeVertexData::FIELD_NORMAL, normalIndices[i] );
  500. int nBaseVertCount = baseVerts.Count();
  501. for ( int k = 0; k < nBaseVertCount; ++k )
  502. {
  503. int nUniqueVertexIndex = s_UniqueVerticesMap[ nStartingUniqueVertexMap + baseVerts[k] ];
  504. AddToDeltaList( pDeltaStateData, nUniqueVertexIndex );
  505. DeltaIndex_t &index = pDeltaStateData->m_DeltaIndices[ nUniqueVertexIndex ];
  506. index.m_nNormalIndex = nNormalIndex;
  507. }
  508. }
  509. // Copy wrinkle
  510. nCount = wrinkle.Count();
  511. for ( int i = 0; i < nCount; ++i )
  512. {
  513. int nWrinkleIndex = pDeltaStateData->m_WrinkleDeltas.AddToTail( wrinkle[i] );
  514. // Indices
  515. const CUtlVector< int > &baseVerts = pBindState->FindVertexIndicesFromDataIndex( CDmeVertexData::FIELD_WRINKLE, wrinkleIndices[i] );
  516. int nBaseVertCount = baseVerts.Count();
  517. for ( int k = 0; k < nBaseVertCount; ++k )
  518. {
  519. int nUniqueVertexIndex = s_UniqueVerticesMap[ nStartingUniqueVertexMap + baseVerts[k] ];
  520. AddToDeltaList( pDeltaStateData, nUniqueVertexIndex );
  521. DeltaIndex_t &index = pDeltaStateData->m_DeltaIndices[ nUniqueVertexIndex ];
  522. index.m_nWrinkleIndex = nWrinkleIndex;
  523. }
  524. }
  525. return true;
  526. }
  527. static int GetExtraTexcoordIndex(CDmeVertexData *pVertexData, int nVertexIndex, int nChannel)
  528. {
  529. FieldIndex_t nFieldIndex = pVertexData->FindFieldIndex(CFmtStr("texcoord$%d", nChannel).Get());
  530. if (nFieldIndex < 0)
  531. return -1;
  532. CDmrArrayConst<int> indices(pVertexData->GetIndexData(nFieldIndex));
  533. return indices[nVertexIndex];
  534. }
  535. // JasonM TODO: unify ParseQuadFaceData() and ParseFaceData()
  536. //-----------------------------------------------------------------------------
  537. // Reads the quad face data from the DMX data
  538. //-----------------------------------------------------------------------------
  539. static void ParseQuadFaceData( CDmeVertexData *pVertexData, int material, int *pIndices, int vi, int ni, int* ti )
  540. {
  541. s_tmpface_t f;
  542. f.material = material;
  543. int p, n, t;
  544. p = pVertexData->GetPositionIndex(pIndices[0]); n = pVertexData->GetNormalIndex(pIndices[0]); t = pVertexData->GetTexCoordIndex(pIndices[0]);
  545. f.a = (p >= 0) ? vi + p : 0; f.na = (n >= 0) ? ni + n : 0; f.ta[0] = (t >= 0) ? ti[0] + t : 0;
  546. p = pVertexData->GetPositionIndex(pIndices[3]); n = pVertexData->GetNormalIndex(pIndices[3]); t = pVertexData->GetTexCoordIndex(pIndices[3]);
  547. f.b = (p >= 0) ? vi + p : 0; f.nb = (n >= 0) ? ni + n : 0; f.tb[0] = (t >= 0) ? ti[0] + t : 0;
  548. p = pVertexData->GetPositionIndex(pIndices[2]); n = pVertexData->GetNormalIndex(pIndices[2]); t = pVertexData->GetTexCoordIndex(pIndices[2]);
  549. f.c = (p >= 0) ? vi + p : 0; f.nc = (n >= 0) ? ni + n : 0; f.tc[0] = (t >= 0) ? ti[0] + t : 0;
  550. p = pVertexData->GetPositionIndex(pIndices[1]); n = pVertexData->GetNormalIndex(pIndices[1]); t = pVertexData->GetTexCoordIndex(pIndices[1]);
  551. f.d = (p >= 0) ? vi + p : 0; f.nd = (n >= 0) ? ni + n : 0; f.td[0] = (t >= 0) ? ti[0] + t : 0;
  552. Assert( f.a <= (unsigned long)g_numverts && f.b <= (unsigned long)g_numverts && f.c <= (unsigned long)g_numverts && f.d <= (unsigned long)g_numverts );
  553. Assert( f.na <= (unsigned long)g_numnormals && f.nb <= (unsigned long)g_numnormals && f.nc <= (unsigned long)g_numnormals && f.nd <= (unsigned long)g_numnormals );
  554. Assert(f.ta[0] <= (unsigned long)g_numtexcoords[0] && f.tb[0] <= (unsigned long)g_numtexcoords[0] && f.tc[0] <= (unsigned long)g_numtexcoords[0] && f.td[0] <= (unsigned long)g_numtexcoords[0]);
  555. for (int i = 1; i < (MAXSTUDIOTEXCOORDS); ++i)
  556. {
  557. t = GetExtraTexcoordIndex(pVertexData, pIndices[0], i);
  558. f.ta[i] = (t >= 0) ? ti[i] + t : 0;
  559. t = GetExtraTexcoordIndex(pVertexData, pIndices[3], i);
  560. f.tb[i] = (t >= 0) ? ti[i] + t : 0;
  561. t = GetExtraTexcoordIndex(pVertexData, pIndices[2], i);
  562. f.tc[i] = (t >= 0) ? ti[i] + t : 0;
  563. t = GetExtraTexcoordIndex(pVertexData, pIndices[1], i);
  564. f.td[i] = (t >= 0) ? ti[i] + t : 0;
  565. Assert(f.ta[i] <= (unsigned long)g_numtexcoords[i] && f.tb[i] <= (unsigned long)g_numtexcoords[i] && f.tc[i] <= (unsigned long)g_numtexcoords[i] && f.td[i] <= (unsigned long)g_numtexcoords[i]);
  566. }
  567. int i = g_numfaces++;
  568. g_face[i] = f;
  569. }
  570. //-----------------------------------------------------------------------------
  571. // Reads the face data from the DMX data
  572. //-----------------------------------------------------------------------------
  573. static void ParseFaceData( CDmeVertexData *pVertexData, int material, int v1, int v2, int v3, int vi, int ni, int* ti )
  574. {
  575. s_tmpface_t f;
  576. f.material = material;
  577. int p, n, t;
  578. p = pVertexData->GetPositionIndex(v1); n = pVertexData->GetNormalIndex(v1); t = pVertexData->GetTexCoordIndex(v1);
  579. f.a = (p >= 0) ? vi + p : 0; f.na = (n >= 0) ? ni + n : 0; f.ta[0] = (t >= 0) ? ti[0] + t : 0;
  580. p = pVertexData->GetPositionIndex(v2); n = pVertexData->GetNormalIndex(v2); t = pVertexData->GetTexCoordIndex(v2);
  581. f.b = (p >= 0) ? vi + p : 0; f.nb = (n >= 0) ? ni + n : 0; f.tb[0] = (t >= 0) ? ti[0] + t : 0;
  582. p = pVertexData->GetPositionIndex(v3); n = pVertexData->GetNormalIndex(v3); t = pVertexData->GetTexCoordIndex(v3);
  583. f.c = (p >= 0) ? vi + p : 0; f.nc = (n >= 0) ? ni + n : 0; f.tc[0] = (t >= 0) ? ti[0] + t : 0;
  584. Assert( f.a <= (unsigned long)g_numverts && f.b <= (unsigned long)g_numverts && f.c <= (unsigned long)g_numverts );
  585. Assert( f.na <= (unsigned long)g_numnormals && f.nb <= (unsigned long)g_numnormals && f.nc <= (unsigned long)g_numnormals );
  586. Assert(f.ta[0] <= (unsigned long)g_numtexcoords[0] && f.tb[0] <= (unsigned long)g_numtexcoords[0] && f.tc[0] <= (unsigned long)g_numtexcoords[0]);
  587. for (int i = 1; i < (MAXSTUDIOTEXCOORDS); ++i)
  588. {
  589. t = GetExtraTexcoordIndex(pVertexData, v1, i);
  590. f.ta[i] = (t >= 0) ? ti[i] + t : 0;
  591. t = GetExtraTexcoordIndex(pVertexData, v2, i);
  592. f.tb[i] = (t >= 0) ? ti[i] + t : 0;
  593. t = GetExtraTexcoordIndex(pVertexData, v3, i);
  594. f.tc[i] = (t >= 0) ? ti[i] + t : 0;
  595. Assert(f.ta[i] <= (unsigned long)g_numtexcoords[i] && f.tb[i] <= (unsigned long)g_numtexcoords[i] && f.tc[i] <= (unsigned long)g_numtexcoords[i]);
  596. }
  597. int i = g_numfaces++;
  598. g_face[i] = f;
  599. }
  600. //-----------------------------------------------------------------------------
  601. // Reads the mesh data from the DMX data
  602. //-----------------------------------------------------------------------------
  603. static bool LoadMesh( CDmeDag *pDmeDag, CDmeMesh *pMesh, CDmeVertexData *pBindState, const matrix3x4_t& mat, float flScale,
  604. int nBoneAssign, int *pBoneRemap, s_source_t *pSource )
  605. {
  606. pMesh->CollapseRedundantNormals( normal_blend );
  607. // Load the vertices
  608. int nStartingVertex = g_numverts;
  609. int nStartingNormal = g_numnormals;
  610. int nStartingUniqueCount = s_UniqueVertices.Count();
  611. int nStartingUniqueMapCount = s_UniqueVerticesMap.Count();
  612. int nStartingTexCoord[MAXSTUDIOTEXCOORDS];
  613. for (int i = 0; i < MAXSTUDIOTEXCOORDS; ++i)
  614. {
  615. nStartingTexCoord[i] = g_numtexcoords[i];
  616. }
  617. // This defines s_UniqueVertices & s_UniqueVerticesMap
  618. LoadVertices( pDmeDag, pBindState, mat, flScale, nBoneAssign, pBoneRemap, pSource );
  619. // Load the deltas
  620. int nDeltaStateCount = pMesh->DeltaStateCount();
  621. for ( int i = 0; i < nDeltaStateCount; ++i )
  622. {
  623. CDmeVertexDeltaData *pDeltaState = pMesh->GetDeltaState( i );
  624. if ( !LoadDeltaState( pDeltaState, pBindState, mat, flScale, nStartingUniqueCount, nStartingUniqueMapCount ) )
  625. return false;
  626. }
  627. // load the base triangles
  628. int texture;
  629. int material;
  630. char pTextureName[MAX_PATH];
  631. int nFaceSetCount = pMesh->FaceSetCount();
  632. for ( int i = 0; i < nFaceSetCount; ++i )
  633. {
  634. CDmeFaceSet *pFaceSet = pMesh->GetFaceSet( i );
  635. CDmeMaterial *pMaterial = pFaceSet->GetMaterial();
  636. // Get the material name
  637. Q_strncpy( pTextureName, pMaterial->GetMaterialName(), sizeof(pTextureName) );
  638. // funky texture overrides (specified with the -t command-line argument)
  639. for ( int j = 0; j < numrep; j++ )
  640. {
  641. if ( sourcetexture[j][0] == '\0' )
  642. {
  643. Q_strncpy( pTextureName, defaulttexture[j], sizeof(pTextureName) );
  644. break;
  645. }
  646. if ( Q_stricmp( pTextureName, sourcetexture[j]) == 0 )
  647. {
  648. Q_strncpy( pTextureName, defaulttexture[j], sizeof(pTextureName) );
  649. break;
  650. }
  651. }
  652. // skip all faces with the null texture on them.
  653. char pPathNoExt[MAX_PATH];
  654. Q_StripExtension( pTextureName, pPathNoExt, sizeof(pPathNoExt) );
  655. if ( !Q_stricmp( pPathNoExt, "null" ) )
  656. continue;
  657. texture = LookupTexture( pTextureName, true );
  658. pSource->texmap[texture] = texture; // hack, make it 1:1
  659. material = UseTextureAsMaterial( texture );
  660. // Is this a quad-only subd?
  661. bool bQuadSubd = ( gflags & STUDIOHDR_FLAGS_SUBDIVISION_SURFACE ) != 0;
  662. // prepare indices
  663. int nFirstIndex = 0;
  664. int nIndexCount = pFaceSet->NumIndices();
  665. while ( nFirstIndex < nIndexCount )
  666. {
  667. int nVertexCount = pFaceSet->GetNextPolygonVertexCount( nFirstIndex );
  668. // Quad subd face?
  669. if ( bQuadSubd && ( nVertexCount == 4 ) )
  670. {
  671. int quadIndices[4];
  672. for ( int j = 0; j < 4; j++ )
  673. {
  674. quadIndices[j] = pFaceSet->GetIndex( nFirstIndex + j );
  675. }
  676. ParseQuadFaceData( pBindState, material, quadIndices, nStartingVertex, nStartingNormal, nStartingTexCoord );
  677. nFirstIndex += 5; // -1 in list between face indices, so jump over 5 elements, not 4
  678. }
  679. else
  680. {
  681. if ( nVertexCount >= 3 )
  682. {
  683. int nOutCount = (nVertexCount-2) * 3;
  684. int *pIndices = (int*)malloc( nOutCount * sizeof(int) );
  685. pMesh->ComputeTriangulatedIndices( pBindState, pFaceSet, nFirstIndex, pIndices, nOutCount );
  686. for ( int ii = 0; ii < nOutCount; ii +=3 )
  687. {
  688. ParseFaceData( pBindState, material, pIndices[ii], pIndices[ii+2], pIndices[ii+1], nStartingVertex, nStartingNormal, nStartingTexCoord );
  689. }
  690. free( pIndices );
  691. }
  692. nFirstIndex += nVertexCount + 1; // -1 in list between face indices, so jump over nVertexCount + 1 elements, not nVertexCount elements
  693. }
  694. }
  695. }
  696. return true;
  697. }
  698. //-----------------------------------------------------------------------------
  699. // Method used to add mesh data
  700. //-----------------------------------------------------------------------------
  701. struct LoadMeshInfo_t
  702. {
  703. s_source_t *m_pSource;
  704. CDmeModel *m_pModel;
  705. float m_flScale;
  706. int *m_pBoneRemap;
  707. matrix3x4_t m_pBindPose[MAXSTUDIOSRCBONES];
  708. };
  709. static bool LoadMeshes( const LoadMeshInfo_t &info, CDmeDag *pDag, const matrix3x4_t &parentToBindPose, int nBoneAssign )
  710. {
  711. // We want to create an aggregate matrix transforming from this dag to its closest
  712. // parent which actually is an animated joint. This is done so we can autoskin
  713. // meshes to their closest parents if they have not been skinned.
  714. matrix3x4_t dagToBindPose;
  715. int nFoundIndex = info.m_pModel->GetJointIndex( pDag );
  716. if ( nFoundIndex >= 0 /* && ( pDag == info.m_pModel || CastElement< CDmeJoint >( pDag ) ) */ )
  717. {
  718. nBoneAssign = nFoundIndex;
  719. }
  720. if ( nFoundIndex >= 0 )
  721. {
  722. ConcatTransforms( parentToBindPose, info.m_pBindPose[nFoundIndex], dagToBindPose );
  723. }
  724. else
  725. {
  726. // NOTE: This isn't particularly kosher; we're using the current pose instead of the bind pose
  727. // because there's no transform in the bind pose
  728. matrix3x4_t dagToParent;
  729. pDag->GetTransform()->GetTransform( dagToParent );
  730. ConcatTransforms( parentToBindPose, dagToParent, dagToBindPose );
  731. }
  732. CDmeMesh *pMesh = CastElement< CDmeMesh >( pDag->GetShape() );
  733. if ( pMesh )
  734. {
  735. CDmeVertexData *pBindState = pMesh->FindBaseState( "bind" );
  736. if ( !pBindState )
  737. return false;
  738. if ( !LoadMesh( pDag, pMesh, pBindState, dagToBindPose, info.m_flScale, nBoneAssign, info.m_pBoneRemap, info.m_pSource ) )
  739. return false;
  740. }
  741. int nCount = pDag->GetChildCount();
  742. for ( int i = 0; i < nCount; ++i )
  743. {
  744. CDmeDag *pChild = pDag->GetChild( i );
  745. if ( !LoadMeshes( info, pChild, dagToBindPose, nBoneAssign ) )
  746. return false;
  747. }
  748. return true;
  749. }
  750. //-----------------------------------------------------------------------------
  751. // Method used to add mesh data
  752. //-----------------------------------------------------------------------------
  753. static bool LoadMeshes( CDmeModel *pModel, float flScale, int *pBoneRemap, s_source_t *pSource )
  754. {
  755. matrix3x4_t mat;
  756. SetIdentityMatrix( mat );
  757. LoadMeshInfo_t info;
  758. info.m_pModel = pModel;
  759. info.m_flScale = flScale;
  760. info.m_pBoneRemap = pBoneRemap;
  761. info.m_pSource = pSource;
  762. CDmeTransformList *pBindPose = pModel->FindBaseState( "bind" );
  763. int nCount = pBindPose ? pBindPose->GetTransformCount() : pModel->GetJointCount();
  764. for ( int i = 0; i < nCount; ++i )
  765. {
  766. CDmeTransform *pTransform = pBindPose ? pBindPose->GetTransform(i) : pModel->GetJointTransform(i);
  767. matrix3x4_t jointTransform;
  768. pTransform->GetTransform( info.m_pBindPose[i] );
  769. }
  770. int nChildCount = pModel->GetChildCount();
  771. for ( int i = 0; i < nChildCount; ++i )
  772. {
  773. CDmeDag *pChild = pModel->GetChild( i );
  774. if ( !LoadMeshes( info, pChild, mat, -1 ) )
  775. return false;
  776. }
  777. return true;
  778. }
  779. //-----------------------------------------------------------------------------
  780. // Builds s_vertanim_ts
  781. //-----------------------------------------------------------------------------
  782. static void BuildVertexAnimations( s_source_t *pSource )
  783. {
  784. int nCount = s_DeltaStates.Count();
  785. if ( nCount == 0 )
  786. return;
  787. Assert( s_Speed.Count() > 0 );
  788. Assert( s_Balance.Count() > 0 );
  789. Assert( s_UniqueVertices.Count() == g_numvlist );
  790. s_vertanim_t *pVertAnim = (s_vertanim_t *)malloc( g_numvlist * sizeof( s_vertanim_t ) );
  791. for ( int i = 0; i < nCount; ++i )
  792. {
  793. DeltaState_t &state = s_DeltaStates[i];
  794. s_sourceanim_t *pSourceAnim = FindOrAddSourceAnim( pSource, state.m_Name );
  795. pSourceAnim->numframes = 1;
  796. pSourceAnim->startframe = 0;
  797. pSourceAnim->endframe = 0;
  798. pSourceAnim->newStyleVertexAnimations = true;
  799. // Traverse the linked list of unique vertex indices j that has a delta
  800. int nVertAnimCount = 0;
  801. for ( int j = state.m_nFirstDelta; j >= 0; j = state.m_DeltaIndices[j].m_nNextDelta )
  802. {
  803. // The Delta Indices array is a parallel array to s_UniqueVertices
  804. // j is used to index into both
  805. DeltaIndex_t &delta = state.m_DeltaIndices[j];
  806. Assert( delta.m_nPositionIndex >= 0 || delta.m_nNormalIndex >= 0 || delta.m_nWrinkleIndex >= 0 );
  807. VertIndices_t &uniqueVert = s_UniqueVertices[j];
  808. const v_unify_t *pList = v_list[uniqueVert.v];
  809. for( ; pList; pList = pList->next )
  810. {
  811. if ( pList->n != uniqueVert.n || pList->t[0] != uniqueVert.t[0] )
  812. continue;
  813. s_vertanim_t& vertanim = pVertAnim[nVertAnimCount++];
  814. vertanim.vertex = pList - v_listdata;
  815. vertanim.speed = s_Speed[ s_UniqueVertices[j].speed ];
  816. vertanim.side = s_Balance[ s_UniqueVertices[j].balance ];
  817. if ( delta.m_nPositionIndex >= 0 )
  818. {
  819. vertanim.pos = state.m_PositionDeltas[ delta.m_nPositionIndex ];
  820. }
  821. else
  822. {
  823. vertanim.pos = vec3_origin;
  824. }
  825. if ( delta.m_nNormalIndex >= 0 )
  826. {
  827. vertanim.normal = state.m_NormalDeltas[ delta.m_nNormalIndex ];
  828. }
  829. else
  830. {
  831. vertanim.normal = vec3_origin;
  832. }
  833. if ( delta.m_nWrinkleIndex >= 0 )
  834. {
  835. vertanim.wrinkle = state.m_WrinkleDeltas[ delta.m_nWrinkleIndex ];
  836. }
  837. else
  838. {
  839. vertanim.wrinkle = 0.0f;
  840. }
  841. }
  842. }
  843. pSourceAnim->numvanims[0] = nVertAnimCount;
  844. pSourceAnim->vanim[0] = (s_vertanim_t *)calloc( nVertAnimCount, sizeof( s_vertanim_t ) );
  845. memcpy( pSourceAnim->vanim[0], pVertAnim, nVertAnimCount * sizeof( s_vertanim_t ) );
  846. }
  847. free( pVertAnim );
  848. }
  849. //-----------------------------------------------------------------------------
  850. // Handles DmeJiggleBones
  851. //-----------------------------------------------------------------------------
  852. static void HandleDmeJiggleBone( const CDmeDag *pDmeDag )
  853. {
  854. const CDmeJiggleBone *pDmeJiggleBone = CastElementConst< CDmeJiggleBone >( pDmeDag );
  855. if ( !pDmeJiggleBone )
  856. return;
  857. const char *pName = pDmeJiggleBone->GetName();
  858. for ( int i = 0; i < g_numjigglebones; ++i )
  859. {
  860. if ( !Q_stricmp( pName, g_jigglebones[i].bonename ) )
  861. {
  862. MdlWarning( "2000: Jiggle Bone: %s already defined, ignoring additional declarations\n", pName );
  863. return;
  864. }
  865. }
  866. struct s_jigglebone_t *pJiggleBone = &g_jigglebones[ g_numjigglebones ];
  867. ++g_numjigglebones;
  868. Q_strncpy( pJiggleBone->bonename, pName, sizeof( pJiggleBone->bonename ) );
  869. // default values
  870. memset( &pJiggleBone->data, 0, sizeof( mstudiojigglebone_t ) );
  871. pJiggleBone->data.length = 10.0f;
  872. pJiggleBone->data.yawStiffness = 100.0f;
  873. pJiggleBone->data.pitchStiffness = 100.0f;
  874. pJiggleBone->data.alongStiffness = 100.0f;
  875. pJiggleBone->data.baseStiffness = 100.0f;
  876. pJiggleBone->data.baseMinUp = -100.0f;
  877. pJiggleBone->data.baseMaxUp = 100.0f;
  878. pJiggleBone->data.baseMinLeft = -100.0f;
  879. pJiggleBone->data.baseMaxLeft = 100.0f;
  880. pJiggleBone->data.baseMinForward = -100.0f;
  881. pJiggleBone->data.baseMaxForward = 100.0f;
  882. // Common Parameters
  883. pJiggleBone->data.length = pDmeJiggleBone->m_flLength;
  884. pJiggleBone->data.tipMass = pDmeJiggleBone->m_flTipMass;
  885. pJiggleBone->data.flags |= ( pDmeJiggleBone->m_bLengthConstrained ? JIGGLE_HAS_LENGTH_CONSTRAINT : 0 );
  886. pJiggleBone->data.angleLimit = DEG2RAD( pDmeJiggleBone->m_flAngleLimit );
  887. pJiggleBone->data.flags |= ( pDmeJiggleBone->m_bYawConstrained ? JIGGLE_HAS_YAW_CONSTRAINT : 0 );
  888. pJiggleBone->data.minYaw = DEG2RAD( pDmeJiggleBone->m_flYawMin );
  889. pJiggleBone->data.maxYaw = DEG2RAD( pDmeJiggleBone->m_flYawMax );
  890. pJiggleBone->data.yawFriction = pDmeJiggleBone->m_flYawFriction;
  891. pJiggleBone->data.yawBounce = pDmeJiggleBone->m_flYawBounce;
  892. pJiggleBone->data.flags |= ( pDmeJiggleBone->m_bAngleConstrained ? JIGGLE_HAS_ANGLE_CONSTRAINT : 0 );
  893. pJiggleBone->data.minPitch = DEG2RAD( pDmeJiggleBone->m_flPitchMin );
  894. pJiggleBone->data.maxPitch = DEG2RAD( pDmeJiggleBone->m_flPitchMax );
  895. pJiggleBone->data.pitchFriction = pDmeJiggleBone->m_flPitchFriction;
  896. pJiggleBone->data.pitchBounce = pDmeJiggleBone->m_flPitchBounce;
  897. if ( pDmeJiggleBone->m_bFlexible )
  898. {
  899. if ( pDmeJiggleBone->m_bRigid )
  900. {
  901. MdlWarning( "2001: Jiggle Bone %s: Both flexible and rigid set, ignoring rigid\n", pName );
  902. }
  903. pJiggleBone->data.flags |= ( JIGGLE_IS_FLEXIBLE );
  904. pJiggleBone->data.flags |= ( pDmeJiggleBone->m_bPitchConstrained ? JIGGLE_HAS_PITCH_CONSTRAINT : 0 );
  905. // flexible parameters - I think damping should be clamped [0, 10] but code
  906. // in studiomdl looks incorrect and clamps 0, 1000.0f
  907. pJiggleBone->data.yawStiffness = clamp( pDmeJiggleBone->m_flYawStiffness.Get(), 0.0f, 1000.0f );
  908. pJiggleBone->data.yawDamping = clamp( pDmeJiggleBone->m_flYawDamping.Get(), 0.0f, 10.0f );
  909. pJiggleBone->data.pitchStiffness = clamp( pDmeJiggleBone->m_flPitchStiffness.Get(), 0.0f, 1000.0f );
  910. pJiggleBone->data.pitchDamping = clamp( pDmeJiggleBone->m_flPitchDamping.Get(), 0.0f, 10.0f );
  911. pJiggleBone->data.alongStiffness = clamp( pDmeJiggleBone->m_flAlongStiffness.Get(), 0.0f, 1000.0f );
  912. pJiggleBone->data.alongDamping = clamp( pDmeJiggleBone->m_flAlongDamping.Get(), 0.0f, 10.0f );
  913. }
  914. else if ( pDmeJiggleBone->m_bRigid )
  915. {
  916. pJiggleBone->data.flags |= ( JIGGLE_IS_FLEXIBLE | JIGGLE_HAS_LENGTH_CONSTRAINT );
  917. }
  918. else
  919. {
  920. // TODO: Is neither rigid or flexible an error?
  921. }
  922. if ( pDmeJiggleBone->m_bBaseSpring )
  923. {
  924. // flexible parameters - I think damping should be clamped [0, 10] but code
  925. // in studiomdl looks incorrect and clamps 0, 1000.0f
  926. pJiggleBone->data.baseMass = pDmeJiggleBone->m_flBaseMass;
  927. pJiggleBone->data.baseStiffness = clamp( pDmeJiggleBone->m_flBaseStiffness.Get(), 0.0f, 1000.0f );
  928. pJiggleBone->data.baseDamping = clamp( pDmeJiggleBone->m_flBaseStiffness.Get(), 0.0f, 10.0f );
  929. pJiggleBone->data.baseMinLeft = pDmeJiggleBone->m_flBaseYawMin;
  930. pJiggleBone->data.baseMaxLeft = pDmeJiggleBone->m_flBaseYawMax;
  931. pJiggleBone->data.baseLeftFriction = pDmeJiggleBone->m_flBaseYawFriction;
  932. pJiggleBone->data.baseMinUp = pDmeJiggleBone->m_flBasePitchMin;
  933. pJiggleBone->data.baseMaxUp = pDmeJiggleBone->m_flBasePitchMax;
  934. pJiggleBone->data.baseUpFriction = pDmeJiggleBone->m_flBasePitchFriction;
  935. pJiggleBone->data.baseMinForward = pDmeJiggleBone->m_flBaseAlongMin;
  936. pJiggleBone->data.baseMaxForward = pDmeJiggleBone->m_flBaseAlongMax;
  937. pJiggleBone->data.baseForwardFriction = pDmeJiggleBone->m_flBaseAlongFriction;
  938. }
  939. }
  940. //-----------------------------------------------------------------------------
  941. // Loads the skeletal hierarchy from the game model, returns bone count
  942. //-----------------------------------------------------------------------------
  943. static bool AddDagJoint( CDmeModel *pModel, CDmeDag *pDag, s_node_t *pNodes, int nParentIndex, BoneTransformMap_t &boneMap )
  944. {
  945. CDmeTransform *pDmeTransform = pDag->GetTransform();
  946. if ( !pDmeTransform )
  947. return true;
  948. // Need room for one implicit bone added
  949. if ( boneMap.m_nBoneCount >= ( MAXSTUDIOSRCBONES - 1 ) )
  950. {
  951. MdlWarning( "Ignoring Bone %s and children, too many bones [max can be %d]!\n", pDag->GetName(), MAXSTUDIOSRCBONES - 1 );
  952. return false;
  953. }
  954. const int nJointIndex = boneMap.m_nBoneCount++;
  955. boneMap.m_ppTransforms[ nJointIndex ] = pDmeTransform;
  956. if ( pModel )
  957. {
  958. const int nFoundIndex = pModel->GetJointIndex( pDag );
  959. if ( nFoundIndex >= 0 )
  960. {
  961. boneMap.m_pnDmeModelToMdl[ nFoundIndex ] = nJointIndex;
  962. boneMap.m_pnMdlToDmeModel[ nJointIndex ] = nFoundIndex;
  963. }
  964. else
  965. {
  966. MdlWarning( "Joint %s doesn't appear in DmeModel[%s].jointList\n", pDag->GetName(), pModel->GetName() );
  967. }
  968. }
  969. HandleDmeJiggleBone( pDag );
  970. Q_strncpy( pNodes[ nJointIndex ].name, pDag->GetName(), sizeof( pNodes[ nJointIndex ].name ) );
  971. pNodes[ nJointIndex ].parent = nParentIndex;
  972. // Now deal with children
  973. for ( int i = 0; i < pDag->GetChildCount(); ++i )
  974. {
  975. CDmeDag *pChild = pDag->GetChild( i );
  976. if ( !pChild )
  977. continue;
  978. if ( !AddDagJoint( pModel, pChild, pNodes, nJointIndex, boneMap ) )
  979. return false;
  980. }
  981. return true;
  982. }
  983. //-----------------------------------------------------------------------------
  984. // Main entry point for loading the skeleton
  985. //-----------------------------------------------------------------------------
  986. static int LoadSkeleton( CDmeDag *pRoot, CDmeModel *pModel, s_node_t *pNodes, BoneTransformMap_t &boneMap )
  987. {
  988. // Initialize bone indices
  989. boneMap.m_nBoneCount = 0;
  990. for ( int i = 0; i < MAXSTUDIOSRCBONES; ++i )
  991. {
  992. pNodes[i].name[0] = 0;
  993. pNodes[i].parent = -1;
  994. boneMap.m_pnDmeModelToMdl[i] = -1;
  995. boneMap.m_pnMdlToDmeModel[i] = -1;
  996. boneMap.m_ppTransforms[i] = NULL;
  997. }
  998. // Don't create joints for the the root dag ever.. just deal with the children
  999. for ( int i = 0; i < pRoot->GetChildCount(); ++i )
  1000. {
  1001. CDmeDag *pChild = pRoot->GetChild( i );
  1002. if ( !pChild )
  1003. continue;
  1004. if ( !AddDagJoint( pModel, pChild, pNodes, -1, boneMap ) )
  1005. return 0;
  1006. }
  1007. // Add a default identity bone used for autoskinning if no joints are specified
  1008. s_nDefaultRootNode = boneMap.m_nBoneCount;
  1009. Q_strncpy( pNodes[s_nDefaultRootNode].name, "defaultRoot", sizeof( pNodes[ s_nDefaultRootNode ].name ) );
  1010. pNodes[s_nDefaultRootNode].parent = -1;
  1011. // +1 for the default identity bone just added
  1012. return boneMap.m_nBoneCount + 1;
  1013. }
  1014. //-----------------------------------------------------------------------------
  1015. // Loads the attachments found in the file
  1016. //-----------------------------------------------------------------------------
  1017. static void LoadAttachments( CDmeDag *pRoot, CDmeDag *pDag, s_source_t *pSource, bool bStaticProp )
  1018. {
  1019. CDmeAttachment *pAttachment = CastElement< CDmeAttachment >( pDag->GetShape() );
  1020. if ( pAttachment && ( pDag != pRoot ) )
  1021. {
  1022. int i = pSource->m_Attachments.AddToTail();
  1023. s_attachment_t &attachment = pSource->m_Attachments[i];
  1024. memset( &attachment, 0, sizeof(s_attachment_t) );
  1025. Q_strncpy( attachment.name, pAttachment->GetName(), sizeof( attachment.name ) );
  1026. Q_strncpy( attachment.bonename, pDag->GetName(), sizeof( attachment.bonename ) );
  1027. SetIdentityMatrix( attachment.local );
  1028. if ( bStaticProp )
  1029. {
  1030. // Static prop will remove all bones so put the attachment transform
  1031. // on the attachment rather than the bone. Also ignore all attachment
  1032. // flags
  1033. pDag->GetAbsTransform( attachment.local );
  1034. }
  1035. else
  1036. {
  1037. if ( pAttachment->m_bIsRigid )
  1038. {
  1039. attachment.type |= IS_RIGID;
  1040. }
  1041. if ( pAttachment->m_bIsWorldAligned )
  1042. {
  1043. attachment.flags |= ATTACHMENT_FLAG_WORLD_ALIGN;
  1044. }
  1045. }
  1046. }
  1047. // Don't create joints for the the root dag ever.. just deal with the children
  1048. int nChildCount = pDag->GetChildCount();
  1049. for ( int i = 0; i < nChildCount; ++i )
  1050. {
  1051. CDmeDag *pChild = pDag->GetChild( i );
  1052. if ( !pChild )
  1053. continue;
  1054. LoadAttachments( pRoot, pChild, pSource, bStaticProp );
  1055. }
  1056. }
  1057. //-----------------------------------------------------------------------------
  1058. // Loads the bind pose
  1059. //-----------------------------------------------------------------------------
  1060. static void LoadBindPose( CDmeModel *pModel, float flScale, const BoneTransformMap_t &boneMap, s_source_t *pSource )
  1061. {
  1062. s_sourceanim_t *pSourceAnim = FindOrAddSourceAnim( pSource, "BindPose" );
  1063. pSourceAnim->startframe = 0;
  1064. pSourceAnim->endframe = 0;
  1065. pSourceAnim->numframes = 1;
  1066. // Default all transforms to identity
  1067. pSourceAnim->rawanim[0] = (s_bone_t *)calloc( pSource->numbones, sizeof(s_bone_t) );
  1068. for ( int i = 0; i < pSource->numbones; ++i )
  1069. {
  1070. pSourceAnim->rawanim[0][i].pos.Init();
  1071. pSourceAnim->rawanim[0][i].rot.Init();
  1072. }
  1073. {
  1074. matrix3x4_t jointTransform;
  1075. CDmeTransformList *pBindPose = pModel->FindBaseState( "bind" );
  1076. for ( int nMdlBoneIndex = 0; nMdlBoneIndex < boneMap.m_nBoneCount; ++nMdlBoneIndex )
  1077. {
  1078. CDmeTransform *pDmeTransform = NULL;
  1079. const int nDmeModelBoneIndex = boneMap.m_pnMdlToDmeModel[ nMdlBoneIndex ];
  1080. if ( nDmeModelBoneIndex < 0 )
  1081. {
  1082. // No bind pose stored for the specified joint, use the current
  1083. // position of the joint from the skeleton instead
  1084. pDmeTransform = boneMap.m_ppTransforms[ nMdlBoneIndex ];
  1085. }
  1086. else
  1087. {
  1088. pDmeTransform = pBindPose ? pBindPose->GetTransform( nDmeModelBoneIndex ) : pModel->GetJointTransform( nDmeModelBoneIndex );
  1089. }
  1090. if ( pDmeTransform )
  1091. {
  1092. pDmeTransform->GetTransform( jointTransform );
  1093. s_bone_t &mdlBone = pSourceAnim->rawanim[0][ nMdlBoneIndex ];
  1094. MatrixAngles( jointTransform, mdlBone.rot, mdlBone.pos );
  1095. mdlBone.pos *= flScale;
  1096. }
  1097. else
  1098. {
  1099. MdlWarning( "Cannot find DmeTransform for MDL Bone %d\n", nMdlBoneIndex );
  1100. }
  1101. }
  1102. }
  1103. Build_Reference( pSource, "BindPose" );
  1104. }
  1105. //-----------------------------------------------------------------------------
  1106. // Does a search through connection operators for dependent DmeOperators
  1107. //-----------------------------------------------------------------------------
  1108. static void GetDependentOperators( CUtlVector< IDmeOperator * > &operatorList, CDmeOperator *pDmeOperator )
  1109. {
  1110. if ( !pDmeOperator || !CastElement< CDmeOperator >( pDmeOperator ) )
  1111. return;
  1112. for ( int i = 0; i < operatorList.Count(); ++i )
  1113. {
  1114. CDmeOperator *pTmpDmeOperator = CastElement< CDmeOperator >( reinterpret_cast< CDmeOperator * >( operatorList[i] ) );
  1115. if ( pTmpDmeOperator && pTmpDmeOperator == pDmeOperator )
  1116. return;
  1117. }
  1118. operatorList.AddToTail( pDmeOperator );
  1119. CUtlVector< CDmAttribute * > outAttrList;
  1120. pDmeOperator->GetOutputAttributes( outAttrList );
  1121. for ( int i = 0; i < outAttrList.Count(); ++i )
  1122. {
  1123. CDmElement *pDmElement = outAttrList[i]->GetOwner();
  1124. if ( !pDmElement )
  1125. continue;
  1126. if ( pDmElement == pDmeOperator )
  1127. {
  1128. CUtlVector< CDmElement * > reList0;
  1129. FindReferringElements( reList0, pDmElement, g_pDataModel->GetSymbol( "element" ) );
  1130. for ( int j = 0; j < reList0.Count(); ++j )
  1131. {
  1132. CDmeAttributeReference *pRe0 = CastElement< CDmeAttributeReference >( reList0[j] );
  1133. if ( !pRe0 )
  1134. continue;
  1135. CUtlVector< CDmElement * > reList1;
  1136. FindReferringElements( reList1, pRe0, g_pDataModel->GetSymbol( "input" ) );
  1137. for ( int k = 0; k < reList1.Count(); ++k )
  1138. {
  1139. CDmeConnectionOperator *pRe1 = CastElement< CDmeConnectionOperator >( reList1[k] );
  1140. if ( !pRe1 )
  1141. continue;
  1142. GetDependentOperators( operatorList, pRe1 );
  1143. }
  1144. }
  1145. }
  1146. else
  1147. {
  1148. GetDependentOperators( operatorList, CastElement< CDmeOperator >( pDmElement ) );
  1149. }
  1150. }
  1151. }
  1152. //-----------------------------------------------------------------------------
  1153. // Main entry point for loading DMX files
  1154. //-----------------------------------------------------------------------------
  1155. static void PrepareChannels(
  1156. CUtlVector< IDmeOperator * > &operatorList,
  1157. CDmeChannelsClip *pAnimation )
  1158. {
  1159. int nChannelsCount = pAnimation->m_Channels.Count();
  1160. for ( int i = 0; i < nChannelsCount; ++i )
  1161. {
  1162. pAnimation->m_Channels[i]->SetMode( CM_PLAY );
  1163. GetDependentOperators( operatorList, pAnimation->m_Channels[i] );
  1164. }
  1165. }
  1166. //-----------------------------------------------------------------------------
  1167. // Update channels so they are in position for the next frame
  1168. //-----------------------------------------------------------------------------
  1169. static void UpdateChannels( CUtlVector< IDmeOperator * > &operators, CDmeChannelsClip *pAnimation, DmeTime_t clipTime )
  1170. {
  1171. int nChannelsCount = pAnimation->m_Channels.Count();
  1172. DmeTime_t channelTime = pAnimation->ToChildMediaTime( clipTime );
  1173. for ( int i = 0; i < nChannelsCount; ++i )
  1174. {
  1175. pAnimation->m_Channels[i]->SetCurrentTime( channelTime );
  1176. }
  1177. // Recompute the position of the joints
  1178. {
  1179. CDisableUndoScopeGuard guard;
  1180. g_pDmElementFramework->SetOperators( operators );
  1181. g_pDmElementFramework->Operate( true );
  1182. }
  1183. g_pDmElementFramework->BeginEdit();
  1184. }
  1185. //-----------------------------------------------------------------------------
  1186. // Initialize the pose for this frame
  1187. //-----------------------------------------------------------------------------
  1188. static void ComputeFramePose( s_sourceanim_t *pSourceAnim, int nFrame, float flScale, BoneTransformMap_t& boneMap )
  1189. {
  1190. pSourceAnim->rawanim[nFrame] = (s_bone_t *)calloc( boneMap.m_nBoneCount, sizeof( s_bone_t ) );
  1191. for ( int i = 0; i < boneMap.m_nBoneCount; ++i )
  1192. {
  1193. matrix3x4_t jointTransform;
  1194. boneMap.m_ppTransforms[i]->GetTransform( jointTransform );
  1195. MatrixAngles( jointTransform, pSourceAnim->rawanim[nFrame][i].rot, pSourceAnim->rawanim[nFrame][i].pos );
  1196. pSourceAnim->rawanim[nFrame][i].pos *= flScale;
  1197. }
  1198. }
  1199. //-----------------------------------------------------------------------------
  1200. // Main entry point for loading animations
  1201. //-----------------------------------------------------------------------------
  1202. static void LoadAnimations( s_source_t *pSource, CDmeAnimationList *pAnimationList, float flScale, BoneTransformMap_t &boneMap )
  1203. {
  1204. int nAnimationCount = pAnimationList->GetAnimationCount();
  1205. for ( int i = 0; i < nAnimationCount; ++i )
  1206. {
  1207. CDmeChannelsClip *pAnimation = pAnimationList->GetAnimation( i );
  1208. if ( !Q_stricmp( pAnimationList->GetName(), "BindPose" ) )
  1209. {
  1210. MdlError( "Error: Cannot use \"BindPose\" as an animation name!\n" );
  1211. break;
  1212. }
  1213. s_sourceanim_t *pSourceAnim = FindOrAddSourceAnim( pSource, pAnimation->GetName() );
  1214. DmeTime_t nStartTime = pAnimation->GetStartTime();
  1215. DmeTime_t nEndTime = pAnimation->GetEndTime();
  1216. int nFrameRateVal = pAnimation->GetValue<int>( "frameRate" );
  1217. if ( nFrameRateVal <= 0 )
  1218. {
  1219. nFrameRateVal = 30;
  1220. }
  1221. DmeFramerate_t nFrameRate = nFrameRateVal;
  1222. pSourceAnim->startframe = nStartTime.CurrentFrame( nFrameRate );
  1223. pSourceAnim->endframe = nEndTime.CurrentFrame( nFrameRate );
  1224. pSourceAnim->numframes = pSourceAnim->endframe - pSourceAnim->startframe + 1;
  1225. CUtlVector< IDmeOperator * > operatorList;
  1226. PrepareChannels( operatorList, pAnimation );
  1227. float flOOFrameRate = 1.0f / (float)nFrameRateVal;
  1228. int nFrame = 0;
  1229. while ( nFrame < pSourceAnim->numframes )
  1230. {
  1231. int nSecond = nFrame / nFrameRateVal;
  1232. int nFraction = nFrame - nSecond * nFrameRateVal;
  1233. DmeTime_t t = nStartTime + DmeTime_t( nSecond * 10000 ) + DmeTime_t( (float)nFraction * flOOFrameRate );
  1234. UpdateChannels( operatorList, pAnimation, t );
  1235. ComputeFramePose( pSourceAnim, nFrame, flScale, boneMap );
  1236. ++nFrame;
  1237. }
  1238. }
  1239. }
  1240. //-----------------------------------------------------------------------------
  1241. // Loads the skeletal hierarchy from the game model, returns bone count
  1242. //-----------------------------------------------------------------------------
  1243. static void AddFlexKeys( CDmeDag *pRoot, CDmeDag *pDag, CDmeCombinationOperator *pComboOp, s_source_t *pSource )
  1244. {
  1245. CDmeMesh *pMesh = CastElement< CDmeMesh >( pDag->GetShape() );
  1246. if ( pMesh && ( pDag != pRoot ) )
  1247. {
  1248. int nDeltaStateCount = pMesh->DeltaStateCount();
  1249. for ( int i = 0; i < nDeltaStateCount; ++i )
  1250. {
  1251. CDmeVertexDeltaData *pDeltaState = pMesh->GetDeltaState( i );
  1252. AddFlexKey( pSource, pComboOp, pDeltaState->GetName() );
  1253. }
  1254. }
  1255. // Don't create joints for the the root dag ever.. just deal with the children
  1256. int nChildCount = pDag->GetChildCount();
  1257. for ( int i = 0; i < nChildCount; ++i )
  1258. {
  1259. CDmeDag *pChild = pDag->GetChild( i );
  1260. if ( !pChild )
  1261. continue;
  1262. AddFlexKeys( pRoot, pChild, pComboOp, pSource );
  1263. }
  1264. }
  1265. //-----------------------------------------------------------------------------
  1266. // Loads all auxilliary model info:
  1267. //
  1268. // * Determine original source files used to generate
  1269. // the current DMX file and schedule them for processing.
  1270. //-----------------------------------------------------------------------------
  1271. void LoadModelInfo( CDmElement *pRoot, char const *pFullPath )
  1272. {
  1273. // Determine original source files and schedule them for processing
  1274. if ( CDmElement *pMakeFile = pRoot->GetValueElement< CDmElement >( "makefile" ) )
  1275. {
  1276. if ( CDmAttribute *pSources = pMakeFile->GetAttribute( "sources" ) )
  1277. {
  1278. CDmrElementArray< CDmElement > arrSources( pSources );
  1279. for ( int kk = 0; kk < arrSources.Count(); ++ kk )
  1280. {
  1281. if ( CDmElement *pModelSource = arrSources.Element( kk ) )
  1282. {
  1283. if ( char const *szName = pModelSource->GetName() )
  1284. {
  1285. ProcessOriginalContentFile( pFullPath, szName );
  1286. }
  1287. }
  1288. }
  1289. }
  1290. }
  1291. }
  1292. //-----------------------------------------------------------------------------
  1293. //
  1294. //-----------------------------------------------------------------------------
  1295. bool LoadTwistConstraint( CDmElement *pDmElement )
  1296. {
  1297. CDmeRigTwistConstraintOperator *pDmeTwist = CastElement< CDmeRigTwistConstraintOperator >( pDmElement );
  1298. if ( !pDmeTwist )
  1299. return false;
  1300. if ( g_twistbones.Count() == MAXSTUDIOBONES )
  1301. return false;
  1302. CDmeDag *pDmeDagParent = pDmeTwist->GetParentTarget();
  1303. CDmeDag *pDmeDagChild = pDmeTwist->GetChildTarget();
  1304. if ( !pDmeDagParent || !pDmeDagChild )
  1305. return false;
  1306. CTwistBone &twistBone = g_twistbones[ g_twistbones.AddToTail() ];
  1307. twistBone.m_bInverse = pDmeTwist->GetInverse();
  1308. twistBone.m_vUpVector = pDmeTwist->GetUpAxis();
  1309. V_strncpy( twistBone.m_szParentBoneName, pDmeDagParent->GetName(), ARRAYSIZE( twistBone.m_szParentBoneName ) );
  1310. twistBone.m_qBaseRotation = twistBone.m_bInverse ? pDmeTwist->GetParentBindRotation() : pDmeTwist->GetChildBindRotation();
  1311. V_strncpy( twistBone.m_szChildBoneName, pDmeDagChild->GetName(), ARRAYSIZE( twistBone.m_szChildBoneName ) );
  1312. for ( int i = 0; i < pDmeTwist->SlaveCount(); ++i )
  1313. {
  1314. CDmeDag *pDmeTwistDag = pDmeTwist->GetSlaveDag( i );
  1315. if ( !pDmeTwistDag )
  1316. continue;
  1317. const char *pszTwistTargetName = pDmeTwistDag->GetName();
  1318. if ( !pszTwistTargetName || *pszTwistTargetName == '\0' )
  1319. continue;
  1320. bool bFound = false;
  1321. // Check to see if this target is already the target of a twist bone
  1322. for ( int j = 0; !bFound && j < g_twistbones.Count(); ++j )
  1323. {
  1324. const CTwistBone &tmpTwistBone = g_twistbones[j];
  1325. for ( int k = 0; k < tmpTwistBone.m_twistBoneTargets.Count(); ++k )
  1326. {
  1327. if ( !Q_stricmp( pszTwistTargetName, tmpTwistBone.m_twistBoneTargets[k].m_szBoneName ) )
  1328. {
  1329. bFound = true;
  1330. break;
  1331. }
  1332. }
  1333. }
  1334. // A Twist bone is already driving this bone, don't make another
  1335. if ( bFound )
  1336. continue;
  1337. s_constraintbonetarget_t &twistBoneTarget = twistBone.m_twistBoneTargets[ twistBone.m_twistBoneTargets.AddToTail() ];
  1338. V_strncpy( twistBoneTarget.m_szBoneName, pDmeTwistDag->GetName(), ARRAYSIZE( twistBoneTarget.m_szBoneName ) );
  1339. twistBoneTarget.m_nBone = -1;
  1340. twistBoneTarget.m_flWeight = pDmeTwist->GetSlaveWeight( i );
  1341. twistBoneTarget.m_vOffset = pDmeTwistDag->GetTransform()->GetPosition();
  1342. twistBoneTarget.m_qOffset = pDmeTwist->GetSlaveBindOrientation( i );
  1343. }
  1344. // No targets, twist constraint is useless
  1345. if ( twistBone.m_twistBoneTargets.Count() <= 0 )
  1346. {
  1347. g_twistbones.RemoveMultipleFromTail( 1 );
  1348. return true;
  1349. }
  1350. return true;
  1351. }
  1352. //-----------------------------------------------------------------------------
  1353. //
  1354. //-----------------------------------------------------------------------------
  1355. bool LoadBaseConstraintParams( CConstraintBoneBase *pConstraintBone, CDmeRigBaseConstraintOperator *pDmeBaseConstraint )
  1356. {
  1357. const CDmaElementArray< CDmeConstraintTarget > &constraintTargets = pDmeBaseConstraint->GetTargets();
  1358. if ( constraintTargets.Count() <= 0 )
  1359. return false;
  1360. const Quaternion qRot = Quaternion( g_defaultrotation );
  1361. for ( int i = 0; i < constraintTargets.Count(); ++i )
  1362. {
  1363. CDmeConstraintTarget *pDmeConstraintTarget = constraintTargets[i];
  1364. if ( !pDmeConstraintTarget )
  1365. continue;
  1366. CDmeDag *pDmeTargetDag = pDmeConstraintTarget->GetDag();
  1367. if ( !pDmeTargetDag )
  1368. continue;
  1369. // Load targets
  1370. s_constraintbonetarget_t &target = pConstraintBone->m_targets[ pConstraintBone->m_targets.AddToTail() ];
  1371. V_strncpy( target.m_szBoneName, pDmeTargetDag->GetName(), ARRAYSIZE( target.m_szBoneName ) );
  1372. target.m_nBone = -1;
  1373. target.m_flWeight = pDmeConstraintTarget->GetWeight();
  1374. target.m_qOffset = pDmeConstraintTarget->GetOrientationOffset();
  1375. if ( pDmeBaseConstraint->IsA( CDmeRigPointConstraintOperator::GetStaticTypeSymbol() ) )
  1376. {
  1377. // Target offsets are in world space for Point constraint
  1378. VectorRotate( pDmeConstraintTarget->GetPositionOfffset(), qRot, target.m_vOffset );
  1379. }
  1380. else
  1381. {
  1382. target.m_vOffset = pDmeConstraintTarget->GetPositionOfffset();
  1383. }
  1384. // QuaternionMult( pDmeConstraintTarget->GetOrientationOffset(), qRot, target.m_qOffset );
  1385. }
  1386. if ( pConstraintBone->m_targets.Count() <= 0 )
  1387. return false;
  1388. const CDmeConstraintSlave *pDmeConstraintSlave = pDmeBaseConstraint->GetConstraintSlave();
  1389. if ( !pDmeConstraintSlave )
  1390. return false;
  1391. const CDmeDag *pDmeSlaveDag = pDmeBaseConstraint->GetSlave();
  1392. if ( !pDmeSlaveDag )
  1393. return false;
  1394. s_constraintboneslave_t &slave = pConstraintBone->m_slave;
  1395. V_strncpy( slave.m_szBoneName, pDmeSlaveDag->GetName(), ARRAYSIZE( slave.m_szBoneName ) );
  1396. slave.m_nBone = -1;
  1397. slave.m_vBaseTranslate = pDmeConstraintSlave->GetBasePosition();
  1398. slave.m_qBaseRotation = pDmeConstraintSlave->GetBaseOrientation();
  1399. return true;
  1400. }
  1401. //-----------------------------------------------------------------------------
  1402. // Most constraints don't have any specialized constraint parameters
  1403. //-----------------------------------------------------------------------------
  1404. template < class S, class T >
  1405. static bool LoadSpecializedConstraintParams( S *pDmeConstraint, T *pConstraint )
  1406. {
  1407. return true;
  1408. }
  1409. //-----------------------------------------------------------------------------
  1410. // Load specialized Aim Constraint parameters
  1411. //-----------------------------------------------------------------------------
  1412. template <>
  1413. static bool LoadSpecializedConstraintParams( CDmeRigAimConstraintOperator *pDmeConstraint, CAimConstraint *pConstraint )
  1414. {
  1415. const Quaternion qRot = Quaternion( g_defaultrotation );
  1416. // Set Aim Constraint Parameters
  1417. pConstraint->m_qAimOffset = pDmeConstraint->GetValue< Quaternion >( "aimOffset" );
  1418. // Up vectors are specified in world space
  1419. VectorRotate( pDmeConstraint->GetValue< Vector >( "upVector" ), qRot, pConstraint->m_vUpVector );
  1420. CDmElement *pDmeUpSpaceTarget = pDmeConstraint->GetValueElement< CDmElement >( "upSpaceTarget" );
  1421. if ( pDmeUpSpaceTarget )
  1422. {
  1423. V_strncpy( pConstraint->m_szUpSpaceTargetBone, pDmeUpSpaceTarget->GetName(), ARRAYSIZE( pConstraint->m_szUpSpaceTargetBone ) );
  1424. }
  1425. pConstraint->m_nUpSpaceTargetBone = -1;
  1426. pConstraint->m_nUpType = pDmeConstraint->GetValue< int > ( "upType" );
  1427. return true;
  1428. }
  1429. //-----------------------------------------------------------------------------
  1430. //
  1431. //-----------------------------------------------------------------------------
  1432. static bool FindDuplicateConstraint( const CConstraintBoneBase *pConstraintA )
  1433. {
  1434. for ( int i = 0; i < g_constraintBones.Count(); ++i )
  1435. {
  1436. const CConstraintBoneBase *pConstraintB = g_constraintBones[i];
  1437. if ( *pConstraintA == *pConstraintB )
  1438. return true;
  1439. }
  1440. return false;
  1441. }
  1442. //-----------------------------------------------------------------------------
  1443. //
  1444. //-----------------------------------------------------------------------------
  1445. template < class S, class T >
  1446. static bool LoadConstraint( CDmElement *pDmElement )
  1447. {
  1448. if ( g_constraintBones.Count() == MAXSTUDIOBONES )
  1449. {
  1450. MdlError( "Too Many Constraint Bones, Max: %d\n", MAXSTUDIOBONES );
  1451. return false;
  1452. }
  1453. S *pDmeConstraint = CastElement< S >( pDmElement );
  1454. if ( !pDmeConstraint )
  1455. return false;
  1456. T *pConstraint = new T();
  1457. if ( !pConstraint )
  1458. return false;
  1459. if ( !LoadBaseConstraintParams( pConstraint, pDmeConstraint ) )
  1460. {
  1461. delete pConstraint;
  1462. return false;
  1463. }
  1464. if ( !LoadSpecializedConstraintParams( pDmeConstraint, pConstraint ) )
  1465. {
  1466. delete pConstraint;
  1467. return false;
  1468. }
  1469. if ( FindDuplicateConstraint( pConstraint ) )
  1470. {
  1471. // Delete this
  1472. delete pConstraint;
  1473. }
  1474. else
  1475. {
  1476. g_constraintBones.AddToTail( pConstraint );
  1477. }
  1478. return true;
  1479. }
  1480. //-----------------------------------------------------------------------------
  1481. //
  1482. //-----------------------------------------------------------------------------
  1483. void LoadConstraints( CDmElement *pDmeRoot )
  1484. {
  1485. if ( !pDmeRoot )
  1486. return;
  1487. CDmAttribute *pDmeConstraintsAttr = pDmeRoot->GetAttribute( "constraints", AT_ELEMENT_ARRAY );
  1488. if ( !pDmeConstraintsAttr )
  1489. return;
  1490. CDmrElementArray< CDmElement > constraints( pDmeConstraintsAttr );
  1491. for ( int i = 0; i < constraints.Count(); ++i )
  1492. {
  1493. if ( LoadTwistConstraint( constraints[i] ) )
  1494. continue;
  1495. if ( LoadConstraint< CDmeRigPointConstraintOperator, CPointConstraint >( constraints[i] ) )
  1496. continue;
  1497. if ( LoadConstraint< CDmeRigOrientConstraintOperator, COrientConstraint >( constraints[i] ) )
  1498. continue;
  1499. if ( LoadConstraint< CDmeRigAimConstraintOperator, CAimConstraint >( constraints[i] ) )
  1500. continue;
  1501. if ( LoadConstraint< CDmeRigParentConstraintOperator, CParentConstraint >( constraints[i] ) )
  1502. continue;
  1503. Error( "TODO: Support Constraint: %s\n", constraints[i]->GetName() );
  1504. }
  1505. }
  1506. //-----------------------------------------------------------------------------
  1507. // Load model and skeleton
  1508. //-----------------------------------------------------------------------------
  1509. static bool LoadModelAndSkeleton( s_source_t *pSource, BoneTransformMap_t &boneMap, CDmeDag *pSkeleton, CDmeModel *pModel, CDmeCombinationOperator *pCombinationOperator, bool bStaticProp )
  1510. {
  1511. s_DeltaStates.RemoveAll();
  1512. s_Balance.RemoveAll();
  1513. s_Speed.RemoveAll();
  1514. s_UniqueVertices.RemoveAll();
  1515. s_UniqueVerticesMap.RemoveAll();
  1516. if ( !pSkeleton )
  1517. return false;
  1518. // BoneRemap[bone index in file] == bone index in studiomdl
  1519. pSource->numbones = LoadSkeleton( pSkeleton, pModel, pSource->localBone, boneMap );
  1520. if ( pSource->numbones == 0 )
  1521. return false;
  1522. g_numfaces = 0;
  1523. if ( pModel )
  1524. {
  1525. if ( pCombinationOperator )
  1526. {
  1527. pCombinationOperator->GenerateWrinkleDeltas( false );
  1528. }
  1529. LoadBindPose( pModel, g_currentscale, boneMap, pSource );
  1530. if ( !LoadMeshes( pModel, g_currentscale, boneMap.m_pnDmeModelToMdl, pSource ) )
  1531. return false;
  1532. UnifyIndices( pSource );
  1533. BuildVertexAnimations( pSource );
  1534. BuildIndividualMeshes( pSource );
  1535. }
  1536. if ( g_numfaces == 0 && pSource->numbones == 1 && !V_strcmp( pSource->localBone[0].name, "defaultRoot" ) )
  1537. {
  1538. MdlError( "Error - dmx has no contents: %s\n", pSource->filename );
  1539. }
  1540. if ( pCombinationOperator )
  1541. {
  1542. AddFlexKeys( pModel, pModel, pCombinationOperator, pSource );
  1543. AddCombination( pSource, pCombinationOperator );
  1544. }
  1545. LoadAttachments( pSkeleton, pSkeleton, pSource, bStaticProp );
  1546. return true;
  1547. }
  1548. //-----------------------------------------------------------------------------
  1549. // Given the s_model_t pointer, finds the index of it in g_model
  1550. // Returns -1 if it cannot be found
  1551. //-----------------------------------------------------------------------------
  1552. static int FindModelIndex( s_model_t *pModel )
  1553. {
  1554. if ( pModel )
  1555. {
  1556. for ( int i = 0; i < g_nummodels; ++i )
  1557. {
  1558. if ( g_model[ i ] == pModel )
  1559. return i;
  1560. }
  1561. MdlWarning( "Cannot Find s_model_t: \"%s\" in g_model\n", pModel->name );
  1562. }
  1563. return -1;
  1564. }
  1565. //-----------------------------------------------------------------------------
  1566. //
  1567. //-----------------------------------------------------------------------------
  1568. static bool AddFlexKey(
  1569. s_source_t *pSource, s_model_t *pModel,
  1570. const char *pszAnimationName,
  1571. int nFlexDesc,
  1572. int nFlexPair,
  1573. EyelidType_t nEyelidType,
  1574. float flLowererHeight,
  1575. float flNeutralHeight,
  1576. float flRaiserHeight,
  1577. float flSplit = 0.0f,
  1578. float flDecay = 1.0f,
  1579. int nFrame = 0 ) // DMX frame is always 0
  1580. {
  1581. if ( g_numflexkeys >= ARRAYSIZE( g_flexkey ) )
  1582. {
  1583. MdlError( "Too Many Flex Keys, Cannot Add %s\n", "TODO: FlexKeyName" );
  1584. return false;
  1585. }
  1586. const int nModelIndex = FindModelIndex( pModel );
  1587. s_flexkey_t *pFlexKey = &g_flexkey[ g_numflexkeys ];
  1588. pFlexKey->source = pSource;
  1589. V_strncpy( pFlexKey->animationname, pszAnimationName, sizeof( pFlexKey->animationname ) );
  1590. pFlexKey->imodel = nModelIndex;
  1591. pFlexKey->flexdesc = nFlexDesc;
  1592. pFlexKey->flexpair = nFlexPair;
  1593. pFlexKey->split = flSplit;
  1594. pFlexKey->decay = flDecay;
  1595. pFlexKey->frame = nFrame;
  1596. switch ( nEyelidType )
  1597. {
  1598. case kLowerer:
  1599. pFlexKey->target0 = -11;
  1600. pFlexKey->target1 = -10;
  1601. pFlexKey->target2 = flLowererHeight;
  1602. pFlexKey->target3 = flNeutralHeight;
  1603. break;
  1604. case kNeutral:
  1605. pFlexKey->target0 = flLowererHeight;
  1606. pFlexKey->target1 = flNeutralHeight;
  1607. pFlexKey->target2 = flNeutralHeight;
  1608. pFlexKey->target3 = flRaiserHeight;
  1609. break;
  1610. case kRaiser:
  1611. pFlexKey->target0 = flNeutralHeight;
  1612. pFlexKey->target1 = flRaiserHeight;
  1613. pFlexKey->target2 = 10;
  1614. pFlexKey->target3 = 11;
  1615. break;
  1616. }
  1617. // Check for a duplicate
  1618. for ( int i = 0; i < g_numflexkeys; ++i )
  1619. {
  1620. const s_flexkey_t *pTmpFlexKey = &( g_flexkey[ i ] );
  1621. if ( !V_stricmp( pFlexKey->animationname, pTmpFlexKey->animationname ) &&
  1622. pFlexKey->flexdesc == pTmpFlexKey->flexdesc &&
  1623. pFlexKey->flexpair == pTmpFlexKey->flexpair &&
  1624. pFlexKey->frame == pTmpFlexKey->frame &&
  1625. pFlexKey->target0 == pTmpFlexKey->target0 &&
  1626. pFlexKey->target1 == pTmpFlexKey->target1 &&
  1627. pFlexKey->target2 == pTmpFlexKey->target2 &&
  1628. pFlexKey->target3 == pTmpFlexKey->target3 )
  1629. {
  1630. // Duplicate, get rid of it
  1631. V_memset( pFlexKey, 0, sizeof( s_flexkey_t ) );
  1632. return false;
  1633. }
  1634. }
  1635. // Not a duplicate, keep it
  1636. ++g_numflexkeys;
  1637. return true;
  1638. }
  1639. //-----------------------------------------------------------------------------
  1640. // In studiomdl.cpp
  1641. //-----------------------------------------------------------------------------
  1642. const s_sourceanim_t *GetNewStyleSourceVertexAnim( s_source_t *pSource, const char *pszVertexAnimName );
  1643. //-----------------------------------------------------------------------------
  1644. //
  1645. //-----------------------------------------------------------------------------
  1646. static bool LoadEyelid( s_model_t *pModel, CDmeEyelid *pDmeEyelid )
  1647. {
  1648. if ( !pModel || !pDmeEyelid )
  1649. return false;
  1650. s_source_t *pSource = pModel->source;
  1651. if ( !pSource )
  1652. return false;
  1653. const bool bUpper = pDmeEyelid->m_bUpper.Get();
  1654. enum RightLeftType_t
  1655. {
  1656. kLeft = 0,
  1657. kRight = 1,
  1658. kRightLeftTypeCount = 2
  1659. };
  1660. struct EyelidData_t
  1661. {
  1662. int m_nFlexDesc[ kRightLeftTypeCount ];
  1663. const s_sourceanim_t *m_pSourceAnim;
  1664. float m_flTarget;
  1665. const char *m_pszSuffix;
  1666. };
  1667. EyelidData_t eyelidData[3] =
  1668. {
  1669. { { -1, -1 }, NULL, 0.0f, "lowerer" },
  1670. { { -1, -1 }, NULL, 0.0f, "neutral" },
  1671. { { -1, -1 }, NULL, 0.0f, "raiser" }
  1672. };
  1673. eyelidData[kLowerer].m_pSourceAnim = GetNewStyleSourceVertexAnim( pSource, pDmeEyelid->m_sLowererFlex.Get() );
  1674. eyelidData[kLowerer].m_flTarget = pDmeEyelid->m_flLowererHeight.Get();
  1675. eyelidData[kNeutral].m_pSourceAnim = GetNewStyleSourceVertexAnim( pSource, pDmeEyelid->m_sNeutralFlex.Get() );
  1676. eyelidData[kNeutral].m_flTarget = pDmeEyelid->m_flNeutralHeight.Get();
  1677. eyelidData[kRaiser].m_pSourceAnim = GetNewStyleSourceVertexAnim( pSource, pDmeEyelid->m_sRaiserFlex.Get() );
  1678. eyelidData[kRaiser].m_flTarget = pDmeEyelid->m_flRaiserHeight.Get();
  1679. // Add a flexdesc for <type>_right & <type>_left
  1680. // Where <type> is "upper" or "lower"
  1681. int nRightLeftBaseDesc[kRightLeftTypeCount] = { -1, -1 };
  1682. const char *sRightBaseDesc = bUpper ? "upper_right" : "lower_right";
  1683. nRightLeftBaseDesc[kRight] = Add_Flexdesc( sRightBaseDesc );
  1684. for ( int i = 0; i < kEyelidTypeCount; ++i )
  1685. {
  1686. CUtlString sRightLocalDesc = sRightBaseDesc;
  1687. sRightLocalDesc += "_";
  1688. sRightLocalDesc += eyelidData[i].m_pszSuffix;
  1689. eyelidData[i].m_nFlexDesc[kRight] = Add_Flexdesc( sRightLocalDesc.Get() );
  1690. }
  1691. const char *sLeftBaseDesc = bUpper ? "upper_left" : "lower_left";
  1692. nRightLeftBaseDesc[kLeft] = Add_Flexdesc( sLeftBaseDesc );
  1693. for ( int i = 0; i < kEyelidTypeCount; ++i )
  1694. {
  1695. CUtlString sLeftLocalDesc = sLeftBaseDesc;
  1696. sLeftLocalDesc += "_";
  1697. sLeftLocalDesc += eyelidData[i].m_pszSuffix;
  1698. eyelidData[i].m_nFlexDesc[kLeft] = Add_Flexdesc( sLeftLocalDesc.Get() );
  1699. }
  1700. for ( int i = 0; i < kEyelidTypeCount; ++i )
  1701. {
  1702. if ( !AddFlexKey( pSource, pModel,
  1703. eyelidData[i].m_pSourceAnim->animationname,
  1704. nRightLeftBaseDesc[kLeft],
  1705. nRightLeftBaseDesc[kRight],
  1706. EyelidType_t( i ),
  1707. eyelidData[kLowerer].m_flTarget,
  1708. eyelidData[kNeutral].m_flTarget,
  1709. eyelidData[kRaiser].m_flTarget ) )
  1710. {
  1711. // Flex Keys Already Added - Eyelid is a duplicate
  1712. return false;
  1713. }
  1714. }
  1715. bool bRightOk = false;
  1716. bool bLeftOk = false;
  1717. for ( int i = 0; i < pModel->numeyeballs; ++i )
  1718. {
  1719. s_eyeball_t *pEyeball = &( pModel->eyeball[i] );
  1720. if ( !pEyeball )
  1721. continue;
  1722. RightLeftType_t nRightLeftIndex = kRight;
  1723. if ( !V_stricmp( pDmeEyelid->m_sRightEyeballName.Get(), pEyeball->name ) )
  1724. {
  1725. nRightLeftIndex = kRight;
  1726. bRightOk = true;
  1727. }
  1728. else if ( !Q_stricmp( pDmeEyelid->m_sLeftEyeballName, pEyeball->name ) )
  1729. {
  1730. nRightLeftIndex = kLeft;
  1731. bLeftOk = true;
  1732. }
  1733. else
  1734. {
  1735. MdlWarning( "Unknown Eyeball: %s\n", pEyeball->name );
  1736. continue;
  1737. }
  1738. for ( int j = 0; j < kEyelidTypeCount; ++j )
  1739. {
  1740. if ( fabs( eyelidData[j].m_flTarget ) > pEyeball->radius )
  1741. {
  1742. MdlError( "Eyelid \"%s\" %s %.1f out of range (+-%.1f)\n", bUpper ? "upper" : "lower", eyelidData[j].m_pszSuffix, eyelidData[j].m_flTarget, pEyeball->radius );
  1743. }
  1744. }
  1745. if ( bUpper )
  1746. {
  1747. pEyeball->upperlidflexdesc = nRightLeftBaseDesc[nRightLeftIndex];
  1748. for ( int j = 0; j < kEyelidTypeCount; ++j )
  1749. {
  1750. pEyeball->upperflexdesc[j] = eyelidData[j].m_nFlexDesc[nRightLeftIndex];
  1751. pEyeball->uppertarget[j] = eyelidData[j].m_flTarget;
  1752. }
  1753. }
  1754. else
  1755. {
  1756. pEyeball->lowerlidflexdesc = nRightLeftBaseDesc[nRightLeftIndex];
  1757. for ( int j = 0; j < kEyelidTypeCount; ++j )
  1758. {
  1759. pEyeball->lowerflexdesc[j] = eyelidData[j].m_nFlexDesc[nRightLeftIndex];
  1760. pEyeball->lowertarget[j] = eyelidData[j].m_flTarget;
  1761. }
  1762. }
  1763. }
  1764. if ( !bRightOk )
  1765. {
  1766. MdlError( "Could not find right eye \"%s\"\n", pDmeEyelid->m_sRightEyeballName.Get() );
  1767. return false;
  1768. }
  1769. if ( !bLeftOk )
  1770. {
  1771. MdlError( "Could not find left eye \"%s\"\n", pDmeEyelid->m_sLeftEyeballName.Get() );
  1772. return false;
  1773. }
  1774. return true;
  1775. }
  1776. //-----------------------------------------------------------------------------
  1777. //
  1778. //-----------------------------------------------------------------------------
  1779. static bool LoadMouth( CDmeMouth *pDmeMouth )
  1780. {
  1781. if ( !pDmeMouth )
  1782. return false;
  1783. const int nMouthIndex = pDmeMouth->m_nMouthNumber.Get();
  1784. // Check if mouth is already defined... not sure why people need to specify a mouth number
  1785. // in the QC though.
  1786. if ( g_nummouths > nMouthIndex )
  1787. return false;
  1788. g_nummouths = nMouthIndex + 1;
  1789. s_mouth_t *pMouth = &( g_mouth[ nMouthIndex ] );
  1790. pMouth->flexdesc = Add_Flexdesc( pDmeMouth->m_sFlexControllerName.Get() );
  1791. V_strncpy( pMouth->bonename, pDmeMouth->m_sBoneName, sizeof( pMouth->bonename ) );
  1792. pMouth->forward = pDmeMouth->m_vForward.Get(); // TODO: Adjust Y Up?
  1793. return false;
  1794. }
  1795. //-----------------------------------------------------------------------------
  1796. // Loads Eyeballs
  1797. //-----------------------------------------------------------------------------
  1798. static void LoadEyeballs( s_source_t *pSource, s_model_t *pModel, CDmrElementArray< CDmElement > &elementArray )
  1799. {
  1800. if ( !pSource || !pModel || elementArray.Count() <= 0 )
  1801. return;
  1802. Assert( pModel->source == NULL || pModel->source == pSource );
  1803. matrix3x4_t mDefRot;
  1804. AngleMatrix( g_defaultrotation, mDefRot );
  1805. Vector vTmp;
  1806. for ( int i = 0; i < elementArray.Count(); ++i )
  1807. {
  1808. CDmeEyeball *pDmeEyeball = CastElement< CDmeEyeball >( elementArray.Element( i ) );
  1809. if ( !pDmeEyeball )
  1810. continue;
  1811. if ( pModel->numeyeballs >= ARRAYSIZE( pModel->eyeball ) )
  1812. {
  1813. MdlWarning( "1100: Max number of eyeballs reached for model %s, ignoring eyeball %s\n", pModel->name, pDmeEyeball->GetName() );
  1814. continue;
  1815. }
  1816. int nFoundBoneIndex = -1;
  1817. for ( int nSearchBoneIndex = 0; nSearchBoneIndex < pSource->numbones; ++nSearchBoneIndex )
  1818. {
  1819. if ( !Q_stricmp( pSource->localBone[ nSearchBoneIndex ].name, pDmeEyeball->m_sParentBoneName.Get() ) )
  1820. {
  1821. nFoundBoneIndex = nSearchBoneIndex;
  1822. break;
  1823. }
  1824. }
  1825. if ( nFoundBoneIndex < 0 )
  1826. {
  1827. MdlWarning( "1101: Couldn't find bone %s on model %s, ignoring eyeball %s\n", pDmeEyeball->m_sParentBoneName.Get(), pModel->name, pDmeEyeball->GetName() );
  1828. continue;
  1829. }
  1830. const char *pszMaterialName = pDmeEyeball->m_sMaterialName.Get();
  1831. const bool bRelative = ( strchr( pszMaterialName, '/' ) || strchr( pszMaterialName, '\\' ) ) ? true : false;
  1832. const int nSearchMeshMatIndex = UseTextureAsMaterial( LookupTexture( pDmeEyeball->m_sMaterialName.Get(), bRelative ) );
  1833. int nFoundMeshMatIndex = -1;
  1834. for ( int i = 0; i < pSource->nummeshes; ++i )
  1835. {
  1836. const int nTmpMeshMatIndex = pSource->meshindex[ i ]; // meshes are internally stored by material index
  1837. if ( nTmpMeshMatIndex == nSearchMeshMatIndex )
  1838. {
  1839. nFoundMeshMatIndex = i;
  1840. break;
  1841. }
  1842. }
  1843. if ( nFoundMeshMatIndex < 0 )
  1844. {
  1845. MdlWarning( "1102: Couldn't find eyeball material %s on model %s, ignoring eyeball %s\n", pDmeEyeball->m_sMaterialName.Get(), pModel->name, pDmeEyeball->GetName() );
  1846. continue;
  1847. }
  1848. s_eyeball_t *ps_eyeball_t = &( pModel->eyeball[ pModel->numeyeballs ] );
  1849. Q_strncpy( ps_eyeball_t->name, pDmeEyeball->GetName(), sizeof( ps_eyeball_t->name ) );
  1850. ps_eyeball_t->bone = nFoundBoneIndex;
  1851. ps_eyeball_t->mesh = nFoundMeshMatIndex;
  1852. ps_eyeball_t->radius = pDmeEyeball->m_flRadius.Get();
  1853. ps_eyeball_t->zoffset = tan( DEG2RAD( pDmeEyeball->m_flYawAngle.Get() ) );
  1854. ps_eyeball_t->iris_scale = 1.0f / pDmeEyeball->m_flIrisScale;
  1855. // translate eyeball into bone space
  1856. VectorITransform( pDmeEyeball->m_vPosition.Get(), pSource->boneToPose[ ps_eyeball_t->bone ], ps_eyeball_t->org );
  1857. VectorIRotate( Vector( 0, 0, 1 ), mDefRot, vTmp );
  1858. VectorIRotate( vTmp, pSource->boneToPose[ ps_eyeball_t->bone ], ps_eyeball_t->up );
  1859. VectorIRotate( Vector( 1, 0, 0 ), mDefRot, vTmp );
  1860. VectorIRotate( vTmp, pSource->boneToPose[ ps_eyeball_t->bone ], ps_eyeball_t->forward );
  1861. // Not applicable
  1862. ps_eyeball_t->upperlidflexdesc = -1;
  1863. ps_eyeball_t->lowerlidflexdesc = -1;
  1864. bool bOk = true;
  1865. // Check for a duplicate eyeball
  1866. for ( int j = 0; j < pModel->numeyeballs; ++j )
  1867. {
  1868. s_eyeball_t *pTmp = &( pModel->eyeball[ j ] );
  1869. if ( !V_stricmp( ps_eyeball_t->name, pTmp->name ) )
  1870. {
  1871. // TODO: Check and warn about duplicate eyeballs with mis-matched parameters
  1872. bOk = false;
  1873. break;
  1874. }
  1875. }
  1876. if ( bOk )
  1877. {
  1878. // Keep eyeball
  1879. pModel->numeyeballs += 1;
  1880. }
  1881. else
  1882. {
  1883. // Clear data
  1884. V_memset( ps_eyeball_t, 0, sizeof( s_eyeball_t ) );
  1885. }
  1886. }
  1887. // Make the standard flex controllers for eyes if required
  1888. static const char *szEyesFlexControllers[] = {
  1889. "eyes_updown",
  1890. "eyes_rightleft"
  1891. };
  1892. for ( int nNewFlexIndex = 0; nNewFlexIndex < ARRAYSIZE( szEyesFlexControllers ); ++nNewFlexIndex )
  1893. {
  1894. bool bHasEyeFlexController = false;
  1895. for ( int nFlexIndex = 0; nFlexIndex < g_numflexcontrollers; ++nFlexIndex )
  1896. {
  1897. if ( !Q_strcmp( szEyesFlexControllers[ nNewFlexIndex ], g_flexcontroller[ nFlexIndex ].name ) )
  1898. {
  1899. bHasEyeFlexController = true;
  1900. break;
  1901. }
  1902. }
  1903. // The flex controller range for eyes_updown & eyes_rightleft is default [-45, 45] because it's clamped by eyesMaxDeflection
  1904. // and changing it based on max deflection would cause animatin changes since flex controller values are normalized [0, 1]
  1905. // [-45, 45 ] gives a maxium range that's useful
  1906. if ( !bHasEyeFlexController )
  1907. {
  1908. if ( g_numflexcontrollers >= MAXSTUDIOFLEXCTRL )
  1909. {
  1910. MdlWarning( "1103: Couldn't make eyes flexcontroller %s, too many flex controllers defined\n", szEyesFlexControllers[ nNewFlexIndex ] );
  1911. continue;
  1912. }
  1913. Q_strncpy( g_flexcontroller[g_numflexcontrollers].name, szEyesFlexControllers[ nNewFlexIndex ], sizeof( g_flexcontroller[ g_numflexcontrollers ].name ) );
  1914. Q_strncpy( g_flexcontroller[g_numflexcontrollers].type, "eyes", sizeof( g_flexcontroller[ g_numflexcontrollers ].name ) );
  1915. g_flexcontroller[g_numflexcontrollers].min = -45.0f;
  1916. g_flexcontroller[g_numflexcontrollers].max = 45.0f;
  1917. ++g_numflexcontrollers;
  1918. }
  1919. }
  1920. }
  1921. //-----------------------------------------------------------------------------
  1922. //
  1923. //-----------------------------------------------------------------------------
  1924. void LoadQcModelElements( s_source_t *pSource, s_model_t *pModel, CDmeModel *pDmeModel )
  1925. {
  1926. if ( !pModel || !pDmeModel )
  1927. return;
  1928. CDmAttribute *pQcModelElementsAttr = pDmeModel->GetAttribute( "qcModelElements", AT_ELEMENT_ARRAY );
  1929. if ( !pQcModelElementsAttr )
  1930. return;
  1931. CDmrElementArray< CDmElement > qcModelElements( pQcModelElementsAttr );
  1932. LoadEyeballs( pSource, pModel, qcModelElements );
  1933. for ( int i = 0; i < qcModelElements.Count(); ++i )
  1934. {
  1935. LoadEyelid( pModel, CastElement< CDmeEyelid >( qcModelElements.Element( i ) ) );
  1936. }
  1937. for ( int i = 0; i < qcModelElements.Count(); ++i )
  1938. {
  1939. LoadMouth( CastElement< CDmeMouth >( qcModelElements.Element( i ) ) );
  1940. }
  1941. }
  1942. #ifdef MDLCOMPILE
  1943. //-----------------------------------------------------------------------------
  1944. // Allocates a source
  1945. // Applies the .dmx extension because the source searching algorithm looks
  1946. // for .dmx
  1947. //-----------------------------------------------------------------------------
  1948. static s_source_t *AllocateDmxSource( const char *pSourceName )
  1949. {
  1950. // Allocate a new source
  1951. s_source_t *pSource = (s_source_t *)calloc( 1, sizeof( s_source_t ) );
  1952. g_source[g_numsources++] = pSource;
  1953. Q_strncpy( pSource->filename, pSourceName, sizeof( pSource->filename ) );
  1954. Q_SetExtension( pSource->filename, "dmx", sizeof( pSource->filename ) );
  1955. VectorCopy( g_defaultadjust, pSource->adjust );
  1956. pSource->scale = 1.0f;
  1957. pSource->rotation = g_defaultrotation;
  1958. return pSource;
  1959. }
  1960. //-----------------------------------------------------------------------------
  1961. // Purpose: Creates an animation from the Dme skeleton specified in the
  1962. // bone map. NOTE: It doesn't look for 'bindPose', it uses the
  1963. // current pose of the skeleton
  1964. //-----------------------------------------------------------------------------
  1965. static void CreateAnimFromSkeleton( s_source_t *pSource, const char *pSequenceName, const BoneTransformMap_t &boneMap )
  1966. {
  1967. s_sourceanim_t *pSourceAnim = FindOrAddSourceAnim( pSource, pSequenceName );
  1968. pSourceAnim->startframe = 0;
  1969. pSourceAnim->endframe = 0;
  1970. pSourceAnim->numframes = 1;
  1971. // Default all transforms to identity
  1972. pSourceAnim->rawanim[0] = (s_bone_t *)calloc( pSource->numbones, sizeof(s_bone_t) );
  1973. for ( int i = 0; i < pSource->numbones; ++i )
  1974. {
  1975. pSourceAnim->rawanim[0][i].pos.Init();
  1976. pSourceAnim->rawanim[0][i].rot.Init();
  1977. }
  1978. matrix3x4_t jointTransform;
  1979. for ( int nBoneIndex = 0; nBoneIndex < boneMap.m_nBoneCount; ++nBoneIndex )
  1980. {
  1981. const CDmeTransform *pDmeTransform = boneMap.m_ppTransforms[ nBoneIndex ];
  1982. s_bone_t &mdlBone = pSourceAnim->rawanim[0][ nBoneIndex ];
  1983. VectorCopy( pDmeTransform->GetPosition() * g_currentscale, mdlBone.pos );
  1984. QuaternionAngles( pDmeTransform->GetOrientation(), mdlBone.rot );
  1985. }
  1986. // This copies the named animation into the poseToBone array in the source
  1987. Build_Reference( pSource, pSequenceName );
  1988. }
  1989. //-----------------------------------------------------------------------------
  1990. //
  1991. //-----------------------------------------------------------------------------
  1992. static void LoadBoneMaskList( CDmeBoneMaskList *pDmeBoneMaskList )
  1993. {
  1994. if ( !pDmeBoneMaskList )
  1995. return;
  1996. CDmeBoneMask *pDmeDefaultBoneMask = pDmeBoneMaskList->m_eDefaultBoneMask.GetElement();
  1997. for ( int i = 0; i < pDmeBoneMaskList->m_BoneMaskList.Count(); ++i )
  1998. {
  1999. CDmeBoneMask *pDmeBoneMask = pDmeBoneMaskList->m_BoneMaskList.Element( i );
  2000. if ( !pDmeBoneMask )
  2001. return;
  2002. int nBoneMaskIndex = g_numweightlist;
  2003. if ( pDmeBoneMask == pDmeDefaultBoneMask )
  2004. {
  2005. nBoneMaskIndex = 0;
  2006. }
  2007. if ( nBoneMaskIndex >= MAXWEIGHTLISTS )
  2008. {
  2009. MdlWarning( "1300: Too many bone masks, max %d, ignoring %s\n", MAXWEIGHTLISTS, pDmeBoneMask->GetName() );
  2010. }
  2011. bool bDuplicate = false;
  2012. for ( int j = 0; j < g_numweightlist; ++j )
  2013. {
  2014. if ( g_weightlist[ j ].name && !Q_stricmp( g_weightlist[ j ].name, pDmeBoneMask->GetName() ) )
  2015. {
  2016. bDuplicate = true;
  2017. MdlWarning( "1301: Ignoring duplicate bone mask %s\n", pDmeBoneMask->GetName() );
  2018. break;
  2019. }
  2020. }
  2021. if ( bDuplicate )
  2022. continue;
  2023. s_weightlist_t *pWeightList = &( g_weightlist[ nBoneMaskIndex ] );
  2024. Q_strncpy( pWeightList->name, pDmeBoneMask->GetName(), sizeof( pWeightList->name ) );
  2025. pWeightList->numbones = 0;
  2026. for ( int j = 0; j < pDmeBoneMask->m_BoneWeights.Count(); ++j )
  2027. {
  2028. CDmeBoneWeight *pDmeBoneWeight = pDmeBoneMask->m_BoneWeights.Element( j );
  2029. if ( !pDmeBoneWeight )
  2030. continue;
  2031. int nBoneWeightIndex = pWeightList->numbones;
  2032. if ( nBoneWeightIndex >= MAXWEIGHTSPERLIST )
  2033. {
  2034. MdlWarning( "1302: Too many bones in weightlist %s, ignoring weight for %s (%f)\n", pWeightList->name, pDmeBoneWeight->GetName(), pDmeBoneWeight->m_flWeight.Get() );
  2035. continue;
  2036. }
  2037. pWeightList->bonename[ nBoneWeightIndex ] = strdup( pDmeBoneWeight->GetName() );
  2038. // 'weight' attribute is normally used for both rotation and position weight
  2039. pWeightList->boneweight[ nBoneWeightIndex ] = pDmeBoneWeight->m_flWeight.Get();
  2040. pWeightList->boneposweight[ nBoneWeightIndex ] = pWeightList->boneweight[ nBoneWeightIndex ];
  2041. // Look for optional 'positionWeight' attribute, use it separately for position if it exists
  2042. CDmAttribute *pDmePositionWeightAttr = pDmeBoneWeight->GetAttribute( "positionWeight", AT_FLOAT );
  2043. if ( pDmePositionWeightAttr )
  2044. {
  2045. pWeightList->boneposweight[ nBoneWeightIndex ] = pDmePositionWeightAttr->GetValue< float >();
  2046. if ( pWeightList->boneweight[ nBoneWeightIndex ] == 0 && pWeightList->boneposweight[ nBoneWeightIndex ] > 0 )
  2047. {
  2048. MdlWarning( "1303: Non-zero position weight with zero rotation weight not allowed for bone weight list %s:%s P: %f R: %f, ignoring position weight\n",
  2049. pWeightList->name, pWeightList->bonename[ nBoneWeightIndex ], pWeightList->boneposweight[ nBoneWeightIndex ], pWeightList->boneweight[ nBoneWeightIndex ] );
  2050. pWeightList->boneposweight[ nBoneWeightIndex ] = pWeightList->boneweight[ nBoneWeightIndex ];
  2051. }
  2052. }
  2053. ++pWeightList->numbones;
  2054. }
  2055. if ( nBoneMaskIndex != 0 )
  2056. {
  2057. ++g_numweightlist;
  2058. }
  2059. }
  2060. }
  2061. //-----------------------------------------------------------------------------
  2062. //
  2063. //-----------------------------------------------------------------------------
  2064. static void LoadPoseParameterList( CDmePoseParameterList *pDmePoseParameterList )
  2065. {
  2066. if ( !pDmePoseParameterList )
  2067. return;
  2068. const int nPoseParameterCount = pDmePoseParameterList->m_ePoseParameterList.Count();
  2069. for ( int i = 0; i < nPoseParameterCount; ++i )
  2070. {
  2071. const CDmePoseParameter *pDmePoseParameter = pDmePoseParameterList->m_ePoseParameterList[ i ];
  2072. if ( g_numposeparameters >= MAXSTUDIOPOSEPARAM )
  2073. {
  2074. MdlWarning( "1900: Too many pose parameters, ignoring from %s\n", pDmePoseParameter->GetName() );
  2075. }
  2076. // This is like FindOrCreatePoseParamater, name is copied into g_pose[].name
  2077. const int nPoseParameterIndex = LookupPoseParameter( pDmePoseParameter->GetName() );
  2078. s_poseparameter_t *pPoseParameter = &g_pose[ nPoseParameterIndex ];
  2079. Q_strncpy( pPoseParameter->name, pDmePoseParameter->GetName(), sizeof( pPoseParameter->name ) );
  2080. pPoseParameter->min = pDmePoseParameter->m_flMin;
  2081. pPoseParameter->max = pDmePoseParameter->m_flMax;
  2082. if ( pDmePoseParameter->m_bWrap )
  2083. {
  2084. pPoseParameter->flags |= STUDIO_LOOPING;
  2085. pPoseParameter->loop = pPoseParameter->max - pPoseParameter->min;
  2086. }
  2087. else if ( pDmePoseParameter->m_bLoop )
  2088. {
  2089. pPoseParameter->flags |= STUDIO_LOOPING;
  2090. pPoseParameter->loop = pDmePoseParameter->m_flLoopRange;
  2091. }
  2092. }
  2093. }
  2094. //-----------------------------------------------------------------------------
  2095. // Purpose: Load dmeSequence.ikChainList into the sequence
  2096. //-----------------------------------------------------------------------------
  2097. static void LoadIkChainList( CDmeSequenceList *pDmeSequenceList )
  2098. {
  2099. if ( !pDmeSequenceList )
  2100. return;
  2101. const int nIkChainCount = pDmeSequenceList->m_eIkChainList.Count();
  2102. for ( int i = 0; i < nIkChainCount; ++i )
  2103. {
  2104. CDmeIkChain *pDmeIkChain = pDmeSequenceList->m_eIkChainList[ i ];
  2105. if ( !pDmeIkChain )
  2106. continue;
  2107. const char *pIkChainName = pDmeIkChain->GetName();
  2108. // Check for duplicates
  2109. int j;
  2110. for ( j = 0; j < g_numikchains; ++j )
  2111. {
  2112. if ( !Q_stricmp( pIkChainName, g_ikchain[ j ].name ) )
  2113. break;
  2114. }
  2115. if ( j < g_numikchains )
  2116. {
  2117. if ( !g_quiet )
  2118. {
  2119. MdlWarning( "1401: Duplicate IkChain: %s Ignored\n", pIkChainName );
  2120. }
  2121. }
  2122. // Set defaults
  2123. g_ikchain[g_numikchains].axis = STUDIO_Z; // Not actually used
  2124. g_ikchain[g_numikchains].value = 0.0; // Not actually used
  2125. g_ikchain[g_numikchains].height = 18.0;
  2126. g_ikchain[g_numikchains].floor = 0.0;
  2127. g_ikchain[g_numikchains].radius = 0.0;
  2128. Q_strncpy( g_ikchain[ g_numikchains ].name, pIkChainName, sizeof( g_ikchain[ g_numikchains ].name ) );
  2129. Q_strncpy( g_ikchain[ g_numikchains ].bonename, pDmeIkChain->m_sEndJoint, sizeof( g_ikchain[ g_numikchains ].bonename ) );
  2130. g_ikchain[ g_numikchains ].height = pDmeIkChain->m_flHeight;
  2131. g_ikchain[ g_numikchains ].floor = pDmeIkChain->m_flFloor;
  2132. g_ikchain[ g_numikchains ].radius = pDmeIkChain->m_flPad / 2.0f;
  2133. g_ikchain[ g_numikchains ].link[0].kneeDir = pDmeIkChain->m_vKnee;
  2134. g_ikchain[ g_numikchains ].center = pDmeIkChain->m_vCenter;
  2135. ++g_numikchains;
  2136. }
  2137. }
  2138. //-----------------------------------------------------------------------------
  2139. //
  2140. //-----------------------------------------------------------------------------
  2141. void LoadAnimationOptions( CDmeSequence *pDmeSimpleSequence, s_animation_t *pAnimation )
  2142. {
  2143. if ( !pAnimation || !pDmeSimpleSequence )
  2144. return;
  2145. pAnimation->fps = pDmeSimpleSequence->m_flFPS;
  2146. pAnimation->adjust = pDmeSimpleSequence->m_vOrigin;
  2147. // Right now don't include rotation, but if added, likely combine it with the
  2148. // default rotation which is already in pAnimation->rotation
  2149. // QuaternionAngles( pDmeSequence->m_qRotation, pAnimation->rotation );
  2150. pAnimation->scale = pDmeSimpleSequence->m_flScale;
  2151. pAnimation->looprestart = pDmeSimpleSequence->m_nStartLoop;
  2152. if ( pDmeSimpleSequence->m_bLoop )
  2153. {
  2154. pAnimation->flags |= STUDIO_LOOPING;
  2155. }
  2156. // This should be removed and handled by assemble, i.e. STUDIO_NOFORCELOOP should always be set
  2157. if ( !pDmeSimpleSequence->m_bForceLoop )
  2158. {
  2159. pAnimation->flags |= STUDIO_NOFORCELOOP;
  2160. }
  2161. if ( pDmeSimpleSequence->m_bSnap )
  2162. {
  2163. pAnimation->flags |= STUDIO_SNAP;
  2164. }
  2165. if ( pDmeSimpleSequence->m_bPost )
  2166. {
  2167. pAnimation->flags |= STUDIO_POST;
  2168. }
  2169. if ( pDmeSimpleSequence->m_bAutoIk )
  2170. {
  2171. pAnimation->noAutoIK = false;
  2172. }
  2173. else
  2174. {
  2175. pAnimation->noAutoIK = true;
  2176. }
  2177. pAnimation->motionrollback = pDmeSimpleSequence->m_flMotionRollback;
  2178. if ( pDmeSimpleSequence->m_bAnimBlocks )
  2179. {
  2180. pAnimation->disableAnimblocks = false;
  2181. }
  2182. else
  2183. {
  2184. pAnimation->disableAnimblocks = true;
  2185. }
  2186. if ( pDmeSimpleSequence->m_bAnimBlockStall )
  2187. {
  2188. pAnimation->isFirstSectionLocal = false;
  2189. }
  2190. else
  2191. {
  2192. pAnimation->isFirstSectionLocal = true;
  2193. }
  2194. pAnimation->motiontype = pDmeSimpleSequence->m_eMotionControl.GetElement()->GetStudioMotionControl();
  2195. }
  2196. //-----------------------------------------------------------------------------
  2197. //
  2198. //-----------------------------------------------------------------------------
  2199. int FindWeightList( const char *pWeightListName )
  2200. {
  2201. for ( int i = 0; i < g_numweightlist; ++i )
  2202. {
  2203. if ( !Q_stricmp( pWeightListName, g_weightlist[ i ].name ) )
  2204. return i;
  2205. }
  2206. return -1;
  2207. }
  2208. //-----------------------------------------------------------------------------
  2209. //
  2210. //-----------------------------------------------------------------------------
  2211. bool ValidateControlType( int nControlType, const char *pszTypeString, const char *pszNameString )
  2212. {
  2213. switch ( nControlType )
  2214. {
  2215. case STUDIO_X:
  2216. case STUDIO_Y:
  2217. case STUDIO_Z:
  2218. case STUDIO_XR:
  2219. case STUDIO_YR:
  2220. case STUDIO_ZR:
  2221. case STUDIO_LX:
  2222. case STUDIO_LY:
  2223. case STUDIO_LZ:
  2224. case STUDIO_LXR:
  2225. case STUDIO_LYR:
  2226. case STUDIO_LZR:
  2227. case STUDIO_LINEAR:
  2228. case STUDIO_QUADRATIC_MOTION:
  2229. return true;
  2230. // OK!
  2231. break;
  2232. default:
  2233. MdlWarning( "1605: Unknown controlType \"0x%04x\" specified for %s:%s\n",
  2234. nControlType,
  2235. pszTypeString,
  2236. pszNameString );
  2237. }
  2238. return false;
  2239. }
  2240. //-----------------------------------------------------------------------------
  2241. //
  2242. // Handles
  2243. //
  2244. // alignto
  2245. // align
  2246. // alignboneto
  2247. // alignbone
  2248. //
  2249. //-----------------------------------------------------------------------------
  2250. bool HandleDmeAnimCmdAlign( s_animcmd_t *pAnimCmd, CDmeAnimCmd *pDmeAnimCmd )
  2251. {
  2252. if ( !pDmeAnimCmd )
  2253. return false;
  2254. CDmeAnimCmdAlign *pDmeAnimCmdAlign = CastElement< CDmeAnimCmdAlign >( pDmeAnimCmd );
  2255. if ( !pDmeAnimCmdAlign )
  2256. return false;
  2257. CDmeSequenceBase *pDmeSequenceBase = pDmeAnimCmdAlign->m_eAnimation.GetElement();
  2258. if ( !pDmeSequenceBase )
  2259. {
  2260. MdlWarning( "1608: No DmeSequence specified for %s:%s\n",
  2261. pDmeAnimCmdAlign->GetTypeString(),
  2262. pDmeAnimCmd->GetName() );
  2263. return false;
  2264. }
  2265. s_animation_t *pExtAnim = LookupAnimation( pDmeSequenceBase->GetName() );
  2266. if ( !pExtAnim )
  2267. {
  2268. MdlWarning( "1604: Unknown animation \"%s\" specified for %s:%s\n",
  2269. pDmeSequenceBase->GetName(),
  2270. pDmeAnimCmdAlign->GetTypeString(),
  2271. pDmeAnimCmd->GetName() );
  2272. return false;
  2273. }
  2274. pAnimCmd->cmd = CMD_AO;
  2275. pAnimCmd->u.ao.ref = pExtAnim;
  2276. pAnimCmd->u.ao.pBonename = pDmeAnimCmdAlign->m_sBoneName.IsEmpty() ? NULL : strdup( pDmeAnimCmdAlign->m_sBoneName );
  2277. pAnimCmd->u.ao.srcframe = pDmeAnimCmdAlign->m_nSourceFrame;
  2278. pAnimCmd->u.ao.destframe = pDmeAnimCmdAlign->m_nDestinatonFrame;
  2279. pAnimCmd->u.ao.motiontype = pDmeAnimCmdAlign->m_eMotionControl.GetElement()->GetStudioMotionControl();
  2280. return true;
  2281. }
  2282. //-----------------------------------------------------------------------------
  2283. //
  2284. //-----------------------------------------------------------------------------
  2285. void LoadAnimationCommands( CDmeSequence *pDmeSimpleSequence, s_animation_t *pAnimation )
  2286. {
  2287. if ( !pDmeSimpleSequence || !pAnimation )
  2288. return;
  2289. const int nAnimCmdCount = pDmeSimpleSequence->m_eAnimationCommandList.Count();
  2290. for ( int i = 0; i < nAnimCmdCount; ++i )
  2291. {
  2292. CDmeAnimCmd *pDmeAnimCmd = pDmeSimpleSequence->m_eAnimationCommandList[ i ];
  2293. if ( !pDmeAnimCmd )
  2294. continue;
  2295. if ( pAnimation->numcmds >= MAXSTUDIOCMDS )
  2296. {
  2297. MdlWarning( "1600: Too many animation commands for anim: %s, ignoring from %d:%s\n", pAnimation->name, i, pDmeAnimCmd->GetName() );
  2298. return;
  2299. }
  2300. s_animcmd_t *pAnimCmd = &pAnimation->cmds[ pAnimation->numcmds ];
  2301. if ( pDmeAnimCmd->IsA( CDmeAnimCmdFixupLoop::GetStaticTypeSymbol() ) )
  2302. {
  2303. CDmeAnimCmdFixupLoop *pDmeAnimCmdFixupLoop = CastElement< CDmeAnimCmdFixupLoop >( pDmeAnimCmd );
  2304. pAnimCmd->cmd = CMD_FIXUP;
  2305. pAnimCmd->u.fixuploop.start = pDmeAnimCmdFixupLoop->m_nStartFrame;
  2306. pAnimCmd->u.fixuploop.end = pDmeAnimCmdFixupLoop->m_nEndFrame;
  2307. }
  2308. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdWeightList::GetStaticTypeSymbol() ) )
  2309. {
  2310. CDmeAnimCmdWeightList *pDmeAnimCmdWeightList = CastElement< CDmeAnimCmdWeightList >( pDmeAnimCmd );
  2311. const int nWeightListIndex = FindWeightList( pDmeAnimCmdWeightList->m_sWeightListName );
  2312. if ( nWeightListIndex < 0 )
  2313. {
  2314. MdlWarning( "1602: Unknown weightList \"%s\" specified for %s animation command %s.%s[%d] %s\n",
  2315. pDmeAnimCmdWeightList->m_sWeightListName,
  2316. pDmeAnimCmdWeightList->GetTypeString(),
  2317. pDmeSimpleSequence->GetName(), pDmeSimpleSequence->m_eAnimationCommandList.GetAttribute()->GetName(), i,
  2318. pDmeAnimCmd->GetName() );
  2319. continue;
  2320. }
  2321. else
  2322. {
  2323. pAnimCmd->cmd = CMD_WEIGHTS;
  2324. pAnimCmd->u.weightlist.index = nWeightListIndex;
  2325. }
  2326. }
  2327. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdSubtract::GetStaticTypeSymbol() ) )
  2328. {
  2329. CDmeAnimCmdSubtract *pDmeAnimCmdSubtract = CastElement< CDmeAnimCmdSubtract >( pDmeAnimCmd );
  2330. CDmeSequenceBase *pDmeSequenceBase = pDmeAnimCmdSubtract->m_eAnimation.GetElement();
  2331. if ( pDmeSequenceBase )
  2332. {
  2333. s_animation_t *pExtAnim = LookupAnimation( pDmeSequenceBase->GetName() );
  2334. if ( pExtAnim )
  2335. {
  2336. pAnimCmd->cmd = CMD_SUBTRACT;
  2337. pAnimCmd->u.subtract.ref = pExtAnim;
  2338. pAnimCmd->u.subtract.frame = pDmeAnimCmdSubtract->m_nFrame;
  2339. if ( !pDmeAnimCmd->IsA( CDmeAnimCmdPreSubtract::GetStaticTypeSymbol() ) )
  2340. {
  2341. pAnimCmd->u.subtract.flags |= STUDIO_POST;
  2342. }
  2343. }
  2344. else
  2345. {
  2346. MdlWarning( "1603: Unknown animation \"%s\" specified for %s %s.%s[%d] %s\n",
  2347. pDmeSequenceBase->GetName(),
  2348. pDmeAnimCmdSubtract->GetTypeString(),
  2349. pDmeSimpleSequence->GetName(), pDmeSimpleSequence->m_eAnimationCommandList.GetAttribute()->GetName(), i,
  2350. pDmeAnimCmd->GetName() );
  2351. continue;
  2352. }
  2353. }
  2354. else
  2355. {
  2356. MdlWarning( "1607: No DmeSequenceBase specified for %s %s.%s[%d] %s\n",
  2357. pDmeAnimCmdSubtract->GetTypeString(),
  2358. pDmeSimpleSequence->GetName(), pDmeSimpleSequence->m_eAnimationCommandList.GetAttribute()->GetName(), i,
  2359. pDmeAnimCmd->GetName() );
  2360. continue;
  2361. }
  2362. }
  2363. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdAlign::GetStaticTypeSymbol() ) )
  2364. {
  2365. if ( !HandleDmeAnimCmdAlign( pAnimCmd, pDmeAnimCmd ) )
  2366. continue;
  2367. }
  2368. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdRotateTo::GetStaticTypeSymbol() ) )
  2369. {
  2370. CDmeAnimCmdRotateTo *pDmeAnimCmdRotateTo = CastElement< CDmeAnimCmdRotateTo >( pDmeAnimCmd );
  2371. pAnimCmd->cmd = CMD_ANGLE;
  2372. pAnimCmd->u.angle.angle = pDmeAnimCmdRotateTo->m_flAngle;
  2373. }
  2374. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdWalkFrame::GetStaticTypeSymbol() ) )
  2375. {
  2376. CDmeAnimCmdWalkFrame *pDmeAnimCmdWalkFrame = CastElement< CDmeAnimCmdWalkFrame >( pDmeAnimCmd );
  2377. pAnimCmd->cmd = CMD_MOTION;
  2378. pAnimCmd->u.motion.iEndFrame = pDmeAnimCmdWalkFrame->m_nEndFrame;
  2379. pAnimCmd->u.motion.motiontype = pDmeAnimCmdWalkFrame->m_eMotionControl.GetElement()->GetStudioMotionControl();
  2380. }
  2381. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdDerivative::GetStaticTypeSymbol() ) )
  2382. {
  2383. CDmeAnimCmdDerivative *pDmeAnimCmdDerivative = CastElement< CDmeAnimCmdDerivative >( pDmeAnimCmd );
  2384. pAnimCmd->cmd = CMD_DERIVATIVE;
  2385. pAnimCmd->u.derivative.scale = pDmeAnimCmdDerivative->m_flScale;
  2386. }
  2387. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdDerivative::GetStaticTypeSymbol() ) )
  2388. {
  2389. CDmeAnimCmdDerivative *pDmeAnimCmdDerivative = CastElement< CDmeAnimCmdDerivative >( pDmeAnimCmd );
  2390. pAnimCmd->cmd = CMD_DERIVATIVE;
  2391. pAnimCmd->u.derivative.scale = pDmeAnimCmdDerivative->m_flScale;
  2392. }
  2393. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdLinearDelta::GetStaticTypeSymbol() ) )
  2394. {
  2395. pAnimCmd->cmd = CMD_LINEARDELTA;
  2396. pAnimCmd->u.linear.flags |= STUDIO_AL_POST;
  2397. }
  2398. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdSplineDelta::GetStaticTypeSymbol() ) )
  2399. {
  2400. pAnimCmd->cmd = CMD_LINEARDELTA;
  2401. pAnimCmd->u.linear.flags |= STUDIO_AL_POST;
  2402. pAnimCmd->u.linear.flags |= STUDIO_AL_SPLINE;
  2403. }
  2404. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdCompress::GetStaticTypeSymbol() ) )
  2405. {
  2406. CDmeAnimCmdCompress *pDmeAnimCmdCompress = CastElement< CDmeAnimCmdCompress >( pDmeAnimCmd );
  2407. pAnimCmd->cmd = CMD_COMPRESS;
  2408. pAnimCmd->u.compress.frames = pDmeAnimCmdCompress->m_nSkipFrames;
  2409. }
  2410. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdNumFrames::GetStaticTypeSymbol() ) )
  2411. {
  2412. CDmeAnimCmdNumFrames *pDmeAnimCmdNumFrames = CastElement< CDmeAnimCmdNumFrames >( pDmeAnimCmd );
  2413. pAnimCmd->cmd = CMD_NUMFRAMES;
  2414. pAnimCmd->u.compress.frames = pDmeAnimCmdNumFrames->m_nFrames;
  2415. }
  2416. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdLocalHierarchy::GetStaticTypeSymbol() ) )
  2417. {
  2418. CDmeAnimCmdLocalHierarchy *pDmeAnimCmdLocalHierarchy = CastElement< CDmeAnimCmdLocalHierarchy >( pDmeAnimCmd );
  2419. pAnimCmd->cmd = CMD_LOCALHIERARCHY;
  2420. pAnimCmd->u.localhierarchy.pBonename = strdup( pDmeAnimCmdLocalHierarchy->m_sBoneName.Get() );
  2421. pAnimCmd->u.localhierarchy.pParentname = strdup( pDmeAnimCmdLocalHierarchy->m_sParentBoneName.Get() );
  2422. pAnimCmd->u.localhierarchy.start = pDmeAnimCmdLocalHierarchy->m_flStartFrame;
  2423. pAnimCmd->u.localhierarchy.peak = pDmeAnimCmdLocalHierarchy->m_flPeakFrame;
  2424. pAnimCmd->u.localhierarchy.tail = pDmeAnimCmdLocalHierarchy->m_flTailFrame;
  2425. pAnimCmd->u.localhierarchy.end = pDmeAnimCmdLocalHierarchy->m_flEndFrame;
  2426. }
  2427. else if ( pDmeAnimCmd->IsA( CDmeAnimCmdNoAnimation::GetStaticTypeSymbol() ) )
  2428. {
  2429. pAnimCmd->cmd = CMD_NOANIMATION;
  2430. }
  2431. else
  2432. {
  2433. MdlWarning( "1601: Unhandled DmeAnimCmd %s (%s)\n", pDmeAnimCmd->GetTypeString(), pDmeAnimCmd->GetName() );
  2434. continue;
  2435. }
  2436. ++pAnimation->numcmds;
  2437. }
  2438. }
  2439. //-----------------------------------------------------------------------------
  2440. // TODO: Rework to handle all animation related commands
  2441. //-----------------------------------------------------------------------------
  2442. void LoadIkRuleList( CDmeSequence *pDmeSimpleSequence, s_animation_t *pAnimation )
  2443. {
  2444. if ( !pDmeSimpleSequence )
  2445. return;
  2446. matrix3x4_t mDefRot;
  2447. AngleMatrix( g_defaultrotation, mDefRot );
  2448. // See if we have any IkRules to load
  2449. const int nIkRuleCount = pDmeSimpleSequence->m_eIkRuleList.Count();
  2450. if ( nIkRuleCount <= 0 )
  2451. return;
  2452. for ( int i = 0; i < nIkRuleCount; ++i )
  2453. {
  2454. CDmeIkRule *pDmeIkRule = pDmeSimpleSequence->m_eIkRuleList[ i ];
  2455. if ( !pDmeIkRule )
  2456. continue;
  2457. if ( pAnimation->numcmds >= MAXSTUDIOCMDS )
  2458. {
  2459. // TODO: Issue a warning
  2460. MdlWarning( "1503: Too many animation commands for anim: %s, ignoring from %s:%s\n",
  2461. pAnimation->name, pDmeIkRule->GetTypeString(), pDmeIkRule->GetName() );
  2462. return;
  2463. }
  2464. // Find the IkChain
  2465. CDmeIkChain *pDmeIkChain = pDmeIkRule->m_eIkChain.GetElement();
  2466. if ( !pDmeIkChain )
  2467. {
  2468. MdlError( "1501: No IkChain element assigned to %s:%s\n", pDmeIkRule->GetTypeString(), pDmeIkRule->GetName() );
  2469. continue;
  2470. }
  2471. int nIkChainIndex = -1;
  2472. for ( int j = 0; j < g_numikchains; ++j )
  2473. {
  2474. if ( !Q_stricmp( pDmeIkChain->GetName(), g_ikchain[ j ].name ) )
  2475. {
  2476. nIkChainIndex = j;
  2477. break;
  2478. }
  2479. }
  2480. if ( nIkChainIndex < 0 )
  2481. {
  2482. MdlWarning( "1504: Cannot find IkChain referenced by IkRule %s:%s, ignoring\n", pDmeIkRule->GetName(), pDmeIkRule->GetTypeString() );
  2483. continue;
  2484. }
  2485. // calloc sets memory to 0
  2486. s_ikrule_t *pIkRule = reinterpret_cast< s_ikrule_t * >( calloc( 1, sizeof( s_ikrule_t ) ) );
  2487. if ( !pIkRule )
  2488. {
  2489. MdlWarning( "1502: Cannot allocate memory for IkRule %s:%s, ignoring\n", pDmeIkRule->GetName(), pDmeIkRule->GetTypeString() );
  2490. return;
  2491. }
  2492. pIkRule->chain = nIkChainIndex;
  2493. pIkRule->slot = nIkChainIndex; // Default slot
  2494. CDmeIkTouchRule *pDmeIkTouchRule = CastElement< CDmeIkTouchRule >( pDmeIkRule );
  2495. CDmeIkFootstepRule *pDmeIkFootstepRule = CastElement< CDmeIkFootstepRule >( pDmeIkRule );
  2496. CDmeIkAttachmentRule *pDmeIkAttachmentRule = CastElement< CDmeIkAttachmentRule >( pDmeIkRule );
  2497. CDmeIkReleaseRule *pDmeIkReleaseRule = CastElement< CDmeIkReleaseRule >( pDmeIkRule );
  2498. if ( pDmeIkTouchRule )
  2499. {
  2500. pIkRule->type = IK_SELF;
  2501. Q_strncpy( pIkRule->bonename, pDmeIkTouchRule->m_sBoneName, sizeof( pIkRule->bonename ) );
  2502. }
  2503. else if ( pDmeIkFootstepRule )
  2504. {
  2505. pIkRule->type = IK_GROUND;
  2506. pIkRule->height = pDmeIkFootstepRule->GetValue< float >( "height", g_ikchain[ pIkRule->chain ].height );
  2507. pIkRule->floor = pDmeIkFootstepRule->GetValue< float >( "floor", g_ikchain[ pIkRule->chain ].floor );
  2508. pIkRule->radius = pDmeIkFootstepRule->GetValue< float >( "pad", g_ikchain[ pIkRule->chain ].radius * 2.0f ) / 2.0f;
  2509. if ( pDmeIkFootstepRule->HasAttribute( "contact", AT_INT ) )
  2510. {
  2511. pIkRule->contact = pDmeIkFootstepRule->GetValue< int >( "contact" );
  2512. }
  2513. }
  2514. else if ( pDmeIkAttachmentRule )
  2515. {
  2516. pIkRule->type = IK_ATTACHMENT;
  2517. Q_strncpy( pIkRule->attachment, pDmeIkAttachmentRule->m_sAttachmentName, sizeof( pIkRule->attachment ) );
  2518. if ( pDmeIkAttachmentRule->HasAttribute( "fallbackBone", AT_STRING ) )
  2519. {
  2520. Q_strncpy( pIkRule->bonename, pDmeIkAttachmentRule->GetValueString( "fallbackBone" ), sizeof( pIkRule->bonename ) );
  2521. }
  2522. if ( pDmeIkAttachmentRule->HasAttribute( "fallbackPosition", AT_VECTOR3 ) )
  2523. {
  2524. VectorIRotate( pDmeIkAttachmentRule->GetValue< Vector >( "fallbackPosition" ), mDefRot, pIkRule->pos );
  2525. pIkRule->bone = -1;
  2526. }
  2527. if ( pDmeIkAttachmentRule->HasAttribute( "fallbackRotation", AT_QUATERNION ) )
  2528. {
  2529. // TODO: Adjust rotation as above for position adjustment?
  2530. pIkRule->q = pDmeIkAttachmentRule->GetValue< Quaternion >( "fallbackRotation" );
  2531. pIkRule->bone = -1;
  2532. }
  2533. }
  2534. else if ( pDmeIkReleaseRule )
  2535. {
  2536. pIkRule->type = IK_RELEASE;
  2537. }
  2538. else
  2539. {
  2540. MdlWarning( "1500: Unknown IkRuleType %s:%s, ignoring\n", pDmeIkRule->GetName(), pDmeIkRule->GetTypeString() );
  2541. continue;
  2542. }
  2543. switch ( pDmeIkRule->m_nUseType )
  2544. {
  2545. case CDmeIkRule::USE_SEQUENCE:
  2546. pIkRule->usesequence = true;
  2547. pIkRule->usesource = false;
  2548. break;
  2549. case CDmeIkRule::USE_SOURCE:
  2550. pIkRule->usesequence = false;
  2551. pIkRule->usesource = true;
  2552. break;
  2553. case CDmeIkRule::USE_NONE:
  2554. default:
  2555. // Nothing
  2556. break;
  2557. }
  2558. CDmeIkRange *pDmeIkRange = pDmeIkRule->m_eRange.GetElement();
  2559. if ( pDmeIkRange )
  2560. {
  2561. pIkRule->start = pDmeIkRange->m_nStartFrame;
  2562. pIkRule->peak = pDmeIkRange->m_nMaxStartFrame;
  2563. pIkRule->tail = pDmeIkRange->m_nMaxEndFrame;
  2564. pIkRule->end = pDmeIkRange->m_nEndFrame;
  2565. }
  2566. s_animcmd_t *pAnimCmd = &( pAnimation->cmds[ pAnimation->numcmds ] );
  2567. pAnimCmd->cmd = CMD_IKRULE;
  2568. pAnimCmd->u.ikrule.pRule = pIkRule;
  2569. pAnimation->numcmds++;
  2570. }
  2571. }
  2572. //-----------------------------------------------------------------------------
  2573. // Purpose: Loads all of the AddLayer/BlendLayer for the specified sequence
  2574. //-----------------------------------------------------------------------------
  2575. void LoadLayerList( CDmeSequenceBase *pDmeSequenceBase, s_sequence_t *pSequence )
  2576. {
  2577. if ( !pDmeSequenceBase || !pSequence )
  2578. return;
  2579. const int nLayerCount = pDmeSequenceBase->m_eLayerList.Count();
  2580. for ( int i = 0; i < nLayerCount; ++i )
  2581. {
  2582. CDmeSequenceLayerBase *pDmeLayerBase = pDmeSequenceBase->m_eLayerList[ i ];
  2583. if ( !pDmeLayerBase )
  2584. continue;
  2585. CDmeSequenceBase *pDmeRefSeq = pDmeLayerBase->m_eAnimation.GetElement();
  2586. if ( !pDmeRefSeq )
  2587. {
  2588. // TODO: Warning message - No sequence specified
  2589. continue;
  2590. }
  2591. if ( pSequence->numautolayers >= ARRAYSIZE( pSequence->autolayer ) )
  2592. {
  2593. // TODO: Warning message - Too many layers
  2594. break;
  2595. }
  2596. Q_strncpy( pSequence->autolayer[ pSequence->numautolayers ].name, pDmeRefSeq->GetName(), sizeof( pSequence->autolayer[ pSequence->numautolayers ].name ) );
  2597. CDmeSequenceAddLayer *pDmeAddLayer = CastElement< CDmeSequenceAddLayer >( pDmeSequenceBase->m_eLayerList[ i ] );
  2598. if ( pDmeAddLayer )
  2599. {
  2600. // Nothing to do
  2601. }
  2602. CDmeSequenceBlendLayer *pDmeBlendLayer = CastElement< CDmeSequenceBlendLayer >( pDmeSequenceBase->m_eLayerList[ i ] );
  2603. if ( pDmeBlendLayer )
  2604. {
  2605. pSequence->autolayer[ pSequence->numautolayers ].start = pDmeBlendLayer->m_flStartFrame;
  2606. pSequence->autolayer[ pSequence->numautolayers ].peak = pDmeBlendLayer->m_flPeakFrame;
  2607. pSequence->autolayer[ pSequence->numautolayers ].tail = pDmeBlendLayer->m_flTailFrame;
  2608. pSequence->autolayer[ pSequence->numautolayers ].end = pDmeBlendLayer->m_flEndFrame;
  2609. pSequence->autolayer[ pSequence->numautolayers ].flags |= pDmeBlendLayer->m_bCrossfade ? STUDIO_AL_XFADE : 0;
  2610. pSequence->autolayer[ pSequence->numautolayers ].flags |= pDmeBlendLayer->m_bSpline ? STUDIO_AL_SPLINE : 0;
  2611. pSequence->autolayer[ pSequence->numautolayers ].flags |= pDmeBlendLayer->m_bNoBlend ? STUDIO_AL_NOBLEND : 0;
  2612. pSequence->autolayer[ pSequence->numautolayers ].flags |= pDmeBlendLayer->m_bLocal ? STUDIO_AL_LOCAL : 0;
  2613. pSequence->flags |= pDmeBlendLayer->m_bLocal ? STUDIO_AL_LOCAL : 0;
  2614. if ( !pDmeBlendLayer->m_sPoseParameterName.IsEmpty() )
  2615. {
  2616. pSequence->autolayer[ pSequence->numautolayers ].flags |= STUDIO_AL_POSE;
  2617. pSequence->autolayer[ pSequence->numautolayers ].pose = LookupPoseParameter( pDmeBlendLayer->m_sPoseParameterName.Get() );
  2618. }
  2619. }
  2620. pSequence->numautolayers++;
  2621. }
  2622. }
  2623. //-----------------------------------------------------------------------------
  2624. // Purpose: Loads all of the IkLocks for the specified Sequence
  2625. //-----------------------------------------------------------------------------
  2626. void LoadIkLockList( CDmeSequenceBase *pDmeSequenceBase, s_sequence_t *pSequence )
  2627. {
  2628. if ( !pDmeSequenceBase || !pSequence )
  2629. return;
  2630. const int nIkLockCount = pDmeSequenceBase->m_eIkLockList.Count();
  2631. for ( int i = 0; i < nIkLockCount; ++i )
  2632. {
  2633. CDmeIkLock *pDmeIkLock = pDmeSequenceBase->m_eIkLockList[ i ];
  2634. if ( !pDmeIkLock )
  2635. continue;
  2636. // TODO: Check for duplicates?
  2637. CDmeIkChain *pDmeIkChain = pDmeIkLock->m_eIkChain.GetElement();
  2638. if ( pDmeIkChain )
  2639. {
  2640. Q_strncpy( pSequence->iklock[ pSequence->numiklocks ].name, pDmeIkChain->GetName(), sizeof( pSequence->iklock[ pSequence->numiklocks ].name ) );
  2641. }
  2642. else
  2643. {
  2644. MdlError( "1700: No IkChain element assigned to %s:%s\n", pDmeIkLock->GetTypeString(), pDmeIkLock->GetName() );
  2645. }
  2646. pSequence->iklock[ pSequence->numiklocks ].flPosWeight = clamp( pDmeIkLock->m_flLockPosition.Get(), 0.0f, 1.0f );
  2647. pSequence->iklock[ pSequence->numiklocks ].flLocalQWeight = RemapValClamped( pDmeIkLock->m_flLockRotation, 0.0f, 1.0f, 1.0f, 0.0f ); // Invert it for historical reasons
  2648. pSequence->numiklocks++;
  2649. }
  2650. }
  2651. //-----------------------------------------------------------------------------
  2652. //
  2653. //-----------------------------------------------------------------------------
  2654. void LoadAnimationEventList( CDmeSequenceBase *pDmeSequenceBase, s_sequence_t *pSequence )
  2655. {
  2656. if ( !pDmeSequenceBase || !pSequence )
  2657. return;
  2658. CDmAttribute *pBlah = pDmeSequenceBase->GetAttribute( "animationEventList" );
  2659. int nFoo = 0;
  2660. if ( pBlah )
  2661. {
  2662. nFoo = CDmrGenericArrayConst( pBlah ).Count();
  2663. }
  2664. const int nAnimEventCount = pDmeSequenceBase->m_eAnimationEventList.Count();
  2665. for ( int i = 0; i < nAnimEventCount; ++i )
  2666. {
  2667. CDmeAnimationEvent *pDmeAnimationEvent = pDmeSequenceBase->m_eAnimationEventList[ i ];
  2668. if ( !pDmeAnimationEvent )
  2669. continue;
  2670. // Not sure why this is +1... always one special event??
  2671. if ( pSequence->numevents + 1 >= MAXSTUDIOEVENTS )
  2672. {
  2673. MdlError( "1800: Too many %s's on %s:%s, ignoring from %s\n",
  2674. pDmeAnimationEvent->GetTypeString(),
  2675. pDmeSequenceBase->GetTypeString(),
  2676. pDmeSequenceBase->GetName(),
  2677. pDmeAnimationEvent->GetName() );
  2678. return;
  2679. }
  2680. Q_strncpy( pSequence->event[ pSequence->numevents ].eventname, pDmeAnimationEvent->GetName(), sizeof( pSequence->event[ pSequence->numevents ].eventname ) );
  2681. pSequence->event[ pSequence->numevents ].frame = pDmeAnimationEvent->m_nFrame;
  2682. if ( pDmeAnimationEvent->m_sDataString.IsEmpty() )
  2683. {
  2684. pSequence->event[ pSequence->numevents ].options[0] = '\0';
  2685. }
  2686. else
  2687. {
  2688. Q_strncpy( pSequence->event[ pSequence->numevents ].options, pDmeAnimationEvent->m_sDataString, sizeof( pSequence->event[ pSequence->numevents ].options ) );
  2689. }
  2690. ++pSequence->numevents;
  2691. }
  2692. }
  2693. //-----------------------------------------------------------------------------
  2694. //
  2695. //-----------------------------------------------------------------------------
  2696. static void LoadSequenceList( CDmeMultiSequence *pDmeMultiSequence, CUtlVector< s_animation_t * > &animations )
  2697. {
  2698. if ( !pDmeMultiSequence )
  2699. return;
  2700. const int nSequenceCount = pDmeMultiSequence->m_eSequenceList.Count();
  2701. for ( int i = 0; i < nSequenceCount; ++i )
  2702. {
  2703. CDmeSequence *pDmeSubSequence = pDmeMultiSequence->m_eSequenceList[ i ];
  2704. if ( !pDmeSubSequence )
  2705. continue;
  2706. s_animation_t *pAnim = LookupAnimation( pDmeSubSequence->GetName() );
  2707. if ( !pAnim )
  2708. {
  2709. MdlWarning( "1208: DmeSequence %s: Couldn't find referenced animation: %s\n", pDmeMultiSequence->GetName(), pDmeSubSequence->GetName() );
  2710. continue;
  2711. }
  2712. // TODO: Limit to 64?
  2713. animations.AddToTail( pAnim );
  2714. }
  2715. }
  2716. //-----------------------------------------------------------------------------
  2717. //
  2718. //-----------------------------------------------------------------------------
  2719. static void LoadSequenceBlends( CDmeMultiSequence *pDmeMultiSequence, s_sequence_t *pSequence )
  2720. {
  2721. if ( !pSequence || !pDmeMultiSequence )
  2722. return;
  2723. const int nBlendCount = pDmeMultiSequence->m_eBlendList.Count();
  2724. for ( int i = 0; i < nBlendCount; ++i )
  2725. {
  2726. CDmeSequenceBlendBase *pDmeSequenceBlendBase = pDmeMultiSequence->m_eBlendList[ i ];
  2727. if ( !pDmeSequenceBlendBase )
  2728. continue;
  2729. if ( pDmeSequenceBlendBase->IsA( CDmeSequenceBlend::GetStaticTypeSymbol() ) )
  2730. {
  2731. CDmeSequenceBlend *pDmeSequenceBlend = CastElement< CDmeSequenceBlend >( pDmeSequenceBlendBase );
  2732. const int i = ( pSequence->paramindex[0] != -1 ) ? 1 : 0;
  2733. const int j = LookupPoseParameter( pDmeSequenceBlend->m_sPoseParameterName.Get() );
  2734. pSequence->paramindex[i] = j;
  2735. pSequence->paramattachment[i] = -1;
  2736. pSequence->paramstart[i] = pDmeSequenceBlend->m_flParamStart;
  2737. pSequence->paramend[i] = pDmeSequenceBlend->m_flParamEnd;
  2738. g_pose[j].min = MIN( g_pose[j].min, pSequence->paramstart[i] );
  2739. g_pose[j].min = MIN( g_pose[j].min, pSequence->paramend[i] );
  2740. g_pose[j].max = MAX( g_pose[j].max, pSequence->paramstart[i] );
  2741. g_pose[j].max = MAX( g_pose[j].max, pSequence->paramend[i] );
  2742. }
  2743. else if ( pDmeSequenceBlendBase->IsA( CDmeSequenceCalcBlend::GetStaticTypeSymbol() ) )
  2744. {
  2745. // TODO: This really isn't an animation command but the distinction might not be important?
  2746. CDmeSequenceCalcBlend *pDmeSequenceCalcBlend = CastElement< CDmeSequenceCalcBlend >( pDmeSequenceBlendBase );
  2747. const int i = ( pSequence->paramindex[0] != -1 ) ? 1 : 0;
  2748. const int j = LookupPoseParameter( pDmeSequenceCalcBlend->m_sPoseParameterName.Get() );
  2749. pSequence->paramindex[i] = j;
  2750. pSequence->paramattachment[i] = LookupAttachment( pDmeSequenceCalcBlend->m_sAttachmentName.Get() );
  2751. pSequence->paramcontrol[i] = pDmeSequenceCalcBlend->m_eMotionControl.GetElement()->GetStudioMotionControl();
  2752. if ( pSequence->paramattachment[i] < 0 )
  2753. {
  2754. MdlWarning( "1606: Unknown Attachment For %s - %s.%s = %s\n",
  2755. pDmeSequenceCalcBlend->GetTypeString(),
  2756. pDmeSequenceCalcBlend->GetName(),
  2757. pDmeSequenceCalcBlend->m_sAttachmentName.GetAttribute()->GetName(),
  2758. pDmeSequenceCalcBlend->m_sAttachmentName.Get() );
  2759. }
  2760. continue; // Don't add it as an animation command
  2761. }
  2762. }
  2763. }
  2764. //-----------------------------------------------------------------------------
  2765. //
  2766. //-----------------------------------------------------------------------------
  2767. void LoadBlendRefCompCenter( CDmeMultiSequence *pDmeMultiSequence, s_sequence_t *pSequence )
  2768. {
  2769. if ( !pDmeMultiSequence || !pSequence )
  2770. return;
  2771. CDmeSequence *pDmeBlendRefSequence = CastElement< CDmeSequence >( pDmeMultiSequence->m_eBlendRef.GetElement() );
  2772. if ( pDmeBlendRefSequence )
  2773. {
  2774. const char *pszBlendRef = pDmeBlendRefSequence->GetName();
  2775. if ( pszBlendRef && *pszBlendRef )
  2776. {
  2777. pSequence->paramanim = LookupAnimation( pszBlendRef );
  2778. if ( pSequence->paramanim == NULL )
  2779. {
  2780. MdlWarning( "1202: DmeSequence %s: Unknown .blendRef animation: %s\n", pDmeMultiSequence->GetName(), pszBlendRef );
  2781. }
  2782. }
  2783. }
  2784. CDmeSequence *pDmeBlendRefComp = CastElement< CDmeSequence >( pDmeMultiSequence->m_eBlendComp.GetElement() );
  2785. if ( pDmeBlendRefComp )
  2786. {
  2787. const char *pszBlendComp = pDmeBlendRefComp->GetName();
  2788. if ( pszBlendComp && *pszBlendComp )
  2789. {
  2790. pSequence->paramcompanim = LookupAnimation( pszBlendComp );
  2791. if ( pSequence->paramcompanim == NULL )
  2792. {
  2793. MdlWarning( "1203: DmeSequence %s: Unknown .blendComp animation: %s\n", pDmeMultiSequence->GetName(), pszBlendComp );
  2794. }
  2795. }
  2796. }
  2797. CDmeSequence *pDmeBlendRefCenter = CastElement< CDmeSequence >( pDmeMultiSequence->m_eBlendCenter.GetElement() );
  2798. if ( pDmeBlendRefCenter )
  2799. {
  2800. const char *pszBlendCenter = pDmeBlendRefCenter->GetName();
  2801. if ( pszBlendCenter && *pszBlendCenter )
  2802. {
  2803. pSequence->paramcenter = LookupAnimation( pszBlendCenter );
  2804. if ( pSequence->paramcenter == NULL )
  2805. {
  2806. MdlWarning( "1204: DmeSequence %s: Unknown .blendCenter animation: %s\n", pDmeMultiSequence->GetName(), pszBlendCenter );
  2807. }
  2808. }
  2809. }
  2810. }
  2811. //-----------------------------------------------------------------------------
  2812. //
  2813. //-----------------------------------------------------------------------------
  2814. static void CreateBindPoseSequence( s_source_t *pMainSource )
  2815. {
  2816. s_sourceanim_t *pSourceAnim = FindSourceAnim( pMainSource, "BindPose" );
  2817. if ( pSourceAnim )
  2818. {
  2819. // Create the first "BindPose" default sequence
  2820. s_sequence_t *pSeq = ProcessCmdSequence( "BindPose" );
  2821. s_animation_t *pAnim = ProcessImpliedAnimation( pSeq, pMainSource->filename );
  2822. pSeq->panim[0][0] = pAnim;
  2823. ProcessSequence( pSeq, 1, &pAnim, false );
  2824. }
  2825. }
  2826. //-----------------------------------------------------------------------------
  2827. // Purpose: Load the data from the CDmeAnimBlockSize element which is
  2828. // specified by the .animBlockSize attribute on the root node
  2829. // of the .mpp file. If it's NULL, do nothing
  2830. // Basically implements Cmd_AnimBlockSize
  2831. //-----------------------------------------------------------------------------
  2832. static void LoadAnimBlockSize( CDmeAnimBlockSize *pDmeAnimBlockSize )
  2833. {
  2834. if ( !pDmeAnimBlockSize )
  2835. return;
  2836. g_animblocksize = pDmeAnimBlockSize->m_nSize;
  2837. if ( g_animblocksize < 1024 )
  2838. {
  2839. g_animblocksize *= 1024;
  2840. }
  2841. g_bNoAnimblockStall = !pDmeAnimBlockSize->m_bStall;
  2842. switch ( pDmeAnimBlockSize->m_nStorageType )
  2843. {
  2844. case CDmeAnimBlockSize::ANIMBLOCKSTORAGETYPE_HIRES:
  2845. g_bAnimblockLowRes = false;
  2846. g_bAnimblockHighRes = true;
  2847. break;
  2848. case CDmeAnimBlockSize::ANIMBLOCKSTORAGETYPE_LOWRES:
  2849. // Fallthrough deliberate
  2850. default:
  2851. g_bAnimblockLowRes = true;
  2852. g_bAnimblockHighRes = false;
  2853. break;
  2854. }
  2855. }
  2856. //-----------------------------------------------------------------------------
  2857. // Purpose: Load all of the DmeSequence elements, if the passed
  2858. // CDmeSequenceList is NULL, empty or doesn't contain any valid
  2859. // sequences, a default "BindPose" sequence is created
  2860. // Returns: The number of sequences created
  2861. //-----------------------------------------------------------------------------
  2862. static int LoadAndCreateSequences( s_source_t *pMainSource, CDmeSequenceList *pSequenceList, bool &bSetUpAxis )
  2863. {
  2864. CreateBindPoseSequence( pMainSource );
  2865. LoadIkChainList( pSequenceList );
  2866. int nSequenceAddedCount = 0;
  2867. char szSeqName[ MAX_PATH ];
  2868. const int nSequenceCount = pSequenceList ? pSequenceList->m_Sequences.Count() : 0;
  2869. CUtlVector< CDmeSequenceBase * > sortedSequenceList;
  2870. // Add all CDmeSequence elements to the list first
  2871. for ( int nSequenceIndex = 0; nSequenceIndex < nSequenceCount; ++nSequenceIndex )
  2872. {
  2873. CDmeSequenceBase *pDmeSequenceBase = pSequenceList->m_Sequences[ nSequenceIndex ];
  2874. if ( !pDmeSequenceBase )
  2875. {
  2876. MdlWarning( "1201: Empty DmeSequence %s[ %d ]\n", pSequenceList->GetName(), nSequenceIndex );
  2877. continue;
  2878. }
  2879. const char *pszSeqName = pDmeSequenceBase->GetName();
  2880. if ( pszSeqName == NULL || *pszSeqName == '\0' )
  2881. {
  2882. MdlWarning( "1200: Ignoring Unnamed Sequence On %s[%d]\n", pSequenceList->GetName(), nSequenceIndex );
  2883. continue;
  2884. }
  2885. sortedSequenceList.AddToTail( pDmeSequenceBase );
  2886. }
  2887. qsort( sortedSequenceList.Base(), sortedSequenceList.Count(), sizeof( CDmeSequenceBase * ), CDmeSequenceBase::QSortFunction );
  2888. // Process the reordered DmeSequenceBase list
  2889. for ( int nSequenceIndex = 0; nSequenceIndex < sortedSequenceList.Count(); ++nSequenceIndex )
  2890. {
  2891. CUtlVector< s_animation_t * > animations;
  2892. CDmeSequenceBase *pDmeSequenceBase = sortedSequenceList[ nSequenceIndex ];
  2893. // Already checked for NULL & unnamed
  2894. const char *pszSeqName = pDmeSequenceBase->GetName();
  2895. Q_StripExtension( pszSeqName, szSeqName, sizeof( szSeqName ) );
  2896. s_sequence_t *pSeq = ProcessCmdSequence( szSeqName );
  2897. {
  2898. CDmeSequence *pDmeSimpleSequence = CastElement< CDmeSequence >( pDmeSequenceBase );
  2899. CDmeMultiSequence *pDmeMultiSequence = CastElement< CDmeMultiSequence >( pDmeSequenceBase );
  2900. if ( !pDmeSimpleSequence && !pDmeMultiSequence )
  2901. {
  2902. MdlWarning( "1209: Invalid DmeSequence %s[ %d ], not Simple or Multi\n", pSequenceList->GetName(), nSequenceIndex );
  2903. continue;
  2904. }
  2905. if ( pDmeSimpleSequence )
  2906. {
  2907. CDmeModel *pDmeModel = CastElement< CDmeModel >( pDmeSimpleSequence->m_eSkeleton.GetElement() );
  2908. if ( bSetUpAxis && pDmeModel )
  2909. {
  2910. const char *pUpAxis = pDmeModel->GetValueString( "upAxis" );
  2911. if ( pUpAxis )
  2912. {
  2913. if ( StringHasPrefix( pUpAxis, "Y" ) )
  2914. {
  2915. // rotate 90 degrees around x to move y into z
  2916. g_defaultrotation = RadianEuler( M_PI / 2.0f, 0.0f, M_PI / 2.0f );
  2917. }
  2918. }
  2919. bSetUpAxis = false;
  2920. }
  2921. CDmeDag *pDmeSkeleton = pDmeSimpleSequence->m_eSkeleton.GetElement();
  2922. if ( !pDmeSkeleton )
  2923. {
  2924. MdlWarning( "1205: Ignoring Sequence %s, No Skeleton Specified\n", pszSeqName );
  2925. continue;
  2926. }
  2927. s_source_t *pSource = AllocateDmxSource( szSeqName );
  2928. BoneTransformMap_t boneMap;
  2929. if ( !LoadModelAndSkeleton( pSource, boneMap, pDmeSkeleton, pDmeModel, NULL, false ) )
  2930. {
  2931. MdlWarning( "1206: Sequence %s: Ignoring Sequence, Couldn't Load Specified Skeleton: %s\n", pszSeqName, pDmeSkeleton->GetName() );
  2932. continue;
  2933. }
  2934. CDmeAnimationList *pDmeAnimationList = pDmeSimpleSequence->m_eAnimationList.GetElement();
  2935. s_animation_t *pAnim = NULL;
  2936. if ( pDmeAnimationList )
  2937. {
  2938. // Simple sequence created from animation data
  2939. LoadAnimations( pSource, pDmeAnimationList, g_currentscale, boneMap );
  2940. // Check for various CDmeAnimCmd's which may or may not be flagged with bDelta
  2941. bool bDmeAnimCmdDelta = false;
  2942. for ( int i = 0; i < pDmeSimpleSequence->m_eAnimationCommandList.Count(); ++i )
  2943. {
  2944. if ( pDmeSimpleSequence->m_eAnimationCommandList[i]->IsA( CDmeAnimCmdSubtract::GetStaticTypeSymbol() ) ||
  2945. pDmeSimpleSequence->m_eAnimationCommandList[i]->IsA( CDmeAnimCmdPreSubtract::GetStaticTypeSymbol() ) ||
  2946. pDmeSimpleSequence->m_eAnimationCommandList[i]->IsA( CDmeAnimCmdLinearDelta::GetStaticTypeSymbol() ) ||
  2947. pDmeSimpleSequence->m_eAnimationCommandList[i]->IsA( CDmeAnimCmdSplineDelta::GetStaticTypeSymbol() ) )
  2948. {
  2949. bDmeAnimCmdDelta = true;
  2950. pSeq->flags |= STUDIO_DELTA;
  2951. }
  2952. }
  2953. {
  2954. // allocate animation entry
  2955. g_panimation[g_numani] = (s_animation_t *)calloc( 1, sizeof( s_animation_t ) );
  2956. g_panimation[g_numani]->index = g_numani;
  2957. pAnim = g_panimation[g_numani];
  2958. g_numani++;
  2959. pAnim->isImplied = true;
  2960. pAnim->startframe = 0;
  2961. pAnim->endframe = MAXSTUDIOANIMFRAMES - 1;
  2962. strcpy( pAnim->name, "@" );
  2963. strcat( pAnim->name, pSeq->name );
  2964. strcpyn( pAnim->filename, pSource->filename );
  2965. VectorCopy( g_defaultadjust, pAnim->adjust );
  2966. pAnim->scale = 1.0f;
  2967. // Don't re-orient delta animations
  2968. if ( bDmeAnimCmdDelta || !( pDmeSimpleSequence->m_bDelta || pDmeSimpleSequence->m_bPreDelta ) )
  2969. {
  2970. pAnim->rotation = g_defaultrotation;
  2971. }
  2972. pAnim->fps = 30;
  2973. pAnim->motionrollback = g_flDefaultMotionRollback;
  2974. pAnim->source = pSource;
  2975. const int nSourceAnimCount = pAnim->source->m_Animations.Count();
  2976. if ( nSourceAnimCount > 0 )
  2977. {
  2978. s_sourceanim_t *pSourceAnim = &pAnim->source->m_Animations[nSourceAnimCount-1];
  2979. Q_strncpy( pAnim->animationname, pAnim->source->m_Animations[nSourceAnimCount-1].animationname, sizeof(pAnim->animationname) );
  2980. if ( pAnim->startframe < pSourceAnim->startframe )
  2981. {
  2982. pAnim->startframe = pSourceAnim->startframe;
  2983. }
  2984. if ( pAnim->endframe > pSourceAnim->endframe )
  2985. {
  2986. pAnim->endframe = pSourceAnim->endframe;
  2987. }
  2988. }
  2989. else
  2990. {
  2991. Q_strncpy( pAnim->animationname, "", sizeof( pAnim->animationname ) );
  2992. }
  2993. pAnim->numframes = pAnim->endframe - pAnim->startframe + 1;
  2994. }
  2995. }
  2996. else
  2997. {
  2998. // Simple sequence created from a single pose
  2999. CreateAnimFromSkeleton( pSource, szSeqName, boneMap );
  3000. pAnim = ProcessImpliedAnimation( pSeq, pSource->filename );
  3001. }
  3002. Assert( pAnim );
  3003. animations.AddToTail( pAnim );
  3004. // Hack to allow animations commands to refer to same sequence in a simple DmeSequence
  3005. pSeq->panim[0][0] = pAnim;
  3006. // Animation Options
  3007. LoadAnimationOptions( pDmeSimpleSequence, pAnim );
  3008. // Animation Commands
  3009. LoadAnimationCommands( pDmeSimpleSequence, pAnim );
  3010. // IkRules
  3011. LoadIkRuleList( pDmeSimpleSequence, pAnim );
  3012. AddBodyAttachments( pSource );
  3013. }
  3014. // Only apply to multi-sequences
  3015. if ( pDmeMultiSequence )
  3016. {
  3017. LoadSequenceList( pDmeMultiSequence, animations );
  3018. LoadSequenceBlends( pDmeMultiSequence, pSeq );
  3019. LoadBlendRefCompCenter( pDmeMultiSequence, pSeq );
  3020. pSeq->groupsize[ 0 ] = pDmeMultiSequence->m_nBlendWidth.Get();
  3021. }
  3022. }
  3023. LoadAnimationEventList( pDmeSequenceBase, pSeq );
  3024. // Same As ParseSequence
  3025. CDmeSequenceActivity *pDmeSequenceActivity = pDmeSequenceBase->m_eActivity.GetElement();
  3026. if ( pDmeSequenceActivity )
  3027. {
  3028. const char *pszActivityName = pDmeSequenceActivity->GetName();
  3029. if ( pszActivityName && Q_strlen( pszActivityName ) > 0 )
  3030. {
  3031. Q_strncpy( pSeq->activityname, pszActivityName, sizeof( pSeq->activityname ) );
  3032. pSeq->actweight = pDmeSequenceActivity->m_nWeight.Get();
  3033. for ( int nModifierIndex = 0; nModifierIndex < pDmeSequenceActivity->m_sModifierList.Count(); ++nModifierIndex )
  3034. {
  3035. strcpyn( pSeq->activitymodifier[ pSeq->numactivitymodifiers++ ].name, pDmeSequenceActivity->m_sModifierList.Get( nModifierIndex ) );
  3036. if ( pSeq->numactivitymodifiers == MAXSTUDIOACTIVITYMODIFIERS )
  3037. break;
  3038. }
  3039. if ( pDmeSequenceActivity->m_sModifierList.Count() > MAXSTUDIOACTIVITYMODIFIERS )
  3040. {
  3041. MdlWarning( "1210: Too many activity modifiers (%d) on DmeSequence %s, only using first %d\n",
  3042. pDmeSequenceActivity->m_sModifierList.Count(),
  3043. pSeq->name,
  3044. MAXSTUDIOACTIVITYMODIFIERS );
  3045. }
  3046. }
  3047. }
  3048. if ( pDmeSequenceBase->m_bLoop )
  3049. {
  3050. pSeq->flags |= STUDIO_LOOPING;
  3051. }
  3052. if ( pDmeSequenceBase->m_bSnap )
  3053. {
  3054. pSeq->flags |= STUDIO_SNAP;
  3055. }
  3056. if ( pDmeSequenceBase->m_bPost )
  3057. {
  3058. pSeq->flags |= STUDIO_POST;
  3059. }
  3060. if ( pDmeSequenceBase->m_bHidden )
  3061. {
  3062. pSeq->flags |= STUDIO_HIDDEN;
  3063. }
  3064. if ( pDmeSequenceBase->m_bDelta )
  3065. {
  3066. pSeq->flags |= STUDIO_DELTA;
  3067. pSeq->flags |= STUDIO_POST;
  3068. }
  3069. if ( pDmeSequenceBase->m_bWorldSpace )
  3070. {
  3071. pSeq->flags |= STUDIO_WORLD;
  3072. pSeq->flags |= STUDIO_POST;
  3073. }
  3074. if ( pDmeSequenceBase->m_bPreDelta )
  3075. {
  3076. pSeq->flags |= STUDIO_DELTA;
  3077. }
  3078. if ( pDmeSequenceBase->m_bAutoPlay )
  3079. {
  3080. pSeq->flags |= STUDIO_AUTOPLAY;
  3081. }
  3082. if ( pDmeSequenceBase->m_bRealtime )
  3083. {
  3084. pSeq->flags |= STUDIO_REALTIME;
  3085. }
  3086. // AddLayer/BlendLayer
  3087. LoadLayerList( pDmeSequenceBase, pSeq );
  3088. // IkLock
  3089. LoadIkLockList( pDmeSequenceBase, pSeq );
  3090. pSeq->fadeintime = pDmeSequenceBase->m_flFadeIn.Get();
  3091. pSeq->fadeouttime = pDmeSequenceBase->m_flFadeOut.Get();
  3092. const CUtlString &entryNode = pDmeSequenceBase->m_sEntryNode.Get();
  3093. const CUtlString &exitNode = pDmeSequenceBase->m_sExitNode.Get();
  3094. if ( !entryNode.IsEmpty() )
  3095. {
  3096. if ( !exitNode.IsEmpty() )
  3097. {
  3098. pSeq->entrynode = LookupXNode( entryNode.Get() );
  3099. pSeq->exitnode = LookupXNode( exitNode.Get() );
  3100. if ( pDmeSequenceBase->m_bReverseNodeTransition )
  3101. {
  3102. pSeq->nodeflags |= 1;
  3103. }
  3104. }
  3105. else
  3106. {
  3107. pSeq->entrynode = pSeq->exitnode = LookupXNode( entryNode.Get() );
  3108. }
  3109. }
  3110. if ( animations.Count() > 0 )
  3111. {
  3112. ProcessSequence( pSeq, animations.Count(), animations.Base(), false );
  3113. ++nSequenceAddedCount;
  3114. }
  3115. else
  3116. {
  3117. MdlWarning( "1207: DmeSequence %s: No animations created or referenced, ignoring\n", pszSeqName );
  3118. }
  3119. const CUtlString &keyValues = pDmeSequenceBase->m_sKeyValues.Get();
  3120. const int nKeyValuesLength = keyValues.Length();
  3121. if ( nKeyValuesLength > 0 )
  3122. {
  3123. pSeq->KeyValue.AddMultipleToTail( nKeyValuesLength, keyValues.Get() );
  3124. }
  3125. }
  3126. return nSequenceAddedCount;
  3127. }
  3128. //-----------------------------------------------------------------------------
  3129. // Purpose: Load all of the strings from the passed
  3130. // CDmeIncludeModelList.includeModels array
  3131. //-----------------------------------------------------------------------------
  3132. static void LoadIncludeModelList( CDmeIncludeModelList *pIncludeModelList )
  3133. {
  3134. if ( !pIncludeModelList )
  3135. return;
  3136. const int nIncludeModelsCount = pIncludeModelList->m_IncludeModels.Count();
  3137. for ( int ni = 0; ni < nIncludeModelsCount; ++ni )
  3138. {
  3139. if ( g_numincludemodels >= ARRAYSIZE( g_includemodel ) )
  3140. {
  3141. MdlError( "Too Many Include Models while including: \"%s\", Max: %d\n", pIncludeModelList->m_IncludeModels[ ni ], ARRAYSIZE( g_includemodel ) );
  3142. }
  3143. Q_strncpy( g_includemodel[ g_numincludemodels ].name, pIncludeModelList->m_IncludeModels[ ni ], MAXSTUDIONAME );
  3144. Q_FixSlashes( g_includemodel[ g_numincludemodels ].name, '/' );
  3145. ++g_numincludemodels;
  3146. }
  3147. }
  3148. // return true if this QAngle is (0,0,0) within tolerance
  3149. static bool IsZero( const QAngle &qa, float tolerance = 0.01f )
  3150. {
  3151. return (qa.x > -tolerance && qa.x < tolerance &&
  3152. qa.y > -tolerance && qa.y < tolerance &&
  3153. qa.z > -tolerance && qa.z < tolerance);
  3154. }
  3155. //-----------------------------------------------------------------------------
  3156. // Split the specified string into substrings separated by "_"'s and then
  3157. // sort the strings alphabetically
  3158. //-----------------------------------------------------------------------------
  3159. static void UnderscoreSplitAndSortStrings( const char *pszString, CUtlVector< CUtlString > &splitAndSortedString )
  3160. {
  3161. splitAndSortedString.RemoveAll();
  3162. const int nStrLen = Q_strlen( pszString );
  3163. if ( nStrLen <= 0 )
  3164. return;
  3165. char *pszTmpString = reinterpret_cast< char * >( stackalloc( ( nStrLen + 1 ) * sizeof( char ) ) );
  3166. if ( !pszTmpString )
  3167. return;
  3168. Q_memset( pszTmpString, 0, ( nStrLen + 1 ) * sizeof( char ) );
  3169. Q_strncpy( pszTmpString, pszString, nStrLen + 1 );
  3170. char *pszEnd = NULL;
  3171. for ( char *pszName = pszTmpString; pszName && *pszName; pszName = pszEnd )
  3172. {
  3173. pszEnd = strchr( pszName, '_' );
  3174. if ( !pszEnd )
  3175. {
  3176. splitAndSortedString.AddToTail( CUtlString( pszName ) );
  3177. }
  3178. else
  3179. {
  3180. *pszEnd = '\0';
  3181. ++pszEnd;
  3182. splitAndSortedString.AddToTail( CUtlString( pszName ) );
  3183. }
  3184. }
  3185. // Insertion sort
  3186. for ( int i = 1; i < splitAndSortedString.Count(); ++i )
  3187. {
  3188. const CUtlString sValue = splitAndSortedString[i];
  3189. int j = i - 1;
  3190. while ( j >= 0 && Q_stricmp( splitAndSortedString[j].Get(), sValue.Get() ) > 0 )
  3191. {
  3192. splitAndSortedString[ j + 1 ] = splitAndSortedString[ j ];
  3193. --j;
  3194. }
  3195. splitAndSortedString[j + 1] = sValue;
  3196. }
  3197. }
  3198. //-----------------------------------------------------------------------------
  3199. //
  3200. //-----------------------------------------------------------------------------
  3201. static bool GetContentsDescription( int &nContentsDescription, CDmElement *pDmElement )
  3202. {
  3203. nContentsDescription = CONTENTS_SOLID;
  3204. if ( !pDmElement )
  3205. return false;
  3206. CDmAttribute *pDmeContentsDescriptionAttr = pDmElement->GetAttribute( "contentsDescription" );
  3207. if ( !pDmeContentsDescriptionAttr )
  3208. return false;
  3209. if ( pDmeContentsDescriptionAttr->GetType() != AT_STRING )
  3210. return false;
  3211. const char *pszContentsDesc = pDmeContentsDescriptionAttr->GetValueString();
  3212. if ( !pszContentsDesc || Q_strlen( pszContentsDesc ) <= 0 )
  3213. return false;
  3214. struct ContentDesc_t
  3215. {
  3216. const char *m_pszName;
  3217. int m_nContentDescriptionFlags;
  3218. };
  3219. ContentDesc_t contentDescs[] = {
  3220. { "notsolid", CONTENTS_EMPTY },
  3221. { "monster", CONTENTS_MONSTER },
  3222. { "ladder", CONTENTS_LADDER },
  3223. { "solid", CONTENTS_SOLID },
  3224. { "solid_monster", CONTENTS_SOLID | CONTENTS_MONSTER },
  3225. { "solid_ladder", CONTENTS_SOLID | CONTENTS_LADDER },
  3226. { "solid_monster_ladder", CONTENTS_SOLID | CONTENTS_MONSTER | CONTENTS_LADDER },
  3227. { "grate", CONTENTS_GRATE },
  3228. { "grate_monster", CONTENTS_GRATE | CONTENTS_MONSTER },
  3229. { "grate_ladder", CONTENTS_GRATE | CONTENTS_LADDER },
  3230. { "grate_monster_ladder", CONTENTS_GRATE | CONTENTS_MONSTER | CONTENTS_LADDER },
  3231. };
  3232. CUtlVector< CUtlString > userContentsDesc;
  3233. UnderscoreSplitAndSortStrings( pszContentsDesc, userContentsDesc );
  3234. CUtlVector< CUtlString > validContentsDesc;
  3235. for ( int i = 0; i < ARRAYSIZE( contentDescs ); ++i )
  3236. {
  3237. UnderscoreSplitAndSortStrings( contentDescs[i].m_pszName, validContentsDesc );
  3238. if ( userContentsDesc.Count() != validContentsDesc.Count() )
  3239. continue;
  3240. bool bFound = true;
  3241. for ( int j = 0; j < userContentsDesc.Count(); ++j )
  3242. {
  3243. if ( Q_stricmp( userContentsDesc[j].Get(), validContentsDesc[j].Get() ) )
  3244. {
  3245. bFound = false;
  3246. break;
  3247. }
  3248. }
  3249. if ( bFound )
  3250. {
  3251. nContentsDescription = contentDescs[i].m_nContentDescriptionFlags;
  3252. return true;
  3253. }
  3254. }
  3255. MdlWarning( "2100: Invalid \"contentsDescription\" \"%s\" on \"%s\"\n",
  3256. pszContentsDesc, pDmElement->GetName() );
  3257. static bool bWarned = false;
  3258. if ( !bWarned )
  3259. {
  3260. bWarned = true;
  3261. CUtlString sWarn;
  3262. const int nContentDescsCount = ARRAYSIZE( contentDescs );
  3263. if ( nContentDescsCount > 0 )
  3264. {
  3265. sWarn = contentDescs[0].m_pszName;
  3266. for ( int i = 1; i < nContentDescsCount; ++i )
  3267. {
  3268. sWarn += ", ";
  3269. sWarn += contentDescs[i].m_pszName;
  3270. }
  3271. }
  3272. MdlWarning( " Valid ones are: %s\n", sWarn.Get() );
  3273. }
  3274. return false;
  3275. }
  3276. //-----------------------------------------------------------------------------
  3277. //
  3278. //-----------------------------------------------------------------------------
  3279. static void LoadDefineBoneList( CDmeDefineBoneList *pDmeDefineBoneList )
  3280. {
  3281. if ( !pDmeDefineBoneList )
  3282. return;
  3283. CDmeDefineBone *pDmeDefineBone = NULL;
  3284. s_importbone_t *pImportBone = NULL;
  3285. const int nDefineBoneCount = pDmeDefineBoneList->m_DefineBones.Count();
  3286. for ( int ni = 0; ni < nDefineBoneCount; ++ni )
  3287. {
  3288. pDmeDefineBone = pDmeDefineBoneList->m_DefineBones[ ni ];
  3289. if ( !pDmeDefineBone )
  3290. continue;
  3291. if ( g_numimportbones >= ARRAYSIZE( g_importbone ) )
  3292. {
  3293. MdlError( "Too Many Define Bones while processing: \"%s\", Max: %d\n", pDmeDefineBone->GetName(), ARRAYSIZE( g_importbone ) );
  3294. break;
  3295. }
  3296. pImportBone = &g_importbone[ g_numimportbones++ ];
  3297. Q_strncpy( pImportBone->name, pDmeDefineBone->GetName(), MAXSTUDIONAME );
  3298. Q_strncpy( pImportBone->parent, pDmeDefineBone->m_Parent.Get(), MAXSTUDIONAME );
  3299. AngleMatrix( pDmeDefineBone->m_Rotation.Get(), pDmeDefineBone->m_Translation.Get(), pImportBone->rawLocal );
  3300. const Vector &rt = pDmeDefineBone->m_RealignTranslation.Get();
  3301. const QAngle &rr = pDmeDefineBone->m_RealignRotation.Get();
  3302. if ( !rt.IsZero() || !IsZero( rr ) )
  3303. {
  3304. pImportBone->bPreAligned = true;
  3305. AngleMatrix( pDmeDefineBone->m_RealignRotation.Get(), pDmeDefineBone->m_RealignTranslation.Get(), pImportBone->srcRealign );
  3306. }
  3307. else
  3308. {
  3309. pImportBone->bPreAligned = false;
  3310. SetIdentityMatrix( pImportBone->srcRealign );
  3311. }
  3312. int nContentsDescription = CONTENTS_SOLID;
  3313. if ( GetContentsDescription( nContentsDescription, pDmeDefineBone ) )
  3314. {
  3315. ContentsName_t *pContentsName = NULL;
  3316. for ( int j = 0; j < s_JointContents.Count(); ++j )
  3317. {
  3318. if ( !Q_stricmp( s_JointContents[j].m_pJointName, pDmeDefineBone->GetName() ) )
  3319. {
  3320. pContentsName = &s_JointContents[j];
  3321. break;
  3322. }
  3323. }
  3324. if ( !pContentsName )
  3325. {
  3326. pContentsName = &s_JointContents[ s_JointContents.AddToTail() ];
  3327. Q_strncpy( pContentsName->m_pJointName, pDmeDefineBone->GetName(), ARRAYSIZE( pContentsName->m_pJointName ) );
  3328. }
  3329. pContentsName->m_nContents = nContentsDescription;
  3330. }
  3331. }
  3332. }
  3333. //-----------------------------------------------------------------------------
  3334. //
  3335. //-----------------------------------------------------------------------------
  3336. static void LoadKeyValues( const char *pszKeyValues )
  3337. {
  3338. if ( !pszKeyValues )
  3339. return;
  3340. const int nKeyValueCount = Q_strlen( pszKeyValues );
  3341. if ( nKeyValueCount <= 0 )
  3342. return;
  3343. const char *pszHeader = "mdlkeyvalue\n{\n";
  3344. const char *pszFooter = "}\n";
  3345. g_KeyValueText.AddMultipleToTail( Q_strlen( pszHeader ), pszHeader );
  3346. g_KeyValueText.AddMultipleToTail( nKeyValueCount, pszKeyValues );
  3347. g_KeyValueText.AddMultipleToTail( Q_strlen( pszFooter ), pszFooter );
  3348. }
  3349. //-----------------------------------------------------------------------------
  3350. //
  3351. //-----------------------------------------------------------------------------
  3352. static void LoadGlobalFlags( CDmElement *pDmeRoot )
  3353. {
  3354. // Get default rotation as a matrix
  3355. matrix3x4_t mDefRot;
  3356. AngleMatrix( g_defaultrotation, mDefRot );
  3357. // QC $bbox
  3358. CDmeBBox *pDmeBBox = pDmeRoot->GetValueElement< CDmeBBox >( "bbox" );
  3359. if ( pDmeBBox )
  3360. {
  3361. ITransformAABB( mDefRot, pDmeBBox->m_vMinBounds, pDmeBBox->m_vMaxBounds, bbox[0], bbox[1] );
  3362. }
  3363. if ( pDmeRoot->HasAttribute( "opacity" ) )
  3364. {
  3365. switch ( pDmeRoot->GetValue< int >( "opacity" ) )
  3366. {
  3367. case 0: // Auto, do nothing
  3368. gflags &= ~STUDIOHDR_FLAGS_FORCE_OPAQUE;
  3369. gflags &= ~STUDIOHDR_FLAGS_TRANSLUCENT_TWOPASS;
  3370. break;
  3371. case 1: // opaque
  3372. // Opaque has precedence over Mostly Opaque (TRANSLUCENT_TWOPASS)
  3373. gflags |= STUDIOHDR_FLAGS_FORCE_OPAQUE;
  3374. gflags &= ~STUDIOHDR_FLAGS_TRANSLUCENT_TWOPASS;
  3375. break;
  3376. case 2: // mostly opaque
  3377. // Opaque has precedence over Mostly Opaque (TRANSLUCENT_TWOPASS)
  3378. if ( ( gflags & STUDIOHDR_FLAGS_FORCE_OPAQUE) == 0)
  3379. {
  3380. gflags |= STUDIOHDR_FLAGS_TRANSLUCENT_TWOPASS;
  3381. }
  3382. break;
  3383. }
  3384. }
  3385. if ( pDmeRoot->HasAttribute( "illuminationPosition", AT_VECTOR3 ) )
  3386. {
  3387. VectorIRotate( pDmeRoot->GetValue< Vector >( "illuminationPosition"), mDefRot, illumposition );
  3388. }
  3389. if ( pDmeRoot->GetValue< bool >( "ambientBoost", false ) )
  3390. {
  3391. gflags |= STUDIOHDR_FLAGS_AMBIENT_BOOST;
  3392. }
  3393. if ( pDmeRoot->GetValue< bool >( "subdivisionSurface", false ) )
  3394. {
  3395. gflags |= STUDIOHDR_FLAGS_SUBDIVISION_SURFACE;
  3396. }
  3397. if ( pDmeRoot->GetValue< bool >( "doNotCastShadows", false ) )
  3398. {
  3399. gflags |= STUDIOHDR_FLAGS_DO_NOT_CAST_SHADOWS;
  3400. }
  3401. if ( pDmeRoot->GetValue< bool >( "castTextureShadows", false ) )
  3402. {
  3403. gflags |= STUDIOHDR_FLAGS_DO_NOT_CAST_SHADOWS;
  3404. }
  3405. if ( pDmeRoot->GetValue< bool >( "noForcedFade", false ) )
  3406. {
  3407. gflags |= STUDIOHDR_FLAGS_NO_FORCED_FADE;
  3408. }
  3409. int nContentsDescription = CONTENTS_SOLID;
  3410. if ( GetContentsDescription( nContentsDescription, pDmeRoot ) )
  3411. {
  3412. s_nDefaultContents = nContentsDescription;
  3413. }
  3414. }
  3415. //-----------------------------------------------------------------------------
  3416. //
  3417. //-----------------------------------------------------------------------------
  3418. static void LoadEyeballGlobals( CDmeEyeballGlobals *pDmeEyeballGlobals )
  3419. {
  3420. if ( !pDmeEyeballGlobals )
  3421. return;
  3422. g_flMaxEyeDeflection = cosf( DEG2RAD( pDmeEyeballGlobals->m_flMaxEyeDeflection.Get() ) );
  3423. matrix3x4_t mDefRot;
  3424. AngleMatrix( g_defaultrotation, mDefRot );
  3425. VectorIRotate( pDmeEyeballGlobals->m_vEyePosition.Get(), mDefRot, eyeposition );
  3426. }
  3427. //-----------------------------------------------------------------------------
  3428. //
  3429. //-----------------------------------------------------------------------------
  3430. static void LoadMaterialGroups( const CDmeMaterialGroupList *pDmeMaterialGroupList )
  3431. {
  3432. if ( !pDmeMaterialGroupList )
  3433. return;
  3434. if ( g_numskinref == 0 )
  3435. g_numskinref = g_numtextures;
  3436. // Studiomdl will read in multiple $texturegroup calls but only the first one
  3437. // is ever used, so in mdlcompile, there will only ever be one
  3438. Assert( g_numtexturegroups == 0 );
  3439. CDmeMaterialGroup *pDmeMaterialGroup = NULL;
  3440. const int nMaterialGroupCount = pDmeMaterialGroupList->m_MaterialGroups.Count();
  3441. if ( nMaterialGroupCount >= ARRAYSIZE( g_texturegroup[ 0 ] ) )
  3442. {
  3443. MdlError( "Too Many Material Groups, Max: %d\n", ARRAYSIZE( g_texturegroup[ 0 ] ) );
  3444. return;
  3445. }
  3446. const int nTextureCount = g_numtextures;
  3447. for ( int nGroupIndex = 0; nGroupIndex < nMaterialGroupCount; ++nGroupIndex )
  3448. {
  3449. pDmeMaterialGroup = pDmeMaterialGroupList->m_MaterialGroups[ nGroupIndex ];
  3450. if ( !pDmeMaterialGroup )
  3451. continue;
  3452. const int nMaterialCount = pDmeMaterialGroup->m_MaterialList.Count();
  3453. if ( nGroupIndex > 0 && nMaterialCount < nTextureCount )
  3454. {
  3455. MdlWarning( "Only Setting %d of %d Textures via MaterialGroup %d, Skin %d will have bad materials\n",
  3456. nMaterialCount, nTextureCount, nGroupIndex, nGroupIndex );
  3457. }
  3458. for ( int nMaterialIndex = 0; nMaterialIndex < nMaterialCount; ++nMaterialIndex )
  3459. {
  3460. const int nMdlMaterialIndex = UseTextureAsMaterial( LookupTexture( pDmeMaterialGroup->m_MaterialList[ nMaterialIndex ], true ) );
  3461. g_texturegroup[ g_numtexturegroups ][ nGroupIndex ][ nMaterialIndex ] = nMdlMaterialIndex;
  3462. if ( nGroupIndex != 0 )
  3463. {
  3464. g_texture[ nMdlMaterialIndex ].parent = g_texturegroup[ g_numtexturegroups ][ 0 ][ nMaterialIndex ];
  3465. }
  3466. g_numtexturelayers[ g_numtexturegroups ] = nGroupIndex + 1;
  3467. g_numtexturereps[ g_numtexturegroups ] = nMaterialIndex + 1;
  3468. }
  3469. }
  3470. ++g_numtexturegroups;
  3471. }
  3472. //-----------------------------------------------------------------------------
  3473. //
  3474. //-----------------------------------------------------------------------------
  3475. static s_hitboxset *AllocateHitboxSet()
  3476. {
  3477. s_hitboxset *pHitboxSet = &g_hitboxsets[ g_hitboxsets.AddToTail() ];
  3478. memset( pHitboxSet, 0, sizeof( s_hitboxset ) );
  3479. return pHitboxSet;
  3480. }
  3481. //-----------------------------------------------------------------------------
  3482. //
  3483. //-----------------------------------------------------------------------------
  3484. static s_bbox_t *AllocateHitbox( s_hitboxset *pHitboxSet )
  3485. {
  3486. if ( pHitboxSet->numhitboxes < ARRAYSIZE( pHitboxSet->hitbox ) )
  3487. return &pHitboxSet->hitbox[ pHitboxSet->numhitboxes++ ];
  3488. MdlWarning( "Too many hitboxes request for hitbox set \"%s\", max %d\n", pHitboxSet->hitboxsetname, ARRAYSIZE( pHitboxSet->hitbox ) );
  3489. return NULL;
  3490. }
  3491. //-----------------------------------------------------------------------------
  3492. //
  3493. //-----------------------------------------------------------------------------
  3494. static void LoadHitboxSetList( const CDmeHitboxSetList *pDmeHitboxSetList )
  3495. {
  3496. if ( !pDmeHitboxSetList )
  3497. return;
  3498. const int nHitboxSetCount = pDmeHitboxSetList->m_HitboxSetList.Count();
  3499. for ( int nHitBoxSetIndex = 0; nHitBoxSetIndex < nHitboxSetCount; ++nHitBoxSetIndex )
  3500. {
  3501. CDmeHitboxSet *pSrcHitboxSet = pDmeHitboxSetList->m_HitboxSetList[ nHitBoxSetIndex ];
  3502. // Add a new hitboxset
  3503. s_hitboxset *pHitboxSet = AllocateHitboxSet();
  3504. Q_strncpy( pHitboxSet->hitboxsetname, pSrcHitboxSet->GetName(), sizeof(pHitboxSet->hitboxsetname) );
  3505. int nHitboxCount = pSrcHitboxSet->m_HitboxList.Count();
  3506. for ( int nHitboxIndex = 0; nHitboxIndex < nHitboxCount; ++nHitboxIndex )
  3507. {
  3508. CDmeHitbox *pSrcHitbox = pSrcHitboxSet->m_HitboxList[ nHitboxIndex ];
  3509. // Find bone
  3510. s_bonetable_t *pStudioBone = NULL;
  3511. const int nBoneIndex = findGlobalBone( pSrcHitbox->m_sBoneName );
  3512. if ( nBoneIndex >= 0 && nBoneIndex < g_numbones )
  3513. {
  3514. pStudioBone = &g_bonetable[ nBoneIndex ];
  3515. }
  3516. // Find bone
  3517. for ( int nBoneIndex = 0; nBoneIndex < g_numbones; ++nBoneIndex )
  3518. {
  3519. }
  3520. s_bbox_t *pHitbox = AllocateHitbox( pHitboxSet );
  3521. Q_strncpy( pHitbox->name, pSrcHitbox->m_sBoneName, sizeof( pHitbox->name ) );
  3522. Q_strncpy( pHitbox->hitboxname, pSrcHitbox->GetName(), sizeof( pHitbox->hitboxname ) );
  3523. pHitbox->group = pSrcHitbox->m_nGroupId;
  3524. pHitbox->bmin = pSrcHitbox->m_vMinBounds;
  3525. pHitbox->bmax = pSrcHitbox->m_vMaxBounds;
  3526. if ( !pSrcHitbox->m_sSurfaceProperty.IsEmpty() )
  3527. {
  3528. const char *pSurfaceProp = FindSurfaceProp( pHitbox->name );
  3529. if ( pSurfaceProp && Q_stricmp( pSurfaceProp, pSrcHitbox->m_sSurfaceProperty ) )
  3530. {
  3531. MdlWarning( "Hitbox surface property \"%s\" for bone \"%s\" conflicts with existing \"%s\"",
  3532. pSrcHitbox->m_sSurfaceProperty.Get(), pSrcHitbox->m_sBoneName.Get(), pSurfaceProp );
  3533. }
  3534. else
  3535. {
  3536. AddSurfaceProp( pHitbox->name, pSrcHitbox->m_sSurfaceProperty );
  3537. }
  3538. }
  3539. }
  3540. }
  3541. }
  3542. //-----------------------------------------------------------------------------
  3543. // Purpose: Handle the root.boneFlexDriverList
  3544. //-----------------------------------------------------------------------------
  3545. static void LoadBoneFlexDriverList( const CDmeBoneFlexDriverList *pDmeBoneFlexDriverList )
  3546. {
  3547. if ( !pDmeBoneFlexDriverList )
  3548. return;
  3549. const CDmeBoneFlexDriverList *pDmeTmp = GetElement< CDmeBoneFlexDriverList >( g_hDmeBoneFlexDriverList );
  3550. if ( pDmeTmp != NULL )
  3551. {
  3552. char szTmpBuf0[40];
  3553. UniqueIdToString( pDmeTmp->GetId(), szTmpBuf0, sizeof( szTmpBuf0 ) );
  3554. char szTmpBuf1[40];
  3555. UniqueIdToString( pDmeBoneFlexDriverList->GetId(), szTmpBuf1, sizeof( szTmpBuf1 ) );
  3556. MdlError( "DmeBoneFlexDriverList already defined (%s:%s), ignoring (%s:%s)\n",
  3557. pDmeTmp->GetName(), szTmpBuf0,
  3558. pDmeBoneFlexDriverList->GetName(), szTmpBuf1 );
  3559. return;
  3560. }
  3561. CDmeBoneFlexDriverList *pDmeCopy = pDmeBoneFlexDriverList->Copy();
  3562. pDmeCopy->SetFileId( DMFILEID_INVALID, TD_DEEP );
  3563. g_hDmeBoneFlexDriverList = pDmeCopy->GetHandle();
  3564. }
  3565. //-----------------------------------------------------------------------------
  3566. //
  3567. //-----------------------------------------------------------------------------
  3568. static void LoadBoneMergeList( CDmAttribute *pDmeBoneMergeListAttr )
  3569. {
  3570. if ( !pDmeBoneMergeListAttr )
  3571. return;
  3572. CDmrStringArrayConst boneMergeList( pDmeBoneMergeListAttr );
  3573. if ( !boneMergeList.IsValid() )
  3574. return;
  3575. const int nBoneMergeCount = boneMergeList.Count();
  3576. for ( int nBoneMergeIndex = 0; nBoneMergeIndex < nBoneMergeCount; ++nBoneMergeIndex )
  3577. {
  3578. strcpyn( g_BoneMerge[ g_BoneMerge.AddToTail() ].bonename, boneMergeList[ nBoneMergeIndex ] );
  3579. }
  3580. }
  3581. //-----------------------------------------------------------------------------
  3582. // Loads LODs from the preprocessed file
  3583. //-----------------------------------------------------------------------------
  3584. static int LodDistanceCompare( const void *elem1, const void *elem2 )
  3585. {
  3586. const CDmeLOD *l1 = *(const CDmeLOD **)elem1;
  3587. const CDmeLOD *l2 = *(const CDmeLOD **)elem2;
  3588. if ( l1->m_bIsShadowLOD != l2->m_bIsShadowLOD )
  3589. return l1->m_bIsShadowLOD ? 1 : -1;
  3590. if ( l1->m_flSwitchMetric > l2->m_flSwitchMetric )
  3591. return 1;
  3592. return ( l1->m_flSwitchMetric == l2->m_flSwitchMetric ) ? 0 : -1;
  3593. }
  3594. //-----------------------------------------------------------------------------
  3595. //
  3596. //-----------------------------------------------------------------------------
  3597. static bool LoadLODs( s_source_t** ppRootLODSource, CDmeLODList *pLodList, bool &bSetUpAxis, bool bStaticProp )
  3598. {
  3599. // NOTE: This is a little bit of a hack; it generates new s_source_ts
  3600. // based on the LOD data, which is somewhat contrary to the existing
  3601. // architecture, but is the easiest method of achieving the goal
  3602. // of loading LODs from the mpp file without reloading the giant mpp
  3603. // file over and over again.
  3604. *ppRootLODSource = NULL;
  3605. int nCount = pLodList->m_LODs.Count();
  3606. if ( nCount == 0 )
  3607. return true;
  3608. // Sort LODs by switch distance
  3609. CDmeLOD **ppLODs = (CDmeLOD**)stackalloc( nCount * sizeof(CDmeLOD*) );
  3610. for ( int i = 0; i < nCount; ++i )
  3611. {
  3612. ppLODs[i] = pLodList->m_LODs[i];
  3613. }
  3614. qsort( ppLODs, nCount, sizeof( CDmeLOD* ), LodDistanceCompare );
  3615. CDmeLOD *pRootLOD = pLodList->GetRootLOD();
  3616. if ( pRootLOD && bSetUpAxis )
  3617. {
  3618. CDmeModel *pDmeModel = pRootLOD->GetValueElement< CDmeModel >( "model" );
  3619. if ( pDmeModel )
  3620. {
  3621. const char *pUpAxis = pDmeModel->GetValueString( "upAxis" );
  3622. if ( pUpAxis )
  3623. {
  3624. if ( StringHasPrefix( pUpAxis, "Y" ) )
  3625. {
  3626. // rotate 90 degrees around x to move y into z
  3627. g_defaultrotation = RadianEuler( M_PI / 2.0f, 0.0f, M_PI / 2.0f );
  3628. }
  3629. }
  3630. bSetUpAxis = false;
  3631. }
  3632. }
  3633. char pSrcLODName[MAX_PATH];
  3634. Q_StripExtension( pRootLOD->GetName(), pSrcLODName, sizeof(pSrcLODName) );
  3635. for ( int i = 0; i < nCount; ++i )
  3636. {
  3637. CDmeLOD *pLOD = ppLODs[i];
  3638. bool bIsShadowLOD = pLOD->m_bIsShadowLOD;
  3639. if ( bIsShadowLOD )
  3640. {
  3641. if ( ( gflags & STUDIOHDR_FLAGS_HASSHADOWLOD ) != 0 )
  3642. {
  3643. MdlError( "Invalid LOD: \"%s\": Multiple Shadow LODs Defined\n", pLOD->GetName() );
  3644. return false;
  3645. }
  3646. gflags |= STUDIOHDR_FLAGS_HASSHADOWLOD;
  3647. }
  3648. else if ( pLOD->m_flSwitchMetric.Get() < 0.0f )
  3649. {
  3650. MdlError( "Invalid LOD: \"%s\": Negative switch value\n", pLOD->GetName() );
  3651. return false;
  3652. }
  3653. // Skip lower LODs if we're stripping them
  3654. bool bIsRootLOD = ( pLOD == pRootLOD );
  3655. if ( g_bStripLods && !bIsShadowLOD && ( !bIsRootLOD ) )
  3656. {
  3657. if ( !g_quiet )
  3658. {
  3659. Msg( "Stripped lod \"%s\" @ %.1f\n", pLOD->m_Model.GetElement() ? pLOD->m_Model->GetName() : "<none>", pLOD->m_flSwitchMetric );
  3660. }
  3661. continue;
  3662. }
  3663. // Now, fill her up! No model means LOD is valid, but has no geometry
  3664. const bool bHasModel = pLOD->m_Model.GetHandle() != DMELEMENT_HANDLE_INVALID;
  3665. const bool bHasSkeleton = pLOD->m_Skeleton.GetHandle() != DMELEMENT_HANDLE_INVALID;
  3666. // No model & no skeleton means LOD is invalid
  3667. if ( !bHasModel && !bHasSkeleton )
  3668. {
  3669. MdlError( "Invalid LOD: \"%s\": No Model or Skeleton defined\n", pLOD->GetName() );
  3670. return false;
  3671. }
  3672. if ( g_ScriptLODs.Count() == MAX_NUM_LODS )
  3673. {
  3674. MdlError( "Too many LODs (MAX_NUM_LODS==%d) while loading LOD: \"%s\"\n", static_cast< int >( MAX_NUM_LODS ), pLOD->GetName() );
  3675. return false;
  3676. }
  3677. // Check for overflow
  3678. if ( g_numsources >= MAXSTUDIOSEQUENCES )
  3679. {
  3680. MdlError( "Too many source models/animations (MAXSTUDIOSEQUENCES==%d) while loading LOD: \"%s\"\n", static_cast< int >( MAXSTUDIOSEQUENCES ), pLOD->GetName() );
  3681. return false;
  3682. }
  3683. s_source_t *pLODSource = AllocateDmxSource( pLOD->m_Path.Get() );
  3684. if ( !pLODSource )
  3685. {
  3686. MdlError( "Couldn't allocate new source while loading LOD: \"%s\"\n", pLOD->GetName() );
  3687. return false;
  3688. }
  3689. if ( bIsRootLOD )
  3690. {
  3691. *ppRootLODSource = pLODSource;
  3692. pLODSource->isActiveModel = true;
  3693. }
  3694. if ( bHasModel )
  3695. {
  3696. BoneTransformMap_t boneMap;
  3697. if ( !LoadModelAndSkeleton( pLODSource, boneMap, pLOD->m_Skeleton, pLOD->m_Model, pLOD->m_CombinationOperator, bStaticProp ) )
  3698. {
  3699. MdlError( "Couldn't load skeleton and model while loading LOD: \"%s\"\n", pLOD->GetName() );
  3700. return false;
  3701. }
  3702. LoadQcModelElements( pLODSource, g_pCurrentModel, pLOD->m_Model );
  3703. }
  3704. if ( bIsRootLOD )
  3705. continue;
  3706. // Create LOD information in terms of how the old system does it
  3707. // Shadow lod reserves -1 as switch value which uniquely identifies a shadow lod
  3708. int j = g_ScriptLODs.AddToTail();
  3709. LodScriptData_t& lod = g_ScriptLODs[j];
  3710. lod.switchValue = bIsShadowLOD ? -1.0f : pLOD->m_flSwitchMetric;
  3711. lod.EnableFacialAnimation( bIsShadowLOD ? false : !pLOD->m_bNoFlex );
  3712. lod.StripFromModel( false );
  3713. // We only support simple model replacement here. Other processing
  3714. // is expected to have occurred in the preprocessing phase
  3715. j = lod.modelReplacements.AddToTail();
  3716. CLodScriptReplacement_t& replacement = lod.modelReplacements[j];
  3717. replacement.SetSrcName( pSrcLODName );
  3718. replacement.SetDstName( pLODSource->filename );
  3719. replacement.m_pSource = pLODSource;
  3720. }
  3721. return true;
  3722. }
  3723. //-----------------------------------------------------------------------------
  3724. //
  3725. //-----------------------------------------------------------------------------
  3726. extern int Option_Blank();
  3727. //-----------------------------------------------------------------------------
  3728. // Loads Eyeballs
  3729. //-----------------------------------------------------------------------------
  3730. static void LoadEyeballs( s_model_t *ps_model_t, CDmeLODList *pDmeLODList )
  3731. {
  3732. if ( !pDmeLODList )
  3733. return;
  3734. matrix3x4_t mDefRot;
  3735. AngleMatrix( g_defaultrotation, mDefRot );
  3736. Vector vTmp;
  3737. const int nEyeballCount = pDmeLODList->m_EyeballList.Count();
  3738. if ( nEyeballCount <= 0 )
  3739. return;
  3740. for ( int nEyeballIndex = 0; nEyeballIndex < nEyeballCount; ++nEyeballIndex )
  3741. {
  3742. CDmeEyeball *pDmeEyeball = pDmeLODList->m_EyeballList.Get( nEyeballIndex );
  3743. if ( !pDmeEyeball )
  3744. continue;
  3745. if ( ps_model_t->numeyeballs >= ARRAYSIZE( ps_model_t->eyeball ) )
  3746. {
  3747. MdlWarning( "1100: Max number of eyeballs reached for model %s, ignoring eyeball %s\n", ps_model_t->name, pDmeEyeball->GetName() );
  3748. continue;
  3749. }
  3750. int nFoundBoneIndex = -1;
  3751. for ( int nSearchBoneIndex = 0; nSearchBoneIndex < ps_model_t->source->numbones; ++nSearchBoneIndex )
  3752. {
  3753. if ( !Q_stricmp( ps_model_t->source->localBone[ nSearchBoneIndex ].name, pDmeEyeball->m_sParentBoneName.Get() ) )
  3754. {
  3755. nFoundBoneIndex = nSearchBoneIndex;
  3756. break;
  3757. }
  3758. }
  3759. if ( nFoundBoneIndex < 0 )
  3760. {
  3761. MdlWarning( "1101: Couldn't find bone %s on model %s, ignoring eyeball %s\n", pDmeEyeball->m_sParentBoneName.Get(), ps_model_t->name, pDmeEyeball->GetName() );
  3762. continue;
  3763. }
  3764. const char *pszMaterialName = pDmeEyeball->m_sMaterialName.Get();
  3765. const bool bRelative = ( strchr( pszMaterialName, '/' ) || strchr( pszMaterialName, '\\' ) ) ? true : false;
  3766. const int nSearchMeshMatIndex = UseTextureAsMaterial( LookupTexture( pDmeEyeball->m_sMaterialName.Get(), bRelative ) );
  3767. int nFoundMeshMatIndex = -1;
  3768. for ( int i = 0; i < ps_model_t->source->nummeshes; ++i )
  3769. {
  3770. const int nTmpMeshMatIndex = ps_model_t->source->meshindex[ i ]; // meshes are internally stored by material index
  3771. if ( nTmpMeshMatIndex == nSearchMeshMatIndex )
  3772. {
  3773. nFoundMeshMatIndex = i;
  3774. break;
  3775. }
  3776. }
  3777. if ( nFoundMeshMatIndex < 0 )
  3778. {
  3779. MdlWarning( "1102: Couldn't find eyeball material %s on model %s, ignoring eyeball %s\n", pDmeEyeball->m_sMaterialName.Get(), ps_model_t->name, pDmeEyeball->GetName() );
  3780. continue;
  3781. }
  3782. s_eyeball_t *ps_eyeball_t = &( ps_model_t->eyeball[ ps_model_t->numeyeballs++ ] );
  3783. Q_strncpy( ps_eyeball_t->name, pDmeEyeball->GetName(), sizeof( ps_eyeball_t->name ) );
  3784. ps_eyeball_t->bone = nFoundBoneIndex;
  3785. ps_eyeball_t->mesh = nFoundMeshMatIndex;
  3786. ps_eyeball_t->radius = pDmeEyeball->m_flRadius.Get();
  3787. ps_eyeball_t->zoffset = tan( DEG2RAD( pDmeEyeball->m_flYawAngle.Get() ) );
  3788. ps_eyeball_t->iris_scale = 1.0f / pDmeEyeball->m_flIrisScale;
  3789. // translate eyeball into bone space
  3790. VectorITransform( pDmeEyeball->m_vPosition.Get(), ps_model_t->source->boneToPose[ ps_eyeball_t->bone ], ps_eyeball_t->org );
  3791. VectorIRotate( Vector( 0, 0, 1 ), mDefRot, vTmp );
  3792. VectorIRotate( vTmp, ps_model_t->source->boneToPose[ ps_eyeball_t->bone ], ps_eyeball_t->up );
  3793. VectorIRotate( Vector( 1, 0, 0 ), mDefRot, vTmp );
  3794. VectorIRotate( vTmp, ps_model_t->source->boneToPose[ ps_eyeball_t->bone ], ps_eyeball_t->forward );
  3795. // Not applicable
  3796. ps_eyeball_t->upperlidflexdesc = -1;
  3797. ps_eyeball_t->lowerlidflexdesc = -1;
  3798. }
  3799. // Make the standard flex controllers for eyes if required
  3800. static const char *szEyesFlexControllers[] = {
  3801. "eyes_updown",
  3802. "eyes_rightleft"
  3803. };
  3804. for ( int nNewFlexIndex = 0; nNewFlexIndex < ARRAYSIZE( szEyesFlexControllers ); ++nNewFlexIndex )
  3805. {
  3806. bool bHasEyeFlexController = false;
  3807. for ( int nFlexIndex = 0; nFlexIndex < g_numflexcontrollers; ++nFlexIndex )
  3808. {
  3809. if ( !Q_strcmp( szEyesFlexControllers[ nNewFlexIndex ], g_flexcontroller[ nFlexIndex ].name ) )
  3810. {
  3811. bHasEyeFlexController = true;
  3812. break;
  3813. }
  3814. }
  3815. // The flex controller range for eyes_updown & eyes_rightleft is default [-45, 45] because it's clamped by eyesMaxDeflection
  3816. // and changing it based on max deflection would cause animatin changes since flex controller values are normalized [0, 1]
  3817. // [-45, 45 ] gives a maxium range that's useful
  3818. if ( !bHasEyeFlexController )
  3819. {
  3820. if ( g_numflexcontrollers >= MAXSTUDIOFLEXCTRL )
  3821. {
  3822. MdlWarning( "1103: Couldn't make eyes flexcontroller %s, too many flex controllers defined\n", szEyesFlexControllers[ nNewFlexIndex ] );
  3823. continue;
  3824. }
  3825. Q_strncpy( g_flexcontroller[g_numflexcontrollers].name, szEyesFlexControllers[ nNewFlexIndex ], sizeof( g_flexcontroller[ g_numflexcontrollers ].name ) );
  3826. Q_strncpy( g_flexcontroller[g_numflexcontrollers].type, "eyes", sizeof( g_flexcontroller[ g_numflexcontrollers ].name ) );
  3827. g_flexcontroller[g_numflexcontrollers].min = -45.0f;
  3828. g_flexcontroller[g_numflexcontrollers].max = 45.0f;
  3829. ++g_numflexcontrollers;
  3830. }
  3831. }
  3832. }
  3833. //-----------------------------------------------------------------------------
  3834. // Loads Body Group Lists from the preprocessed file
  3835. //-----------------------------------------------------------------------------
  3836. static bool LoadBodyGroupList( s_source_t **ppMainSource, CDmeBodyGroupList *pBodyGroupList, CDmeEyeballGlobals *pDmeEyeballGlobals, bool bStaticProp, bool &bSetUpAxis )
  3837. {
  3838. *ppMainSource = NULL;
  3839. CDmaElementArray< CDmeBodyGroup > &dmeBodyGroups = pBodyGroupList->m_BodyGroups;
  3840. const int nDmeBodyGroupCount = dmeBodyGroups.Count();
  3841. if ( nDmeBodyGroupCount == 0 )
  3842. return true;
  3843. // Eyeball globals needs to be loaded after g_defaultrotation is set, which is after the first LOD is loaded
  3844. bool bLoadEyeballGlobals = true;
  3845. // Compute the 'main' body part
  3846. const CDmeLODList *pMainBodyPart = pBodyGroupList->GetMainBodyPart();
  3847. for ( int i = 0; i < nDmeBodyGroupCount; ++i )
  3848. {
  3849. const CDmeBodyGroup *pDmeBodyGroup = dmeBodyGroups[i];
  3850. s_bodypart_t *pBodyPart = &g_bodypart[ g_numbodyparts ];
  3851. pBodyPart->nummodels = 0;
  3852. if ( g_numbodyparts == 0 )
  3853. {
  3854. pBodyPart->base = 1;
  3855. }
  3856. else
  3857. {
  3858. pBodyPart->base = g_bodypart[g_numbodyparts-1].base * g_bodypart[g_numbodyparts-1].nummodels;
  3859. }
  3860. Q_strncpy( pBodyPart->name, pDmeBodyGroup->GetName(), sizeof( pBodyPart->name ) );
  3861. ++g_numbodyparts;
  3862. // Load all body parts for this body group
  3863. const int nDmeBodyPartCount = pDmeBodyGroup->m_BodyParts.Count();
  3864. for ( int j = 0; j < nDmeBodyPartCount; ++j )
  3865. {
  3866. s_model_t *pModel = (s_model_t *)calloc( 1, sizeof( s_model_t ) );
  3867. const int nModel = g_nummodels++;
  3868. g_model[nModel] = pModel;
  3869. pBodyPart->pmodel[ pBodyPart->nummodels++ ] = pModel;
  3870. pModel->scale = 1.0f;
  3871. CDmeBodyPart *pDmeBodyPart = pDmeBodyGroup->m_BodyParts[j];
  3872. CDmeLODList *pDmeLODList = CastElement< CDmeLODList >( pDmeBodyPart );
  3873. if ( pDmeBodyPart->LODCount() == 0 || !pDmeLODList )
  3874. {
  3875. pModel->source = AllocateDmxSource( "blank" );
  3876. Q_strncpy( pModel->name, "blank", sizeof(pModel->name) );
  3877. }
  3878. else
  3879. {
  3880. Q_strncpy( pModel->name, pDmeLODList->GetName(), sizeof(pModel->name) );
  3881. g_pCurrentModel = pModel;
  3882. if ( !LoadLODs( &pModel->source, pDmeLODList, bSetUpAxis, bStaticProp ) )
  3883. {
  3884. MdlError( "Bad LOD On BodyGroup \"%s\".bodyPartList[%d]\n", pDmeBodyGroup->GetName(), j );
  3885. return false;
  3886. }
  3887. g_pCurrentModel = NULL;
  3888. // This needs to be done after g_defaultRotation is set, which should be set after the first LOD is loaded
  3889. if ( bLoadEyeballGlobals )
  3890. {
  3891. bLoadEyeballGlobals = false;
  3892. LoadEyeballGlobals( pDmeEyeballGlobals );
  3893. }
  3894. LoadEyeballs( pModel, pDmeLODList );
  3895. if ( pModel->source )
  3896. {
  3897. Q_strncpy( pModel->filename, pModel->source->filename, sizeof(pModel->filename) );
  3898. }
  3899. PostProcessSource( pModel->source, nModel );
  3900. if ( pMainBodyPart == pDmeLODList )
  3901. {
  3902. *ppMainSource = pModel->source;
  3903. }
  3904. }
  3905. }
  3906. }
  3907. return true;
  3908. }
  3909. //-----------------------------------------------------------------------------
  3910. // Loads the collision model from the preprocessed file
  3911. //-----------------------------------------------------------------------------
  3912. bool LoadCollisionModel( CDmeCollisionModel *pCollisionInfo, bool bStaticProp )
  3913. {
  3914. if ( !pCollisionInfo )
  3915. return false;
  3916. // Check for overflow - TODO: Move to AllocateSource()
  3917. if ( g_numsources >= MAXSTUDIOSEQUENCES )
  3918. {
  3919. MdlError( "Load_Source - overflowed g_numsources loading LODs." );
  3920. return false;
  3921. }
  3922. s_source_t *pCollisionSource = AllocateDmxSource( pCollisionInfo->GetName() );
  3923. if ( !pCollisionSource )
  3924. return false;
  3925. int nummaterials = g_nummaterials;
  3926. int numtextures = g_numtextures;
  3927. // BoneRemap[bone index in file] == bone index in studiomdl
  3928. CDmeDag *pSkeleton = pCollisionInfo->GetValueElement< CDmeDag >( "skeleton" );
  3929. if ( !pSkeleton )
  3930. {
  3931. MdlError( "%s(%s): No \"skeleton\" defined\n", pCollisionInfo->GetTypeString(), pCollisionInfo->GetName() );
  3932. return false;
  3933. }
  3934. CDmeModel *pModel = pCollisionInfo->GetValueElement< CDmeModel >( "model" );
  3935. if ( !pModel )
  3936. {
  3937. MdlError( "%s(%s): No \"model\" defined\n", pCollisionInfo->GetTypeString(), pCollisionInfo->GetName() );
  3938. return false;
  3939. }
  3940. BoneTransformMap_t boneMap;
  3941. if ( !LoadModelAndSkeleton( pCollisionSource, boneMap, pSkeleton, pModel, NULL, bStaticProp ) )
  3942. {
  3943. MdlError( "%s(%s): Couldn't Load Skeleton: %s(%s) & Model: %s(%s)\n",
  3944. pCollisionInfo->GetTypeString(), pCollisionInfo->GetName(),
  3945. pSkeleton->GetTypeString(), pSkeleton->GetName(),
  3946. pModel->GetTypeString(), pModel->GetName() );
  3947. return false;
  3948. }
  3949. // auto-remove any new materials/textures
  3950. if ( nummaterials && numtextures && ( numtextures != g_numtextures || nummaterials != g_nummaterials ) )
  3951. {
  3952. g_numtextures = numtextures;
  3953. g_nummaterials = nummaterials;
  3954. pCollisionSource->texmap[0] = 0;
  3955. }
  3956. if ( DoCollisionModel( pCollisionSource, pCollisionInfo, bStaticProp ) == 0 )
  3957. return false;
  3958. const char *pSurfaceProperty = pCollisionInfo->GetValueString( "surfaceProperty" );
  3959. if ( pSurfaceProperty && pSurfaceProperty[0] )
  3960. {
  3961. SetDefaultSurfaceProp( pSurfaceProperty );
  3962. }
  3963. return true;
  3964. }
  3965. #endif // MDLCOMPILE
  3966. //-----------------------------------------------------------------------------
  3967. // Sets up the DMX if it was a static prop
  3968. //-----------------------------------------------------------------------------
  3969. static void SetupStaticProp( s_source_t *pSource )
  3970. {
  3971. #ifdef MDLCOMPILE
  3972. ProcessStaticProp();
  3973. s_sequence_t *pSeq = ProcessCmdSequence( "BindPose" );
  3974. s_animation_t *pAnim = ProcessImpliedAnimation( pSeq, pSource->filename );
  3975. pSeq->panim[0][0] = pAnim;
  3976. ProcessSequence( pSeq, 1, &pAnim, false );
  3977. #endif
  3978. }
  3979. //-----------------------------------------------------------------------------
  3980. // Main entry point for loading DMX files
  3981. //-----------------------------------------------------------------------------
  3982. int Load_DMX( s_source_t *pSource )
  3983. {
  3984. DmFileId_t fileId;
  3985. // use the full search tree, including mod hierarchy to find the file
  3986. char pFullPath[MAX_PATH];
  3987. if ( !GetGlobalFilePath( pSource->filename, pFullPath, sizeof(pFullPath) ) )
  3988. return 0;
  3989. // When reading, keep the CRLF; this will make ReadFile read it in binary format
  3990. // and also append a couple 0s to the end of the buffer.
  3991. CDmElement *pRoot;
  3992. if ( g_pDataModel->RestoreFromFile( pFullPath, NULL, NULL, &pRoot ) == DMFILEID_INVALID )
  3993. return 0;
  3994. if ( !g_quiet )
  3995. {
  3996. Msg( "DMX Model %s\n", pFullPath );
  3997. }
  3998. // Load model info
  3999. LoadModelInfo( pRoot, pFullPath );
  4000. // Load constraints
  4001. LoadConstraints( pRoot );
  4002. // Extract out the skeleton
  4003. // BoneRemap[bone index in file] == bone index in studiomdl
  4004. CDmeDag *pSkeleton = pRoot->GetValueElement< CDmeDag >( "skeleton" );
  4005. CDmeModel *pModel = pRoot->GetValueElement< CDmeModel >( "model" );
  4006. CDmeCombinationOperator *pCombinationOperator = pRoot->GetValueElement< CDmeCombinationOperator >( "combinationOperator" );
  4007. BoneTransformMap_t boneMap;
  4008. if ( !LoadModelAndSkeleton( pSource, boneMap, pSkeleton, pModel, pCombinationOperator, false ) )
  4009. goto dmxError;
  4010. LoadQcModelElements( pSource, g_pCurrentModel, pModel );
  4011. CDmeAnimationList *pAnimationList = pRoot->GetValueElement< CDmeAnimationList >( "animationList" );
  4012. if ( pAnimationList )
  4013. {
  4014. LoadAnimations( pSource, pAnimationList, g_currentscale, boneMap );
  4015. }
  4016. fileId = pRoot->GetFileId();
  4017. g_pDataModel->RemoveFileId( fileId );
  4018. return 1;
  4019. dmxError:
  4020. fileId = pRoot->GetFileId();
  4021. g_pDataModel->RemoveFileId( fileId );
  4022. return 0;
  4023. }
  4024. //-----------------------------------------------------------------------------
  4025. // Main entry point for loading FBX files
  4026. //-----------------------------------------------------------------------------
  4027. int Load_FBX( s_source_t *pSource )
  4028. {
  4029. // use the full search tree, including mod hierarchy to find the file
  4030. char pFullPath[ MAX_PATH ];
  4031. if ( !GetGlobalFilePath( pSource->filename, pFullPath, sizeof( pFullPath ) ) )
  4032. return 0;
  4033. CDmFbxSerializer dmFbxSerializer;
  4034. dmFbxSerializer.m_eOptUpAxis = CDmeAxisSystem::AS_AXIS_Y;
  4035. dmFbxSerializer.m_eOptForwardParity = CDmeAxisSystem::AS_PARITY_ODD;
  4036. CDmElement *pRoot = dmFbxSerializer.ReadFBX( pFullPath );
  4037. if ( !pRoot )
  4038. return 0;
  4039. if ( !g_quiet )
  4040. {
  4041. Msg( "FBX Model %s\n", pFullPath );
  4042. }
  4043. // Load model info
  4044. LoadModelInfo( pRoot, pFullPath );
  4045. // Load constraints
  4046. LoadConstraints( pRoot );
  4047. // Extract out the skeleton
  4048. // BoneRemap[bone index in file] == bone index in studiomdl
  4049. CDmeDag *pSkeleton = pRoot->GetValueElement< CDmeDag >( "skeleton" );
  4050. CDmeModel *pModel = pRoot->GetValueElement< CDmeModel >( "model" );
  4051. CDmeCombinationOperator *pCombinationOperator = pRoot->GetValueElement< CDmeCombinationOperator >( "combinationOperator" );
  4052. BoneTransformMap_t boneMap;
  4053. int nReturn = 0;
  4054. if ( LoadModelAndSkeleton( pSource, boneMap, pSkeleton, pModel, pCombinationOperator, false ) )
  4055. {
  4056. LoadQcModelElements( pSource, g_pCurrentModel, pModel );
  4057. CDmeAnimationList *pAnimationList = pRoot->GetValueElement< CDmeAnimationList >( "animationList" );
  4058. if ( pAnimationList )
  4059. {
  4060. LoadAnimations( pSource, pAnimationList, g_currentscale, boneMap );
  4061. }
  4062. if ( CommandLine()->FindParm( "-debugfbx2dmx" ) )
  4063. g_pDataModel->SaveToFile( CUtlString( pFullPath ).StripExtension() + ".fbx2dmx.dmx", NULL, "keyvalues2", "model", pRoot );
  4064. nReturn = 1; // loaded ok
  4065. }
  4066. g_pDataModel->UnloadFile/*RemoveFileId?*/( pRoot->GetFileId() );
  4067. return nReturn;
  4068. }
  4069. //-----------------------------------------------------------------------------
  4070. // Declare it so we can call it, defined in studiomdl.cpp
  4071. //-----------------------------------------------------------------------------
  4072. extern void ProcessModelName( const char *pMdlName );
  4073. //-----------------------------------------------------------------------------
  4074. // Main entry point for loading preprocessed files
  4075. //-----------------------------------------------------------------------------
  4076. bool LoadPreprocessedFile( const char *pFileName, float flScale )
  4077. {
  4078. #ifndef MDLCOMPILE
  4079. return false;
  4080. #else
  4081. DmFileId_t fileId;
  4082. // use the full search tree, including mod hierarchy to find the file
  4083. char pFullPath[MAX_PATH];
  4084. if ( !GetGlobalFilePath( pFileName, pFullPath, sizeof(pFullPath) ) )
  4085. {
  4086. MdlError( "Invalid MPP Filename: %s\n", pFileName );
  4087. return false;
  4088. }
  4089. // When reading, keep the CRLF; this will make ReadFile read it in binary format
  4090. // and also append a couple 0s to the end of the buffer.
  4091. CDmElement *pRoot;
  4092. if ( g_pDataModel->RestoreFromFile( pFullPath, NULL, NULL, &pRoot ) == DMFILEID_INVALID )
  4093. {
  4094. MdlError( "0001: Couldn't Load MPP File: %s\n", pFullPath );
  4095. return false;
  4096. }
  4097. if ( !g_quiet )
  4098. {
  4099. Msg( "Loaded Preprocessed File %s\n", pFullPath );
  4100. }
  4101. const char *pMdlPath = pRoot->GetValueString( "mdlPath" );
  4102. if ( pMdlPath && *pMdlPath )
  4103. {
  4104. // This is a hack... really the model path should be able to be anywhere relative to the game
  4105. // directory but currently "models/" is prepended everywhere... would like to get rid of that
  4106. // pattern but would also like to limit changes required for mdlcompile
  4107. if ( !Q_strnicmp( pMdlPath, "models", 6 ) && pMdlPath[6] == '/' || pMdlPath[7] == '\\' )
  4108. {
  4109. ProcessModelName( pMdlPath + 7 );
  4110. }
  4111. else
  4112. {
  4113. ProcessModelName( pMdlPath );
  4114. }
  4115. }
  4116. // Get whether we're doing skinned LODs from the pre-process file
  4117. g_bSkinnedLODs = pRoot->GetValue< bool >( "skinnedLODs", false );
  4118. // Load model info
  4119. LoadModelInfo( pRoot, pFullPath );
  4120. // Find out if it's marked as a static prop
  4121. const bool bStaticProp = pRoot->GetValue< bool >( "staticProp" );
  4122. bool bSetUpAxis = true;
  4123. s_source_t *pMainSource = NULL;
  4124. CDmeBodyGroupList *pBodyGroupList = pRoot->GetValueElement< CDmeBodyGroupList >( "bodyGroupList" );
  4125. if ( pBodyGroupList )
  4126. {
  4127. // Loads all body groups
  4128. if ( !LoadBodyGroupList( &pMainSource, pBodyGroupList, pRoot->GetValueElement< CDmeEyeballGlobals >( "eyeballGlobals" ), bStaticProp, bSetUpAxis ) )
  4129. goto dmxError;
  4130. CDmeCollisionModel *pCollisionModel = pRoot->GetValueElement< CDmeCollisionModel >( "collisionModel" );
  4131. if ( pCollisionModel && !LoadCollisionModel( pCollisionModel, bStaticProp ) )
  4132. goto dmxError;
  4133. LoadCollisionText( pRoot->GetValueString( "collisionText" ) );
  4134. // Deal with material groups. Ok to pass NULL for CDmeMaterialGroupList
  4135. LoadMaterialGroups( pRoot->GetValueElement< CDmeMaterialGroupList >( "materialGroupList" ) );
  4136. // Deal with bone merge directives. Ok to pass NULL DmAttribute for string array
  4137. LoadBoneMergeList( pBodyGroupList->GetAttribute( "boneMergeList" ) );
  4138. // Deal with bone merge directives. Ok to pass NULL DmAttribute for string array
  4139. // TODO: Bone keep list is a little funny, right now just treat the same as bone
  4140. // merge list which will ensure the bone is always present. This will also
  4141. // increase the bone priority and make the bone available to the server
  4142. LoadBoneMergeList( pBodyGroupList->GetAttribute( "boneKeepList" ) );
  4143. }
  4144. else
  4145. {
  4146. if ( bStaticProp )
  4147. {
  4148. MdlError( "0002: Static prop specified but no body groups present\n" );
  4149. goto dmxError;
  4150. }
  4151. // This MPP has no body groups, so maybe it's an animation only MPP?
  4152. pMainSource = AllocateDmxSource( "anim" );
  4153. }
  4154. // Deal with static props
  4155. if ( bStaticProp && pBodyGroupList )
  4156. {
  4157. // FIXME: This source should come from the skeleton;
  4158. // need to figure out if static props can deal with multiple sources
  4159. SetupStaticProp( pMainSource );
  4160. goto dmxSuccess;
  4161. }
  4162. // Nothing after here is applied if this is a static prop
  4163. LoadBoneMaskList( pRoot->GetValueElement< CDmeBoneMaskList >( "boneMaskList" ) );
  4164. // Deal with pose parameters. Ok to pass NULL for CDmePoseParameterList
  4165. LoadPoseParameterList( pRoot->GetValueElement< CDmePoseParameterList >( "poseParameterList" ) );
  4166. // Deal with animBlockSize, Ok to pass NULL for CDmeAnimBlockSize
  4167. LoadAnimBlockSize( pRoot->GetValueElement< CDmeAnimBlockSize >( "animBlockSize" ) );
  4168. // Deal with sequences. Ok to pass NULL for CDmeSequenceList
  4169. const int nSequenceCount = LoadAndCreateSequences( pMainSource, pRoot->GetValueElement< CDmeSequenceList >( "sequenceList" ), bSetUpAxis );
  4170. if ( nSequenceCount == 0 && !pBodyGroupList )
  4171. {
  4172. MdlError( "0003: MPP has no body groups and no animations\n" );
  4173. goto dmxError;
  4174. }
  4175. // Deal with include models. Ok to pass NULL for CDmeIncludeModelList
  4176. LoadIncludeModelList( pRoot->GetValueElement< CDmeIncludeModelList >( "includeModelList" ) );
  4177. // Deal with define bones. Ok to pass NULL for CDmeDefineBoneList
  4178. LoadDefineBoneList( pRoot->GetValueElement< CDmeDefineBoneList >( "defineBoneList" ) );
  4179. // Deal with hitbox sets. Ok to pass NULL for CDmeHitboxSetList
  4180. LoadHitboxSetList( pRoot->GetValueElement< CDmeHitboxSetList >( "hitboxSetList" ) );
  4181. // Deal with boneFlexDriver
  4182. LoadBoneFlexDriverList( pRoot->GetValueElement< CDmeBoneFlexDriverList >( "boneFlexDriverList" ) );
  4183. // At this point, reorienting of skeleton defined stuff will likely be required
  4184. // Deal with KeyValues, Ok to pass NULL or empty string
  4185. LoadKeyValues( pRoot->GetValueString( "keyValues" ) );
  4186. LoadGlobalFlags( pRoot );
  4187. dmxSuccess:
  4188. fileId = pRoot->GetFileId();
  4189. g_pDataModel->RemoveFileId( fileId );
  4190. return true;
  4191. dmxError:
  4192. fileId = pRoot->GetFileId();
  4193. g_pDataModel->RemoveFileId( fileId );
  4194. return false;
  4195. #endif // MDLCOMPILE
  4196. }