ObjFileImporter.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 DeadlyImportError( "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 DeadlyImportError( "OBJ-file is too small.");
  90. // Allocate buffer and read file into it
  91. TextFileToBuffer(file.get(),m_Buffer);
  92. // Get the model name
  93. std::string strModelName;
  94. std::string::size_type pos = pFile.find_last_of( "\\/" );
  95. if ( pos != std::string::npos )
  96. {
  97. strModelName = pFile.substr(pos+1, pFile.size() - pos - 1);
  98. }
  99. else
  100. {
  101. strModelName = pFile;
  102. }
  103. // parse the file into a temporary representation
  104. ObjFileParser parser(m_Buffer, strModelName, pIOHandler);
  105. // And create the proper return structures out of it
  106. CreateDataFromImport(parser.GetModel(), pScene);
  107. // Clean up allocated storage for the next import
  108. m_Buffer.clear();
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. // Create the data from parsed obj-file
  112. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model* pModel, aiScene* pScene)
  113. {
  114. if (0L == pModel)
  115. return;
  116. // Create the root node of the scene
  117. pScene->mRootNode = new aiNode();
  118. if (!pModel->m_ModelName.empty())
  119. {
  120. // Set the name of the scene
  121. pScene->mRootNode->mName.Set(pModel->m_ModelName);
  122. }
  123. else
  124. {
  125. // This is an error, so break down the application
  126. ai_assert (false);
  127. }
  128. // Create nodes for the whole scene
  129. std::vector<aiMesh*> MeshArray;
  130. for (size_t index = 0; index < pModel->m_Objects.size(); index++)
  131. {
  132. createNodes(pModel, pModel->m_Objects[ index ], index, pScene->mRootNode, pScene, MeshArray);
  133. }
  134. // Create mesh pointer buffer for this scene
  135. if (pScene->mNumMeshes > 0)
  136. {
  137. pScene->mMeshes = new aiMesh*[ MeshArray.size() ];
  138. for (size_t index =0; index < MeshArray.size(); index++)
  139. {
  140. pScene->mMeshes [ index ] = MeshArray[ index ];
  141. }
  142. }
  143. // Create all materials
  144. createMaterials( pModel, pScene );
  145. }
  146. // ------------------------------------------------------------------------------------------------
  147. // Creates all nodes of the model
  148. aiNode *ObjFileImporter::createNodes(const ObjFile::Model* pModel, const ObjFile::Object* pData,
  149. unsigned int uiMeshIndex,
  150. aiNode *pParent, aiScene* pScene,
  151. std::vector<aiMesh*> &MeshArray)
  152. {
  153. ai_assert( NULL != pModel );
  154. if (NULL == pData)
  155. return NULL;
  156. // Store older mesh size to be able to computate mesh offsets for new mesh instances
  157. const size_t oldMeshSize = MeshArray.size();
  158. aiNode *pNode = new aiNode();
  159. if (pParent != NULL)
  160. this->appendChildToParentNode(pParent, pNode);
  161. aiMesh *pMesh = new aiMesh;
  162. createTopology( pModel, pData, uiMeshIndex, pMesh );
  163. if ( pMesh->mNumVertices > 0 )
  164. {
  165. MeshArray.push_back( pMesh );
  166. }
  167. else
  168. {
  169. delete pMesh;
  170. }
  171. // Create all nodes from the subobjects stored in the current object
  172. if ( !pData->m_SubObjects.empty() )
  173. {
  174. pNode->mNumChildren = (unsigned int)pData->m_SubObjects.size();
  175. pNode->mChildren = new aiNode*[pData->m_SubObjects.size()];
  176. pNode->mNumMeshes = 1;
  177. pNode->mMeshes = new unsigned int[1];
  178. }
  179. // Set mesh instances into scene- and node-instances
  180. const size_t meshSizeDiff = MeshArray.size()- oldMeshSize;
  181. if ( meshSizeDiff > 0 )
  182. {
  183. pNode->mMeshes = new unsigned int[ meshSizeDiff ];
  184. pNode->mNumMeshes = (unsigned int)meshSizeDiff;
  185. size_t index = 0;
  186. for (size_t i = oldMeshSize; i < MeshArray.size(); i++)
  187. {
  188. pNode->mMeshes[ index ] = pScene->mNumMeshes;
  189. pScene->mNumMeshes++;
  190. index++;
  191. }
  192. }
  193. return pNode;
  194. }
  195. // ------------------------------------------------------------------------------------------------
  196. // Create topology data
  197. void ObjFileImporter::createTopology(const ObjFile::Model* pModel,
  198. const ObjFile::Object* pData,
  199. unsigned int uiMeshIndex,
  200. aiMesh* pMesh )
  201. {
  202. // Checking preconditions
  203. ai_assert( NULL != pModel );
  204. if (NULL == pData)
  205. return;
  206. // Create faces
  207. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  208. ai_assert( NULL != pObjMesh );
  209. pMesh->mNumFaces = static_cast<unsigned int>( pObjMesh->m_Faces.size() );
  210. if ( pMesh->mNumFaces > 0 )
  211. {
  212. pMesh->mFaces = new aiFace[ pMesh->mNumFaces ];
  213. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  214. // Copy all data from all stored meshes
  215. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++)
  216. {
  217. aiFace *pFace = &pMesh->mFaces[ index ];
  218. const unsigned int uiNumIndices = (unsigned int) pObjMesh->m_Faces[ index ]->m_pVertices->size();
  219. pFace->mNumIndices = (unsigned int) uiNumIndices;
  220. if (pFace->mNumIndices > 0)
  221. {
  222. pFace->mIndices = new unsigned int[ uiNumIndices ];
  223. ObjFile::Face::IndexArray *pIndexArray = pObjMesh->m_Faces[ index ]->m_pVertices;
  224. ai_assert ( NULL != pIndexArray );
  225. for ( size_t a=0; a<pFace->mNumIndices; a++ )
  226. {
  227. pFace->mIndices[ a ] = pIndexArray->at( a );
  228. }
  229. }
  230. else
  231. {
  232. pFace->mIndices = NULL;
  233. }
  234. }
  235. }
  236. // Create mesh vertices
  237. createVertexArray(pModel, pData, uiMeshIndex, pMesh);
  238. }
  239. // ------------------------------------------------------------------------------------------------
  240. // Creates a vretex array
  241. void ObjFileImporter::createVertexArray(const ObjFile::Model* pModel,
  242. const ObjFile::Object* pCurrentObject,
  243. unsigned int uiMeshIndex,
  244. aiMesh* pMesh)
  245. {
  246. // Checking preconditions
  247. ai_assert( NULL != pCurrentObject );
  248. // Break, if no faces are stored in object
  249. if (pCurrentObject->m_Faces.empty())
  250. return;
  251. // Get current mesh
  252. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[ uiMeshIndex ];
  253. if ( NULL == pObjMesh || pObjMesh->m_uiNumIndices < 1)
  254. return;
  255. // Copy vertices of this mesh instance
  256. pMesh->mNumVertices = (unsigned int) pObjMesh->m_uiNumIndices;
  257. pMesh->mVertices = new aiVector3D[ pMesh->mNumVertices ];
  258. // Allocate buffer for normal vectors
  259. if ( !pModel->m_Normals.empty() && pObjMesh->m_hasNormals )
  260. pMesh->mNormals = new aiVector3D[ pMesh->mNumVertices ];
  261. // Allocate buffer for texture coordinates
  262. if ( !pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0] )
  263. {
  264. pMesh->mNumUVComponents[ 0 ] = 2;
  265. pMesh->mTextureCoords[ 0 ] = new aiVector3D[ pMesh->mNumVertices ];
  266. }
  267. // Copy vertices, normals and textures into aiMesh instance
  268. unsigned int newIndex = 0;
  269. for ( size_t index=0; index < pObjMesh->m_Faces.size(); index++ )
  270. {
  271. // Get destination face
  272. aiFace *pDestFace = &pMesh->mFaces[ index ];
  273. // Get source face
  274. ObjFile::Face *pSourceFace = pObjMesh->m_Faces[ index ];
  275. // Copy all index arrays
  276. for ( size_t vertexIndex = 0; vertexIndex < pSourceFace->m_pVertices->size(); vertexIndex++ )
  277. {
  278. unsigned int vertex = pSourceFace->m_pVertices->at( vertexIndex );
  279. assert ( vertex < pModel->m_Vertices.size() );
  280. pMesh->mVertices[ newIndex ] = pModel->m_Vertices[ vertex ];
  281. // Copy all normals
  282. if ( !pSourceFace->m_pNormals->empty() )
  283. {
  284. const unsigned int normal = pSourceFace->m_pNormals->at( vertexIndex );
  285. ai_assert( normal < pModel->m_Normals.size() );
  286. pMesh->mNormals[ newIndex ] = pModel->m_Normals[ normal ];
  287. }
  288. // Copy all texture coordinates
  289. if ( !pModel->m_TextureCoord.empty() )
  290. {
  291. if ( !pSourceFace->m_pTexturCoords->empty() )
  292. {
  293. const unsigned int tex = pSourceFace->m_pTexturCoords->at( vertexIndex );
  294. ai_assert( tex < pModel->m_TextureCoord.size() );
  295. for ( size_t i=0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; i++)
  296. {
  297. if ( pMesh->mNumUVComponents[ i ] > 0 )
  298. {
  299. aiVector2D coord2d = pModel->m_TextureCoord[ tex ];
  300. pMesh->mTextureCoords[ i ][ newIndex ] = aiVector3D( coord2d.x, coord2d.y, 0.0 );
  301. }
  302. }
  303. }
  304. }
  305. ai_assert( pMesh->mNumVertices > newIndex );
  306. pDestFace->mIndices[ vertexIndex ] = newIndex;
  307. ++newIndex;
  308. }
  309. }
  310. }
  311. // ------------------------------------------------------------------------------------------------
  312. // Counts all stored meshes
  313. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object*> &rObjects, int &iNumMeshes)
  314. {
  315. iNumMeshes = 0;
  316. if (rObjects.empty())
  317. return;
  318. iNumMeshes += (unsigned int)rObjects.size();
  319. for (std::vector<ObjFile::Object*>::const_iterator it = rObjects.begin();
  320. it != rObjects.end();
  321. ++it)
  322. {
  323. if (!(*it)->m_SubObjects.empty())
  324. {
  325. countObjects((*it)->m_SubObjects, iNumMeshes);
  326. }
  327. }
  328. }
  329. // ------------------------------------------------------------------------------------------------
  330. // Creates the material
  331. void ObjFileImporter::createMaterials(const ObjFile::Model* pModel, aiScene* pScene )
  332. {
  333. ai_assert( NULL != pScene );
  334. if ( NULL == pScene )
  335. return;
  336. const unsigned int numMaterials = (unsigned int) pModel->m_MaterialLib.size();
  337. pScene->mNumMaterials = 0;
  338. if ( pModel->m_MaterialLib.empty() )
  339. return;
  340. pScene->mMaterials = new aiMaterial*[ numMaterials ];
  341. for ( unsigned int matIndex = 0; matIndex < numMaterials; matIndex++ )
  342. {
  343. Assimp::MaterialHelper* mat = new Assimp::MaterialHelper();
  344. // Store material name
  345. std::map<std::string, ObjFile::Material*>::const_iterator it = pModel->m_MaterialMap.find( pModel->m_MaterialLib[ matIndex ] );
  346. // No material found, use the default material
  347. if ( pModel->m_MaterialMap.end() == it)
  348. continue;
  349. ObjFile::Material *pCurrentMaterial = (*it).second;
  350. mat->AddProperty( &pCurrentMaterial->MaterialName, AI_MATKEY_NAME );
  351. // convert illumination model
  352. int sm;
  353. switch (pCurrentMaterial->illumination_model)
  354. {
  355. case 0:
  356. sm = aiShadingMode_NoShading;
  357. break;
  358. case 1:
  359. sm = aiShadingMode_Gouraud;
  360. break;
  361. case 2:
  362. sm = aiShadingMode_Phong;
  363. break;
  364. default:
  365. sm = aiShadingMode_Gouraud;
  366. DefaultLogger::get()->error("OBJ/MTL: Unexpected illumination model (0-2 recognized)");
  367. }
  368. mat->AddProperty<int>( &sm, 1, AI_MATKEY_SHADING_MODEL);
  369. // multiplying the specular exponent with 2 seems to yield better results
  370. pCurrentMaterial->shineness *= 4.f;
  371. // Adding material colors
  372. mat->AddProperty( &pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT );
  373. mat->AddProperty( &pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE );
  374. mat->AddProperty( &pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR );
  375. mat->AddProperty( &pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS );
  376. mat->AddProperty( &pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY );
  377. // Adding refraction index
  378. mat->AddProperty( &pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI );
  379. // Adding textures
  380. if ( 0 != pCurrentMaterial->texture.length )
  381. mat->AddProperty( &pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  382. if ( 0 != pCurrentMaterial->textureAmbient.length )
  383. mat->AddProperty( &pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  384. if ( 0 != pCurrentMaterial->textureSpecular.length )
  385. mat->AddProperty( &pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  386. if ( 0 != pCurrentMaterial->textureBump.length )
  387. mat->AddProperty( &pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  388. if ( 0 != pCurrentMaterial->textureOpacity.length )
  389. mat->AddProperty( &pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  390. if ( 0 != pCurrentMaterial->textureSpecularity.length )
  391. mat->AddProperty( &pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  392. // Store material property info in material array in scene
  393. pScene->mMaterials[ pScene->mNumMaterials ] = mat;
  394. pScene->mNumMaterials++;
  395. }
  396. // Test number of created materials.
  397. ai_assert( pScene->mNumMaterials == numMaterials );
  398. }
  399. // ------------------------------------------------------------------------------------------------
  400. // Appends this node to the parent node
  401. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild)
  402. {
  403. // Checking preconditions
  404. ai_assert (NULL != pParent);
  405. ai_assert (NULL != pChild);
  406. // Assign parent to child
  407. pChild->mParent = pParent;
  408. size_t sNumChildren = 0;
  409. // If already children was assigned to the parent node, store them in a
  410. std::vector<aiNode*> temp;
  411. if (pParent->mChildren != NULL)
  412. {
  413. sNumChildren = pParent->mNumChildren;
  414. ai_assert (0 != sNumChildren);
  415. for (size_t index = 0; index < pParent->mNumChildren; index++)
  416. {
  417. temp.push_back(pParent->mChildren [ index ] );
  418. }
  419. delete [] pParent->mChildren;
  420. }
  421. // Copy node instances into parent node
  422. pParent->mNumChildren++;
  423. pParent->mChildren = new aiNode*[ pParent->mNumChildren ];
  424. for (size_t index = 0; index < pParent->mNumChildren-1; index++)
  425. {
  426. pParent->mChildren[ index ] = temp [ index ];
  427. }
  428. pParent->mChildren[ pParent->mNumChildren-1 ] = pChild;
  429. }
  430. // ------------------------------------------------------------------------------------------------
  431. } // Namespace Assimp
  432. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER