Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

700 linhas
24 KiB

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