SMDLoader.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, 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 SMDLoader.cpp
  35. * @brief Implementation of the SMD importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_SMD_IMPORTER
  38. // internal headers
  39. #include "SMDLoader.h"
  40. #include "fast_atof.h"
  41. #include "SkeletonMeshBuilder.h"
  42. #include "../include/assimp/Importer.hpp"
  43. #include "../include/assimp/IOSystem.hpp"
  44. #include <boost/scoped_ptr.hpp>
  45. #include "../include/assimp/scene.h"
  46. #include "../include/assimp/DefaultLogger.hpp"
  47. using namespace Assimp;
  48. static const aiImporterDesc desc = {
  49. "Valve SMD Importer",
  50. "",
  51. "",
  52. "",
  53. aiImporterFlags_SupportTextFlavour,
  54. 0,
  55. 0,
  56. 0,
  57. 0,
  58. "smd vta"
  59. };
  60. // ------------------------------------------------------------------------------------------------
  61. // Constructor to be privately used by Importer
  62. SMDImporter::SMDImporter()
  63. : configFrameID(),
  64. mBuffer(),
  65. pScene(),
  66. iFileSize(),
  67. iSmallestFrame(),
  68. dLengthOfAnim(),
  69. bHasUVs(),
  70. iLineNumber()
  71. {}
  72. // ------------------------------------------------------------------------------------------------
  73. // Destructor, private as well
  74. SMDImporter::~SMDImporter()
  75. {}
  76. // ------------------------------------------------------------------------------------------------
  77. // Returns whether the class can handle the format of the given file.
  78. bool SMDImporter::CanRead( const std::string& pFile, IOSystem* /*pIOHandler*/, bool) const
  79. {
  80. // fixme: auto format detection
  81. return SimpleExtensionCheck(pFile,"smd","vta");
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. // Get a list of all supported file extensions
  85. const aiImporterDesc* SMDImporter::GetInfo () const
  86. {
  87. return &desc;
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. // Setup configuration properties
  91. void SMDImporter::SetupProperties(const Importer* pImp)
  92. {
  93. // The
  94. // AI_CONFIG_IMPORT_SMD_KEYFRAME option overrides the
  95. // AI_CONFIG_IMPORT_GLOBAL_KEYFRAME option.
  96. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_SMD_KEYFRAME,-1);
  97. if(static_cast<unsigned int>(-1) == configFrameID) {
  98. configFrameID = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_GLOBAL_KEYFRAME,0);
  99. }
  100. }
  101. // ------------------------------------------------------------------------------------------------
  102. // Imports the given file into the given scene structure.
  103. void SMDImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  104. {
  105. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
  106. // Check whether we can read from the file
  107. if( file.get() == NULL) {
  108. throw DeadlyImportError( "Failed to open SMD/VTA file " + pFile + ".");
  109. }
  110. iFileSize = (unsigned int)file->FileSize();
  111. // Allocate storage and copy the contents of the file to a memory buffer
  112. this->pScene = pScene;
  113. std::vector<char> buff(iFileSize+1);
  114. TextFileToBuffer(file.get(),buff);
  115. mBuffer = &buff[0];
  116. iSmallestFrame = (1 << 31);
  117. bHasUVs = true;
  118. iLineNumber = 1;
  119. // Reserve enough space for ... hm ... 10 textures
  120. aszTextures.reserve(10);
  121. // Reserve enough space for ... hm ... 1000 triangles
  122. asTriangles.reserve(1000);
  123. // Reserve enough space for ... hm ... 20 bones
  124. asBones.reserve(20);
  125. // parse the file ...
  126. ParseFile();
  127. // If there are no triangles it seems to be an animation SMD,
  128. // containing only the animation skeleton.
  129. if (asTriangles.empty())
  130. {
  131. if (asBones.empty())
  132. {
  133. throw DeadlyImportError("SMD: No triangles and no bones have "
  134. "been found in the file. This file seems to be invalid.");
  135. }
  136. // Set the flag in the scene structure which indicates
  137. // that there is nothing than an animation skeleton
  138. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  139. }
  140. if (!asBones.empty())
  141. {
  142. // Check whether all bones have been initialized
  143. for (std::vector<SMD::Bone>::const_iterator
  144. i = asBones.begin();
  145. i != asBones.end();++i)
  146. {
  147. if (!(*i).mName.length())
  148. {
  149. DefaultLogger::get()->warn("SMD: Not all bones have been initialized");
  150. break;
  151. }
  152. }
  153. // now fix invalid time values and make sure the animation starts at frame 0
  154. FixTimeValues();
  155. // compute absolute bone transformation matrices
  156. // ComputeAbsoluteBoneTransformations();
  157. }
  158. if (!(pScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE))
  159. {
  160. // create output meshes
  161. CreateOutputMeshes();
  162. // build an output material list
  163. CreateOutputMaterials();
  164. }
  165. // build the output animation
  166. CreateOutputAnimations();
  167. // build output nodes (bones are added as empty dummy nodes)
  168. CreateOutputNodes();
  169. if (pScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE)
  170. {
  171. SkeletonMeshBuilder skeleton(pScene);
  172. }
  173. }
  174. // ------------------------------------------------------------------------------------------------
  175. // Write an error message with line number to the log file
  176. void SMDImporter::LogErrorNoThrow(const char* msg)
  177. {
  178. char szTemp[1024];
  179. ai_snprintf(szTemp,1024,"Line %u: %s",iLineNumber,msg);
  180. DefaultLogger::get()->error(szTemp);
  181. }
  182. // ------------------------------------------------------------------------------------------------
  183. // Write a warning with line number to the log file
  184. void SMDImporter::LogWarning(const char* msg)
  185. {
  186. char szTemp[1024];
  187. ai_assert(strlen(msg) < 1000);
  188. ai_snprintf(szTemp,1024,"Line %u: %s",iLineNumber,msg);
  189. DefaultLogger::get()->warn(szTemp);
  190. }
  191. // ------------------------------------------------------------------------------------------------
  192. // Fix invalid time values in the file
  193. void SMDImporter::FixTimeValues()
  194. {
  195. double dDelta = (double)iSmallestFrame;
  196. double dMax = 0.0f;
  197. for (std::vector<SMD::Bone>::iterator
  198. iBone = asBones.begin();
  199. iBone != asBones.end();++iBone)
  200. {
  201. for (std::vector<SMD::Bone::Animation::MatrixKey>::iterator
  202. iKey = (*iBone).sAnim.asKeys.begin();
  203. iKey != (*iBone).sAnim.asKeys.end();++iKey)
  204. {
  205. (*iKey).dTime -= dDelta;
  206. dMax = std::max(dMax, (*iKey).dTime);
  207. }
  208. }
  209. dLengthOfAnim = dMax;
  210. }
  211. // ------------------------------------------------------------------------------------------------
  212. // create output meshes
  213. void SMDImporter::CreateOutputMeshes()
  214. {
  215. if (aszTextures.empty())
  216. aszTextures.push_back(std::string());
  217. // we need to sort all faces by their material index
  218. // in opposition to other loaders we can be sure that each
  219. // material is at least used once.
  220. pScene->mNumMeshes = (unsigned int) aszTextures.size();
  221. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  222. typedef std::vector<unsigned int> FaceList;
  223. FaceList* aaiFaces = new FaceList[pScene->mNumMeshes];
  224. // approximate the space that will be required
  225. unsigned int iNum = (unsigned int)asTriangles.size() / pScene->mNumMeshes;
  226. iNum += iNum >> 1;
  227. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  228. aaiFaces[i].reserve(iNum);
  229. // collect all faces
  230. iNum = 0;
  231. for (std::vector<SMD::Face>::const_iterator
  232. iFace = asTriangles.begin();
  233. iFace != asTriangles.end();++iFace,++iNum)
  234. {
  235. if (UINT_MAX == (*iFace).iTexture)aaiFaces[(*iFace).iTexture].push_back( 0 );
  236. else if ((*iFace).iTexture >= aszTextures.size())
  237. {
  238. DefaultLogger::get()->error("[SMD/VTA] Material index overflow in face");
  239. aaiFaces[(*iFace).iTexture].push_back((unsigned int)aszTextures.size()-1);
  240. }
  241. else aaiFaces[(*iFace).iTexture].push_back(iNum);
  242. }
  243. // now create the output meshes
  244. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  245. {
  246. aiMesh*& pcMesh = pScene->mMeshes[i] = new aiMesh();
  247. ai_assert(!aaiFaces[i].empty()); // should not be empty ...
  248. pcMesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;
  249. pcMesh->mNumVertices = (unsigned int)aaiFaces[i].size()*3;
  250. pcMesh->mNumFaces = (unsigned int)aaiFaces[i].size();
  251. pcMesh->mMaterialIndex = i;
  252. // storage for bones
  253. typedef std::pair<unsigned int,float> TempWeightListEntry;
  254. typedef std::vector< TempWeightListEntry > TempBoneWeightList;
  255. TempBoneWeightList* aaiBones = new TempBoneWeightList[asBones.size()]();
  256. // try to reserve enough memory without wasting too much
  257. for (unsigned int iBone = 0; iBone < asBones.size();++iBone)
  258. {
  259. aaiBones[iBone].reserve(pcMesh->mNumVertices/asBones.size());
  260. }
  261. // allocate storage
  262. pcMesh->mFaces = new aiFace[pcMesh->mNumFaces];
  263. aiVector3D* pcNormals = pcMesh->mNormals = new aiVector3D[pcMesh->mNumVertices];
  264. aiVector3D* pcVerts = pcMesh->mVertices = new aiVector3D[pcMesh->mNumVertices];
  265. aiVector3D* pcUVs = NULL;
  266. if (bHasUVs)
  267. {
  268. pcUVs = pcMesh->mTextureCoords[0] = new aiVector3D[pcMesh->mNumVertices];
  269. pcMesh->mNumUVComponents[0] = 2;
  270. }
  271. iNum = 0;
  272. for (unsigned int iFace = 0; iFace < pcMesh->mNumFaces;++iFace)
  273. {
  274. pcMesh->mFaces[iFace].mIndices = new unsigned int[3];
  275. pcMesh->mFaces[iFace].mNumIndices = 3;
  276. // fill the vertices
  277. unsigned int iSrcFace = aaiFaces[i][iFace];
  278. SMD::Face& face = asTriangles[iSrcFace];
  279. *pcVerts++ = face.avVertices[0].pos;
  280. *pcVerts++ = face.avVertices[1].pos;
  281. *pcVerts++ = face.avVertices[2].pos;
  282. // fill the normals
  283. *pcNormals++ = face.avVertices[0].nor;
  284. *pcNormals++ = face.avVertices[1].nor;
  285. *pcNormals++ = face.avVertices[2].nor;
  286. // fill the texture coordinates
  287. if (pcUVs)
  288. {
  289. *pcUVs++ = face.avVertices[0].uv;
  290. *pcUVs++ = face.avVertices[1].uv;
  291. *pcUVs++ = face.avVertices[2].uv;
  292. }
  293. for (unsigned int iVert = 0; iVert < 3;++iVert)
  294. {
  295. float fSum = 0.0f;
  296. for (unsigned int iBone = 0;iBone < face.avVertices[iVert].aiBoneLinks.size();++iBone)
  297. {
  298. TempWeightListEntry& pairval = face.avVertices[iVert].aiBoneLinks[iBone];
  299. // FIX: The second check is here just to make sure we won't
  300. // assign more than one weight to a single vertex index
  301. if (pairval.first >= asBones.size() ||
  302. pairval.first == face.avVertices[iVert].iParentNode)
  303. {
  304. DefaultLogger::get()->error("[SMD/VTA] Bone index overflow. "
  305. "The bone index will be ignored, the weight will be assigned "
  306. "to the vertex' parent node");
  307. continue;
  308. }
  309. aaiBones[pairval.first].push_back(TempWeightListEntry(iNum,pairval.second));
  310. fSum += pairval.second;
  311. }
  312. // ******************************************************************
  313. // If the sum of all vertex weights is not 1.0 we must assign
  314. // the rest to the vertex' parent node. Well, at least the doc says
  315. // we should ...
  316. // FIX: We use 0.975 as limit, floating-point inaccuracies seem to
  317. // be very strong in some SMD exporters. Furthermore it is possible
  318. // that the parent of a vertex is 0xffffffff (if the corresponding
  319. // entry in the file was unreadable)
  320. // ******************************************************************
  321. if (fSum < 0.975f && face.avVertices[iVert].iParentNode != UINT_MAX)
  322. {
  323. if (face.avVertices[iVert].iParentNode >= asBones.size())
  324. {
  325. DefaultLogger::get()->error("[SMD/VTA] Bone index overflow. "
  326. "The index of the vertex parent bone is invalid. "
  327. "The remaining weights will be normalized to 1.0");
  328. if (fSum)
  329. {
  330. fSum = 1 / fSum;
  331. for (unsigned int iBone = 0;iBone < face.avVertices[iVert].aiBoneLinks.size();++iBone)
  332. {
  333. TempWeightListEntry& pairval = face.avVertices[iVert].aiBoneLinks[iBone];
  334. if (pairval.first >= asBones.size())continue;
  335. aaiBones[pairval.first].back().second *= fSum;
  336. }
  337. }
  338. }
  339. else
  340. {
  341. aaiBones[face.avVertices[iVert].iParentNode].push_back(
  342. TempWeightListEntry(iNum,1.0f-fSum));
  343. }
  344. }
  345. pcMesh->mFaces[iFace].mIndices[iVert] = iNum++;
  346. }
  347. }
  348. // now build all bones of the mesh
  349. iNum = 0;
  350. for (unsigned int iBone = 0; iBone < asBones.size();++iBone)
  351. if (!aaiBones[iBone].empty())++iNum;
  352. if (false && iNum)
  353. {
  354. pcMesh->mNumBones = iNum;
  355. pcMesh->mBones = new aiBone*[pcMesh->mNumBones];
  356. iNum = 0;
  357. for (unsigned int iBone = 0; iBone < asBones.size();++iBone)
  358. {
  359. if (aaiBones[iBone].empty())continue;
  360. aiBone*& bone = pcMesh->mBones[iNum] = new aiBone();
  361. bone->mNumWeights = (unsigned int)aaiBones[iBone].size();
  362. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  363. bone->mOffsetMatrix = asBones[iBone].mOffsetMatrix;
  364. bone->mName.Set( asBones[iBone].mName );
  365. asBones[iBone].bIsUsed = true;
  366. for (unsigned int iWeight = 0; iWeight < bone->mNumWeights;++iWeight)
  367. {
  368. bone->mWeights[iWeight].mVertexId = aaiBones[iBone][iWeight].first;
  369. bone->mWeights[iWeight].mWeight = aaiBones[iBone][iWeight].second;
  370. }
  371. ++iNum;
  372. }
  373. }
  374. delete[] aaiBones;
  375. }
  376. delete[] aaiFaces;
  377. }
  378. // ------------------------------------------------------------------------------------------------
  379. // add bone child nodes
  380. void SMDImporter::AddBoneChildren(aiNode* pcNode, uint32_t iParent)
  381. {
  382. ai_assert(NULL != pcNode && 0 == pcNode->mNumChildren && NULL == pcNode->mChildren);
  383. // first count ...
  384. for (unsigned int i = 0; i < asBones.size();++i)
  385. {
  386. SMD::Bone& bone = asBones[i];
  387. if (bone.iParent == iParent)++pcNode->mNumChildren;
  388. }
  389. // now allocate the output array
  390. pcNode->mChildren = new aiNode*[pcNode->mNumChildren];
  391. // and fill all subnodes
  392. unsigned int qq = 0;
  393. for (unsigned int i = 0; i < asBones.size();++i)
  394. {
  395. SMD::Bone& bone = asBones[i];
  396. if (bone.iParent != iParent)continue;
  397. aiNode* pc = pcNode->mChildren[qq++] = new aiNode();
  398. pc->mName.Set(bone.mName);
  399. // store the local transformation matrix of the bind pose
  400. pc->mTransformation = bone.sAnim.asKeys[bone.sAnim.iFirstTimeKey].matrix;
  401. pc->mParent = pcNode;
  402. // add children to this node, too
  403. AddBoneChildren(pc,i);
  404. }
  405. }
  406. // ------------------------------------------------------------------------------------------------
  407. // create output nodes
  408. void SMDImporter::CreateOutputNodes()
  409. {
  410. pScene->mRootNode = new aiNode();
  411. if (!(pScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE))
  412. {
  413. // create one root node that renders all meshes
  414. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  415. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  416. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  417. pScene->mRootNode->mMeshes[i] = i;
  418. }
  419. // now add all bones as dummy sub nodes to the graph
  420. // AddBoneChildren(pScene->mRootNode,(uint32_t)-1);
  421. // if we have only one bone we can even remove the root node
  422. if (pScene->mFlags & AI_SCENE_FLAGS_INCOMPLETE &&
  423. 1 == pScene->mRootNode->mNumChildren)
  424. {
  425. aiNode* pcOldRoot = pScene->mRootNode;
  426. pScene->mRootNode = pcOldRoot->mChildren[0];
  427. pcOldRoot->mChildren[0] = NULL;
  428. delete pcOldRoot;
  429. pScene->mRootNode->mParent = NULL;
  430. }
  431. else
  432. {
  433. ::strcpy(pScene->mRootNode->mName.data, "<SMD_root>");
  434. pScene->mRootNode->mName.length = 10;
  435. }
  436. }
  437. // ------------------------------------------------------------------------------------------------
  438. // create output animations
  439. void SMDImporter::CreateOutputAnimations()
  440. {
  441. unsigned int iNumBones = 0;
  442. for (std::vector<SMD::Bone>::const_iterator
  443. i = asBones.begin();
  444. i != asBones.end();++i)
  445. {
  446. if ((*i).bIsUsed)++iNumBones;
  447. }
  448. if (!iNumBones)
  449. {
  450. // just make sure this case doesn't occur ... (it could occur
  451. // if the file was invalid)
  452. return;
  453. }
  454. pScene->mNumAnimations = 1;
  455. pScene->mAnimations = new aiAnimation*[1];
  456. aiAnimation*& anim = pScene->mAnimations[0] = new aiAnimation();
  457. anim->mDuration = dLengthOfAnim;
  458. anim->mNumChannels = iNumBones;
  459. anim->mTicksPerSecond = 25.0; // FIXME: is this correct?
  460. aiNodeAnim** pp = anim->mChannels = new aiNodeAnim*[anim->mNumChannels];
  461. // now build valid keys
  462. unsigned int a = 0;
  463. for (std::vector<SMD::Bone>::const_iterator
  464. i = asBones.begin();
  465. i != asBones.end();++i)
  466. {
  467. if (!(*i).bIsUsed)continue;
  468. aiNodeAnim* p = pp[a] = new aiNodeAnim();
  469. // copy the name of the bone
  470. p->mNodeName.Set( i->mName);
  471. p->mNumRotationKeys = (unsigned int) (*i).sAnim.asKeys.size();
  472. if (p->mNumRotationKeys)
  473. {
  474. p->mNumPositionKeys = p->mNumRotationKeys;
  475. aiVectorKey* pVecKeys = p->mPositionKeys = new aiVectorKey[p->mNumRotationKeys];
  476. aiQuatKey* pRotKeys = p->mRotationKeys = new aiQuatKey[p->mNumRotationKeys];
  477. for (std::vector<SMD::Bone::Animation::MatrixKey>::const_iterator
  478. qq = (*i).sAnim.asKeys.begin();
  479. qq != (*i).sAnim.asKeys.end(); ++qq)
  480. {
  481. pRotKeys->mTime = pVecKeys->mTime = (*qq).dTime;
  482. // compute the rotation quaternion from the euler angles
  483. pRotKeys->mValue = aiQuaternion( (*qq).vRot.x, (*qq).vRot.y, (*qq).vRot.z );
  484. pVecKeys->mValue = (*qq).vPos;
  485. ++pVecKeys; ++pRotKeys;
  486. }
  487. }
  488. ++a;
  489. // there are no scaling keys ...
  490. }
  491. }
  492. // ------------------------------------------------------------------------------------------------
  493. void SMDImporter::ComputeAbsoluteBoneTransformations()
  494. {
  495. // For each bone: determine the key with the lowest time value
  496. // theoretically the SMD format should have all keyframes
  497. // in order. However, I've seen a file where this wasn't true.
  498. for (unsigned int i = 0; i < asBones.size();++i)
  499. {
  500. SMD::Bone& bone = asBones[i];
  501. uint32_t iIndex = 0;
  502. double dMin = 10e10;
  503. for (unsigned int i = 0; i < bone.sAnim.asKeys.size();++i)
  504. {
  505. double d = std::min(bone.sAnim.asKeys[i].dTime,dMin);
  506. if (d < dMin)
  507. {
  508. dMin = d;
  509. iIndex = i;
  510. }
  511. }
  512. bone.sAnim.iFirstTimeKey = iIndex;
  513. }
  514. unsigned int iParent = 0;
  515. while (iParent < asBones.size())
  516. {
  517. for (unsigned int iBone = 0; iBone < asBones.size();++iBone)
  518. {
  519. SMD::Bone& bone = asBones[iBone];
  520. if (iParent == bone.iParent)
  521. {
  522. SMD::Bone& parentBone = asBones[iParent];
  523. uint32_t iIndex = bone.sAnim.iFirstTimeKey;
  524. const aiMatrix4x4& mat = bone.sAnim.asKeys[iIndex].matrix;
  525. aiMatrix4x4& matOut = bone.sAnim.asKeys[iIndex].matrixAbsolute;
  526. // The same for the parent bone ...
  527. iIndex = parentBone.sAnim.iFirstTimeKey;
  528. const aiMatrix4x4& mat2 = parentBone.sAnim.asKeys[iIndex].matrixAbsolute;
  529. // Compute the absolute transformation matrix
  530. matOut = mat * mat2;
  531. }
  532. }
  533. ++iParent;
  534. }
  535. // Store the inverse of the absolute transformation matrix
  536. // of the first key as bone offset matrix
  537. for (iParent = 0; iParent < asBones.size();++iParent)
  538. {
  539. SMD::Bone& bone = asBones[iParent];
  540. bone.mOffsetMatrix = bone.sAnim.asKeys[bone.sAnim.iFirstTimeKey].matrixAbsolute;
  541. bone.mOffsetMatrix.Inverse();
  542. }
  543. }
  544. // ------------------------------------------------------------------------------------------------
  545. // create output materials
  546. void SMDImporter::CreateOutputMaterials()
  547. {
  548. pScene->mNumMaterials = (unsigned int)aszTextures.size();
  549. pScene->mMaterials = new aiMaterial*[std::max(1u, pScene->mNumMaterials)];
  550. for (unsigned int iMat = 0; iMat < pScene->mNumMaterials;++iMat)
  551. {
  552. aiMaterial* pcMat = new aiMaterial();
  553. pScene->mMaterials[iMat] = pcMat;
  554. aiString szName;
  555. szName.length = (size_t)ai_snprintf(szName.data,MAXLEN,"Texture_%u",iMat);
  556. pcMat->AddProperty(&szName,AI_MATKEY_NAME);
  557. if (aszTextures[iMat].length())
  558. {
  559. ::strcpy(szName.data, aszTextures[iMat].c_str() );
  560. szName.length = aszTextures[iMat].length();
  561. pcMat->AddProperty(&szName,AI_MATKEY_TEXTURE_DIFFUSE(0));
  562. }
  563. }
  564. // create a default material if necessary
  565. if (0 == pScene->mNumMaterials)
  566. {
  567. pScene->mNumMaterials = 1;
  568. aiMaterial* pcHelper = new aiMaterial();
  569. pScene->mMaterials[0] = pcHelper;
  570. int iMode = (int)aiShadingMode_Gouraud;
  571. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  572. aiColor3D clr;
  573. clr.b = clr.g = clr.r = 0.7f;
  574. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  575. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  576. clr.b = clr.g = clr.r = 0.05f;
  577. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  578. aiString szName;
  579. szName.Set(AI_DEFAULT_MATERIAL_NAME);
  580. pcHelper->AddProperty(&szName,AI_MATKEY_NAME);
  581. }
  582. }
  583. // ------------------------------------------------------------------------------------------------
  584. // Parse the file
  585. void SMDImporter::ParseFile()
  586. {
  587. const char* szCurrent = mBuffer;
  588. // read line per line ...
  589. for ( ;; )
  590. {
  591. if(!SkipSpacesAndLineEnd(szCurrent,&szCurrent)) break;
  592. // "version <n> \n", <n> should be 1 for hl and hl� SMD files
  593. if (TokenMatch(szCurrent,"version",7))
  594. {
  595. if(!SkipSpaces(szCurrent,&szCurrent)) break;
  596. if (1 != strtoul10(szCurrent,&szCurrent))
  597. {
  598. DefaultLogger::get()->warn("SMD.version is not 1. This "
  599. "file format is not known. Continuing happily ...");
  600. }
  601. continue;
  602. }
  603. // "nodes\n" - Starts the node section
  604. if (TokenMatch(szCurrent,"nodes",5))
  605. {
  606. ParseNodesSection(szCurrent,&szCurrent);
  607. continue;
  608. }
  609. // "triangles\n" - Starts the triangle section
  610. if (TokenMatch(szCurrent,"triangles",9))
  611. {
  612. ParseTrianglesSection(szCurrent,&szCurrent);
  613. continue;
  614. }
  615. // "vertexanimation\n" - Starts the vertex animation section
  616. if (TokenMatch(szCurrent,"vertexanimation",15))
  617. {
  618. bHasUVs = false;
  619. ParseVASection(szCurrent,&szCurrent);
  620. continue;
  621. }
  622. // "skeleton\n" - Starts the skeleton section
  623. if (TokenMatch(szCurrent,"skeleton",8))
  624. {
  625. ParseSkeletonSection(szCurrent,&szCurrent);
  626. continue;
  627. }
  628. SkipLine(szCurrent,&szCurrent);
  629. }
  630. return;
  631. }
  632. // ------------------------------------------------------------------------------------------------
  633. unsigned int SMDImporter::GetTextureIndex(const std::string& filename)
  634. {
  635. unsigned int iIndex = 0;
  636. for (std::vector<std::string>::const_iterator
  637. i = aszTextures.begin();
  638. i != aszTextures.end();++i,++iIndex)
  639. {
  640. // case-insensitive ... it's a path
  641. if (0 == ASSIMP_stricmp ( filename.c_str(),(*i).c_str()))return iIndex;
  642. }
  643. iIndex = (unsigned int)aszTextures.size();
  644. aszTextures.push_back(filename);
  645. return iIndex;
  646. }
  647. // ------------------------------------------------------------------------------------------------
  648. // Parse the nodes section of the file
  649. void SMDImporter::ParseNodesSection(const char* szCurrent,
  650. const char** szCurrentOut)
  651. {
  652. for ( ;; )
  653. {
  654. // "end\n" - Ends the nodes section
  655. if (0 == ASSIMP_strincmp(szCurrent,"end",3) &&
  656. IsSpaceOrNewLine(*(szCurrent+3)))
  657. {
  658. szCurrent += 4;
  659. break;
  660. }
  661. ParseNodeInfo(szCurrent,&szCurrent);
  662. }
  663. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  664. *szCurrentOut = szCurrent;
  665. }
  666. // ------------------------------------------------------------------------------------------------
  667. // Parse the triangles section of the file
  668. void SMDImporter::ParseTrianglesSection(const char* szCurrent,
  669. const char** szCurrentOut)
  670. {
  671. // Parse a triangle, parse another triangle, parse the next triangle ...
  672. // and so on until we reach a token that looks quite similar to "end"
  673. for ( ;; )
  674. {
  675. if(!SkipSpacesAndLineEnd(szCurrent,&szCurrent)) break;
  676. // "end\n" - Ends the triangles section
  677. if (TokenMatch(szCurrent,"end",3))
  678. break;
  679. ParseTriangle(szCurrent,&szCurrent);
  680. }
  681. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  682. *szCurrentOut = szCurrent;
  683. }
  684. // ------------------------------------------------------------------------------------------------
  685. // Parse the vertex animation section of the file
  686. void SMDImporter::ParseVASection(const char* szCurrent,
  687. const char** szCurrentOut)
  688. {
  689. unsigned int iCurIndex = 0;
  690. for ( ;; )
  691. {
  692. if(!SkipSpacesAndLineEnd(szCurrent,&szCurrent)) break;
  693. // "end\n" - Ends the "vertexanimation" section
  694. if (TokenMatch(szCurrent,"end",3))
  695. break;
  696. // "time <n>\n"
  697. if (TokenMatch(szCurrent,"time",4))
  698. {
  699. // NOTE: The doc says that time values COULD be negative ...
  700. // NOTE2: this is the shape key -> valve docs
  701. int iTime = 0;
  702. if(!ParseSignedInt(szCurrent,&szCurrent,iTime) || configFrameID != (unsigned int)iTime)break;
  703. SkipLine(szCurrent,&szCurrent);
  704. }
  705. else
  706. {
  707. if(0 == iCurIndex)
  708. {
  709. asTriangles.push_back(SMD::Face());
  710. }
  711. if (++iCurIndex == 3)iCurIndex = 0;
  712. ParseVertex(szCurrent,&szCurrent,asTriangles.back().avVertices[iCurIndex],true);
  713. }
  714. }
  715. if (iCurIndex != 2 && !asTriangles.empty())
  716. {
  717. // we want to no degenerates, so throw this triangle away
  718. asTriangles.pop_back();
  719. }
  720. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  721. *szCurrentOut = szCurrent;
  722. }
  723. // ------------------------------------------------------------------------------------------------
  724. // Parse the skeleton section of the file
  725. void SMDImporter::ParseSkeletonSection(const char* szCurrent,
  726. const char** szCurrentOut)
  727. {
  728. int iTime = 0;
  729. for ( ;; )
  730. {
  731. if(!SkipSpacesAndLineEnd(szCurrent,&szCurrent)) break;
  732. // "end\n" - Ends the skeleton section
  733. if (TokenMatch(szCurrent,"end",3))
  734. break;
  735. // "time <n>\n" - Specifies the current animation frame
  736. else if (TokenMatch(szCurrent,"time",4))
  737. {
  738. // NOTE: The doc says that time values COULD be negative ...
  739. if(!ParseSignedInt(szCurrent,&szCurrent,iTime))break;
  740. iSmallestFrame = std::min(iSmallestFrame,iTime);
  741. SkipLine(szCurrent,&szCurrent);
  742. }
  743. else ParseSkeletonElement(szCurrent,&szCurrent,iTime);
  744. }
  745. *szCurrentOut = szCurrent;
  746. }
  747. // ------------------------------------------------------------------------------------------------
  748. #define SMDI_PARSE_RETURN { \
  749. SkipLine(szCurrent,&szCurrent); \
  750. *szCurrentOut = szCurrent; \
  751. return; \
  752. }
  753. // ------------------------------------------------------------------------------------------------
  754. // Parse a node line
  755. void SMDImporter::ParseNodeInfo(const char* szCurrent,
  756. const char** szCurrentOut)
  757. {
  758. unsigned int iBone = 0;
  759. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  760. if(!ParseUnsignedInt(szCurrent,&szCurrent,iBone) || !SkipSpaces(szCurrent,&szCurrent))
  761. {
  762. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone index");
  763. SMDI_PARSE_RETURN;
  764. }
  765. // add our bone to the list
  766. if (iBone >= asBones.size())asBones.resize(iBone+1);
  767. SMD::Bone& bone = asBones[iBone];
  768. bool bQuota = true;
  769. if ('\"' != *szCurrent)
  770. {
  771. LogWarning("Bone name is expcted to be enclosed in "
  772. "double quotation marks. ");
  773. bQuota = false;
  774. }
  775. else ++szCurrent;
  776. const char* szEnd = szCurrent;
  777. for ( ;; )
  778. {
  779. if (bQuota && '\"' == *szEnd)
  780. {
  781. iBone = (unsigned int)(szEnd - szCurrent);
  782. ++szEnd;
  783. break;
  784. }
  785. else if (IsSpaceOrNewLine(*szEnd))
  786. {
  787. iBone = (unsigned int)(szEnd - szCurrent);
  788. break;
  789. }
  790. else if (!(*szEnd))
  791. {
  792. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone name");
  793. SMDI_PARSE_RETURN;
  794. }
  795. ++szEnd;
  796. }
  797. bone.mName = std::string(szCurrent,iBone);
  798. szCurrent = szEnd;
  799. // the only negative bone parent index that could occur is -1 AFAIK
  800. if(!ParseSignedInt(szCurrent,&szCurrent,(int&)bone.iParent))
  801. {
  802. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone parent index. Assuming -1");
  803. SMDI_PARSE_RETURN;
  804. }
  805. // go to the beginning of the next line
  806. SMDI_PARSE_RETURN;
  807. }
  808. // ------------------------------------------------------------------------------------------------
  809. // Parse a skeleton element
  810. void SMDImporter::ParseSkeletonElement(const char* szCurrent,
  811. const char** szCurrentOut,int iTime)
  812. {
  813. aiVector3D vPos;
  814. aiVector3D vRot;
  815. unsigned int iBone = 0;
  816. if(!ParseUnsignedInt(szCurrent,&szCurrent,iBone))
  817. {
  818. DefaultLogger::get()->error("Unexpected EOF/EOL while parsing bone index");
  819. SMDI_PARSE_RETURN;
  820. }
  821. if (iBone >= asBones.size())
  822. {
  823. LogErrorNoThrow("Bone index in skeleton section is out of range");
  824. SMDI_PARSE_RETURN;
  825. }
  826. SMD::Bone& bone = asBones[iBone];
  827. bone.sAnim.asKeys.push_back(SMD::Bone::Animation::MatrixKey());
  828. SMD::Bone::Animation::MatrixKey& key = bone.sAnim.asKeys.back();
  829. key.dTime = (double)iTime;
  830. if(!ParseFloat(szCurrent,&szCurrent,(float&)vPos.x))
  831. {
  832. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.pos.x");
  833. SMDI_PARSE_RETURN;
  834. }
  835. if(!ParseFloat(szCurrent,&szCurrent,(float&)vPos.y))
  836. {
  837. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.pos.y");
  838. SMDI_PARSE_RETURN;
  839. }
  840. if(!ParseFloat(szCurrent,&szCurrent,(float&)vPos.z))
  841. {
  842. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.pos.z");
  843. SMDI_PARSE_RETURN;
  844. }
  845. if(!ParseFloat(szCurrent,&szCurrent,(float&)vRot.x))
  846. {
  847. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.rot.x");
  848. SMDI_PARSE_RETURN;
  849. }
  850. if(!ParseFloat(szCurrent,&szCurrent,(float&)vRot.y))
  851. {
  852. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.rot.y");
  853. SMDI_PARSE_RETURN;
  854. }
  855. if(!ParseFloat(szCurrent,&szCurrent,(float&)vRot.z))
  856. {
  857. LogErrorNoThrow("Unexpected EOF/EOL while parsing bone.rot.z");
  858. SMDI_PARSE_RETURN;
  859. }
  860. // build the transformation matrix of the key
  861. key.matrix.FromEulerAnglesXYZ(vRot.x,vRot.y,vRot.z);
  862. {
  863. aiMatrix4x4 mTemp;
  864. mTemp.a4 = vPos.x;
  865. mTemp.b4 = vPos.y;
  866. mTemp.c4 = vPos.z;
  867. key.matrix = key.matrix * mTemp;
  868. }
  869. // go to the beginning of the next line
  870. SMDI_PARSE_RETURN;
  871. }
  872. // ------------------------------------------------------------------------------------------------
  873. // Parse a triangle
  874. void SMDImporter::ParseTriangle(const char* szCurrent,
  875. const char** szCurrentOut)
  876. {
  877. asTriangles.push_back(SMD::Face());
  878. SMD::Face& face = asTriangles.back();
  879. if(!SkipSpaces(szCurrent,&szCurrent))
  880. {
  881. LogErrorNoThrow("Unexpected EOF/EOL while parsing a triangle");
  882. return;
  883. }
  884. // read the texture file name
  885. const char* szLast = szCurrent;
  886. while (!IsSpaceOrNewLine(*szCurrent++));
  887. // ... and get the index that belongs to this file name
  888. face.iTexture = GetTextureIndex(std::string(szLast,(uintptr_t)szCurrent-(uintptr_t)szLast));
  889. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  890. // load three vertices
  891. for (unsigned int iVert = 0; iVert < 3;++iVert)
  892. {
  893. ParseVertex(szCurrent,&szCurrent,
  894. face.avVertices[iVert]);
  895. }
  896. *szCurrentOut = szCurrent;
  897. }
  898. // ------------------------------------------------------------------------------------------------
  899. // Parse a float
  900. bool SMDImporter::ParseFloat(const char* szCurrent,
  901. const char** szCurrentOut, float& out)
  902. {
  903. if(!SkipSpaces(&szCurrent))
  904. return false;
  905. *szCurrentOut = fast_atoreal_move<float>(szCurrent,out);
  906. return true;
  907. }
  908. // ------------------------------------------------------------------------------------------------
  909. // Parse an unsigned int
  910. bool SMDImporter::ParseUnsignedInt(const char* szCurrent,
  911. const char** szCurrentOut, unsigned int& out)
  912. {
  913. if(!SkipSpaces(&szCurrent))
  914. return false;
  915. out = strtoul10(szCurrent,szCurrentOut);
  916. return true;
  917. }
  918. // ------------------------------------------------------------------------------------------------
  919. // Parse a signed int
  920. bool SMDImporter::ParseSignedInt(const char* szCurrent,
  921. const char** szCurrentOut, int& out)
  922. {
  923. if(!SkipSpaces(&szCurrent))
  924. return false;
  925. out = strtol10(szCurrent,szCurrentOut);
  926. return true;
  927. }
  928. // ------------------------------------------------------------------------------------------------
  929. // Parse a vertex
  930. void SMDImporter::ParseVertex(const char* szCurrent,
  931. const char** szCurrentOut, SMD::Vertex& vertex,
  932. bool bVASection /*= false*/)
  933. {
  934. if (SkipSpaces(&szCurrent) && IsLineEnd(*szCurrent))
  935. {
  936. SkipSpacesAndLineEnd(szCurrent,&szCurrent);
  937. return ParseVertex(szCurrent,szCurrentOut,vertex,bVASection);
  938. }
  939. if(!ParseSignedInt(szCurrent,&szCurrent,(int&)vertex.iParentNode))
  940. {
  941. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.parent");
  942. SMDI_PARSE_RETURN;
  943. }
  944. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.pos.x))
  945. {
  946. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.pos.x");
  947. SMDI_PARSE_RETURN;
  948. }
  949. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.pos.y))
  950. {
  951. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.pos.y");
  952. SMDI_PARSE_RETURN;
  953. }
  954. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.pos.z))
  955. {
  956. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.pos.z");
  957. SMDI_PARSE_RETURN;
  958. }
  959. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.nor.x))
  960. {
  961. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.nor.x");
  962. SMDI_PARSE_RETURN;
  963. }
  964. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.nor.y))
  965. {
  966. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.nor.y");
  967. SMDI_PARSE_RETURN;
  968. }
  969. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.nor.z))
  970. {
  971. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.nor.z");
  972. SMDI_PARSE_RETURN;
  973. }
  974. if (bVASection)SMDI_PARSE_RETURN;
  975. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.uv.x))
  976. {
  977. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.uv.x");
  978. SMDI_PARSE_RETURN;
  979. }
  980. if(!ParseFloat(szCurrent,&szCurrent,(float&)vertex.uv.y))
  981. {
  982. LogErrorNoThrow("Unexpected EOF/EOL while parsing vertex.uv.y");
  983. SMDI_PARSE_RETURN;
  984. }
  985. // now read the number of bones affecting this vertex
  986. // all elements from now are fully optional, we don't need them
  987. unsigned int iSize = 0;
  988. if(!ParseUnsignedInt(szCurrent,&szCurrent,iSize))SMDI_PARSE_RETURN;
  989. vertex.aiBoneLinks.resize(iSize,std::pair<unsigned int, float>(0,0.0f));
  990. for (std::vector<std::pair<unsigned int, float> >::iterator
  991. i = vertex.aiBoneLinks.begin();
  992. i != vertex.aiBoneLinks.end();++i)
  993. {
  994. if(!ParseUnsignedInt(szCurrent,&szCurrent,(*i).first))
  995. SMDI_PARSE_RETURN;
  996. if(!ParseFloat(szCurrent,&szCurrent,(*i).second))
  997. SMDI_PARSE_RETURN;
  998. }
  999. // go to the beginning of the next line
  1000. SMDI_PARSE_RETURN;
  1001. }
  1002. #endif // !! ASSIMP_BUILD_NO_SMD_IMPORTER