No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

1142 líneas
34 KiB

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