ObjFileImporter.cpp 29 KB

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