ObjFileParser.cpp 28 KB

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