ObjFileImporter.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, 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. #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER
  35. #include "DefaultIOSystem.h"
  36. #include "ObjFileImporter.h"
  37. #include "ObjFileParser.h"
  38. #include "ObjFileData.h"
  39. #include "IOStreamBuffer.h"
  40. #include <memory>
  41. #include <assimp/Importer.hpp>
  42. #include <assimp/scene.h>
  43. #include <assimp/ai_assert.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. static const aiImporterDesc desc = {
  46. "Wavefront Object Importer",
  47. "",
  48. "",
  49. "surfaces not supported",
  50. aiImporterFlags_SupportTextFlavour,
  51. 0,
  52. 0,
  53. 0,
  54. 0,
  55. "obj"
  56. };
  57. static const unsigned int ObjMinSize = 16;
  58. namespace Assimp {
  59. using namespace std;
  60. // ------------------------------------------------------------------------------------------------
  61. // Default constructor
  62. ObjFileImporter::ObjFileImporter() :
  63. m_Buffer(),
  64. m_pRootObject( NULL ),
  65. m_strAbsPath( "" )
  66. {
  67. DefaultIOSystem io;
  68. m_strAbsPath = io.getOsSeparator();
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Destructor.
  72. ObjFileImporter::~ObjFileImporter()
  73. {
  74. delete m_pRootObject;
  75. m_pRootObject = NULL;
  76. }
  77. // ------------------------------------------------------------------------------------------------
  78. // Returns true, if file is an obj file.
  79. bool ObjFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler , bool checkSig ) const
  80. {
  81. if(!checkSig) //Check File Extension
  82. {
  83. return SimpleExtensionCheck(pFile,"obj");
  84. }
  85. else //Check file Header
  86. {
  87. static const char *pTokens[] = { "mtllib", "usemtl", "v ", "vt ", "vn ", "o ", "g ", "s ", "f " };
  88. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, pTokens, 9 );
  89. }
  90. }
  91. // ------------------------------------------------------------------------------------------------
  92. const aiImporterDesc* ObjFileImporter::GetInfo () const
  93. {
  94. return &desc;
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. // Obj-file import implementation
  98. void ObjFileImporter::InternReadFile( const std::string &file, aiScene* pScene, IOSystem* pIOHandler) {
  99. // Read file into memory
  100. static const std::string mode = "rb";
  101. std::unique_ptr<IOStream> fileStream( pIOHandler->Open( file, mode));
  102. if( !fileStream.get() ) {
  103. throw DeadlyImportError( "Failed to open file " + file + "." );
  104. }
  105. // Get the file-size and validate it, throwing an exception when fails
  106. size_t fileSize = fileStream->FileSize();
  107. if( fileSize < ObjMinSize ) {
  108. throw DeadlyImportError( "OBJ-file is too small.");
  109. }
  110. IOStreamBuffer<char> streamedBuffer;
  111. streamedBuffer.open( fileStream.get() );
  112. // Allocate buffer and read file into it
  113. //TextFileToBuffer( fileStream.get(),m_Buffer);
  114. // Get the model name
  115. std::string modelName, folderName;
  116. std::string::size_type pos = file.find_last_of( "\\/" );
  117. if ( pos != std::string::npos ) {
  118. modelName = file.substr(pos+1, file.size() - pos - 1);
  119. folderName = file.substr( 0, pos );
  120. if ( !folderName.empty() ) {
  121. pIOHandler->PushDirectory( folderName );
  122. }
  123. } else {
  124. modelName = file;
  125. }
  126. // This next stage takes ~ 1/3th of the total readFile task
  127. // so should amount for 1/3th of the progress
  128. // only update every 100KB or it'll be too slow
  129. /*unsigned int progress = 0;
  130. unsigned int progressCounter = 0;
  131. const unsigned int updateProgressEveryBytes = 100 * 1024;
  132. const unsigned int progressTotal = static_cast<unsigned int>(3*m_Buffer.size()/updateProgressEveryBytes);*/
  133. // process all '\'
  134. /*std::vector<char> ::iterator iter = m_Buffer.begin();
  135. while (iter != m_Buffer.end())
  136. {
  137. if (*iter == '\\')
  138. {
  139. // remove '\'
  140. iter = m_Buffer.erase(iter);
  141. // remove next character
  142. while (*iter == '\r' || *iter == '\n')
  143. iter = m_Buffer.erase(iter);
  144. }
  145. else
  146. ++iter;
  147. if (++progressCounter >= updateProgressEveryBytes)
  148. {
  149. m_progress->UpdateFileRead(++progress, progressTotal);
  150. progressCounter = 0;
  151. }
  152. }*/
  153. // 1/3rd progress
  154. m_progress->UpdateFileRead(1, 3);
  155. // parse the file into a temporary representation
  156. ObjFileParser parser( streamedBuffer, modelName, pIOHandler, m_progress, file);
  157. // And create the proper return structures out of it
  158. CreateDataFromImport(parser.GetModel(), pScene);
  159. streamedBuffer.close();
  160. // Clean up allocated storage for the next import
  161. m_Buffer.clear();
  162. // Pop directory stack
  163. if ( pIOHandler->StackSize() > 0 ) {
  164. pIOHandler->PopDirectory();
  165. }
  166. }
  167. // ------------------------------------------------------------------------------------------------
  168. // Create the data from parsed obj-file
  169. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene) {
  170. if( 0L == pModel ) {
  171. return;
  172. }
  173. // Create the root node of the scene
  174. pScene->mRootNode = new aiNode;
  175. if ( !pModel->m_ModelName.empty() )
  176. {
  177. // Set the name of the scene
  178. pScene->mRootNode->mName.Set(pModel->m_ModelName);
  179. }
  180. else
  181. {
  182. // This is a fatal error, so break down the application
  183. ai_assert(false);
  184. }
  185. // Create nodes for the whole scene
  186. std::vector<aiMesh*> MeshArray;
  187. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  188. {
  189. createNodes(pModel, pModel->m_Objects[ index ], pScene->mRootNode, pScene, MeshArray);
  190. }
  191. // Create mesh pointer buffer for this scene
  192. if (pScene->mNumMeshes > 0)
  193. {
  194. pScene->mMeshes = new aiMesh*[ MeshArray.size() ];
  195. for (size_t index =0; index < MeshArray.size(); index++)
  196. {
  197. pScene->mMeshes[ index ] = MeshArray[ index ];
  198. }
  199. }
  200. // Create all materials
  201. createMaterials( pModel, pScene );
  202. }
  203. // ------------------------------------------------------------------------------------------------
  204. // Creates all nodes of the model
  205. aiNode *ObjFileImporter::createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pObject,
  206. aiNode *pParent, aiScene* pScene,
  207. std::vector<aiMesh*> &MeshArray )
  208. {
  209. ai_assert( NULL != pModel );
  210. if( NULL == pObject ) {
  211. return NULL;
  212. }
  213. // Store older mesh size to be able to computes mesh offsets for new mesh instances
  214. const size_t oldMeshSize = MeshArray.size();
  215. aiNode *pNode = new aiNode;
  216. pNode->mName = pObject->m_strObjName;
  217. // If we have a parent node, store it
  218. if( pParent != NULL ) {
  219. appendChildToParentNode( pParent, pNode );
  220. }
  221. for ( size_t i=0; i< pObject->m_Meshes.size(); i++ )
  222. {
  223. unsigned int meshId = pObject->m_Meshes[ i ];
  224. aiMesh *pMesh = createTopology( pModel, pObject, meshId );
  225. if( pMesh && pMesh->mNumFaces > 0 ) {
  226. MeshArray.push_back( pMesh );
  227. }
  228. }
  229. // Create all nodes from the sub-objects stored in the current object
  230. if ( !pObject->m_SubObjects.empty() )
  231. {
  232. size_t numChilds = pObject->m_SubObjects.size();
  233. pNode->mNumChildren = static_cast<unsigned int>( numChilds );
  234. pNode->mChildren = new aiNode*[ numChilds ];
  235. pNode->mNumMeshes = 1;
  236. pNode->mMeshes = new unsigned int[ 1 ];
  237. }
  238. // Set mesh instances into scene- and node-instances
  239. const size_t meshSizeDiff = MeshArray.size()- oldMeshSize;
  240. if ( meshSizeDiff > 0 )
  241. {
  242. pNode->mMeshes = new unsigned int[ meshSizeDiff ];
  243. pNode->mNumMeshes = static_cast<unsigned int>( meshSizeDiff );
  244. size_t index = 0;
  245. for (size_t i = oldMeshSize; i < MeshArray.size(); i++)
  246. {
  247. pNode->mMeshes[ index ] = pScene->mNumMeshes;
  248. pScene->mNumMeshes++;
  249. index++;
  250. }
  251. }
  252. return pNode;
  253. }
  254. // ------------------------------------------------------------------------------------------------
  255. // Create topology data
  256. aiMesh *ObjFileImporter::createTopology( const ObjFile::Model* pModel, const ObjFile::Object* pData, unsigned int meshIndex ) {
  257. // Checking preconditions
  258. ai_assert( NULL != pModel );
  259. if( NULL == pData ) {
  260. return NULL;
  261. }
  262. // Create faces
  263. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ meshIndex ];
  264. if( !pObjMesh ) {
  265. return NULL;
  266. }
  267. if( pObjMesh->m_Faces.empty() ) {
  268. return NULL;
  269. }
  270. aiMesh* pMesh = new aiMesh;
  271. if( !pObjMesh->m_name.empty() ) {
  272. pMesh->mName.Set( pObjMesh->m_name );
  273. }
  274. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
  275. {
  276. ObjFile::Face *const inp = pObjMesh->m_Faces[ index ];
  277. ai_assert( NULL != inp );
  278. if (inp->m_PrimitiveType == aiPrimitiveType_LINE) {
  279. pMesh->mNumFaces += static_cast<unsigned int>(inp->m_vertices.size() - 1);
  280. pMesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  281. } else if (inp->m_PrimitiveType == aiPrimitiveType_POINT) {
  282. pMesh->mNumFaces += static_cast<unsigned int>(inp->m_vertices.size());
  283. pMesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  284. } else {
  285. ++pMesh->mNumFaces;
  286. if (inp->m_vertices.size() > 3) {
  287. pMesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  288. } else {
  289. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  290. }
  291. }
  292. }
  293. unsigned int uiIdxCount( 0u );
  294. if ( pMesh->mNumFaces > 0 ) {
  295. pMesh->mFaces = new aiFace[ pMesh->mNumFaces ];
  296. if ( pObjMesh->m_uiMaterialIndex != ObjFile::Mesh::NoMaterial ) {
  297. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  298. }
  299. unsigned int outIndex( 0 );
  300. // Copy all data from all stored meshes
  301. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++) {
  302. ObjFile::Face* const inp = pObjMesh->m_Faces[ index ];
  303. if (inp->m_PrimitiveType == aiPrimitiveType_LINE) {
  304. for(size_t i = 0; i < inp->m_vertices.size() - 1; ++i) {
  305. aiFace& f = pMesh->mFaces[ outIndex++ ];
  306. uiIdxCount += f.mNumIndices = 2;
  307. f.mIndices = new unsigned int[2];
  308. }
  309. continue;
  310. }
  311. else if (inp->m_PrimitiveType == aiPrimitiveType_POINT) {
  312. for(size_t i = 0; i < inp->m_vertices.size(); ++i) {
  313. aiFace& f = pMesh->mFaces[ outIndex++ ];
  314. uiIdxCount += f.mNumIndices = 1;
  315. f.mIndices = new unsigned int[1];
  316. }
  317. continue;
  318. }
  319. aiFace *pFace = &pMesh->mFaces[ outIndex++ ];
  320. const unsigned int uiNumIndices = (unsigned int) pObjMesh->m_Faces[ index ]->m_vertices.size();
  321. uiIdxCount += pFace->mNumIndices = (unsigned int) uiNumIndices;
  322. if (pFace->mNumIndices > 0) {
  323. pFace->mIndices = new unsigned int[ uiNumIndices ];
  324. }
  325. }
  326. }
  327. // Create mesh vertices
  328. createVertexArray(pModel, pData, meshIndex, pMesh, uiIdxCount);
  329. return pMesh;
  330. }
  331. // ------------------------------------------------------------------------------------------------
  332. // Creates a vertex array
  333. void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel,
  334. const ObjFile::Object* pCurrentObject,
  335. unsigned int uiMeshIndex,
  336. aiMesh* pMesh,
  337. unsigned int numIndices) {
  338. // Checking preconditions
  339. ai_assert( NULL != pCurrentObject );
  340. // Break, if no faces are stored in object
  341. if ( pCurrentObject->m_Meshes.empty() )
  342. return;
  343. // Get current mesh
  344. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  345. if ( NULL == pObjMesh || pObjMesh->m_uiNumIndices < 1 ) {
  346. return;
  347. }
  348. // Copy vertices of this mesh instance
  349. pMesh->mNumVertices = numIndices;
  350. if (pMesh->mNumVertices == 0) {
  351. throw DeadlyImportError( "OBJ: no vertices" );
  352. } else if (pMesh->mNumVertices > AI_MAX_ALLOC(aiVector3D)) {
  353. throw DeadlyImportError( "OBJ: Too many vertices, would run out of memory" );
  354. }
  355. pMesh->mVertices = new aiVector3D[ pMesh->mNumVertices ];
  356. // Allocate buffer for normal vectors
  357. if ( !pModel->m_Normals.empty() && pObjMesh->m_hasNormals )
  358. pMesh->mNormals = new aiVector3D[ pMesh->mNumVertices ];
  359. // Allocate buffer for vertex-color vectors
  360. if ( !pModel->m_VertexColors.empty() )
  361. pMesh->mColors[0] = new aiColor4D[ pMesh->mNumVertices ];
  362. // Allocate buffer for texture coordinates
  363. if ( !pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0] )
  364. {
  365. pMesh->mNumUVComponents[ 0 ] = 2;
  366. pMesh->mTextureCoords[ 0 ] = new aiVector3D[ pMesh->mNumVertices ];
  367. }
  368. // Copy vertices, normals and textures into aiMesh instance
  369. unsigned int newIndex = 0, outIndex = 0;
  370. for ( size_t index=0; index < pObjMesh->m_Faces.size(); index++ ) {
  371. // Get source face
  372. ObjFile::Face *pSourceFace = pObjMesh->m_Faces[ index ];
  373. // Copy all index arrays
  374. for ( size_t vertexIndex = 0, outVertexIndex = 0; vertexIndex < pSourceFace->m_vertices.size(); vertexIndex++ ) {
  375. const unsigned int vertex = pSourceFace->m_vertices.at( vertexIndex );
  376. if ( vertex >= pModel->m_Vertices.size() ) {
  377. throw DeadlyImportError( "OBJ: vertex index out of range" );
  378. }
  379. pMesh->mVertices[ newIndex ] = pModel->m_Vertices[ vertex ];
  380. // Copy all normals
  381. if ( !pModel->m_Normals.empty() && vertexIndex < pSourceFace->m_normals.size()) {
  382. const unsigned int normal = pSourceFace->m_normals.at( vertexIndex );
  383. if ( normal >= pModel->m_Normals.size() ) {
  384. throw DeadlyImportError( "OBJ: vertex normal index out of range" );
  385. }
  386. pMesh->mNormals[ newIndex ] = pModel->m_Normals[ normal ];
  387. }
  388. // Copy all vertex colors
  389. if ( !pModel->m_VertexColors.empty())
  390. {
  391. const aiVector3D color = pModel->m_VertexColors[ vertex ];
  392. pMesh->mColors[0][ newIndex ] = aiColor4D(color.x, color.y, color.z, 1.0);
  393. }
  394. // Copy all texture coordinates
  395. if ( !pModel->m_TextureCoord.empty() && vertexIndex < pSourceFace->m_texturCoords.size())
  396. {
  397. const unsigned int tex = pSourceFace->m_texturCoords.at( vertexIndex );
  398. ai_assert( tex < pModel->m_TextureCoord.size() );
  399. if ( tex >= pModel->m_TextureCoord.size() )
  400. throw DeadlyImportError("OBJ: texture coordinate index out of range");
  401. const aiVector3D &coord3d = pModel->m_TextureCoord[ tex ];
  402. pMesh->mTextureCoords[ 0 ][ newIndex ] = aiVector3D( coord3d.x, coord3d.y, coord3d.z );
  403. }
  404. if ( pMesh->mNumVertices <= newIndex ) {
  405. throw DeadlyImportError("OBJ: bad vertex index");
  406. }
  407. // Get destination face
  408. aiFace *pDestFace = &pMesh->mFaces[ outIndex ];
  409. const bool last = ( vertexIndex == pSourceFace->m_vertices.size() - 1 );
  410. if (pSourceFace->m_PrimitiveType != aiPrimitiveType_LINE || !last) {
  411. pDestFace->mIndices[ outVertexIndex ] = newIndex;
  412. outVertexIndex++;
  413. }
  414. if (pSourceFace->m_PrimitiveType == aiPrimitiveType_POINT) {
  415. outIndex++;
  416. outVertexIndex = 0;
  417. } else if (pSourceFace->m_PrimitiveType == aiPrimitiveType_LINE) {
  418. outVertexIndex = 0;
  419. if(!last)
  420. outIndex++;
  421. if (vertexIndex) {
  422. if(!last) {
  423. pMesh->mVertices[ newIndex+1 ] = pMesh->mVertices[ newIndex ];
  424. if ( !pSourceFace->m_normals.empty() && !pModel->m_Normals.empty()) {
  425. pMesh->mNormals[ newIndex+1 ] = pMesh->mNormals[newIndex ];
  426. }
  427. if ( !pModel->m_TextureCoord.empty() ) {
  428. for ( size_t i=0; i < pMesh->GetNumUVChannels(); i++ ) {
  429. pMesh->mTextureCoords[ i ][ newIndex+1 ] = pMesh->mTextureCoords[ i ][ newIndex ];
  430. }
  431. }
  432. ++newIndex;
  433. }
  434. pDestFace[-1].mIndices[1] = newIndex;
  435. }
  436. }
  437. else if (last) {
  438. outIndex++;
  439. }
  440. ++newIndex;
  441. }
  442. }
  443. }
  444. // ------------------------------------------------------------------------------------------------
  445. // Counts all stored meshes
  446. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object*> &rObjects, int &iNumMeshes)
  447. {
  448. iNumMeshes = 0;
  449. if ( rObjects.empty() )
  450. return;
  451. iNumMeshes += static_cast<unsigned int>( rObjects.size() );
  452. for (std::vector<ObjFile::Object*>::const_iterator it = rObjects.begin();
  453. it != rObjects.end();
  454. ++it)
  455. {
  456. if (!(*it)->m_SubObjects.empty())
  457. {
  458. countObjects((*it)->m_SubObjects, iNumMeshes);
  459. }
  460. }
  461. }
  462. // ------------------------------------------------------------------------------------------------
  463. // Add clamp mode property to material if necessary
  464. void ObjFileImporter::addTextureMappingModeProperty( aiMaterial* mat, aiTextureType type, int clampMode, int index) {
  465. if ( nullptr == mat ) {
  466. return;
  467. }
  468. mat->AddProperty<int>( &clampMode, 1, AI_MATKEY_MAPPINGMODE_U( type, index ) );
  469. mat->AddProperty<int>( &clampMode, 1, AI_MATKEY_MAPPINGMODE_V( type, index ) );
  470. }
  471. // ------------------------------------------------------------------------------------------------
  472. // Creates the material
  473. void ObjFileImporter::createMaterials(const ObjFile::Model* pModel, aiScene* pScene ) {
  474. if ( NULL == pScene ) {
  475. return;
  476. }
  477. const unsigned int numMaterials = (unsigned int) pModel->m_MaterialLib.size();
  478. pScene->mNumMaterials = 0;
  479. if ( pModel->m_MaterialLib.empty() ) {
  480. DefaultLogger::get()->debug("OBJ: no materials specified");
  481. return;
  482. }
  483. pScene->mMaterials = new aiMaterial*[ numMaterials ];
  484. for ( unsigned int matIndex = 0; matIndex < numMaterials; matIndex++ )
  485. {
  486. // Store material name
  487. std::map<std::string, ObjFile::Material*>::const_iterator it;
  488. it = pModel->m_MaterialMap.find( pModel->m_MaterialLib[ matIndex ] );
  489. // No material found, use the default material
  490. if ( pModel->m_MaterialMap.end() == it )
  491. continue;
  492. aiMaterial* mat = new aiMaterial;
  493. ObjFile::Material *pCurrentMaterial = (*it).second;
  494. mat->AddProperty( &pCurrentMaterial->MaterialName, AI_MATKEY_NAME );
  495. // convert illumination model
  496. int sm = 0;
  497. switch (pCurrentMaterial->illumination_model)
  498. {
  499. case 0:
  500. sm = aiShadingMode_NoShading;
  501. break;
  502. case 1:
  503. sm = aiShadingMode_Gouraud;
  504. break;
  505. case 2:
  506. sm = aiShadingMode_Phong;
  507. break;
  508. default:
  509. sm = aiShadingMode_Gouraud;
  510. DefaultLogger::get()->error("OBJ: unexpected illumination model (0-2 recognized)");
  511. }
  512. mat->AddProperty<int>( &sm, 1, AI_MATKEY_SHADING_MODEL);
  513. // Adding material colors
  514. mat->AddProperty( &pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT );
  515. mat->AddProperty( &pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  516. mat->AddProperty( &pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR );
  517. mat->AddProperty( &pCurrentMaterial->emissive, 1, AI_MATKEY_COLOR_EMISSIVE );
  518. mat->AddProperty( &pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS );
  519. mat->AddProperty( &pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY );
  520. // Adding refraction index
  521. mat->AddProperty( &pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI );
  522. // Adding textures
  523. if ( 0 != pCurrentMaterial->texture.length )
  524. {
  525. mat->AddProperty( &pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  526. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDiffuseType])
  527. {
  528. addTextureMappingModeProperty(mat, aiTextureType_DIFFUSE);
  529. }
  530. }
  531. if ( 0 != pCurrentMaterial->textureAmbient.length )
  532. {
  533. mat->AddProperty( &pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  534. if (pCurrentMaterial->clamp[ObjFile::Material::TextureAmbientType])
  535. {
  536. addTextureMappingModeProperty(mat, aiTextureType_AMBIENT);
  537. }
  538. }
  539. if ( 0 != pCurrentMaterial->textureEmissive.length )
  540. mat->AddProperty( &pCurrentMaterial->textureEmissive, AI_MATKEY_TEXTURE_EMISSIVE(0));
  541. if ( 0 != pCurrentMaterial->textureSpecular.length )
  542. {
  543. mat->AddProperty( &pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  544. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularType])
  545. {
  546. addTextureMappingModeProperty(mat, aiTextureType_SPECULAR);
  547. }
  548. }
  549. if ( 0 != pCurrentMaterial->textureBump.length )
  550. {
  551. mat->AddProperty( &pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  552. if (pCurrentMaterial->clamp[ObjFile::Material::TextureBumpType])
  553. {
  554. addTextureMappingModeProperty(mat, aiTextureType_HEIGHT);
  555. }
  556. }
  557. if ( 0 != pCurrentMaterial->textureNormal.length )
  558. {
  559. mat->AddProperty( &pCurrentMaterial->textureNormal, AI_MATKEY_TEXTURE_NORMALS(0));
  560. if (pCurrentMaterial->clamp[ObjFile::Material::TextureNormalType])
  561. {
  562. addTextureMappingModeProperty(mat, aiTextureType_NORMALS);
  563. }
  564. }
  565. if( 0 != pCurrentMaterial->textureReflection[0].length )
  566. {
  567. ObjFile::Material::TextureType type = 0 != pCurrentMaterial->textureReflection[1].length ?
  568. ObjFile::Material::TextureReflectionCubeTopType :
  569. ObjFile::Material::TextureReflectionSphereType;
  570. unsigned count = type == ObjFile::Material::TextureReflectionSphereType ? 1 : 6;
  571. for( unsigned i = 0; i < count; i++ )
  572. {
  573. mat->AddProperty(&pCurrentMaterial->textureReflection[i], AI_MATKEY_TEXTURE_REFLECTION(i));
  574. if(pCurrentMaterial->clamp[type])
  575. addTextureMappingModeProperty(mat, aiTextureType_REFLECTION, 1, i);
  576. }
  577. }
  578. if ( 0 != pCurrentMaterial->textureDisp.length )
  579. {
  580. mat->AddProperty( &pCurrentMaterial->textureDisp, AI_MATKEY_TEXTURE_DISPLACEMENT(0) );
  581. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDispType])
  582. {
  583. addTextureMappingModeProperty(mat, aiTextureType_DISPLACEMENT);
  584. }
  585. }
  586. if ( 0 != pCurrentMaterial->textureOpacity.length )
  587. {
  588. mat->AddProperty( &pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  589. if (pCurrentMaterial->clamp[ObjFile::Material::TextureOpacityType])
  590. {
  591. addTextureMappingModeProperty(mat, aiTextureType_OPACITY);
  592. }
  593. }
  594. if ( 0 != pCurrentMaterial->textureSpecularity.length )
  595. {
  596. mat->AddProperty( &pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  597. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularityType])
  598. {
  599. addTextureMappingModeProperty(mat, aiTextureType_SHININESS);
  600. }
  601. }
  602. // Store material property info in material array in scene
  603. pScene->mMaterials[ pScene->mNumMaterials ] = mat;
  604. pScene->mNumMaterials++;
  605. }
  606. // Test number of created materials.
  607. ai_assert( pScene->mNumMaterials == numMaterials );
  608. }
  609. // ------------------------------------------------------------------------------------------------
  610. // Appends this node to the parent node
  611. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild)
  612. {
  613. // Checking preconditions
  614. ai_assert( NULL != pParent );
  615. ai_assert( NULL != pChild );
  616. // Assign parent to child
  617. pChild->mParent = pParent;
  618. // If already children was assigned to the parent node, store them in a
  619. std::vector<aiNode*> temp;
  620. if (pParent->mChildren != NULL)
  621. {
  622. ai_assert( 0 != pParent->mNumChildren );
  623. for (size_t index = 0; index < pParent->mNumChildren; index++)
  624. {
  625. temp.push_back(pParent->mChildren [ index ] );
  626. }
  627. delete [] pParent->mChildren;
  628. }
  629. // Copy node instances into parent node
  630. pParent->mNumChildren++;
  631. pParent->mChildren = new aiNode*[ pParent->mNumChildren ];
  632. for (size_t index = 0; index < pParent->mNumChildren-1; index++)
  633. {
  634. pParent->mChildren[ index ] = temp [ index ];
  635. }
  636. pParent->mChildren[ pParent->mNumChildren-1 ] = pChild;
  637. }
  638. // ------------------------------------------------------------------------------------------------
  639. } // Namespace Assimp
  640. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER