MD5Loader.cpp 30 KB

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