ObjFileImporter.cpp 28 KB

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