SMDLoader.cpp 35 KB

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