ObjFileImporter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development Team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the ASSIMP team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the ASSIMP Development Team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. #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. // ------------------------------------------------------------------------------------------------
  42. using namespace std;
  43. // ------------------------------------------------------------------------------------------------
  44. // Default constructor
  45. ObjFileImporter::ObjFileImporter() :
  46. m_pRootObject(NULL)
  47. {
  48. DefaultIOSystem io;
  49. m_strAbsPath = io.getOsSeparator();
  50. }
  51. // ------------------------------------------------------------------------------------------------
  52. // Destructor
  53. ObjFileImporter::~ObjFileImporter()
  54. {
  55. // Release root object instance
  56. if (NULL != m_pRootObject)
  57. {
  58. delete m_pRootObject;
  59. m_pRootObject = NULL;
  60. }
  61. }
  62. // ------------------------------------------------------------------------------------------------
  63. // Returns true, fi file is an obj file
  64. bool ObjFileImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler , bool checkSig ) const
  65. {
  66. if(!checkSig) //Check File Extension
  67. {
  68. return SimpleExtensionCheck(pFile,"obj");
  69. }
  70. else //Check file Header
  71. {
  72. const char* tokens[] = {"mtllib","usemtl","vt ","vn ","o "};
  73. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, tokens, 5);
  74. }
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Obj-file import implementation
  78. void ObjFileImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  79. {
  80. DefaultIOSystem io;
  81. // Read file into memory
  82. const std::string mode = "rb";
  83. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile, mode));
  84. if (NULL == file.get())
  85. throw new ImportErrorException( "Failed to open file " + pFile + ".");
  86. // Get the filesize and vaslidate it, throwing an exception when failes
  87. size_t fileSize = file->FileSize();
  88. if( fileSize < 16)
  89. throw new ImportErrorException( "OBJ-file is too small.");
  90. // Allocate buffer and read file into it
  91. TextFileToBuffer(file.get(),m_Buffer);
  92. //
  93. std::string strModelName;
  94. std::string::size_type pos = pFile.find_last_of( "\\/" );
  95. if ( pos != std::string::npos ) {
  96. strModelName = pFile.substr(pos+1, pFile.size() - pos - 1);
  97. }
  98. else
  99. {
  100. strModelName = pFile;
  101. }
  102. // parse the file into a temporary representation
  103. ObjFileParser parser(m_Buffer, strModelName, pIOHandler);
  104. // And create the proper return structures out of it
  105. CreateDataFromImport(parser.GetModel(), pScene);
  106. // Clean up allocated storage for the next import
  107. m_Buffer.clear();
  108. }
  109. // ------------------------------------------------------------------------------------------------
  110. // Create the data from parsed obj-file
  111. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene)
  112. {
  113. if (0L == pModel)
  114. return;
  115. // Create the root node of the scene
  116. pScene->mRootNode = new aiNode();
  117. if (!pModel->m_ModelName.empty())
  118. {
  119. // Set the name of the scene
  120. pScene->mRootNode->mName.Set(pModel->m_ModelName);
  121. }
  122. else
  123. {
  124. // This is an error, so break down the application
  125. ai_assert (false);
  126. }
  127. // Create nodes for the whole scene
  128. std::vector<aiMesh*> MeshArray;
  129. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  130. {
  131. createNodes(pModel, pModel->m_Objects[ index ], pScene->mRootNode, pScene, MeshArray);
  132. }
  133. // Create mesh pointer buffer for this scene
  134. if (pScene->mNumMeshes > 0)
  135. {
  136. pScene->mMeshes = new aiMesh*[ MeshArray.size() ];
  137. for (size_t index =0; index < MeshArray.size(); index++)
  138. {
  139. pScene->mMeshes [ index ] = MeshArray[ index ];
  140. }
  141. }
  142. // Create all materials
  143. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  144. {
  145. createMaterial( pModel, pModel->m_Objects[ index ], pScene );
  146. }
  147. }
  148. // ------------------------------------------------------------------------------------------------
  149. // Creates all nodes of the model
  150. aiNode *ObjFileImporter::createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pData,
  151. aiNode *pParent, aiScene* pScene,
  152. std::vector<aiMesh*> &MeshArray)
  153. {
  154. if (NULL == pData)
  155. return NULL;
  156. // Store older mesh size to be able to computate mesh offsets for new mesh instances
  157. size_t oldMeshSize = MeshArray.size();
  158. aiNode *pNode = new aiNode();
  159. if (pParent != NULL)
  160. this->appendChildToParentNode(pParent, pNode);
  161. aiMesh *pMesh = NULL;
  162. for (unsigned int meshIndex = 0; meshIndex < pModel->m_Meshes.size(); meshIndex++)
  163. {
  164. pMesh = new aiMesh();
  165. createTopology( pModel, pData, meshIndex, pMesh );
  166. if (pMesh->mNumVertices > 0) {
  167. MeshArray.push_back( pMesh );
  168. }
  169. }
  170. // Create all nodes from the subobjects stored in the current object
  171. if (!pData->m_SubObjects.empty())
  172. {
  173. pNode->mNumChildren = (unsigned int)pData->m_SubObjects.size();
  174. pNode->mChildren = new aiNode*[pData->m_SubObjects.size()];
  175. pNode->mNumMeshes = 1;
  176. pNode->mMeshes = new unsigned int[1];
  177. // Loop over all child objects, TODO
  178. /*for (size_t index = 0; index < pData->m_SubObjects.size(); index++)
  179. {
  180. // Create all child nodes
  181. pNode->mChildren[ index ] = createNodes( pModel, pData, pNode, pScene, MeshArray );
  182. for (unsigned int meshIndex = 0; meshIndex < pData->m_SubObjects[ index ]->m_Meshes.size(); meshIndex++)
  183. {
  184. pMesh = new aiMesh();
  185. MeshArray.push_back( pMesh );
  186. createTopology( pModel, pData, meshIndex, pMesh );
  187. }
  188. // Create material of this object
  189. createMaterial(pModel, pData->m_SubObjects[ index ], pScene);
  190. }*/
  191. }
  192. // Set mesh instances into scene- and node-instances
  193. const size_t meshSizeDiff = MeshArray.size()- oldMeshSize;
  194. if ( meshSizeDiff > 0 )
  195. {
  196. pNode->mMeshes = new unsigned int[ meshSizeDiff ];
  197. pNode->mNumMeshes = (unsigned int)meshSizeDiff;
  198. size_t index = 0;
  199. for (size_t i = oldMeshSize; i < MeshArray.size(); i++)
  200. {
  201. pNode->mMeshes[ index ] = pScene->mNumMeshes;
  202. pScene->mNumMeshes++;
  203. index++;
  204. }
  205. }
  206. return pNode;
  207. }
  208. // ------------------------------------------------------------------------------------------------
  209. // Create topology data
  210. void ObjFileImporter::createTopology(const ObjFile::Model* pModel,
  211. const ObjFile::Object* pData,
  212. unsigned int uiMeshIndex,
  213. aiMesh* pMesh )
  214. {
  215. // Checking preconditions
  216. ai_assert( NULL != pModel );
  217. if (NULL == pData)
  218. return;
  219. // Create faces
  220. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  221. ai_assert( NULL != pObjMesh );
  222. pMesh->mNumFaces = static_cast<unsigned int>( pObjMesh->m_Faces.size() );
  223. if ( pMesh->mNumFaces > 0 )
  224. {
  225. pMesh->mFaces = new aiFace[ pMesh->mNumFaces ];
  226. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  227. // Copy all data from all stored meshes
  228. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
  229. {
  230. aiFace *pFace = &pMesh->mFaces[ index ];
  231. const unsigned int uiNumIndices = (unsigned int) pObjMesh->m_Faces[ index ]->m_pVertices->size();
  232. pFace->mNumIndices = (unsigned int) uiNumIndices;
  233. if (pFace->mNumIndices > 0)
  234. {
  235. pFace->mIndices = new unsigned int[ uiNumIndices ];
  236. ObjFile::Face::IndexArray *pIndexArray = pObjMesh->m_Faces[ index ]->m_pVertices;
  237. ai_assert ( NULL != pIndexArray );
  238. for ( size_t a=0; a<pFace->mNumIndices; a++ )
  239. {
  240. pFace->mIndices[ a ] = pIndexArray->at( a );
  241. }
  242. }
  243. else
  244. {
  245. pFace->mIndices = NULL;
  246. }
  247. }
  248. }
  249. // Create mesh vertices
  250. createVertexArray(pModel, pData, uiMeshIndex, pMesh);
  251. }
  252. // ------------------------------------------------------------------------------------------------
  253. // Creates a vretex array
  254. void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel,
  255. const ObjFile::Object* pCurrentObject,
  256. unsigned int uiMeshIndex,
  257. aiMesh* pMesh)
  258. {
  259. // Checking preconditions
  260. ai_assert( NULL != pCurrentObject );
  261. // Break, if no faces are stored in object
  262. if (pCurrentObject->m_Faces.empty())
  263. return;
  264. // Get current mesh
  265. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  266. if ( NULL == pObjMesh || pObjMesh->m_uiNumIndices < 1)
  267. return;
  268. // Copy vertices of this mesh instance
  269. pMesh->mNumVertices = (unsigned int) pObjMesh->m_uiNumIndices;
  270. pMesh->mVertices = new aiVector3D[ pMesh->mNumVertices ];
  271. // Allocate buffer for normal vectors
  272. if ( !pModel->m_Normals.empty() && pObjMesh->m_hasNormals )
  273. pMesh->mNormals = new aiVector3D[ pMesh->mNumVertices ];
  274. // Allocate buffer for texture coordinates
  275. if ( !pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0] )
  276. {
  277. pMesh->mNumUVComponents[ 0 ] = 2;
  278. pMesh->mTextureCoords[ 0 ] = new aiVector3D[ pMesh->mNumVertices ];
  279. }
  280. // Copy vertices, normals and textures into aiMesh instance
  281. unsigned int newIndex = 0;
  282. for ( size_t index=0; index < pObjMesh->m_Faces.size(); index++ )
  283. {
  284. // Get destination face
  285. aiFace *pDestFace = &pMesh->mFaces[ index ];
  286. // Get source face
  287. ObjFile::Face *pSourceFace = pObjMesh->m_Faces[ index ];
  288. // Copy all index arrays
  289. for ( size_t vertexIndex = 0; vertexIndex < pSourceFace->m_pVertices->size(); vertexIndex++ )
  290. {
  291. unsigned int vertex = pSourceFace->m_pVertices->at( vertexIndex );
  292. assert ( vertex < pModel->m_Vertices.size() );
  293. pMesh->mVertices[ newIndex ] = pModel->m_Vertices[ vertex ];
  294. // Copy all normals
  295. if ( !pSourceFace->m_pNormals->empty() )
  296. {
  297. const unsigned int normal = pSourceFace->m_pNormals->at( vertexIndex );
  298. ai_assert( normal < pModel->m_Normals.size() );
  299. pMesh->mNormals[ newIndex ] = pModel->m_Normals[ normal ];
  300. }
  301. // Copy all texture coordinates
  302. if ( !pModel->m_TextureCoord.empty() )
  303. {
  304. if ( !pSourceFace->m_pTexturCoords->empty() )
  305. {
  306. const unsigned int tex = pSourceFace->m_pTexturCoords->at( vertexIndex );
  307. ai_assert( tex < pModel->m_TextureCoord.size() );
  308. for ( size_t i=0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; i++)
  309. {
  310. if ( pMesh->mNumUVComponents[ i ] > 0 )
  311. {
  312. aiVector2D coord2d = pModel->m_TextureCoord[ tex ];
  313. pMesh->mTextureCoords[ i ][ newIndex ] = aiVector3D( coord2d.x, coord2d.y, 0.0 );
  314. }
  315. }
  316. }
  317. }
  318. ai_assert( pMesh->mNumVertices > newIndex );
  319. pDestFace->mIndices[ vertexIndex ] = newIndex;
  320. ++newIndex;
  321. }
  322. }
  323. }
  324. // ------------------------------------------------------------------------------------------------
  325. // Counts all stored meshes
  326. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object*> &rObjects, int &iNumMeshes)
  327. {
  328. iNumMeshes = 0;
  329. if (rObjects.empty())
  330. return;
  331. iNumMeshes += (unsigned int)rObjects.size();
  332. for (std::vector<ObjFile::Object*>::const_iterator it = rObjects.begin();
  333. it != rObjects.end();
  334. ++it)
  335. {
  336. if (!(*it)->m_SubObjects.empty())
  337. {
  338. countObjects((*it)->m_SubObjects, iNumMeshes);
  339. }
  340. }
  341. }
  342. // ------------------------------------------------------------------------------------------------
  343. // Creates the material
  344. void ObjFileImporter::createMaterial(const ObjFile::Model* pModel, const ObjFile::Object* pData,
  345. aiScene* pScene)
  346. {
  347. ai_assert (NULL != pScene);
  348. if (NULL == pData)
  349. return;
  350. const unsigned int numMaterials = (unsigned int) pModel->m_MaterialLib.size();
  351. pScene->mNumMaterials = 0;
  352. if ( pModel->m_MaterialLib.empty() )
  353. return;
  354. pScene->mMaterials = new aiMaterial*[ numMaterials ];
  355. for ( unsigned int matIndex = 0; matIndex < numMaterials; matIndex++ )
  356. {
  357. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper();
  358. // Store material name
  359. std::map<std::string, ObjFile::Material*>::const_iterator it = pModel->m_MaterialMap.find( pModel->m_MaterialLib[ matIndex ] );
  360. // No material found, use the default material
  361. if ( pModel->m_MaterialMap.end() == it)
  362. continue;
  363. ObjFile::Material *pCurrentMaterial = (*it).second;
  364. mat->AddProperty( &pCurrentMaterial->MaterialName, AI_MATKEY_NAME );
  365. // convert illumination model
  366. int sm;
  367. switch (pCurrentMaterial->illumination_model)
  368. {
  369. case 0:
  370. sm = aiShadingMode_NoShading;
  371. break;
  372. case 1:
  373. sm = aiShadingMode_Gouraud;
  374. break;
  375. case 2:
  376. sm = aiShadingMode_Phong;
  377. break;
  378. default:
  379. sm = aiShadingMode_Gouraud;
  380. DefaultLogger::get()->error("OBJ/MTL: Unexpected illumination model (0-2 recognized)");
  381. }
  382. mat->AddProperty<int>( &sm, 1, AI_MATKEY_SHADING_MODEL);
  383. // multiplying the specular exponent with 2 seems to yield better results
  384. pCurrentMaterial->shineness *= 4.f;
  385. // Adding material colors
  386. mat->AddProperty( &pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT );
  387. mat->AddProperty( &pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  388. mat->AddProperty( &pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR );
  389. mat->AddProperty( &pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS );
  390. mat->AddProperty( &pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY );
  391. // Adding refraction index
  392. mat->AddProperty( &pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI );
  393. // Adding textures
  394. if ( 0 != pCurrentMaterial->texture.length )
  395. mat->AddProperty( &pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  396. if ( 0 != pCurrentMaterial->textureAmbient.length )
  397. mat->AddProperty( &pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  398. if ( 0 != pCurrentMaterial->textureSpecular.length )
  399. mat->AddProperty( &pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  400. if ( 0 != pCurrentMaterial->textureBump.length )
  401. mat->AddProperty( &pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  402. if ( 0 != pCurrentMaterial->textureOpacity.length )
  403. mat->AddProperty( &pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  404. if ( 0 != pCurrentMaterial->textureSpecularity.length )
  405. mat->AddProperty( &pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  406. // Store material property info in material array in scene
  407. pScene->mMaterials[ pScene->mNumMaterials ] = mat;
  408. pScene->mNumMaterials++;
  409. }
  410. // Test number of created materials.
  411. ai_assert( pScene->mNumMaterials == numMaterials );
  412. }
  413. // ------------------------------------------------------------------------------------------------
  414. // Appends this node to the parent node
  415. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild)
  416. {
  417. // Checking preconditions
  418. ai_assert (NULL != pParent);
  419. ai_assert (NULL != pChild);
  420. // Assign parent to child
  421. pChild->mParent = pParent;
  422. size_t sNumChildren = 0;
  423. // If already children was assigned to the parent node, store them in a
  424. std::vector<aiNode*> temp;
  425. if (pParent->mChildren != NULL)
  426. {
  427. sNumChildren = pParent->mNumChildren;
  428. ai_assert (0 != sNumChildren);
  429. for (size_t index = 0; index < pParent->mNumChildren; index++)
  430. {
  431. temp.push_back(pParent->mChildren [ index ] );
  432. }
  433. delete [] pParent->mChildren;
  434. }
  435. // Copy node instances into parent node
  436. pParent->mNumChildren++;
  437. pParent->mChildren = new aiNode*[ pParent->mNumChildren ];
  438. for (size_t index = 0; index < pParent->mNumChildren-1; index++)
  439. {
  440. pParent->mChildren[ index ] = temp [ index ];
  441. }
  442. pParent->mChildren[ pParent->mNumChildren-1 ] = pChild;
  443. }
  444. // ------------------------------------------------------------------------------------------------
  445. } // Namespace Assimp
  446. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER