XFileImporter.cpp 25 KB

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