MD5Loader.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2012, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file MD5Loader.cpp
  35. * @brief Implementation of the MD5 importer class
  36. */
  37. #include "AssimpPCH.h"
  38. #ifndef ASSIMP_BUILD_NO_MD5_IMPORTER
  39. // internal headers
  40. #include "RemoveComments.h"
  41. #include "MD5Loader.h"
  42. #include "StringComparison.h"
  43. #include "fast_atof.h"
  44. #include "SkeletonMeshBuilder.h"
  45. using namespace Assimp;
  46. // Minimum weight value. Weights inside [-n ... n] are ignored
  47. #define AI_MD5_WEIGHT_EPSILON 1e-5f
  48. static const aiImporterDesc desc = {
  49. "Doom 3 / MD5 Mesh Importer",
  50. "",
  51. "",
  52. "",
  53. aiImporterFlags_SupportBinaryFlavour,
  54. 0,
  55. 0,
  56. 0,
  57. 0,
  58. "md5mesh md5camera md5anim"
  59. };
  60. // ------------------------------------------------------------------------------------------------
  61. // Constructor to be privately used by Importer
  62. MD5Importer::MD5Importer()
  63. : mBuffer()
  64. , configNoAutoLoad (false)
  65. {}
  66. // ------------------------------------------------------------------------------------------------
  67. // Destructor, private as well
  68. MD5Importer::~MD5Importer()
  69. {}
  70. // ------------------------------------------------------------------------------------------------
  71. // Returns whether the class can handle the format of the given file.
  72. bool MD5Importer::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  73. {
  74. const std::string extension = GetExtension(pFile);
  75. if (extension == "md5anim" || extension == "md5mesh" || extension == "md5camera")
  76. return true;
  77. else if (!extension.length() || checkSig) {
  78. if (!pIOHandler) {
  79. return true;
  80. }
  81. const char* tokens[] = {"MD5Version"};
  82. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  83. }
  84. return false;
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Get list of all supported extensions
  88. const aiImporterDesc* MD5Importer::GetInfo () const
  89. {
  90. return &desc;
  91. }
  92. // ------------------------------------------------------------------------------------------------
  93. // Setup import properties
  94. void MD5Importer::SetupProperties(const Importer* pImp)
  95. {
  96. // AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD
  97. configNoAutoLoad = (0 != pImp->GetPropertyInteger(AI_CONFIG_IMPORT_MD5_NO_ANIM_AUTOLOAD,0));
  98. }
  99. // ------------------------------------------------------------------------------------------------
  100. // Imports the given file into the given scene structure.
  101. void MD5Importer::InternReadFile( const std::string& pFile,
  102. aiScene* _pScene, IOSystem* _pIOHandler)
  103. {
  104. pIOHandler = _pIOHandler;
  105. pScene = _pScene;
  106. bHadMD5Mesh = bHadMD5Anim = bHadMD5Camera = false;
  107. // remove the file extension
  108. const std::string::size_type pos = pFile.find_last_of('.');
  109. mFile = (std::string::npos == pos ? pFile : pFile.substr(0,pos+1));
  110. const std::string extension = GetExtension(pFile);
  111. try {
  112. if (extension == "md5camera") {
  113. LoadMD5CameraFile();
  114. }
  115. else if (configNoAutoLoad || extension == "md5anim") {
  116. // determine file extension and process just *one* file
  117. if (extension.length() == 0) {
  118. throw DeadlyImportError("Failure, need file extension to determine MD5 part type");
  119. }
  120. if (extension == "md5anim") {
  121. LoadMD5AnimFile();
  122. }
  123. else if (extension == "md5mesh") {
  124. LoadMD5MeshFile();
  125. }
  126. }
  127. else {
  128. LoadMD5MeshFile();
  129. LoadMD5AnimFile();
  130. }
  131. }
  132. catch ( ... ) { // std::exception, Assimp::DeadlyImportError
  133. UnloadFileFromMemory();
  134. throw;
  135. }
  136. // make sure we have at least one file
  137. if (!bHadMD5Mesh && !bHadMD5Anim && !bHadMD5Camera) {
  138. throw DeadlyImportError("Failed to read valid contents out of this MD5* file");
  139. }
  140. // Now rotate the whole scene 90 degrees around the x axis to match our internal coordinate system
  141. pScene->mRootNode->mTransformation = aiMatrix4x4(1.f,0.f,0.f,0.f,
  142. 0.f,0.f,1.f,0.f,0.f,-1.f,0.f,0.f,0.f,0.f,0.f,1.f);
  143. // the output scene wouldn't pass the validation without this flag
  144. if (!bHadMD5Mesh) {
  145. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  146. }
  147. // clean the instance -- the BaseImporter instance may be reused later.
  148. UnloadFileFromMemory();
  149. }
  150. // ------------------------------------------------------------------------------------------------
  151. // Load a file into a memory buffer
  152. void MD5Importer::LoadFileIntoMemory (IOStream* file)
  153. {
  154. // unload the previous buffer, if any
  155. UnloadFileFromMemory();
  156. ai_assert(NULL != file);
  157. fileSize = (unsigned int)file->FileSize();
  158. ai_assert(fileSize);
  159. // allocate storage and copy the contents of the file to a memory buffer
  160. mBuffer = new char[fileSize+1];
  161. file->Read( (void*)mBuffer, 1, fileSize);
  162. iLineNumber = 1;
  163. // append a terminal 0
  164. mBuffer[fileSize] = '\0';
  165. // now remove all line comments from the file
  166. CommentRemover::RemoveLineComments("//",mBuffer,' ');
  167. }
  168. // ------------------------------------------------------------------------------------------------
  169. // Unload the current memory buffer
  170. void MD5Importer::UnloadFileFromMemory ()
  171. {
  172. // delete the file buffer
  173. delete[] mBuffer;
  174. mBuffer = NULL;
  175. fileSize = 0;
  176. }
  177. // ------------------------------------------------------------------------------------------------
  178. // Build unique vertices
  179. void MD5Importer::MakeDataUnique (MD5::MeshDesc& meshSrc)
  180. {
  181. std::vector<bool> abHad(meshSrc.mVertices.size(),false);
  182. // allocate enough storage to keep the output structures
  183. const unsigned int iNewNum = meshSrc.mFaces.size()*3;
  184. unsigned int iNewIndex = meshSrc.mVertices.size();
  185. meshSrc.mVertices.resize(iNewNum);
  186. // try to guess how much storage we'll need for new weights
  187. const float fWeightsPerVert = meshSrc.mWeights.size() / (float)iNewIndex;
  188. const unsigned int guess = (unsigned int)(fWeightsPerVert*iNewNum);
  189. meshSrc.mWeights.reserve(guess + (guess >> 3)); // + 12.5% as buffer
  190. for (FaceList::const_iterator iter = meshSrc.mFaces.begin(),iterEnd = meshSrc.mFaces.end();iter != iterEnd;++iter){
  191. const aiFace& face = *iter;
  192. for (unsigned int i = 0; i < 3;++i) {
  193. if (face.mIndices[0] >= meshSrc.mVertices.size()) {
  194. throw DeadlyImportError("MD5MESH: Invalid vertex index");
  195. }
  196. if (abHad[face.mIndices[i]]) {
  197. // generate a new vertex
  198. meshSrc.mVertices[iNewIndex] = meshSrc.mVertices[face.mIndices[i]];
  199. face.mIndices[i] = iNewIndex++;
  200. }
  201. else abHad[face.mIndices[i]] = true;
  202. }
  203. // swap face order
  204. std::swap(face.mIndices[0],face.mIndices[2]);
  205. }
  206. }
  207. // ------------------------------------------------------------------------------------------------
  208. // Recursive node graph construction from a MD5MESH
  209. void MD5Importer::AttachChilds_Mesh(int iParentID,aiNode* piParent, BoneList& bones)
  210. {
  211. ai_assert(NULL != piParent && !piParent->mNumChildren);
  212. // First find out how many children we'll have
  213. for (int i = 0; i < (int)bones.size();++i) {
  214. if (iParentID != i && bones[i].mParentIndex == iParentID) {
  215. ++piParent->mNumChildren;
  216. }
  217. }
  218. if (piParent->mNumChildren) {
  219. piParent->mChildren = new aiNode*[piParent->mNumChildren];
  220. for (int i = 0; i < (int)bones.size();++i) {
  221. // (avoid infinite recursion)
  222. if (iParentID != i && bones[i].mParentIndex == iParentID) {
  223. aiNode* pc;
  224. // setup a new node
  225. *piParent->mChildren++ = pc = new aiNode();
  226. pc->mName = aiString(bones[i].mName);
  227. pc->mParent = piParent;
  228. // get the transformation matrix from rotation and translational components
  229. aiQuaternion quat;
  230. MD5::ConvertQuaternion ( bones[i].mRotationQuat, quat );
  231. // FIX to get to Assimp's quaternion conventions
  232. quat.w *= -1.f;
  233. bones[i].mTransform = aiMatrix4x4 ( quat.GetMatrix());
  234. bones[i].mTransform.a4 = bones[i].mPositionXYZ.x;
  235. bones[i].mTransform.b4 = bones[i].mPositionXYZ.y;
  236. bones[i].mTransform.c4 = bones[i].mPositionXYZ.z;
  237. // store it for later use
  238. pc->mTransformation = bones[i].mInvTransform = bones[i].mTransform;
  239. bones[i].mInvTransform.Inverse();
  240. // the transformations for each bone are absolute, so we need to multiply them
  241. // with the inverse of the absolute matrix of the parent joint
  242. if (-1 != iParentID) {
  243. pc->mTransformation = bones[iParentID].mInvTransform * pc->mTransformation;
  244. }
  245. // add children to this node, too
  246. AttachChilds_Mesh( i, pc, bones);
  247. }
  248. }
  249. // undo offset computations
  250. piParent->mChildren -= piParent->mNumChildren;
  251. }
  252. }
  253. // ------------------------------------------------------------------------------------------------
  254. // Recursive node graph construction from a MD5ANIM
  255. void MD5Importer::AttachChilds_Anim(int iParentID,aiNode* piParent, AnimBoneList& bones,const aiNodeAnim** node_anims)
  256. {
  257. ai_assert(NULL != piParent && !piParent->mNumChildren);
  258. // First find out how many children we'll have
  259. for (int i = 0; i < (int)bones.size();++i) {
  260. if (iParentID != i && bones[i].mParentIndex == iParentID) {
  261. ++piParent->mNumChildren;
  262. }
  263. }
  264. if (piParent->mNumChildren) {
  265. piParent->mChildren = new aiNode*[piParent->mNumChildren];
  266. for (int i = 0; i < (int)bones.size();++i) {
  267. // (avoid infinite recursion)
  268. if (iParentID != i && bones[i].mParentIndex == iParentID)
  269. {
  270. aiNode* pc;
  271. // setup a new node
  272. *piParent->mChildren++ = pc = new aiNode();
  273. pc->mName = aiString(bones[i].mName);
  274. pc->mParent = piParent;
  275. // get the corresponding animation channel and its first frame
  276. const aiNodeAnim** cur = node_anims;
  277. while ((**cur).mNodeName != pc->mName)++cur;
  278. aiMatrix4x4::Translation((**cur).mPositionKeys[0].mValue,pc->mTransformation);
  279. pc->mTransformation = pc->mTransformation * aiMatrix4x4((**cur).mRotationKeys[0].mValue.GetMatrix()) ;
  280. // add children to this node, too
  281. AttachChilds_Anim( i, pc, bones,node_anims);
  282. }
  283. }
  284. // undo offset computations
  285. piParent->mChildren -= piParent->mNumChildren;
  286. }
  287. }
  288. // ------------------------------------------------------------------------------------------------
  289. // Load a MD5MESH file
  290. void MD5Importer::LoadMD5MeshFile ()
  291. {
  292. std::string pFile = mFile + "md5mesh";
  293. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  294. // Check whether we can read from the file
  295. if( file.get() == NULL || !file->FileSize()) {
  296. DefaultLogger::get()->warn("Failed to access MD5MESH file: " + pFile);
  297. return;
  298. }
  299. bHadMD5Mesh = true;
  300. LoadFileIntoMemory(file.get());
  301. // now construct a parser and parse the file
  302. MD5::MD5Parser parser(mBuffer,fileSize);
  303. // load the mesh information from it
  304. MD5::MD5MeshParser meshParser(parser.mSections);
  305. // create the bone hierarchy - first the root node and dummy nodes for all meshes
  306. pScene->mRootNode = new aiNode("<MD5_Root>");
  307. pScene->mRootNode->mNumChildren = 2;
  308. pScene->mRootNode->mChildren = new aiNode*[2];
  309. // build the hierarchy from the MD5MESH file
  310. aiNode* pcNode = pScene->mRootNode->mChildren[1] = new aiNode();
  311. pcNode->mName.Set("<MD5_Hierarchy>");
  312. pcNode->mParent = pScene->mRootNode;
  313. AttachChilds_Mesh(-1,pcNode,meshParser.mJoints);
  314. pcNode = pScene->mRootNode->mChildren[0] = new aiNode();
  315. pcNode->mName.Set("<MD5_Mesh>");
  316. pcNode->mParent = pScene->mRootNode;
  317. #if 0
  318. if (pScene->mRootNode->mChildren[1]->mNumChildren) /* start at the right hierarchy level */
  319. SkeletonMeshBuilder skeleton_maker(pScene,pScene->mRootNode->mChildren[1]->mChildren[0]);
  320. #else
  321. // FIX: MD5 files exported from Blender can have empty meshes
  322. for (std::vector<MD5::MeshDesc>::const_iterator it = meshParser.mMeshes.begin(),end = meshParser.mMeshes.end(); it != end;++it) {
  323. if (!(*it).mFaces.empty() && !(*it).mVertices.empty())
  324. ++pScene->mNumMaterials;
  325. }
  326. // generate all meshes
  327. pScene->mNumMeshes = pScene->mNumMaterials;
  328. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  329. pScene->mMaterials = new aiMaterial*[pScene->mNumMeshes];
  330. // storage for node mesh indices
  331. pcNode->mNumMeshes = pScene->mNumMeshes;
  332. pcNode->mMeshes = new unsigned int[pcNode->mNumMeshes];
  333. for (unsigned int m = 0; m < pcNode->mNumMeshes;++m)
  334. pcNode->mMeshes[m] = m;
  335. unsigned int n = 0;
  336. for (std::vector<MD5::MeshDesc>::iterator it = meshParser.mMeshes.begin(),end = meshParser.mMeshes.end(); it != end;++it) {
  337. MD5::MeshDesc& meshSrc = *it;
  338. if (meshSrc.mFaces.empty() || meshSrc.mVertices.empty())
  339. continue;
  340. aiMesh* mesh = pScene->mMeshes[n] = new aiMesh();
  341. mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  342. // generate unique vertices in our internal verbose format
  343. MakeDataUnique(meshSrc);
  344. mesh->mNumVertices = (unsigned int) meshSrc.mVertices.size();
  345. mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  346. mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  347. mesh->mNumUVComponents[0] = 2;
  348. // copy texture coordinates
  349. aiVector3D* pv = mesh->mTextureCoords[0];
  350. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  351. pv->x = (*iter).mUV.x;
  352. pv->y = 1.0f-(*iter).mUV.y; // D3D to OpenGL
  353. pv->z = 0.0f;
  354. }
  355. // sort all bone weights - per bone
  356. unsigned int* piCount = new unsigned int[meshParser.mJoints.size()];
  357. ::memset(piCount,0,sizeof(unsigned int)*meshParser.mJoints.size());
  358. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  359. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w)
  360. {
  361. MD5::WeightDesc& desc = meshSrc.mWeights[w];
  362. /* FIX for some invalid exporters */
  363. if (!(desc.mWeight < AI_MD5_WEIGHT_EPSILON && desc.mWeight >= -AI_MD5_WEIGHT_EPSILON ))
  364. ++piCount[desc.mBone];
  365. }
  366. }
  367. // check how many we will need
  368. for (unsigned int p = 0; p < meshParser.mJoints.size();++p)
  369. if (piCount[p])mesh->mNumBones++;
  370. if (mesh->mNumBones) // just for safety
  371. {
  372. mesh->mBones = new aiBone*[mesh->mNumBones];
  373. for (unsigned int q = 0,h = 0; q < meshParser.mJoints.size();++q)
  374. {
  375. if (!piCount[q])continue;
  376. aiBone* p = mesh->mBones[h] = new aiBone();
  377. p->mNumWeights = piCount[q];
  378. p->mWeights = new aiVertexWeight[p->mNumWeights];
  379. p->mName = aiString(meshParser.mJoints[q].mName);
  380. p->mOffsetMatrix = meshParser.mJoints[q].mInvTransform;
  381. // store the index for later use
  382. MD5::BoneDesc& boneSrc = meshParser.mJoints[q];
  383. boneSrc.mMap = h++;
  384. // compute w-component of quaternion
  385. MD5::ConvertQuaternion( boneSrc.mRotationQuat, boneSrc.mRotationQuatConverted );
  386. }
  387. //unsigned int g = 0;
  388. pv = mesh->mVertices;
  389. for (MD5::VertexList::const_iterator iter = meshSrc.mVertices.begin();iter != meshSrc.mVertices.end();++iter,++pv) {
  390. // compute the final vertex position from all single weights
  391. *pv = aiVector3D();
  392. // there are models which have weights which don't sum to 1 ...
  393. float fSum = 0.0f;
  394. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w)
  395. fSum += meshSrc.mWeights[w].mWeight;
  396. if (!fSum) {
  397. DefaultLogger::get()->error("MD5MESH: The sum of all vertex bone weights is 0");
  398. continue;
  399. }
  400. // process bone weights
  401. for (unsigned int jub = (*iter).mFirstWeight, w = jub; w < jub + (*iter).mNumWeights;++w) {
  402. if (w >= meshSrc.mWeights.size())
  403. throw DeadlyImportError("MD5MESH: Invalid weight index");
  404. MD5::WeightDesc& desc = meshSrc.mWeights[w];
  405. if ( desc.mWeight < AI_MD5_WEIGHT_EPSILON && desc.mWeight >= -AI_MD5_WEIGHT_EPSILON) {
  406. continue;
  407. }
  408. const float fNewWeight = desc.mWeight / fSum;
  409. // transform the local position into worldspace
  410. MD5::BoneDesc& boneSrc = meshParser.mJoints[desc.mBone];
  411. const aiVector3D v = boneSrc.mRotationQuatConverted.Rotate (desc.vOffsetPosition);
  412. // use the original weight to compute the vertex position
  413. // (some MD5s seem to depend on the invalid weight values ...)
  414. *pv += ((boneSrc.mPositionXYZ+v)* desc.mWeight);
  415. aiBone* bone = mesh->mBones[boneSrc.mMap];
  416. *bone->mWeights++ = aiVertexWeight((unsigned int)(pv-mesh->mVertices),fNewWeight);
  417. }
  418. }
  419. // undo our nice offset tricks ...
  420. for (unsigned int p = 0; p < mesh->mNumBones;++p) {
  421. mesh->mBones[p]->mWeights -= mesh->mBones[p]->mNumWeights;
  422. }
  423. }
  424. delete[] piCount;
  425. // now setup all faces - we can directly copy the list
  426. // (however, take care that the aiFace destructor doesn't delete the mIndices array)
  427. mesh->mNumFaces = (unsigned int)meshSrc.mFaces.size();
  428. mesh->mFaces = new aiFace[mesh->mNumFaces];
  429. for (unsigned int c = 0; c < mesh->mNumFaces;++c) {
  430. mesh->mFaces[c].mNumIndices = 3;
  431. mesh->mFaces[c].mIndices = meshSrc.mFaces[c].mIndices;
  432. meshSrc.mFaces[c].mIndices = NULL;
  433. }
  434. // generate a material for the mesh
  435. aiMaterial* mat = new aiMaterial();
  436. pScene->mMaterials[n] = mat;
  437. // insert the typical doom3 textures:
  438. // nnn_local.tga - normal map
  439. // nnn_h.tga - height map
  440. // nnn_s.tga - specular map
  441. // nnn_d.tga - diffuse map
  442. if (meshSrc.mShader.length && !strchr(meshSrc.mShader.data,'.')) {
  443. aiString temp(meshSrc.mShader);
  444. temp.Append("_local.tga");
  445. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_NORMALS(0));
  446. temp = aiString(meshSrc.mShader);
  447. temp.Append("_s.tga");
  448. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_SPECULAR(0));
  449. temp = aiString(meshSrc.mShader);
  450. temp.Append("_d.tga");
  451. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_DIFFUSE(0));
  452. temp = aiString(meshSrc.mShader);
  453. temp.Append("_h.tga");
  454. mat->AddProperty(&temp,AI_MATKEY_TEXTURE_HEIGHT(0));
  455. // set this also as material name
  456. mat->AddProperty(&meshSrc.mShader,AI_MATKEY_NAME);
  457. }
  458. else mat->AddProperty(&meshSrc.mShader,AI_MATKEY_TEXTURE_DIFFUSE(0));
  459. mesh->mMaterialIndex = n++;
  460. }
  461. #endif
  462. }
  463. // ------------------------------------------------------------------------------------------------
  464. // Load an MD5ANIM file
  465. void MD5Importer::LoadMD5AnimFile ()
  466. {
  467. std::string pFile = mFile + "md5anim";
  468. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  469. // Check whether we can read from the file
  470. if( !file.get() || !file->FileSize()) {
  471. DefaultLogger::get()->warn("Failed to read MD5ANIM file: " + pFile);
  472. return;
  473. }
  474. LoadFileIntoMemory(file.get());
  475. // parse the basic file structure
  476. MD5::MD5Parser parser(mBuffer,fileSize);
  477. // load the animation information from the parse tree
  478. MD5::MD5AnimParser animParser(parser.mSections);
  479. // generate and fill the output animation
  480. if (animParser.mAnimatedBones.empty() || animParser.mFrames.empty() ||
  481. animParser.mBaseFrames.size() != animParser.mAnimatedBones.size()) {
  482. DefaultLogger::get()->error("MD5ANIM: No frames or animated bones loaded");
  483. }
  484. else {
  485. bHadMD5Anim = true;
  486. pScene->mAnimations = new aiAnimation*[pScene->mNumAnimations = 1];
  487. aiAnimation* anim = pScene->mAnimations[0] = new aiAnimation();
  488. anim->mNumChannels = (unsigned int)animParser.mAnimatedBones.size();
  489. anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  490. for (unsigned int i = 0; i < anim->mNumChannels;++i) {
  491. aiNodeAnim* node = anim->mChannels[i] = new aiNodeAnim();
  492. node->mNodeName = aiString( animParser.mAnimatedBones[i].mName );
  493. // allocate storage for the keyframes
  494. node->mPositionKeys = new aiVectorKey[animParser.mFrames.size()];
  495. node->mRotationKeys = new aiQuatKey[animParser.mFrames.size()];
  496. }
  497. // 1 tick == 1 frame
  498. anim->mTicksPerSecond = animParser.fFrameRate;
  499. for (FrameList::const_iterator iter = animParser.mFrames.begin(), iterEnd = animParser.mFrames.end();iter != iterEnd;++iter){
  500. double dTime = (double)(*iter).iIndex;
  501. aiNodeAnim** pcAnimNode = anim->mChannels;
  502. if (!(*iter).mValues.empty() || iter == animParser.mFrames.begin()) /* be sure we have at least one frame */
  503. {
  504. // now process all values in there ... read all joints
  505. MD5::BaseFrameDesc* pcBaseFrame = &animParser.mBaseFrames[0];
  506. for (AnimBoneList::const_iterator iter2 = animParser.mAnimatedBones.begin(); iter2 != animParser.mAnimatedBones.end();++iter2,
  507. ++pcAnimNode,++pcBaseFrame)
  508. {
  509. if((*iter2).iFirstKeyIndex >= (*iter).mValues.size()) {
  510. // Allow for empty frames
  511. if ((*iter2).iFlags != 0) {
  512. throw DeadlyImportError("MD5: Keyframe index is out of range");
  513. }
  514. continue;
  515. }
  516. const float* fpCur = &(*iter).mValues[(*iter2).iFirstKeyIndex];
  517. aiNodeAnim* pcCurAnimBone = *pcAnimNode;
  518. aiVectorKey* vKey = &pcCurAnimBone->mPositionKeys[pcCurAnimBone->mNumPositionKeys++];
  519. aiQuatKey* qKey = &pcCurAnimBone->mRotationKeys [pcCurAnimBone->mNumRotationKeys++];
  520. aiVector3D vTemp;
  521. // translational component
  522. for (unsigned int i = 0; i < 3; ++i) {
  523. if ((*iter2).iFlags & (1u << i)) {
  524. vKey->mValue[i] = *fpCur++;
  525. }
  526. else vKey->mValue[i] = pcBaseFrame->vPositionXYZ[i];
  527. }
  528. // orientation component
  529. for (unsigned int i = 0; i < 3; ++i) {
  530. if ((*iter2).iFlags & (8u << i)) {
  531. vTemp[i] = *fpCur++;
  532. }
  533. else vTemp[i] = pcBaseFrame->vRotationQuat[i];
  534. }
  535. MD5::ConvertQuaternion(vTemp, qKey->mValue);
  536. qKey->mTime = vKey->mTime = dTime;
  537. // we need this to get to Assimp quaternion conventions
  538. qKey->mValue.w *= -1.f;
  539. }
  540. }
  541. // compute the duration of the animation
  542. anim->mDuration = std::max(dTime,anim->mDuration);
  543. }
  544. // If we didn't build the hierarchy yet (== we didn't load a MD5MESH),
  545. // construct it now from the data given in the MD5ANIM.
  546. if (!pScene->mRootNode) {
  547. pScene->mRootNode = new aiNode();
  548. pScene->mRootNode->mName.Set("<MD5_Hierarchy>");
  549. AttachChilds_Anim(-1,pScene->mRootNode,animParser.mAnimatedBones,(const aiNodeAnim**)anim->mChannels);
  550. // Call SkeletonMeshBuilder to construct a mesh to represent the shape
  551. if (pScene->mRootNode->mNumChildren) {
  552. SkeletonMeshBuilder skeleton_maker(pScene,pScene->mRootNode->mChildren[0]);
  553. }
  554. }
  555. }
  556. }
  557. // ------------------------------------------------------------------------------------------------
  558. // Load an MD5CAMERA file
  559. void MD5Importer::LoadMD5CameraFile ()
  560. {
  561. std::string pFile = mFile + "md5camera";
  562. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  563. // Check whether we can read from the file
  564. if( !file.get() || !file->FileSize()) {
  565. throw DeadlyImportError("Failed to read MD5CAMERA file: " + pFile);
  566. }
  567. bHadMD5Camera = true;
  568. LoadFileIntoMemory(file.get());
  569. // parse the basic file structure
  570. MD5::MD5Parser parser(mBuffer,fileSize);
  571. // load the camera animation data from the parse tree
  572. MD5::MD5CameraParser cameraParser(parser.mSections);
  573. if (cameraParser.frames.empty()) {
  574. throw DeadlyImportError("MD5CAMERA: No frames parsed");
  575. }
  576. std::vector<unsigned int>& cuts = cameraParser.cuts;
  577. std::vector<MD5::CameraAnimFrameDesc>& frames = cameraParser.frames;
  578. // Construct output graph - a simple root with a dummy child.
  579. // The root node performs the coordinate system conversion
  580. aiNode* root = pScene->mRootNode = new aiNode("<MD5CameraRoot>");
  581. root->mChildren = new aiNode*[root->mNumChildren = 1];
  582. root->mChildren[0] = new aiNode("<MD5Camera>");
  583. root->mChildren[0]->mParent = root;
  584. // ... but with one camera assigned to it
  585. pScene->mCameras = new aiCamera*[pScene->mNumCameras = 1];
  586. aiCamera* cam = pScene->mCameras[0] = new aiCamera();
  587. cam->mName = "<MD5Camera>";
  588. // FIXME: Fov is currently set to the first frame's value
  589. cam->mHorizontalFOV = AI_DEG_TO_RAD( frames.front().fFOV );
  590. // every cut is written to a separate aiAnimation
  591. if (!cuts.size()) {
  592. cuts.push_back(0);
  593. cuts.push_back(frames.size()-1);
  594. }
  595. else {
  596. cuts.insert(cuts.begin(),0);
  597. if (cuts.back() < frames.size()-1)
  598. cuts.push_back(frames.size()-1);
  599. }
  600. pScene->mNumAnimations = cuts.size()-1;
  601. aiAnimation** tmp = pScene->mAnimations = new aiAnimation*[pScene->mNumAnimations];
  602. for (std::vector<unsigned int>::const_iterator it = cuts.begin(); it != cuts.end()-1; ++it) {
  603. aiAnimation* anim = *tmp++ = new aiAnimation();
  604. anim->mName.length = ::sprintf(anim->mName.data,"anim%u_from_%u_to_%u",(unsigned int)(it-cuts.begin()),(*it),*(it+1));
  605. anim->mTicksPerSecond = cameraParser.fFrameRate;
  606. anim->mChannels = new aiNodeAnim*[anim->mNumChannels = 1];
  607. aiNodeAnim* nd = anim->mChannels[0] = new aiNodeAnim();
  608. nd->mNodeName.Set("<MD5Camera>");
  609. nd->mNumPositionKeys = nd->mNumRotationKeys = *(it+1) - (*it);
  610. nd->mPositionKeys = new aiVectorKey[nd->mNumPositionKeys];
  611. nd->mRotationKeys = new aiQuatKey [nd->mNumRotationKeys];
  612. for (unsigned int i = 0; i < nd->mNumPositionKeys; ++i) {
  613. nd->mPositionKeys[i].mValue = frames[*it+i].vPositionXYZ;
  614. MD5::ConvertQuaternion(frames[*it+i].vRotationQuat,nd->mRotationKeys[i].mValue);
  615. nd->mRotationKeys[i].mTime = nd->mPositionKeys[i].mTime = *it+i;
  616. }
  617. }
  618. }
  619. #endif // !! ASSIMP_BUILD_NO_MD5_IMPORTER