SMDLoader.cpp 35 KB

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