SMDLoader.cpp 34 KB

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