2
0

ObjFileImporter.cpp 16 KB

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