ObjFileImporter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2010, 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. #include "AssimpPCH.h"
  35. #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER
  36. #include "DefaultIOSystem.h"
  37. #include "ObjFileImporter.h"
  38. #include "ObjFileParser.h"
  39. #include "ObjFileData.h"
  40. namespace Assimp {
  41. using namespace std;
  42. // ------------------------------------------------------------------------------------------------
  43. // Default constructor
  44. ObjFileImporter::ObjFileImporter() :
  45. m_Buffer(),
  46. m_pRootObject( NULL ),
  47. m_strAbsPath( "" )
  48. {
  49. DefaultIOSystem io;
  50. m_strAbsPath = io.getOsSeparator();
  51. }
  52. // ------------------------------------------------------------------------------------------------
  53. // Destructor.
  54. ObjFileImporter::~ObjFileImporter()
  55. {
  56. // Release root object instance
  57. if (NULL != m_pRootObject)
  58. {
  59. delete m_pRootObject;
  60. m_pRootObject = NULL;
  61. }
  62. }
  63. // ------------------------------------------------------------------------------------------------
  64. // Returns true, if file is an obj file.
  65. bool ObjFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler , bool checkSig ) const
  66. {
  67. if(!checkSig) //Check File Extension
  68. {
  69. return SimpleExtensionCheck(pFile,"obj");
  70. }
  71. else //Check file Header
  72. {
  73. static const char *pTokens[] = { "mtllib", "usemtl", "v ", "vt ", "vn ", "o ", "g ", "s ", "f " };
  74. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, pTokens, 9 );
  75. }
  76. }
  77. // ------------------------------------------------------------------------------------------------
  78. // Obj-file import implementation
  79. void ObjFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  80. {
  81. DefaultIOSystem io;
  82. // Read file into memory
  83. const std::string mode = "rb";
  84. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, mode));
  85. if (NULL == file.get())
  86. throw DeadlyImportError( "Failed to open file " + pFile + ".");
  87. // Get the filesize and vaslidate it, throwing an exception when failes
  88. size_t fileSize = file->FileSize();
  89. if( fileSize < 16)
  90. throw DeadlyImportError( "OBJ-file is too small.");
  91. // Allocate buffer and read file into it
  92. TextFileToBuffer(file.get(),m_Buffer);
  93. // Get the model name
  94. std::string strModelName;
  95. std::string::size_type pos = pFile.find_last_of( "\\/" );
  96. if ( pos != std::string::npos )
  97. {
  98. strModelName = pFile.substr(pos+1, pFile.size() - pos - 1);
  99. }
  100. else
  101. {
  102. strModelName = pFile;
  103. }
  104. // parse the file into a temporary representation
  105. ObjFileParser parser(m_Buffer, strModelName, pIOHandler);
  106. // And create the proper return structures out of it
  107. CreateDataFromImport(parser.GetModel(), pScene);
  108. // Clean up allocated storage for the next import
  109. m_Buffer.clear();
  110. }
  111. // ------------------------------------------------------------------------------------------------
  112. // Create the data from parsed obj-file
  113. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene)
  114. {
  115. if (0L == pModel)
  116. return;
  117. // Create the root node of the scene
  118. pScene->mRootNode = new aiNode;
  119. if ( !pModel->m_ModelName.empty() )
  120. {
  121. // Set the name of the scene
  122. pScene->mRootNode->mName.Set(pModel->m_ModelName);
  123. }
  124. else
  125. {
  126. // This is an error, so break down the application
  127. ai_assert(false);
  128. }
  129. // Create nodes for the whole scene
  130. std::vector<aiMesh*> MeshArray;
  131. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  132. {
  133. createNodes(pModel, pModel->m_Objects[ index ], index, pScene->mRootNode, pScene, MeshArray);
  134. }
  135. // Create mesh pointer buffer for this scene
  136. if (pScene->mNumMeshes > 0)
  137. {
  138. pScene->mMeshes = new aiMesh*[ MeshArray.size() ];
  139. for (size_t index =0; index < MeshArray.size(); index++)
  140. {
  141. pScene->mMeshes [ index ] = MeshArray[ index ];
  142. }
  143. }
  144. // Create all materials
  145. createMaterials( pModel, pScene );
  146. }
  147. // ------------------------------------------------------------------------------------------------
  148. // Creates all nodes of the model
  149. aiNode *ObjFileImporter::createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pObject,
  150. unsigned int /*uiMeshIndex*/,
  151. aiNode *pParent, aiScene* pScene,
  152. std::vector<aiMesh*> &MeshArray )
  153. {
  154. ai_assert( NULL != pModel );
  155. if ( NULL == pObject )
  156. return NULL;
  157. // Store older mesh size to be able to computes mesh offsets for new mesh instances
  158. const size_t oldMeshSize = MeshArray.size();
  159. aiNode *pNode = new aiNode;
  160. pNode->mName = pObject->m_strObjName;
  161. if (pParent != NULL)
  162. appendChildToParentNode(pParent, pNode);
  163. for ( unsigned int i=0; i< pObject->m_Meshes.size(); i++ )
  164. {
  165. unsigned int meshId = pObject->m_Meshes[ i ];
  166. aiMesh *pMesh = new aiMesh;
  167. createTopology( pModel, pObject, meshId, pMesh );
  168. if ( pMesh->mNumVertices > 0 )
  169. {
  170. MeshArray.push_back( pMesh );
  171. }
  172. else
  173. {
  174. delete pMesh;
  175. }
  176. }
  177. // Create all nodes from the sub-objects stored in the current object
  178. if ( !pObject->m_SubObjects.empty() )
  179. {
  180. size_t numChilds = pObject->m_SubObjects.size();
  181. pNode->mNumChildren = static_cast<unsigned int>( numChilds );
  182. pNode->mChildren = new aiNode*[ numChilds ];
  183. pNode->mNumMeshes = 1;
  184. pNode->mMeshes = new unsigned int[ 1 ];
  185. }
  186. // Set mesh instances into scene- and node-instances
  187. const size_t meshSizeDiff = MeshArray.size()- oldMeshSize;
  188. if ( meshSizeDiff > 0 )
  189. {
  190. pNode->mMeshes = new unsigned int[ meshSizeDiff ];
  191. pNode->mNumMeshes = static_cast<unsigned int>( meshSizeDiff );
  192. size_t index = 0;
  193. for (size_t i = oldMeshSize; i < MeshArray.size(); i++)
  194. {
  195. pNode->mMeshes[ index ] = pScene->mNumMeshes;
  196. pScene->mNumMeshes++;
  197. index++;
  198. }
  199. }
  200. return pNode;
  201. }
  202. // ------------------------------------------------------------------------------------------------
  203. // Create topology data
  204. void ObjFileImporter::createTopology(const ObjFile::Model* pModel,
  205. const ObjFile::Object* pData,
  206. unsigned int uiMeshIndex,
  207. aiMesh* pMesh )
  208. {
  209. // Checking preconditions
  210. ai_assert( NULL != pModel );
  211. if (NULL == pData)
  212. return;
  213. // Create faces
  214. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  215. ai_assert( NULL != pObjMesh );
  216. pMesh->mNumFaces = static_cast<unsigned int>( pObjMesh->m_Faces.size() );
  217. if ( pMesh->mNumFaces > 0 )
  218. {
  219. pMesh->mFaces = new aiFace[ pMesh->mNumFaces ];
  220. if ( pObjMesh->m_uiMaterialIndex != ObjFile::Mesh::NoMaterial )
  221. {
  222. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  223. }
  224. // Copy all data from all stored meshes
  225. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
  226. {
  227. aiFace *pFace = &pMesh->mFaces[ index ];
  228. const unsigned int uiNumIndices = (unsigned int) pObjMesh->m_Faces[ index ]->m_pVertices->size();
  229. pFace->mNumIndices = (unsigned int) uiNumIndices;
  230. if (pFace->mNumIndices > 0)
  231. {
  232. pFace->mIndices = new unsigned int[ uiNumIndices ];
  233. ObjFile::Face::IndexArray *pIndexArray = pObjMesh->m_Faces[ index ]->m_pVertices;
  234. ai_assert ( NULL != pIndexArray );
  235. for ( size_t a=0; a<pFace->mNumIndices; a++ )
  236. {
  237. pFace->mIndices[ a ] = pIndexArray->at( a );
  238. }
  239. }
  240. else
  241. {
  242. pFace->mIndices = NULL;
  243. }
  244. }
  245. }
  246. // Create mesh vertices
  247. createVertexArray(pModel, pData, uiMeshIndex, pMesh);
  248. }
  249. // ------------------------------------------------------------------------------------------------
  250. // Creates a vertex array
  251. void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel,
  252. const ObjFile::Object* pCurrentObject,
  253. unsigned int uiMeshIndex,
  254. aiMesh* pMesh)
  255. {
  256. // Checking preconditions
  257. ai_assert( NULL != pCurrentObject );
  258. // Break, if no faces are stored in object
  259. if ( pCurrentObject->m_Meshes.empty() )
  260. return;
  261. // Get current mesh
  262. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  263. if ( NULL == pObjMesh || pObjMesh->m_uiNumIndices < 1)
  264. return;
  265. // Copy vertices of this mesh instance
  266. pMesh->mNumVertices = (unsigned int) pObjMesh->m_uiNumIndices;
  267. pMesh->mVertices = new aiVector3D[ pMesh->mNumVertices ];
  268. // Allocate buffer for normal vectors
  269. if ( !pModel->m_Normals.empty() && pObjMesh->m_hasNormals )
  270. pMesh->mNormals = new aiVector3D[ pMesh->mNumVertices ];
  271. // Allocate buffer for texture coordinates
  272. if ( !pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0] )
  273. {
  274. pMesh->mNumUVComponents[ 0 ] = 2;
  275. pMesh->mTextureCoords[ 0 ] = new aiVector3D[ pMesh->mNumVertices ];
  276. }
  277. // Copy vertices, normals and textures into aiMesh instance
  278. unsigned int newIndex = 0;
  279. for ( size_t index=0; index < pObjMesh->m_Faces.size(); index++ )
  280. {
  281. // Get destination face
  282. aiFace *pDestFace = &pMesh->mFaces[ index ];
  283. // Get source face
  284. ObjFile::Face *pSourceFace = pObjMesh->m_Faces[ index ];
  285. // Copy all index arrays
  286. for ( size_t vertexIndex = 0; vertexIndex < pSourceFace->m_pVertices->size(); vertexIndex++ )
  287. {
  288. const unsigned int vertex = pSourceFace->m_pVertices->at( vertexIndex );
  289. if (vertex >= pModel->m_Vertices.size()) {
  290. throw DeadlyImportError("OBJ: vertex index out of range");
  291. }
  292. pMesh->mVertices[ newIndex ] = pModel->m_Vertices[ vertex ];
  293. // Copy all normals
  294. if ( !pSourceFace->m_pNormals->empty() && !pModel->m_Normals.empty())
  295. {
  296. const unsigned int normal = pSourceFace->m_pNormals->at( vertexIndex );
  297. if (normal >= pModel->m_Normals.size()) {
  298. throw DeadlyImportError("OBJ: vertex normal index out of range");
  299. }
  300. pMesh->mNormals[ newIndex ] = pModel->m_Normals[ normal ];
  301. }
  302. // Copy all texture coordinates
  303. if ( !pModel->m_TextureCoord.empty() )
  304. {
  305. if ( !pSourceFace->m_pTexturCoords->empty() )
  306. {
  307. const unsigned int tex = pSourceFace->m_pTexturCoords->at( vertexIndex );
  308. ai_assert( tex < pModel->m_TextureCoord.size() );
  309. for ( size_t i=0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; i++ )
  310. {
  311. if ( pMesh->mNumUVComponents[ i ] > 0 )
  312. {
  313. aiVector2D coord2d = pModel->m_TextureCoord[ tex ];
  314. pMesh->mTextureCoords[ i ][ newIndex ] = aiVector3D( coord2d.x, coord2d.y, 0.0 );
  315. }
  316. }
  317. }
  318. }
  319. ai_assert( pMesh->mNumVertices > newIndex );
  320. pDestFace->mIndices[ vertexIndex ] = newIndex;
  321. ++newIndex;
  322. }
  323. }
  324. }
  325. // ------------------------------------------------------------------------------------------------
  326. // Counts all stored meshes
  327. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object*> &rObjects, int &iNumMeshes)
  328. {
  329. iNumMeshes = 0;
  330. if ( rObjects.empty() )
  331. return;
  332. iNumMeshes += static_cast<unsigned int>( rObjects.size() );
  333. for (std::vector<ObjFile::Object*>::const_iterator it = rObjects.begin();
  334. it != rObjects.end();
  335. ++it)
  336. {
  337. if (!(*it)->m_SubObjects.empty())
  338. {
  339. countObjects((*it)->m_SubObjects, iNumMeshes);
  340. }
  341. }
  342. }
  343. // ------------------------------------------------------------------------------------------------
  344. // Creates the material
  345. void ObjFileImporter::createMaterials(const ObjFile::Model* pModel, aiScene* pScene )
  346. {
  347. ai_assert( NULL != pScene );
  348. if ( NULL == pScene )
  349. return;
  350. const unsigned int numMaterials = (unsigned int) pModel->m_MaterialLib.size();
  351. pScene->mNumMaterials = 0;
  352. if ( pModel->m_MaterialLib.empty() ) {
  353. DefaultLogger::get()->debug("OBJ: no materials specified");
  354. return;
  355. }
  356. pScene->mMaterials = new aiMaterial*[ numMaterials ];
  357. for ( unsigned int matIndex = 0; matIndex < numMaterials; matIndex++ )
  358. {
  359. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper;
  360. // Store material name
  361. std::map<std::string, ObjFile::Material*>::const_iterator it;
  362. it = pModel->m_MaterialMap.find( pModel->m_MaterialLib[ matIndex ] );
  363. // No material found, use the default material
  364. if ( pModel->m_MaterialMap.end() == it )
  365. continue;
  366. ObjFile::Material *pCurrentMaterial = (*it).second;
  367. mat->AddProperty( &pCurrentMaterial->MaterialName, AI_MATKEY_NAME );
  368. // convert illumination model
  369. int sm = 0;
  370. switch (pCurrentMaterial->illumination_model)
  371. {
  372. case 0:
  373. sm = aiShadingMode_NoShading;
  374. break;
  375. case 1:
  376. sm = aiShadingMode_Gouraud;
  377. break;
  378. case 2:
  379. sm = aiShadingMode_Phong;
  380. break;
  381. default:
  382. sm = aiShadingMode_Gouraud;
  383. DefaultLogger::get()->error("OBJ: unexpected illumination model (0-2 recognized)");
  384. }
  385. mat->AddProperty<int>( &sm, 1, AI_MATKEY_SHADING_MODEL);
  386. // multiplying the specular exponent with 2 seems to yield better results
  387. pCurrentMaterial->shineness *= 4.f;
  388. // Adding material colors
  389. mat->AddProperty( &pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT );
  390. mat->AddProperty( &pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  391. mat->AddProperty( &pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR );
  392. mat->AddProperty( &pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS );
  393. mat->AddProperty( &pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY );
  394. // Adding refraction index
  395. mat->AddProperty( &pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI );
  396. // Adding textures
  397. if ( 0 != pCurrentMaterial->texture.length )
  398. mat->AddProperty( &pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  399. if ( 0 != pCurrentMaterial->textureAmbient.length )
  400. mat->AddProperty( &pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  401. if ( 0 != pCurrentMaterial->textureSpecular.length )
  402. mat->AddProperty( &pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  403. if ( 0 != pCurrentMaterial->textureBump.length )
  404. mat->AddProperty( &pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  405. if ( 0 != pCurrentMaterial->textureOpacity.length )
  406. mat->AddProperty( &pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  407. if ( 0 != pCurrentMaterial->textureSpecularity.length )
  408. mat->AddProperty( &pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  409. // Store material property info in material array in scene
  410. pScene->mMaterials[ pScene->mNumMaterials ] = mat;
  411. pScene->mNumMaterials++;
  412. }
  413. // Test number of created materials.
  414. ai_assert( pScene->mNumMaterials == numMaterials );
  415. }
  416. // ------------------------------------------------------------------------------------------------
  417. // Appends this node to the parent node
  418. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild)
  419. {
  420. // Checking preconditions
  421. ai_assert( NULL != pParent );
  422. ai_assert( NULL != pChild );
  423. // Assign parent to child
  424. pChild->mParent = pParent;
  425. size_t sNumChildren = 0;
  426. (void)sNumChildren; // remove warning on release build
  427. // If already children was assigned to the parent node, store them in a
  428. std::vector<aiNode*> temp;
  429. if (pParent->mChildren != NULL)
  430. {
  431. sNumChildren = pParent->mNumChildren;
  432. ai_assert( 0 != sNumChildren );
  433. for (size_t index = 0; index < pParent->mNumChildren; index++)
  434. {
  435. temp.push_back(pParent->mChildren [ index ] );
  436. }
  437. delete [] pParent->mChildren;
  438. }
  439. // Copy node instances into parent node
  440. pParent->mNumChildren++;
  441. pParent->mChildren = new aiNode*[ pParent->mNumChildren ];
  442. for (size_t index = 0; index < pParent->mNumChildren-1; index++)
  443. {
  444. pParent->mChildren[ index ] = temp [ index ];
  445. }
  446. pParent->mChildren[ pParent->mNumChildren-1 ] = pChild;
  447. }
  448. // ------------------------------------------------------------------------------------------------
  449. } // Namespace Assimp
  450. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER