SMDLoader.cpp 35 KB

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