MD5Loader.cpp 30 KB

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