ObjFileParser.cpp 28 KB

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