ObjFileParser.cpp 28 KB

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