ObjFileParser.cpp 27 KB

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