SMDLoader.cpp 39 KB

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