ObjFileParser.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, 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 "ObjFileParser.h"
  36. #include "ObjFileMtlImporter.h"
  37. #include "ObjTools.h"
  38. #include "ObjFileData.h"
  39. #include "ParsingUtils.h"
  40. #include "DefaultIOSystem.h"
  41. #include "BaseImporter.h"
  42. #include <assimp/DefaultLogger.hpp>
  43. #include <assimp/material.h>
  44. #include <assimp/Importer.hpp>
  45. #include <cstdlib>
  46. namespace Assimp {
  47. const std::string ObjFileParser::DEFAULT_MATERIAL = AI_DEFAULT_MATERIAL_NAME;
  48. // -------------------------------------------------------------------
  49. // Constructor with loaded data and directories.
  50. ObjFileParser::ObjFileParser( IOStreamBuffer<char> &streamBuffer, const std::string &modelName, IOSystem *io, ProgressHandler* progress, const std::string &originalObjFileName) :
  51. m_DataIt(),
  52. m_DataItEnd(),
  53. m_pModel(NULL),
  54. m_uiLine(0),
  55. m_pIO( io ),
  56. m_progress(progress),
  57. m_originalObjFileName(originalObjFileName)
  58. {
  59. std::fill_n(m_buffer,Buffersize,0);
  60. // Create the model instance to store all the data
  61. m_pModel = new ObjFile::Model();
  62. m_pModel->m_ModelName = modelName;
  63. // create default material and store it
  64. m_pModel->m_pDefaultMaterial = new ObjFile::Material;
  65. m_pModel->m_pDefaultMaterial->MaterialName.Set( DEFAULT_MATERIAL );
  66. m_pModel->m_MaterialLib.push_back( DEFAULT_MATERIAL );
  67. m_pModel->m_MaterialMap[ DEFAULT_MATERIAL ] = m_pModel->m_pDefaultMaterial;
  68. // Start parsing the file
  69. parseFile( streamBuffer );
  70. }
  71. // -------------------------------------------------------------------
  72. // Destructor
  73. ObjFileParser::~ObjFileParser()
  74. {
  75. delete m_pModel;
  76. m_pModel = NULL;
  77. }
  78. // -------------------------------------------------------------------
  79. // Returns a pointer to the model instance.
  80. ObjFile::Model *ObjFileParser::GetModel() const
  81. {
  82. return m_pModel;
  83. }
  84. // -------------------------------------------------------------------
  85. // File parsing method.
  86. void ObjFileParser::parseFile( IOStreamBuffer<char> &streamBuffer ) {
  87. // only update every 100KB or it'll be too slow
  88. const unsigned int updateProgressEveryBytes = 100 * 1024;
  89. unsigned int progressCounter = 0;
  90. const unsigned int bytesToProcess = streamBuffer.size();
  91. const unsigned int progressTotal = 3 * bytesToProcess;
  92. const unsigned int progressOffset = bytesToProcess;
  93. unsigned int processed = 0;
  94. //DataArrayIt lastDataIt = m_DataIt;
  95. bool endOfFile( false );
  96. std::vector<char> buffer;
  97. //while ( m_DataIt != m_DataItEnd )
  98. while ( streamBuffer.getNextLine( buffer ) ) {
  99. m_DataIt = buffer.begin();
  100. m_DataItEnd = buffer.end();
  101. // Handle progress reporting
  102. /*processed += std::distance(lastDataIt, m_DataIt);
  103. lastDataIt = m_DataIt;
  104. if (processed > (progressCounter * updateProgressEveryBytes))
  105. {
  106. progressCounter++;
  107. m_progress->UpdateFileRead(progressOffset + processed*2, progressTotal);
  108. }*/
  109. // parse line
  110. switch (*m_DataIt)
  111. {
  112. case 'v': // Parse a vertex texture coordinate
  113. {
  114. ++m_DataIt;
  115. if (*m_DataIt == ' ' || *m_DataIt == '\t') {
  116. size_t numComponents = getNumComponentsInLine();
  117. if (numComponents == 3) {
  118. // read in vertex definition
  119. getVector3(m_pModel->m_Vertices);
  120. } else if (numComponents == 4) {
  121. // read in vertex definition (homogeneous coords)
  122. getHomogeneousVector3(m_pModel->m_Vertices);
  123. } else if (numComponents == 6) {
  124. // read vertex and vertex-color
  125. getTwoVectors3(m_pModel->m_Vertices, m_pModel->m_VertexColors);
  126. }
  127. } else if (*m_DataIt == 't') {
  128. // read in texture coordinate ( 2D or 3D )
  129. ++m_DataIt;
  130. getVector( m_pModel->m_TextureCoord );
  131. } else if (*m_DataIt == 'n') {
  132. // Read in normal vector definition
  133. ++m_DataIt;
  134. getVector3( m_pModel->m_Normals );
  135. }
  136. }
  137. break;
  138. case 'p': // Parse a face, line or point statement
  139. case 'l':
  140. case 'f':
  141. {
  142. getFace(*m_DataIt == 'f' ? aiPrimitiveType_POLYGON : (*m_DataIt == 'l'
  143. ? aiPrimitiveType_LINE : aiPrimitiveType_POINT));
  144. }
  145. break;
  146. case '#': // Parse a comment
  147. {
  148. getComment();
  149. }
  150. break;
  151. case 'u': // Parse a material desc. setter
  152. {
  153. getMaterialDesc();
  154. }
  155. break;
  156. case 'm': // Parse a material library or merging group ('mg')
  157. {
  158. std::string name;
  159. getName(m_DataIt, m_DataItEnd, name);
  160. size_t nextSpace = name.find(" ");
  161. if (nextSpace != std::string::npos)
  162. name = name.substr(0, nextSpace);
  163. if (name == "mg")
  164. getGroupNumberAndResolution();
  165. else if(name == "mtllib")
  166. getMaterialLib();
  167. else
  168. goto pf_skip_line;
  169. }
  170. break;
  171. case 'g': // Parse group name
  172. {
  173. getGroupName();
  174. }
  175. break;
  176. case 's': // Parse group number
  177. {
  178. getGroupNumber();
  179. }
  180. break;
  181. case 'o': // Parse object name
  182. {
  183. getObjectName();
  184. }
  185. break;
  186. default:
  187. {
  188. pf_skip_line:
  189. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  190. }
  191. break;
  192. }
  193. }
  194. }
  195. // -------------------------------------------------------------------
  196. // Copy the next word in a temporary buffer
  197. void ObjFileParser::copyNextWord(char *pBuffer, size_t length)
  198. {
  199. size_t index = 0;
  200. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  201. while( m_DataIt != m_DataItEnd && !IsSpaceOrNewLine( *m_DataIt ) ) {
  202. pBuffer[index] = *m_DataIt;
  203. index++;
  204. if( index == length - 1 ) {
  205. break;
  206. }
  207. ++m_DataIt;
  208. }
  209. ai_assert(index < length);
  210. pBuffer[index] = '\0';
  211. }
  212. // -------------------------------------------------------------------
  213. // Copy the next line into a temporary buffer
  214. void ObjFileParser::copyNextLine(char *pBuffer, size_t length)
  215. {
  216. size_t index = 0u;
  217. // some OBJ files have line continuations using \ (such as in C++ et al)
  218. bool continuation = false;
  219. for (;m_DataIt != m_DataItEnd && index < length-1; ++m_DataIt)
  220. {
  221. const char c = *m_DataIt;
  222. if (c == '\\') {
  223. continuation = true;
  224. continue;
  225. }
  226. if (c == '\n' || c == '\r') {
  227. if(continuation) {
  228. pBuffer[ index++ ] = ' ';
  229. continue;
  230. }
  231. break;
  232. }
  233. continuation = false;
  234. pBuffer[ index++ ] = c;
  235. }
  236. ai_assert(index < length);
  237. pBuffer[ index ] = '\0';
  238. }
  239. size_t ObjFileParser::getNumComponentsInLine() {
  240. size_t numComponents( 0 );
  241. const char* tmp( &m_DataIt[0] );
  242. while( !IsLineEnd( *tmp ) ) {
  243. if ( !SkipSpaces( &tmp ) ) {
  244. break;
  245. }
  246. SkipToken( tmp );
  247. ++numComponents;
  248. }
  249. return numComponents;
  250. }
  251. // -------------------------------------------------------------------
  252. void ObjFileParser::getVector( std::vector<aiVector3D> &point3d_array ) {
  253. size_t numComponents = getNumComponentsInLine();
  254. ai_real x, y, z;
  255. if( 2 == numComponents ) {
  256. copyNextWord( m_buffer, Buffersize );
  257. x = ( ai_real ) fast_atof( m_buffer );
  258. copyNextWord( m_buffer, Buffersize );
  259. y = ( ai_real ) fast_atof( m_buffer );
  260. z = 0.0;
  261. } else if( 3 == numComponents ) {
  262. copyNextWord( m_buffer, Buffersize );
  263. x = ( ai_real ) fast_atof( m_buffer );
  264. copyNextWord( m_buffer, Buffersize );
  265. y = ( ai_real ) fast_atof( m_buffer );
  266. copyNextWord( m_buffer, Buffersize );
  267. z = ( ai_real ) fast_atof( m_buffer );
  268. } else {
  269. throw DeadlyImportError( "OBJ: Invalid number of components" );
  270. }
  271. point3d_array.push_back( aiVector3D( x, y, z ) );
  272. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  273. }
  274. // -------------------------------------------------------------------
  275. // Get values for a new 3D vector instance
  276. void ObjFileParser::getVector3( std::vector<aiVector3D> &point3d_array ) {
  277. ai_real x, y, z;
  278. copyNextWord(m_buffer, Buffersize);
  279. x = (ai_real) fast_atof(m_buffer);
  280. copyNextWord(m_buffer, Buffersize);
  281. y = (ai_real) fast_atof(m_buffer);
  282. copyNextWord( m_buffer, Buffersize );
  283. z = ( ai_real ) fast_atof( m_buffer );
  284. point3d_array.push_back( aiVector3D( x, y, z ) );
  285. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  286. }
  287. void ObjFileParser::getHomogeneousVector3( std::vector<aiVector3D> &point3d_array ) {
  288. ai_real x, y, z, w;
  289. copyNextWord(m_buffer, Buffersize);
  290. x = (ai_real) fast_atof(m_buffer);
  291. copyNextWord(m_buffer, Buffersize);
  292. y = (ai_real) fast_atof(m_buffer);
  293. copyNextWord( m_buffer, Buffersize );
  294. z = ( ai_real ) fast_atof( m_buffer );
  295. copyNextWord( m_buffer, Buffersize );
  296. w = ( ai_real ) fast_atof( m_buffer );
  297. ai_assert( w != 0 );
  298. point3d_array.push_back( aiVector3D( x/w, y/w, z/w ) );
  299. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  300. }
  301. // -------------------------------------------------------------------
  302. // Get values for two 3D vectors on the same line
  303. void ObjFileParser::getTwoVectors3( std::vector<aiVector3D> &point3d_array_a, std::vector<aiVector3D> &point3d_array_b ) {
  304. ai_real x, y, z;
  305. copyNextWord(m_buffer, Buffersize);
  306. x = (ai_real) fast_atof(m_buffer);
  307. copyNextWord(m_buffer, Buffersize);
  308. y = (ai_real) fast_atof(m_buffer);
  309. copyNextWord( m_buffer, Buffersize );
  310. z = ( ai_real ) fast_atof( m_buffer );
  311. point3d_array_a.push_back( aiVector3D( x, y, z ) );
  312. copyNextWord(m_buffer, Buffersize);
  313. x = (ai_real) fast_atof(m_buffer);
  314. copyNextWord(m_buffer, Buffersize);
  315. y = (ai_real) fast_atof(m_buffer);
  316. copyNextWord( m_buffer, Buffersize );
  317. z = ( ai_real ) fast_atof( m_buffer );
  318. point3d_array_b.push_back( aiVector3D( x, y, z ) );
  319. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  320. }
  321. // -------------------------------------------------------------------
  322. // Get values for a new 2D vector instance
  323. void ObjFileParser::getVector2( std::vector<aiVector2D> &point2d_array ) {
  324. ai_real x, y;
  325. copyNextWord(m_buffer, Buffersize);
  326. x = (ai_real) fast_atof(m_buffer);
  327. copyNextWord(m_buffer, Buffersize);
  328. y = (ai_real) fast_atof(m_buffer);
  329. point2d_array.push_back(aiVector2D(x, y));
  330. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  331. }
  332. static const std::string DefaultObjName = "defaultobject";
  333. // -------------------------------------------------------------------
  334. // Get values for a new face instance
  335. void ObjFileParser::getFace(aiPrimitiveType type) {
  336. copyNextLine(m_buffer, Buffersize);
  337. char *pPtr = m_buffer;
  338. char *pEnd = &pPtr[Buffersize];
  339. pPtr = getNextToken<char*>(pPtr, pEnd);
  340. if ( pPtr == pEnd || *pPtr == '\0' ) {
  341. return;
  342. }
  343. std::vector<unsigned int> *pIndices = new std::vector<unsigned int>;
  344. std::vector<unsigned int> *pTexID = new std::vector<unsigned int>;
  345. std::vector<unsigned int> *pNormalID = new std::vector<unsigned int>;
  346. bool hasNormal = false;
  347. const int vSize = m_pModel->m_Vertices.size();
  348. const int vtSize = m_pModel->m_TextureCoord.size();
  349. const int vnSize = m_pModel->m_Normals.size();
  350. const bool vt = (!m_pModel->m_TextureCoord.empty());
  351. const bool vn = (!m_pModel->m_Normals.empty());
  352. int iStep = 0, iPos = 0;
  353. while (pPtr != pEnd) {
  354. iStep = 1;
  355. if ( IsLineEnd( *pPtr ) ) {
  356. break;
  357. }
  358. if (*pPtr=='/' ) {
  359. if (type == aiPrimitiveType_POINT) {
  360. DefaultLogger::get()->error("Obj: Separator unexpected in point statement");
  361. }
  362. if (iPos == 0) {
  363. //if there are no texture coordinates in the file, but normals
  364. if (!vt && vn) {
  365. iPos = 1;
  366. iStep++;
  367. }
  368. }
  369. iPos++;
  370. } else if( IsSpaceOrNewLine( *pPtr ) ) {
  371. iPos = 0;
  372. } else {
  373. //OBJ USES 1 Base ARRAYS!!!!
  374. const int iVal( ::atoi( pPtr ) );
  375. // increment iStep position based off of the sign and # of digits
  376. int tmp = iVal;
  377. if ( iVal < 0 ) {
  378. ++iStep;
  379. }
  380. while ( ( tmp = tmp / 10 ) != 0 ) {
  381. ++iStep;
  382. }
  383. if ( iVal > 0 )
  384. {
  385. // Store parsed index
  386. if ( 0 == iPos )
  387. {
  388. pIndices->push_back( iVal-1 );
  389. }
  390. else if ( 1 == iPos )
  391. {
  392. pTexID->push_back( iVal-1 );
  393. }
  394. else if ( 2 == iPos )
  395. {
  396. pNormalID->push_back( iVal-1 );
  397. hasNormal = true;
  398. }
  399. else
  400. {
  401. reportErrorTokenInFace();
  402. }
  403. }
  404. else if ( iVal < 0 )
  405. {
  406. // Store relatively index
  407. if ( 0 == iPos )
  408. {
  409. pIndices->push_back( vSize + iVal );
  410. }
  411. else if ( 1 == iPos )
  412. {
  413. pTexID->push_back( vtSize + iVal );
  414. }
  415. else if ( 2 == iPos )
  416. {
  417. pNormalID->push_back( vnSize + iVal );
  418. hasNormal = true;
  419. }
  420. else
  421. {
  422. reportErrorTokenInFace();
  423. }
  424. }
  425. }
  426. pPtr += iStep;
  427. }
  428. if ( pIndices->empty() ) {
  429. DefaultLogger::get()->error("Obj: Ignoring empty face");
  430. // skip line and clean up
  431. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  432. delete pNormalID;
  433. delete pTexID;
  434. delete pIndices;
  435. return;
  436. }
  437. ObjFile::Face *face = new ObjFile::Face( pIndices, pNormalID, pTexID, type );
  438. // Set active material, if one set
  439. if( NULL != m_pModel->m_pCurrentMaterial ) {
  440. face->m_pMaterial = m_pModel->m_pCurrentMaterial;
  441. } else {
  442. face->m_pMaterial = m_pModel->m_pDefaultMaterial;
  443. }
  444. // Create a default object, if nothing is there
  445. if( NULL == m_pModel->m_pCurrent ) {
  446. createObject( DefaultObjName );
  447. }
  448. // Assign face to mesh
  449. if ( NULL == m_pModel->m_pCurrentMesh ) {
  450. createMesh( DefaultObjName );
  451. }
  452. // Store the face
  453. m_pModel->m_pCurrentMesh->m_Faces.push_back( face );
  454. m_pModel->m_pCurrentMesh->m_uiNumIndices += (unsigned int)face->m_pVertices->size();
  455. m_pModel->m_pCurrentMesh->m_uiUVCoordinates[ 0 ] += (unsigned int)face->m_pTexturCoords[0].size();
  456. if( !m_pModel->m_pCurrentMesh->m_hasNormals && hasNormal ) {
  457. m_pModel->m_pCurrentMesh->m_hasNormals = true;
  458. }
  459. // Skip the rest of the line
  460. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  461. }
  462. // -------------------------------------------------------------------
  463. // Get values for a new material description
  464. void ObjFileParser::getMaterialDesc()
  465. {
  466. // Get next data for material data
  467. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  468. if (m_DataIt == m_DataItEnd) {
  469. return;
  470. }
  471. char *pStart = &(*m_DataIt);
  472. while( m_DataIt != m_DataItEnd && !IsLineEnd( *m_DataIt ) ) {
  473. ++m_DataIt;
  474. }
  475. // In some cases we should ignore this 'usemtl' command, this variable helps us to do so
  476. bool skip = false;
  477. // Get name
  478. std::string strName(pStart, &(*m_DataIt));
  479. strName = trim_whitespaces(strName);
  480. if (strName.empty())
  481. skip = true;
  482. // If the current mesh has the same material, we simply ignore that 'usemtl' command
  483. // There is no need to create another object or even mesh here
  484. if (m_pModel->m_pCurrentMaterial && m_pModel->m_pCurrentMaterial->MaterialName == aiString(strName))
  485. skip = true;
  486. if (!skip)
  487. {
  488. // Search for material
  489. std::map<std::string, ObjFile::Material*>::iterator it = m_pModel->m_MaterialMap.find(strName);
  490. if (it == m_pModel->m_MaterialMap.end())
  491. {
  492. // Not found, use default material
  493. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  494. DefaultLogger::get()->error("OBJ: failed to locate material " + strName + ", skipping");
  495. strName = m_pModel->m_pDefaultMaterial->MaterialName.C_Str();
  496. }
  497. else
  498. {
  499. // Found, using detected material
  500. m_pModel->m_pCurrentMaterial = (*it).second;
  501. }
  502. if (needsNewMesh(strName))
  503. createMesh(strName);
  504. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex(strName);
  505. }
  506. // Skip rest of line
  507. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  508. }
  509. // -------------------------------------------------------------------
  510. // Get a comment, values will be skipped
  511. void ObjFileParser::getComment()
  512. {
  513. while (m_DataIt != m_DataItEnd)
  514. {
  515. if ( '\n' == (*m_DataIt))
  516. {
  517. ++m_DataIt;
  518. break;
  519. }
  520. else
  521. {
  522. ++m_DataIt;
  523. }
  524. }
  525. }
  526. // -------------------------------------------------------------------
  527. // Get material library from file.
  528. void ObjFileParser::getMaterialLib()
  529. {
  530. // Translate tuple
  531. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  532. if( m_DataIt == m_DataItEnd ) {
  533. return;
  534. }
  535. char *pStart = &(*m_DataIt);
  536. while( m_DataIt != m_DataItEnd && !IsLineEnd( *m_DataIt ) ) {
  537. ++m_DataIt;
  538. }
  539. // Check for existence
  540. const std::string strMatName(pStart, &(*m_DataIt));
  541. std::string absName;
  542. // Check if directive is valid.
  543. if(!strMatName.length()) throw DeadlyImportError("File name of the material is absent.");
  544. if ( m_pIO->StackSize() > 0 ) {
  545. std::string path = m_pIO->CurrentDirectory();
  546. if ( '/' != *path.rbegin() ) {
  547. path += '/';
  548. }
  549. absName = path + strMatName;
  550. } else {
  551. absName = strMatName;
  552. }
  553. IOStream *pFile = m_pIO->Open( absName );
  554. if (!pFile ) {
  555. DefaultLogger::get()->error("OBJ: Unable to locate material file " + strMatName);
  556. std::string strMatFallbackName = m_originalObjFileName.substr(0, m_originalObjFileName.length() - 3) + "mtl";
  557. DefaultLogger::get()->info("OBJ: Opening fallback material file " + strMatFallbackName);
  558. pFile = m_pIO->Open(strMatFallbackName);
  559. if (!pFile) {
  560. DefaultLogger::get()->error("OBJ: Unable to locate fallback material file " + strMatName);
  561. m_DataIt = skipLine<DataArrayIt>(m_DataIt, m_DataItEnd, m_uiLine);
  562. return;
  563. }
  564. }
  565. // Import material library data from file.
  566. // Some exporters (e.g. Silo) will happily write out empty
  567. // material files if the model doesn't use any materials, so we
  568. // allow that.
  569. std::vector<char> buffer;
  570. BaseImporter::TextFileToBuffer( pFile, buffer, BaseImporter::ALLOW_EMPTY );
  571. m_pIO->Close( pFile );
  572. // Importing the material library
  573. ObjFileMtlImporter mtlImporter( buffer, strMatName, m_pModel );
  574. }
  575. // -------------------------------------------------------------------
  576. // Set a new material definition as the current material.
  577. void ObjFileParser::getNewMaterial()
  578. {
  579. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  580. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  581. if( m_DataIt == m_DataItEnd ) {
  582. return;
  583. }
  584. char *pStart = &(*m_DataIt);
  585. std::string strMat( pStart, *m_DataIt );
  586. while( m_DataIt != m_DataItEnd && IsSpaceOrNewLine( *m_DataIt ) ) {
  587. ++m_DataIt;
  588. }
  589. std::map<std::string, ObjFile::Material*>::iterator it = m_pModel->m_MaterialMap.find( strMat );
  590. if ( it == m_pModel->m_MaterialMap.end() )
  591. {
  592. // Show a warning, if material was not found
  593. DefaultLogger::get()->warn("OBJ: Unsupported material requested: " + strMat);
  594. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  595. }
  596. else
  597. {
  598. // Set new material
  599. if ( needsNewMesh( strMat ) )
  600. {
  601. createMesh( strMat );
  602. }
  603. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex( strMat );
  604. }
  605. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  606. }
  607. // -------------------------------------------------------------------
  608. int ObjFileParser::getMaterialIndex( const std::string &strMaterialName )
  609. {
  610. int mat_index = -1;
  611. if( strMaterialName.empty() ) {
  612. return mat_index;
  613. }
  614. for (size_t index = 0; index < m_pModel->m_MaterialLib.size(); ++index)
  615. {
  616. if ( strMaterialName == m_pModel->m_MaterialLib[ index ])
  617. {
  618. mat_index = (int)index;
  619. break;
  620. }
  621. }
  622. return mat_index;
  623. }
  624. // -------------------------------------------------------------------
  625. // Getter for a group name.
  626. void ObjFileParser::getGroupName() {
  627. std::string groupName;
  628. // here we skip 'g ' from line
  629. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  630. m_DataIt = getName<DataArrayIt>(m_DataIt, m_DataItEnd, groupName);
  631. if( isEndOfBuffer( m_DataIt, m_DataItEnd ) ) {
  632. return;
  633. }
  634. // Change active group, if necessary
  635. if ( m_pModel->m_strActiveGroup != groupName ) {
  636. // Search for already existing entry
  637. ObjFile::Model::ConstGroupMapIt it = m_pModel->m_Groups.find(groupName);
  638. // We are mapping groups into the object structure
  639. createObject( groupName );
  640. // New group name, creating a new entry
  641. if (it == m_pModel->m_Groups.end())
  642. {
  643. std::vector<unsigned int> *pFaceIDArray = new std::vector<unsigned int>;
  644. m_pModel->m_Groups[ groupName ] = pFaceIDArray;
  645. m_pModel->m_pGroupFaceIDs = (pFaceIDArray);
  646. }
  647. else
  648. {
  649. m_pModel->m_pGroupFaceIDs = (*it).second;
  650. }
  651. m_pModel->m_strActiveGroup = groupName;
  652. }
  653. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  654. }
  655. // -------------------------------------------------------------------
  656. // Not supported
  657. void ObjFileParser::getGroupNumber()
  658. {
  659. // Not used
  660. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  661. }
  662. // -------------------------------------------------------------------
  663. // Not supported
  664. void ObjFileParser::getGroupNumberAndResolution()
  665. {
  666. // Not used
  667. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  668. }
  669. // -------------------------------------------------------------------
  670. // Stores values for a new object instance, name will be used to
  671. // identify it.
  672. void ObjFileParser::getObjectName()
  673. {
  674. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  675. if( m_DataIt == m_DataItEnd ) {
  676. return;
  677. }
  678. char *pStart = &(*m_DataIt);
  679. while( m_DataIt != m_DataItEnd && !IsSpaceOrNewLine( *m_DataIt ) ) {
  680. ++m_DataIt;
  681. }
  682. std::string strObjectName(pStart, &(*m_DataIt));
  683. if (!strObjectName.empty())
  684. {
  685. // Reset current object
  686. m_pModel->m_pCurrent = NULL;
  687. // Search for actual object
  688. for (std::vector<ObjFile::Object*>::const_iterator it = m_pModel->m_Objects.begin();
  689. it != m_pModel->m_Objects.end();
  690. ++it)
  691. {
  692. if ((*it)->m_strObjName == strObjectName)
  693. {
  694. m_pModel->m_pCurrent = *it;
  695. break;
  696. }
  697. }
  698. // Allocate a new object, if current one was not found before
  699. if( NULL == m_pModel->m_pCurrent ) {
  700. createObject( strObjectName );
  701. }
  702. }
  703. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  704. }
  705. // -------------------------------------------------------------------
  706. // Creates a new object instance
  707. void ObjFileParser::createObject(const std::string &objName)
  708. {
  709. ai_assert( NULL != m_pModel );
  710. m_pModel->m_pCurrent = new ObjFile::Object;
  711. m_pModel->m_pCurrent->m_strObjName = objName;
  712. m_pModel->m_Objects.push_back( m_pModel->m_pCurrent );
  713. createMesh( objName );
  714. if( m_pModel->m_pCurrentMaterial )
  715. {
  716. m_pModel->m_pCurrentMesh->m_uiMaterialIndex =
  717. getMaterialIndex( m_pModel->m_pCurrentMaterial->MaterialName.data );
  718. m_pModel->m_pCurrentMesh->m_pMaterial = m_pModel->m_pCurrentMaterial;
  719. }
  720. }
  721. // -------------------------------------------------------------------
  722. // Creates a new mesh
  723. void ObjFileParser::createMesh( const std::string &meshName )
  724. {
  725. ai_assert( NULL != m_pModel );
  726. m_pModel->m_pCurrentMesh = new ObjFile::Mesh( meshName );
  727. m_pModel->m_Meshes.push_back( m_pModel->m_pCurrentMesh );
  728. unsigned int meshId = m_pModel->m_Meshes.size()-1;
  729. if ( NULL != m_pModel->m_pCurrent )
  730. {
  731. m_pModel->m_pCurrent->m_Meshes.push_back( meshId );
  732. }
  733. else
  734. {
  735. DefaultLogger::get()->error("OBJ: No object detected to attach a new mesh instance.");
  736. }
  737. }
  738. // -------------------------------------------------------------------
  739. // Returns true, if a new mesh must be created.
  740. bool ObjFileParser::needsNewMesh( const std::string &materialName )
  741. {
  742. // If no mesh data yet
  743. if(m_pModel->m_pCurrentMesh == 0)
  744. {
  745. return true;
  746. }
  747. bool newMat = false;
  748. int matIdx = getMaterialIndex( materialName );
  749. int curMatIdx = m_pModel->m_pCurrentMesh->m_uiMaterialIndex;
  750. if ( curMatIdx != int(ObjFile::Mesh::NoMaterial)
  751. && curMatIdx != matIdx
  752. // no need create a new mesh if no faces in current
  753. // lets say 'usemtl' goes straight after 'g'
  754. && m_pModel->m_pCurrentMesh->m_Faces.size() > 0 )
  755. {
  756. // New material -> only one material per mesh, so we need to create a new
  757. // material
  758. newMat = true;
  759. }
  760. return newMat;
  761. }
  762. // -------------------------------------------------------------------
  763. // Shows an error in parsing process.
  764. void ObjFileParser::reportErrorTokenInFace()
  765. {
  766. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  767. DefaultLogger::get()->error("OBJ: Not supported token in face description detected");
  768. }
  769. // -------------------------------------------------------------------
  770. } // Namespace Assimp
  771. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER