ObjFileParser.cpp 28 KB

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