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