XFileImporter.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Implementation of the XFile importer class */
  35. #include "AssimpPCH.h"
  36. #include "XFileImporter.h"
  37. #include "XFileParser.h"
  38. #include "MaterialSystem.h"
  39. #include "ConvertToLHProcess.h"
  40. using namespace Assimp;
  41. #if _MSC_VER >= 1400
  42. # define sprintf sprintf_s
  43. #endif
  44. // ------------------------------------------------------------------------------------------------
  45. // Constructor to be privately used by Importer
  46. XFileImporter::XFileImporter()
  47. {
  48. }
  49. // ------------------------------------------------------------------------------------------------
  50. // Destructor, private as well
  51. XFileImporter::~XFileImporter()
  52. {
  53. }
  54. // ------------------------------------------------------------------------------------------------
  55. // Returns whether the class can handle the format of the given file.
  56. bool XFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler) const
  57. {
  58. // simple check of file extension is enough for the moment
  59. std::string::size_type pos = pFile.find_last_of( '.');
  60. // no file extension - can't read
  61. if( pos == std::string::npos)
  62. return false;
  63. std::string extension = pFile.substr( pos);
  64. if( extension == ".x" || extension == ".X")
  65. return true;
  66. return false;
  67. }
  68. // ------------------------------------------------------------------------------------------------
  69. // Imports the given file into the given scene structure.
  70. void XFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  71. {
  72. // read file into memory
  73. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  74. if( file.get() == NULL)
  75. throw new ImportErrorException( "Failed to open file " + pFile + ".");
  76. size_t fileSize = file->FileSize();
  77. if( fileSize < 16)
  78. throw new ImportErrorException( "XFile is too small.");
  79. mBuffer.resize( fileSize);
  80. file->Read( &mBuffer.front(), 1, fileSize);
  81. // parse the file into a temporary representation
  82. XFileParser parser( mBuffer);
  83. // and create the proper return structures out of it
  84. CreateDataRepresentationFromImport( pScene, parser.GetImportedData());
  85. // if nothing came from it, report it as error
  86. if( !pScene->mRootNode)
  87. throw new ImportErrorException( "XFile is ill-formatted - no content imported.");
  88. }
  89. // ------------------------------------------------------------------------------------------------
  90. // Constructs the return data structure out of the imported data.
  91. void XFileImporter::CreateDataRepresentationFromImport( aiScene* pScene, const XFile::Scene* pData)
  92. {
  93. // Read the global materials first so that meshes referring to them can find them later
  94. ConvertMaterials( pScene, pData->mGlobalMaterials);
  95. // copy nodes, extracting meshes and materials on the way
  96. pScene->mRootNode = CreateNodes( pScene, NULL, pData->mRootNode);
  97. // extract animations
  98. CreateAnimations( pScene, pData);
  99. // read the global meshes that were stored outside of any node
  100. if( pData->mGlobalMeshes.size() > 0)
  101. {
  102. // create a root node to hold them if there isn't any, yet
  103. if( pScene->mRootNode == NULL)
  104. {
  105. pScene->mRootNode = new aiNode;
  106. pScene->mRootNode->mName.Set( "$dummy_node");
  107. }
  108. // convert all global meshes and store them in the root node.
  109. // If there was one before, the global meshes now suddenly have its transformation matrix...
  110. // Don't know what to do there, I don't want to insert another node under the present root node
  111. // just to avoid this.
  112. CreateMeshes( pScene, pScene->mRootNode, pData->mGlobalMeshes);
  113. }
  114. // convert the root node's transformation to OGL coords
  115. if( pScene->mRootNode)
  116. ConvertToLHProcess::ConvertToOGL( pScene->mRootNode->mTransformation);
  117. // finally: create a dummy material if not material was imported
  118. if( pScene->mNumMaterials == 0)
  119. {
  120. pScene->mNumMaterials = 1;
  121. // create the Material
  122. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  123. int shadeMode = (int) aiShadingMode_Gouraud;
  124. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  125. // material colours
  126. int specExp = 1;
  127. aiColor3D clr = aiColor3D( 0, 0, 0);
  128. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_EMISSIVE);
  129. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_SPECULAR);
  130. clr = aiColor3D( 0.5f, 0.5f, 0.5f);
  131. mat->AddProperty( &clr, 1, AI_MATKEY_COLOR_DIFFUSE);
  132. mat->AddProperty( &specExp, 1, AI_MATKEY_SHININESS);
  133. pScene->mMaterials = new aiMaterial*[1];
  134. pScene->mMaterials[0] = mat;
  135. }
  136. }
  137. // ------------------------------------------------------------------------------------------------
  138. // Recursively creates scene nodes from the imported hierarchy.
  139. aiNode* XFileImporter::CreateNodes( aiScene* pScene, aiNode* pParent, const XFile::Node* pNode)
  140. {
  141. if( !pNode)
  142. return NULL;
  143. // create node
  144. aiNode* node = new aiNode;
  145. node->mName.length = pNode->mName.length();
  146. node->mParent = pParent;
  147. memcpy( node->mName.data, pNode->mName.c_str(), pNode->mName.length());
  148. node->mName.data[node->mName.length] = 0;
  149. node->mTransformation = pNode->mTrafoMatrix;
  150. // convert meshes from the source node
  151. CreateMeshes( pScene, node, pNode->mMeshes);
  152. // handle childs
  153. if( pNode->mChildren.size() > 0)
  154. {
  155. node->mNumChildren = (unsigned int)pNode->mChildren.size();
  156. node->mChildren = new aiNode* [node->mNumChildren];
  157. for( unsigned int a = 0; a < pNode->mChildren.size(); a++)
  158. node->mChildren[a] = CreateNodes( pScene, node, pNode->mChildren[a]);
  159. }
  160. return node;
  161. }
  162. // ------------------------------------------------------------------------------------------------
  163. // Creates the meshes for the given node.
  164. void XFileImporter::CreateMeshes( aiScene* pScene, aiNode* pNode, const std::vector<XFile::Mesh*>& pMeshes)
  165. {
  166. if( pMeshes.size() == 0)
  167. return;
  168. // create a mesh for each mesh-material combination in the source node
  169. std::vector<aiMesh*> meshes;
  170. for( unsigned int a = 0; a < pMeshes.size(); a++)
  171. {
  172. const XFile::Mesh* sourceMesh = pMeshes[a];
  173. // first convert its materials so that we can find them when searching by name afterwards
  174. ConvertMaterials( pScene, sourceMesh->mMaterials);
  175. unsigned int numMaterials = std::max( (unsigned int)sourceMesh->mMaterials.size(), 1u);
  176. for( unsigned int b = 0; b < numMaterials; b++)
  177. {
  178. // collect the faces belonging to this material
  179. std::vector<unsigned int> faces;
  180. unsigned int numVertices = 0;
  181. if( sourceMesh->mFaceMaterials.size() > 0)
  182. {
  183. // if there is a per-face material defined, select the faces with the corresponding material
  184. for( unsigned int c = 0; c < sourceMesh->mFaceMaterials.size(); c++)
  185. {
  186. if( sourceMesh->mFaceMaterials[c] == b)
  187. {
  188. faces.push_back( c);
  189. numVertices += (unsigned int)sourceMesh->mPosFaces[c].mIndices.size();
  190. }
  191. }
  192. } else
  193. {
  194. // if there is no per-face material, place everything into one mesh
  195. for( unsigned int c = 0; c < sourceMesh->mPosFaces.size(); c++)
  196. {
  197. faces.push_back( c);
  198. numVertices += (unsigned int)sourceMesh->mPosFaces[c].mIndices.size();
  199. }
  200. }
  201. // no faces/vertices using this material? strange...
  202. if( numVertices == 0)
  203. continue;
  204. // create a submesh using this material
  205. aiMesh* mesh = new aiMesh;
  206. meshes.push_back( mesh);
  207. // find the material by name in the scene's material list. Either own material
  208. // or referenced material, it should already be found there
  209. if( sourceMesh->mFaceMaterials.size() > 0)
  210. {
  211. std::map<std::string, unsigned int>::const_iterator matIt = mImportedMats.find( sourceMesh->mMaterials[b].mName);
  212. if( matIt == mImportedMats.end())
  213. mesh->mMaterialIndex = 0;
  214. else
  215. mesh->mMaterialIndex = matIt->second;
  216. } else
  217. {
  218. mesh->mMaterialIndex = 0;
  219. }
  220. // Create properly sized data arrays in the mesh. We store unique vertices per face,
  221. // as specified
  222. mesh->mNumVertices = numVertices;
  223. mesh->mVertices = new aiVector3D[numVertices];
  224. mesh->mNumFaces = (unsigned int)faces.size();
  225. mesh->mFaces = new aiFace[mesh->mNumFaces];
  226. // normals?
  227. if( sourceMesh->mNormals.size() > 0)
  228. mesh->mNormals = new aiVector3D[numVertices];
  229. // texture coords
  230. for( unsigned int c = 0; c < AI_MAX_NUMBER_OF_TEXTURECOORDS; c++)
  231. {
  232. if( sourceMesh->mTexCoords[c].size() > 0)
  233. mesh->mTextureCoords[c] = new aiVector3D[numVertices];
  234. }
  235. // vertex colors
  236. for( unsigned int c = 0; c < AI_MAX_NUMBER_OF_COLOR_SETS; c++)
  237. {
  238. if( sourceMesh->mColors[c].size() > 0)
  239. mesh->mColors[c] = new aiColor4D[numVertices];
  240. }
  241. // now collect the vertex data of all data streams present in the imported mesh
  242. unsigned int newIndex = 0;
  243. std::vector<unsigned int> orgPoints; // from which original point each new vertex stems
  244. orgPoints.resize( numVertices, 0);
  245. for( unsigned int c = 0; c < faces.size(); c++)
  246. {
  247. unsigned int f = faces[c]; // index of the source face
  248. const XFile::Face& pf = sourceMesh->mPosFaces[f]; // position source face
  249. // create face. either triangle or triangle fan depending on the index count
  250. aiFace& df = mesh->mFaces[c]; // destination face
  251. df.mNumIndices = (unsigned int)pf.mIndices.size();
  252. df.mIndices = new unsigned int[ df.mNumIndices];
  253. // collect vertex data for indices of this face
  254. for( unsigned int d = 0; d < df.mNumIndices; d++)
  255. {
  256. df.mIndices[df.mNumIndices - 1 - d] = newIndex; // inverted face orientation for OGL
  257. orgPoints[newIndex] = pf.mIndices[d];
  258. // Position
  259. mesh->mVertices[newIndex] = sourceMesh->mPositions[pf.mIndices[d]];
  260. // Normal, if present
  261. if( mesh->HasNormals())
  262. mesh->mNormals[newIndex] = sourceMesh->mNormals[sourceMesh->mNormFaces[f].mIndices[d]];
  263. // texture coord sets
  264. for( unsigned int e = 0; e < AI_MAX_NUMBER_OF_TEXTURECOORDS; e++)
  265. {
  266. if( mesh->HasTextureCoords( e))
  267. {
  268. aiVector2D tex = sourceMesh->mTexCoords[e][pf.mIndices[d]];
  269. mesh->mTextureCoords[e][newIndex] = aiVector3D( tex.x, 1.0f - tex.y, 0.0f);
  270. }
  271. }
  272. // vertex color sets
  273. for( unsigned int e = 0; e < AI_MAX_NUMBER_OF_COLOR_SETS; e++)
  274. if( mesh->HasVertexColors( e))
  275. mesh->mColors[e][newIndex] = sourceMesh->mColors[e][pf.mIndices[d]];
  276. newIndex++;
  277. }
  278. }
  279. // there should be as much new vertices as we calculated before
  280. assert( newIndex == numVertices);
  281. // convert all bones of the source mesh which influence vertices in this newly created mesh
  282. const std::vector<XFile::Bone>& bones = sourceMesh->mBones;
  283. std::vector<aiBone*> newBones;
  284. for( unsigned int c = 0; c < bones.size(); c++)
  285. {
  286. const XFile::Bone& obone = bones[c];
  287. // set up a vertex-linear array of the weights for quick searching if a bone influences a vertex
  288. std::vector<float> oldWeights( sourceMesh->mPositions.size(), 0.0f);
  289. for( unsigned int d = 0; d < obone.mWeights.size(); d++)
  290. oldWeights[obone.mWeights[d].mVertex] = obone.mWeights[d].mWeight;
  291. // collect all vertex weights that influence a vertex in the new mesh
  292. std::vector<aiVertexWeight> newWeights;
  293. newWeights.reserve( numVertices);
  294. for( unsigned int d = 0; d < orgPoints.size(); d++)
  295. {
  296. // does the new vertex stem from an old vertex which was influenced by this bone?
  297. float w = oldWeights[orgPoints[d]];
  298. if( w > 0.0f)
  299. newWeights.push_back( aiVertexWeight( d, w));
  300. }
  301. // if the bone has no weights in the newly created mesh, ignore it
  302. if( newWeights.size() == 0)
  303. continue;
  304. // create
  305. aiBone* nbone = new aiBone;
  306. newBones.push_back( nbone);
  307. // copy name and matrix
  308. nbone->mName.Set( obone.mName);
  309. nbone->mOffsetMatrix = obone.mOffsetMatrix;
  310. nbone->mNumWeights = (unsigned int)newWeights.size();
  311. nbone->mWeights = new aiVertexWeight[nbone->mNumWeights];
  312. for( unsigned int d = 0; d < newWeights.size(); d++)
  313. nbone->mWeights[d] = newWeights[d];
  314. }
  315. // store the bones in the mesh
  316. mesh->mNumBones = (unsigned int)newBones.size();
  317. if( newBones.size() > 0)
  318. {
  319. mesh->mBones = new aiBone*[mesh->mNumBones];
  320. std::copy( newBones.begin(), newBones.end(), mesh->mBones);
  321. }
  322. }
  323. }
  324. // reallocate scene mesh array to be large enough
  325. aiMesh** prevArray = pScene->mMeshes;
  326. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes + meshes.size()];
  327. if( prevArray)
  328. {
  329. memcpy( pScene->mMeshes, prevArray, pScene->mNumMeshes * sizeof( aiMesh*));
  330. delete [] prevArray;
  331. }
  332. // allocate mesh index array in the node
  333. pNode->mNumMeshes = (unsigned int)meshes.size();
  334. pNode->mMeshes = new unsigned int[pNode->mNumMeshes];
  335. // store all meshes in the mesh library of the scene and store their indices in the node
  336. for( unsigned int a = 0; a < meshes.size(); a++)
  337. {
  338. pScene->mMeshes[pScene->mNumMeshes] = meshes[a];
  339. pNode->mMeshes[a] = pScene->mNumMeshes;
  340. pScene->mNumMeshes++;
  341. }
  342. }
  343. // ------------------------------------------------------------------------------------------------
  344. // Converts the animations from the given imported data and creates them in the scene.
  345. void XFileImporter::CreateAnimations( aiScene* pScene, const XFile::Scene* pData)
  346. {
  347. std::vector<aiAnimation*> newAnims;
  348. for( unsigned int a = 0; a < pData->mAnims.size(); a++)
  349. {
  350. const XFile::Animation* anim = pData->mAnims[a];
  351. // some exporters mock me with empty animation tags.
  352. if( anim->mAnims.size() == 0)
  353. continue;
  354. // create a new animation to hold the data
  355. aiAnimation* nanim = new aiAnimation;
  356. newAnims.push_back( nanim);
  357. nanim->mName.Set( anim->mName);
  358. // duration will be determined by the maximum length
  359. nanim->mDuration = 0;
  360. nanim->mTicksPerSecond = pData->mAnimTicksPerSecond;
  361. nanim->mNumChannels = (unsigned int)anim->mAnims.size();
  362. nanim->mChannels = new aiNodeAnim*[nanim->mNumChannels];
  363. for( unsigned int b = 0; b < anim->mAnims.size(); b++)
  364. {
  365. const XFile::AnimBone* bone = anim->mAnims[b];
  366. aiNodeAnim* nbone = new aiNodeAnim;
  367. nbone->mNodeName.Set( bone->mBoneName);
  368. nanim->mChannels[b] = nbone;
  369. // apply the LH->RH conversion if the animation affects the root bone
  370. bool isRootAnim = (bone->mBoneName == pScene->mRootNode->mName.data);
  371. // keyframes are given as combined transformation matrix keys
  372. if( bone->mTrafoKeys.size() > 0)
  373. {
  374. nbone->mNumPositionKeys = (unsigned int)bone->mTrafoKeys.size();
  375. nbone->mPositionKeys = new aiVectorKey[nbone->mNumPositionKeys];
  376. nbone->mNumRotationKeys = (unsigned int)bone->mTrafoKeys.size();
  377. nbone->mRotationKeys = new aiQuatKey[nbone->mNumRotationKeys];
  378. nbone->mNumScalingKeys = (unsigned int)bone->mTrafoKeys.size();
  379. nbone->mScalingKeys = new aiVectorKey[nbone->mNumScalingKeys];
  380. for( unsigned int c = 0; c < bone->mTrafoKeys.size(); c++)
  381. {
  382. // deconstruct each matrix into separate position, rotation and scaling
  383. double time = bone->mTrafoKeys[c].mTime;
  384. aiMatrix4x4 trafo = bone->mTrafoKeys[c].mMatrix;
  385. // extract position
  386. aiVector3D pos( trafo.a4, trafo.b4, trafo.c4);
  387. if( isRootAnim)
  388. ConvertToLHProcess::ConvertToOGL( pos);
  389. nbone->mPositionKeys[c].mTime = time;
  390. nbone->mPositionKeys[c].mValue = pos;
  391. // extract scaling
  392. aiVector3D scale;
  393. scale.x = aiVector3D( trafo.a1, trafo.b1, trafo.c1).Length();
  394. scale.y = aiVector3D( trafo.a2, trafo.b2, trafo.c2).Length();
  395. scale.z = aiVector3D( trafo.a3, trafo.b3, trafo.c3).Length();
  396. nbone->mScalingKeys[c].mTime = time;
  397. nbone->mScalingKeys[c].mValue = scale;
  398. // reconstruct rotation matrix without scaling
  399. aiMatrix3x3 rotmat(
  400. trafo.a1 / scale.x, trafo.a2 / scale.y, trafo.a3 / scale.z,
  401. trafo.b1 / scale.x, trafo.b2 / scale.y, trafo.b3 / scale.z,
  402. trafo.c1 / scale.x, trafo.c2 / scale.y, trafo.c3 / scale.z);
  403. if( isRootAnim)
  404. ConvertToLHProcess::ConvertToOGL( rotmat);
  405. // and convert it into a quaternion
  406. nbone->mRotationKeys[c].mTime = time;
  407. nbone->mRotationKeys[c].mValue = aiQuaternion( rotmat);
  408. }
  409. // longest lasting key sequence determines duration
  410. nanim->mDuration = std::max( nanim->mDuration, bone->mTrafoKeys.back().mTime);
  411. } else
  412. {
  413. // separate key sequences for position, rotation, scaling
  414. nbone->mNumPositionKeys = (unsigned int)bone->mPosKeys.size();
  415. nbone->mPositionKeys = new aiVectorKey[nbone->mNumPositionKeys];
  416. for( unsigned int c = 0; c < nbone->mNumPositionKeys; c++)
  417. {
  418. aiVector3D pos = bone->mPosKeys[c].mValue;
  419. if( isRootAnim)
  420. ConvertToLHProcess::ConvertToOGL( pos);
  421. nbone->mPositionKeys[c].mTime = bone->mPosKeys[c].mTime;
  422. nbone->mPositionKeys[c].mValue = pos;
  423. }
  424. // rotation
  425. nbone->mNumRotationKeys = (unsigned int)bone->mRotKeys.size();
  426. nbone->mRotationKeys = new aiQuatKey[nbone->mNumRotationKeys];
  427. for( unsigned int c = 0; c < nbone->mNumRotationKeys; c++)
  428. {
  429. aiMatrix3x3 rotmat = bone->mRotKeys[c].mValue.GetMatrix();
  430. if( isRootAnim)
  431. ConvertToLHProcess::ConvertToOGL( rotmat);
  432. nbone->mRotationKeys[c].mTime = bone->mRotKeys[c].mTime;
  433. nbone->mRotationKeys[c].mValue = aiQuaternion( rotmat);
  434. }
  435. // scaling
  436. nbone->mNumScalingKeys = (unsigned int)bone->mScaleKeys.size();
  437. nbone->mScalingKeys = new aiVectorKey[nbone->mNumScalingKeys];
  438. for( unsigned int c = 0; c < nbone->mNumScalingKeys; c++)
  439. nbone->mScalingKeys[c] = bone->mScaleKeys[c];
  440. // longest lasting key sequence determines duration
  441. if( bone->mPosKeys.size() > 0)
  442. nanim->mDuration = std::max( nanim->mDuration, bone->mPosKeys.back().mTime);
  443. if( bone->mRotKeys.size() > 0)
  444. nanim->mDuration = std::max( nanim->mDuration, bone->mRotKeys.back().mTime);
  445. if( bone->mScaleKeys.size() > 0)
  446. nanim->mDuration = std::max( nanim->mDuration, bone->mScaleKeys.back().mTime);
  447. }
  448. }
  449. }
  450. // store all converted animations in the scene
  451. if( newAnims.size() > 0)
  452. {
  453. pScene->mNumAnimations = (unsigned int)newAnims.size();
  454. pScene->mAnimations = new aiAnimation* [pScene->mNumAnimations];
  455. for( unsigned int a = 0; a < newAnims.size(); a++)
  456. pScene->mAnimations[a] = newAnims[a];
  457. }
  458. }
  459. // ------------------------------------------------------------------------------------------------
  460. // Converts all materials in the given array and stores them in the scene's material list.
  461. void XFileImporter::ConvertMaterials( aiScene* pScene, const std::vector<XFile::Material>& pMaterials)
  462. {
  463. // count the non-referrer materials in the array
  464. unsigned int numMaterials = 0;
  465. for( unsigned int a = 0; a < pMaterials.size(); a++)
  466. if( !pMaterials[a].mIsReference)
  467. numMaterials++;
  468. if( numMaterials == 0)
  469. return;
  470. // resize the scene's material list to offer enough space for the new materials
  471. aiMaterial** prevMats = pScene->mMaterials;
  472. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials + numMaterials];
  473. if( prevMats)
  474. {
  475. memcpy( pScene->mMaterials, prevMats, pScene->mNumMaterials * sizeof( aiMaterial*));
  476. delete [] prevMats;
  477. }
  478. // convert all the materials given in the array
  479. for( unsigned int a = 0; a < pMaterials.size(); a++)
  480. {
  481. const XFile::Material& oldMat = pMaterials[a];
  482. if( oldMat.mIsReference)
  483. continue;
  484. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  485. aiString name;
  486. name.Set( oldMat.mName);
  487. mat->AddProperty( &name, AI_MATKEY_NAME);
  488. // Shading model: hardcoded to PHONG, there is no such information in an XFile
  489. // FIX (aramis): If the specular exponent is 0, use gouraud shading. This is a bugfix
  490. // for some models in the SDK (e.g. good old tiny.x)
  491. int shadeMode = (int)oldMat.mSpecularExponent == 0.0f
  492. ? aiShadingMode_Gouraud : aiShadingMode_Phong;
  493. mat->AddProperty<int>( &shadeMode, 1, AI_MATKEY_SHADING_MODEL);
  494. // material colours
  495. // FIX: Setup this as ambient not as emissive color
  496. mat->AddProperty( &oldMat.mEmissive, 1, AI_MATKEY_COLOR_AMBIENT);
  497. mat->AddProperty( &oldMat.mDiffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  498. mat->AddProperty( &oldMat.mSpecular, 1, AI_MATKEY_COLOR_SPECULAR);
  499. mat->AddProperty( &oldMat.mSpecularExponent, 1, AI_MATKEY_SHININESS);
  500. // texture, if there is one
  501. if (1 == oldMat.mTextures.size())
  502. {
  503. const XFile::TexEntry& otex = oldMat.mTextures.back();
  504. if (otex.mName.length())
  505. {
  506. // if there is only one texture assume it contains the diffuse color
  507. aiString tex( otex.mName);
  508. if( otex.mIsNormalMap)
  509. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_NORMALS(0));
  510. else
  511. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE(0));
  512. }
  513. }
  514. else
  515. {
  516. // Otherwise ... try to search for typical strings in the
  517. // texture's file name like 'bump' or 'diffuse'
  518. unsigned int iHM = 0,iNM = 0,iDM = 0,iSM = 0,iAM = 0,iEM = 0;
  519. for( unsigned int b = 0; b < oldMat.mTextures.size(); b++)
  520. {
  521. const XFile::TexEntry& otex = oldMat.mTextures[b];
  522. std::string sz = otex.mName;
  523. if (!sz.length())continue;
  524. // find the file name
  525. const size_t iLen = sz.length();
  526. std::string::size_type s = sz.rfind('\\',iLen-1);
  527. if (std::string::npos == s)
  528. {
  529. s = sz.rfind('/',iLen-1);
  530. if (std::string::npos == s)s = 0;
  531. }
  532. // cut off the file extension
  533. std::string::size_type sExt = sz.rfind('.',iLen-1);
  534. if (std::string::npos != sExt)
  535. {
  536. sz[sExt] = '\0';
  537. }
  538. // convert to lower case for easier comparision
  539. for( unsigned int c = 0; c < sz.length(); c++)
  540. if( isalpha( sz[c]))
  541. sz[c] = tolower( sz[c]);
  542. // Place texture filename property under the corresponding name
  543. aiString tex( oldMat.mTextures[b].mName);
  544. // bump map
  545. if (std::string::npos != sz.find("bump", s) || std::string::npos != sz.find("height", s))
  546. {
  547. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_HEIGHT(iHM++));
  548. } else
  549. if (otex.mIsNormalMap || std::string::npos != sz.find( "normal", s) || std::string::npos != sz.find("nm", s))
  550. {
  551. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_NORMALS(iNM++));
  552. } else
  553. if (std::string::npos != sz.find( "spec", s) || std::string::npos != sz.find( "glanz", s))
  554. {
  555. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_SPECULAR(iSM++));
  556. } else
  557. if (std::string::npos != sz.find( "ambi", s) || std::string::npos != sz.find( "env", s))
  558. {
  559. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_AMBIENT(iAM++));
  560. } else
  561. if (std::string::npos != sz.find( "emissive", s) || std::string::npos != sz.find( "self", s))
  562. {
  563. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_EMISSIVE(iEM++));
  564. } else
  565. {
  566. // Assume it is a diffuse texture
  567. mat->AddProperty( &tex, AI_MATKEY_TEXTURE_DIFFUSE(iDM++));
  568. }
  569. }
  570. }
  571. pScene->mMaterials[pScene->mNumMaterials] = mat;
  572. mImportedMats[oldMat.mName] = pScene->mNumMaterials;
  573. pScene->mNumMaterials++;
  574. }
  575. }