XFileImporter.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2017, 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 XFileImporter.cpp
  35. * @brief Implementation of the XFile importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_X_IMPORTER
  38. #include "XFileImporter.h"
  39. #include "XFileParser.h"
  40. #include "TinyFormatter.h"
  41. #include "ConvertToLHProcess.h"
  42. #include <assimp/Defines.h>
  43. #include <assimp/IOSystem.hpp>
  44. #include <assimp/scene.h>
  45. #include <assimp/DefaultLogger.hpp>
  46. #include <assimp/importerdesc.h>
  47. #include <cctype>
  48. #include <memory>
  49. using namespace Assimp;
  50. using namespace Assimp::Formatter;
  51. static const aiImporterDesc desc = {
  52. "Direct3D XFile Importer",
  53. "",
  54. "",
  55. "",
  56. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour,
  57. 1,
  58. 3,
  59. 1,
  60. 5,
  61. "x"
  62. };
  63. // ------------------------------------------------------------------------------------------------
  64. // Constructor to be privately used by Importer
  65. XFileImporter::XFileImporter()
  66. {}
  67. // ------------------------------------------------------------------------------------------------
  68. // Destructor, private as well
  69. XFileImporter::~XFileImporter()
  70. {}
  71. // ------------------------------------------------------------------------------------------------
  72. // Returns whether the class can handle the format of the given file.
  73. bool XFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  74. {
  75. std::string extension = GetExtension(pFile);
  76. if(extension == "x") {
  77. return true;
  78. }
  79. if (!extension.length() || checkSig) {
  80. uint32_t token[1];
  81. token[0] = AI_MAKE_MAGIC("xof ");
  82. return CheckMagicToken(pIOHandler,pFile,token,1,0);
  83. }
  84. return false;
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // Get file extension list
  88. const aiImporterDesc* XFileImporter::GetInfo () const
  89. {
  90. return &desc;
  91. }
  92. // ------------------------------------------------------------------------------------------------
  93. // Imports the given file into the given scene structure.
  94. void XFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  95. {
  96. // read file into memory
  97. std::unique_ptr<IOStream> file( pIOHandler->Open( pFile));
  98. if( file.get() == NULL)
  99. throw DeadlyImportError( "Failed to open file " + pFile + ".");
  100. size_t fileSize = file->FileSize();
  101. if( fileSize < 16)
  102. throw DeadlyImportError( "XFile is too small.");
  103. // in the hope that binary files will never start with a BOM ...
  104. mBuffer.resize( fileSize + 1);
  105. file->Read( &mBuffer.front(), 1, fileSize);
  106. ConvertToUTF8(mBuffer);
  107. // parse the file into a temporary representation
  108. XFileParser parser( mBuffer);
  109. // and create the proper return structures out of it
  110. CreateDataRepresentationFromImport( pScene, parser.GetImportedData());
  111. // if nothing came from it, report it as error
  112. if( !pScene->mRootNode)
  113. throw DeadlyImportError( "XFile is ill-formatted - no content imported.");
  114. }
  115. // ------------------------------------------------------------------------------------------------
  116. // Constructs the return data structure out of the imported data.
  117. void XFileImporter::CreateDataRepresentationFromImport( aiScene* pScene, XFile::Scene* pData)
  118. {
  119. // Read the global materials first so that meshes referring to them can find them later
  120. ConvertMaterials( pScene, pData->mGlobalMaterials);
  121. // copy nodes, extracting meshes and materials on the way
  122. pScene->mRootNode = CreateNodes( pScene, NULL, pData->mRootNode);
  123. // extract animations
  124. CreateAnimations( pScene, pData);
  125. // read the global meshes that were stored outside of any node
  126. if( pData->mGlobalMeshes.size() > 0)
  127. {
  128. // create a root node to hold them if there isn't any, yet
  129. if( pScene->mRootNode == NULL)
  130. {
  131. pScene->mRootNode = new aiNode;
  132. pScene->mRootNode->mName.Set( "$dummy_node");
  133. }
  134. // convert all global meshes and store them in the root node.
  135. // If there was one before, the global meshes now suddenly have its transformation matrix...
  136. // Don't know what to do there, I don't want to insert another node under the present root node
  137. // just to avoid this.
  138. CreateMeshes( pScene, pScene->mRootNode, pData->mGlobalMeshes);
  139. }
  140. if (!pScene->mRootNode) {
  141. throw DeadlyImportError( "No root node" );
  142. }
  143. // Convert everything to OpenGL space... it's the same operation as the conversion back, so we can reuse the step directly
  144. MakeLeftHandedProcess convertProcess;
  145. convertProcess.Execute( pScene);
  146. FlipWindingOrderProcess flipper;
  147. flipper.Execute(pScene);
  148. // finally: create a dummy material if not material was imported
  149. if( pScene->mNumMaterials == 0)
  150. {
  151. pScene->mNumMaterials = 1;
  152. // create the Material
  153. aiMaterial* mat = new aiMaterial;
  154. int shadeMode = (int) aiShadingMode_Gouraud;
  155. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  156. // material colours
  157. int specExp = 1;
  158. aiColor3D clr = aiColor3D( 0, 0, 0);
  159. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_EMISSIVE);
  160. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_SPECULAR);
  161. clr = aiColor3D( 0.5f, 0.5f, 0.5f);
  162. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  163. mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
  164. pScene->mMaterials = new aiMaterial*[1];
  165. pScene->mMaterials[0] = mat;
  166. }
  167. }
  168. // ------------------------------------------------------------------------------------------------
  169. // Recursively creates scene nodes from the imported hierarchy.
  170. aiNode* XFileImporter::CreateNodes( aiScene* pScene, aiNode* pParent, const XFile::Node* pNode)
  171. {
  172. if( !pNode)
  173. return NULL;
  174. // create node
  175. aiNode* node = new aiNode;
  176. node->mName.length = pNode->mName.length();
  177. node->mParent = pParent;
  178. memcpy( node->mName.data, pNode->mName.c_str(), pNode->mName.length());
  179. node->mName.data[node->mName.length] = 0;
  180. node->mTransformation = pNode->mTrafoMatrix;
  181. // convert meshes from the source node
  182. CreateMeshes( pScene, node, pNode->mMeshes);
  183. // handle childs
  184. if( pNode->mChildren.size() > 0)
  185. {
  186. node->mNumChildren = (unsigned int)pNode->mChildren.size();
  187. node->mChildren = new aiNode* [node->mNumChildren];
  188. for( unsigned int a = 0; a < pNode->mChildren.size(); a++)
  189. node->mChildren[a] = CreateNodes( pScene, node, pNode->mChildren[a]);
  190. }
  191. return node;
  192. }
  193. // ------------------------------------------------------------------------------------------------
  194. // Creates the meshes for the given node.
  195. void XFileImporter::CreateMeshes( aiScene* pScene, aiNode* pNode, const std::vector<XFile::Mesh*>& pMeshes)
  196. {
  197. if (pMeshes.empty()) {
  198. return;
  199. }
  200. // create a mesh for each mesh-material combination in the source node
  201. std::vector<aiMesh*> meshes;
  202. for( unsigned int a = 0; a < pMeshes.size(); a++)
  203. {
  204. XFile::Mesh* sourceMesh = pMeshes[a];
  205. // first convert its materials so that we can find them with their index afterwards
  206. ConvertMaterials( pScene, sourceMesh->mMaterials);
  207. unsigned int numMaterials = std::max( (unsigned int)sourceMesh->mMaterials.size(), 1u);
  208. for( unsigned int b = 0; b < numMaterials; b++)
  209. {
  210. // collect the faces belonging to this material
  211. std::vector<unsigned int> faces;
  212. unsigned int numVertices = 0;
  213. if( sourceMesh->mFaceMaterials.size() > 0)
  214. {
  215. // if there is a per-face material defined, select the faces with the corresponding material
  216. for( unsigned int c = 0; c < sourceMesh->mFaceMaterials.size(); c++)
  217. {
  218. if( sourceMesh->mFaceMaterials[c] == b)
  219. {
  220. faces.push_back( c);
  221. numVertices += (unsigned int)sourceMesh->mPosFaces[c].mIndices.size();
  222. }
  223. }
  224. } else
  225. {
  226. // if there is no per-face material, place everything into one mesh
  227. for( unsigned int c = 0; c < sourceMesh->mPosFaces.size(); c++)
  228. {
  229. faces.push_back( c);
  230. numVertices += (unsigned int)sourceMesh->mPosFaces[c].mIndices.size();
  231. }
  232. }
  233. // no faces/vertices using this material? strange...
  234. if( numVertices == 0)
  235. continue;
  236. // create a submesh using this material
  237. aiMesh* mesh = new aiMesh;
  238. meshes.push_back( mesh);
  239. // find the material in the scene's material list. Either own material
  240. // or referenced material, it should already have a valid index
  241. if( sourceMesh->mFaceMaterials.size() > 0)
  242. {
  243. mesh->mMaterialIndex = static_cast<unsigned int>(sourceMesh->mMaterials[b].sceneIndex);
  244. } else
  245. {
  246. mesh->mMaterialIndex = 0;
  247. }
  248. // Create properly sized data arrays in the mesh. We store unique vertices per face,
  249. // as specified
  250. mesh->mNumVertices = numVertices;
  251. mesh->mVertices = new aiVector3D[numVertices];
  252. mesh->mNumFaces = (unsigned int)faces.size();
  253. mesh->mFaces = new aiFace[mesh->mNumFaces];
  254. // name
  255. mesh->mName.Set(sourceMesh->mName);
  256. // normals?
  257. if( sourceMesh->mNormals.size() > 0)
  258. mesh->mNormals = new aiVector3D[numVertices];
  259. // texture coords
  260. for( unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; c++)
  261. {
  262. if( sourceMesh->mTexCoords[c].size() > 0)
  263. mesh->mTextureCoords[c] = new aiVector3D[numVertices];
  264. }
  265. // vertex colors
  266. for( unsigned int c = 0; c < AI_MAX_NUMBER_OF_COLOR_SETS; c++)
  267. {
  268. if( sourceMesh->mColors[c].size() > 0)
  269. mesh->mColors[c] = new aiColor4D[numVertices];
  270. }
  271. // now collect the vertex data of all data streams present in the imported mesh
  272. unsigned int newIndex = 0;
  273. std::vector<unsigned int> orgPoints; // from which original point each new vertex stems
  274. orgPoints.resize( numVertices, 0);
  275. for( unsigned int c = 0; c < faces.size(); c++)
  276. {
  277. unsigned int f = faces[c]; // index of the source face
  278. const XFile::Face& pf = sourceMesh->mPosFaces[f]; // position source face
  279. // create face. either triangle or triangle fan depending on the index count
  280. aiFace& df = mesh->mFaces[c]; // destination face
  281. df.mNumIndices = (unsigned int)pf.mIndices.size();
  282. df.mIndices = new unsigned int[ df.mNumIndices];
  283. // collect vertex data for indices of this face
  284. for( unsigned int d = 0; d < df.mNumIndices; d++)
  285. {
  286. df.mIndices[d] = newIndex;
  287. orgPoints[newIndex] = pf.mIndices[d];
  288. // Position
  289. mesh->mVertices[newIndex] = sourceMesh->mPositions[pf.mIndices[d]];
  290. // Normal, if present
  291. if( mesh->HasNormals())
  292. mesh->mNormals[newIndex] = sourceMesh->mNormals[sourceMesh->mNormFaces[f].mIndices[d]];
  293. // texture coord sets
  294. for( unsigned int e = 0; e < AI_MAX_NUMBER_OF_TEXTURECOORDS; e++)
  295. {
  296. if( mesh->HasTextureCoords( e))
  297. {
  298. aiVector2D tex = sourceMesh->mTexCoords[e][pf.mIndices[d]];
  299. mesh->mTextureCoords[e][newIndex] = aiVector3D( tex.x, 1.0f - tex.y, 0.0f);
  300. }
  301. }
  302. // vertex color sets
  303. for( unsigned int e = 0; e < AI_MAX_NUMBER_OF_COLOR_SETS; e++)
  304. if( mesh->HasVertexColors( e))
  305. mesh->mColors[e][newIndex] = sourceMesh->mColors[e][pf.mIndices[d]];
  306. newIndex++;
  307. }
  308. }
  309. // there should be as much new vertices as we calculated before
  310. ai_assert( newIndex == numVertices);
  311. // convert all bones of the source mesh which influence vertices in this newly created mesh
  312. const std::vector<XFile::Bone>& bones = sourceMesh->mBones;
  313. std::vector<aiBone*> newBones;
  314. for( unsigned int c = 0; c < bones.size(); c++)
  315. {
  316. const XFile::Bone& obone = bones[c];
  317. // set up a vertex-linear array of the weights for quick searching if a bone influences a vertex
  318. std::vector<ai_real> oldWeights( sourceMesh->mPositions.size(), 0.0);
  319. for( unsigned int d = 0; d < obone.mWeights.size(); d++)
  320. oldWeights[obone.mWeights[d].mVertex] = obone.mWeights[d].mWeight;
  321. // collect all vertex weights that influence a vertex in the new mesh
  322. std::vector<aiVertexWeight> newWeights;
  323. newWeights.reserve( numVertices);
  324. for( unsigned int d = 0; d < orgPoints.size(); d++)
  325. {
  326. // does the new vertex stem from an old vertex which was influenced by this bone?
  327. ai_real w = oldWeights[orgPoints[d]];
  328. if( w > 0.0)
  329. newWeights.push_back( aiVertexWeight( d, w));
  330. }
  331. // if the bone has no weights in the newly created mesh, ignore it
  332. if( newWeights.size() == 0)
  333. continue;
  334. // create
  335. aiBone* nbone = new aiBone;
  336. newBones.push_back( nbone);
  337. // copy name and matrix
  338. nbone->mName.Set( obone.mName);
  339. nbone->mOffsetMatrix = obone.mOffsetMatrix;
  340. nbone->mNumWeights = (unsigned int)newWeights.size();
  341. nbone->mWeights = new aiVertexWeight[nbone->mNumWeights];
  342. for( unsigned int d = 0; d < newWeights.size(); d++)
  343. nbone->mWeights[d] = newWeights[d];
  344. }
  345. // store the bones in the mesh
  346. mesh->mNumBones = (unsigned int)newBones.size();
  347. if( newBones.size() > 0)
  348. {
  349. mesh->mBones = new aiBone*[mesh->mNumBones];
  350. std::copy( newBones.begin(), newBones.end(), mesh->mBones);
  351. }
  352. }
  353. }
  354. // reallocate scene mesh array to be large enough
  355. aiMesh** prevArray = pScene->mMeshes;
  356. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes + meshes.size()];
  357. if( prevArray)
  358. {
  359. memcpy( pScene->mMeshes, prevArray, pScene->mNumMeshes * sizeof( aiMesh*));
  360. delete [] prevArray;
  361. }
  362. // allocate mesh index array in the node
  363. pNode->mNumMeshes = (unsigned int)meshes.size();
  364. pNode->mMeshes = new unsigned int[pNode->mNumMeshes];
  365. // store all meshes in the mesh library of the scene and store their indices in the node
  366. for( unsigned int a = 0; a < meshes.size(); a++)
  367. {
  368. pScene->mMeshes[pScene->mNumMeshes] = meshes[a];
  369. pNode->mMeshes[a] = pScene->mNumMeshes;
  370. pScene->mNumMeshes++;
  371. }
  372. }
  373. // ------------------------------------------------------------------------------------------------
  374. // Converts the animations from the given imported data and creates them in the scene.
  375. void XFileImporter::CreateAnimations( aiScene* pScene, const XFile::Scene* pData)
  376. {
  377. std::vector<aiAnimation*> newAnims;
  378. for( unsigned int a = 0; a < pData->mAnims.size(); a++)
  379. {
  380. const XFile::Animation* anim = pData->mAnims[a];
  381. // some exporters mock me with empty animation tags.
  382. if( anim->mAnims.size() == 0)
  383. continue;
  384. // create a new animation to hold the data
  385. aiAnimation* nanim = new aiAnimation;
  386. newAnims.push_back( nanim);
  387. nanim->mName.Set( anim->mName);
  388. // duration will be determined by the maximum length
  389. nanim->mDuration = 0;
  390. nanim->mTicksPerSecond = pData->mAnimTicksPerSecond;
  391. nanim->mNumChannels = (unsigned int)anim->mAnims.size();
  392. nanim->mChannels = new aiNodeAnim*[nanim->mNumChannels];
  393. for( unsigned int b = 0; b < anim->mAnims.size(); b++)
  394. {
  395. const XFile::AnimBone* bone = anim->mAnims[b];
  396. aiNodeAnim* nbone = new aiNodeAnim;
  397. nbone->mNodeName.Set( bone->mBoneName);
  398. nanim->mChannels[b] = nbone;
  399. // keyframes are given as combined transformation matrix keys
  400. if( bone->mTrafoKeys.size() > 0)
  401. {
  402. nbone->mNumPositionKeys = (unsigned int)bone->mTrafoKeys.size();
  403. nbone->mPositionKeys = new aiVectorKey[nbone->mNumPositionKeys];
  404. nbone->mNumRotationKeys = (unsigned int)bone->mTrafoKeys.size();
  405. nbone->mRotationKeys = new aiQuatKey[nbone->mNumRotationKeys];
  406. nbone->mNumScalingKeys = (unsigned int)bone->mTrafoKeys.size();
  407. nbone->mScalingKeys = new aiVectorKey[nbone->mNumScalingKeys];
  408. for( unsigned int c = 0; c < bone->mTrafoKeys.size(); c++)
  409. {
  410. // deconstruct each matrix into separate position, rotation and scaling
  411. double time = bone->mTrafoKeys[c].mTime;
  412. aiMatrix4x4 trafo = bone->mTrafoKeys[c].mMatrix;
  413. // extract position
  414. aiVector3D pos( trafo.a4, trafo.b4, trafo.c4);
  415. nbone->mPositionKeys[c].mTime = time;
  416. nbone->mPositionKeys[c].mValue = pos;
  417. // extract scaling
  418. aiVector3D scale;
  419. scale.x = aiVector3D( trafo.a1, trafo.b1, trafo.c1).Length();
  420. scale.y = aiVector3D( trafo.a2, trafo.b2, trafo.c2).Length();
  421. scale.z = aiVector3D( trafo.a3, trafo.b3, trafo.c3).Length();
  422. nbone->mScalingKeys[c].mTime = time;
  423. nbone->mScalingKeys[c].mValue = scale;
  424. // reconstruct rotation matrix without scaling
  425. aiMatrix3x3 rotmat(
  426. trafo.a1 / scale.x, trafo.a2 / scale.y, trafo.a3 / scale.z,
  427. trafo.b1 / scale.x, trafo.b2 / scale.y, trafo.b3 / scale.z,
  428. trafo.c1 / scale.x, trafo.c2 / scale.y, trafo.c3 / scale.z);
  429. // and convert it into a quaternion
  430. nbone->mRotationKeys[c].mTime = time;
  431. nbone->mRotationKeys[c].mValue = aiQuaternion( rotmat);
  432. }
  433. // longest lasting key sequence determines duration
  434. nanim->mDuration = std::max( nanim->mDuration, bone->mTrafoKeys.back().mTime);
  435. } else
  436. {
  437. // separate key sequences for position, rotation, scaling
  438. nbone->mNumPositionKeys = (unsigned int)bone->mPosKeys.size();
  439. nbone->mPositionKeys = new aiVectorKey[nbone->mNumPositionKeys];
  440. for( unsigned int c = 0; c < nbone->mNumPositionKeys; c++)
  441. {
  442. aiVector3D pos = bone->mPosKeys[c].mValue;
  443. nbone->mPositionKeys[c].mTime = bone->mPosKeys[c].mTime;
  444. nbone->mPositionKeys[c].mValue = pos;
  445. }
  446. // rotation
  447. nbone->mNumRotationKeys = (unsigned int)bone->mRotKeys.size();
  448. nbone->mRotationKeys = new aiQuatKey[nbone->mNumRotationKeys];
  449. for( unsigned int c = 0; c < nbone->mNumRotationKeys; c++)
  450. {
  451. aiMatrix3x3 rotmat = bone->mRotKeys[c].mValue.GetMatrix();
  452. nbone->mRotationKeys[c].mTime = bone->mRotKeys[c].mTime;
  453. nbone->mRotationKeys[c].mValue = aiQuaternion( rotmat);
  454. nbone->mRotationKeys[c].mValue.w *= -1.0f; // needs quat inversion
  455. }
  456. // scaling
  457. nbone->mNumScalingKeys = (unsigned int)bone->mScaleKeys.size();
  458. nbone->mScalingKeys = new aiVectorKey[nbone->mNumScalingKeys];
  459. for( unsigned int c = 0; c < nbone->mNumScalingKeys; c++)
  460. nbone->mScalingKeys[c] = bone->mScaleKeys[c];
  461. // longest lasting key sequence determines duration
  462. if( bone->mPosKeys.size() > 0)
  463. nanim->mDuration = std::max( nanim->mDuration, bone->mPosKeys.back().mTime);
  464. if( bone->mRotKeys.size() > 0)
  465. nanim->mDuration = std::max( nanim->mDuration, bone->mRotKeys.back().mTime);
  466. if( bone->mScaleKeys.size() > 0)
  467. nanim->mDuration = std::max( nanim->mDuration, bone->mScaleKeys.back().mTime);
  468. }
  469. }
  470. }
  471. // store all converted animations in the scene
  472. if( newAnims.size() > 0)
  473. {
  474. pScene->mNumAnimations = (unsigned int)newAnims.size();
  475. pScene->mAnimations = new aiAnimation* [pScene->mNumAnimations];
  476. for( unsigned int a = 0; a < newAnims.size(); a++)
  477. pScene->mAnimations[a] = newAnims[a];
  478. }
  479. }
  480. // ------------------------------------------------------------------------------------------------
  481. // Converts all materials in the given array and stores them in the scene's material list.
  482. void XFileImporter::ConvertMaterials( aiScene* pScene, std::vector<XFile::Material>& pMaterials)
  483. {
  484. // count the non-referrer materials in the array
  485. unsigned int numNewMaterials = 0;
  486. for( unsigned int a = 0; a < pMaterials.size(); a++)
  487. if( !pMaterials[a].mIsReference)
  488. numNewMaterials++;
  489. // resize the scene's material list to offer enough space for the new materials
  490. if( numNewMaterials > 0 )
  491. {
  492. aiMaterial** prevMats = pScene->mMaterials;
  493. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials + numNewMaterials];
  494. if( prevMats)
  495. {
  496. memcpy( pScene->mMaterials, prevMats, pScene->mNumMaterials * sizeof( aiMaterial*));
  497. delete [] prevMats;
  498. }
  499. }
  500. // convert all the materials given in the array
  501. for( unsigned int a = 0; a < pMaterials.size(); a++)
  502. {
  503. XFile::Material& oldMat = pMaterials[a];
  504. if( oldMat.mIsReference)
  505. {
  506. // find the material it refers to by name, and store its index
  507. for( size_t a = 0; a < pScene->mNumMaterials; ++a )
  508. {
  509. aiString name;
  510. pScene->mMaterials[a]->Get( AI_MATKEY_NAME, name);
  511. if( strcmp( name.C_Str(), oldMat.mName.data()) == 0 )
  512. {
  513. oldMat.sceneIndex = a;
  514. break;
  515. }
  516. }
  517. if( oldMat.sceneIndex == SIZE_MAX )
  518. {
  519. DefaultLogger::get()->warn( format() << "Could not resolve global material reference \"" << oldMat.mName << "\"" );
  520. oldMat.sceneIndex = 0;
  521. }
  522. continue;
  523. }
  524. aiMaterial* mat = new aiMaterial;
  525. aiString name;
  526. name.Set( oldMat.mName);
  527. mat->AddProperty( &name, AI_MATKEY_NAME);
  528. // Shading model: hardcoded to PHONG, there is no such information in an XFile
  529. // FIX (aramis): If the specular exponent is 0, use gouraud shading. This is a bugfix
  530. // for some models in the SDK (e.g. good old tiny.x)
  531. int shadeMode = (int)oldMat.mSpecularExponent == 0.0f
  532. ? aiShadingMode_Gouraud : aiShadingMode_Phong;
  533. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  534. // material colours
  535. // Unclear: there's no ambient colour, but emissive. What to put for ambient?
  536. // Probably nothing at all, let the user select a suitable default.
  537. mat->AddProperty( &oldMat.mEmissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  538. mat->AddProperty( &oldMat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  539. mat->AddProperty( &oldMat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  540. mat->AddProperty( &oldMat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  541. // texture, if there is one
  542. if (1 == oldMat.mTextures.size())
  543. {
  544. const XFile::TexEntry& otex = oldMat.mTextures.back();
  545. if (otex.mName.length())
  546. {
  547. // if there is only one texture assume it contains the diffuse color
  548. aiString tex( otex.mName);
  549. if( otex.mIsNormalMap)
  550. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_NORMALS(0));
  551. else
  552. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE(0));
  553. }
  554. }
  555. else
  556. {
  557. // Otherwise ... try to search for typical strings in the
  558. // texture's file name like 'bump' or 'diffuse'
  559. unsigned int iHM = 0,iNM = 0,iDM = 0,iSM = 0,iAM = 0,iEM = 0;
  560. for( unsigned int b = 0; b < oldMat.mTextures.size(); b++)
  561. {
  562. const XFile::TexEntry& otex = oldMat.mTextures[b];
  563. std::string sz = otex.mName;
  564. if (!sz.length())continue;
  565. // find the file name
  566. //const size_t iLen = sz.length();
  567. std::string::size_type s = sz.find_last_of("\\/");
  568. if (std::string::npos == s)
  569. s = 0;
  570. // cut off the file extension
  571. std::string::size_type sExt = sz.find_last_of('.');
  572. if (std::string::npos != sExt){
  573. sz[sExt] = '\0';
  574. }
  575. // convert to lower case for easier comparison
  576. for( unsigned int c = 0; c < sz.length(); c++)
  577. if( isalpha( sz[c]))
  578. sz[c] = tolower( sz[c]);
  579. // Place texture filename property under the corresponding name
  580. aiString tex( oldMat.mTextures[b].mName);
  581. // bump map
  582. if (std::string::npos != sz.find("bump", s) || std::string::npos != sz.find("height", s))
  583. {
  584. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_HEIGHT(iHM++));
  585. } else
  586. if (otex.mIsNormalMap || std::string::npos != sz.find( "normal", s) || std::string::npos != sz.find("nm", s))
  587. {
  588. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_NORMALS(iNM++));
  589. } else
  590. if (std::string::npos != sz.find( "spec", s) || std::string::npos != sz.find( "glanz", s))
  591. {
  592. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_SPECULAR(iSM++));
  593. } else
  594. if (std::string::npos != sz.find( "ambi", s) || std::string::npos != sz.find( "env", s))
  595. {
  596. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_AMBIENT(iAM++));
  597. } else
  598. if (std::string::npos != sz.find( "emissive", s) || std::string::npos != sz.find( "self", s))
  599. {
  600. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_EMISSIVE(iEM++));
  601. } else
  602. {
  603. // Assume it is a diffuse texture
  604. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE(iDM++));
  605. }
  606. }
  607. }
  608. pScene->mMaterials[pScene->mNumMaterials] = mat;
  609. oldMat.sceneIndex = pScene->mNumMaterials;
  610. pScene->mNumMaterials++;
  611. }
  612. }
  613. #endif // !! ASSIMP_BUILD_NO_X_IMPORTER