MD5Loader.cpp 30 KB

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