SMDLoader.cpp 35 KB

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