ObjFileParser.cpp 28 KB

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