SMDLoader.cpp 34 KB

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