ObjFileParser.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (ASSIMP)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2008, ASSIMP Development 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 Development 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. #include "AssimpPCH.h"
  35. #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER
  36. #include "ObjFileParser.h"
  37. #include "ObjFileMtlImporter.h"
  38. #include "ObjTools.h"
  39. #include "ObjFileData.h"
  40. #include "fast_atof.h"
  41. #include "DefaultIOSystem.h"
  42. namespace Assimp {
  43. // -------------------------------------------------------------------
  44. const std::string ObjFileParser::DEFAULT_MATERIAL = AI_DEFAULT_MATERIAL_NAME;
  45. // fix: changed that to our standard default name
  46. // -------------------------------------------------------------------
  47. // Constructor with loaded data and directories.
  48. ObjFileParser::ObjFileParser(std::vector<char> &Data,
  49. const std::string &strAbsPath,
  50. const std::string &strModelName, IOSystem* _io) :
  51. m_strAbsPath(strAbsPath),
  52. m_DataIt(Data.begin()),
  53. m_DataItEnd(Data.end()),
  54. m_pModel(NULL),
  55. m_uiLine(0),
  56. io(_io)
  57. {
  58. // Create the model instance to store all the data
  59. m_pModel = new ObjFile::Model();
  60. m_pModel->m_ModelName = strModelName;
  61. m_pModel->m_pDefaultMaterial = new ObjFile::Material();
  62. m_pModel->m_pDefaultMaterial->MaterialName.Set( DEFAULT_MATERIAL );
  63. m_pModel->m_MaterialLib.push_back( DEFAULT_MATERIAL );
  64. m_pModel->m_MaterialMap[ DEFAULT_MATERIAL ] = m_pModel->m_pDefaultMaterial;
  65. // Start parsing the file
  66. parseFile();
  67. }
  68. // -------------------------------------------------------------------
  69. ObjFileParser::~ObjFileParser()
  70. {
  71. delete m_pModel->m_pDefaultMaterial;
  72. m_pModel->m_pDefaultMaterial = NULL;
  73. delete m_pModel;
  74. m_pModel = NULL;
  75. }
  76. // -------------------------------------------------------------------
  77. ObjFile::Model *ObjFileParser::GetModel() const
  78. {
  79. return m_pModel;
  80. }
  81. // -------------------------------------------------------------------
  82. void ObjFileParser::parseFile()
  83. {
  84. if (m_DataIt == m_DataItEnd)
  85. return;
  86. while (m_DataIt != m_DataItEnd)
  87. {
  88. switch (*m_DataIt)
  89. {
  90. case 'v': // Parse a vertex texture coordinate
  91. {
  92. ++m_DataIt;
  93. if (*m_DataIt == ' ')
  94. {
  95. // Read in vertex definition
  96. getVector3(m_pModel->m_Vertices);
  97. }
  98. else if (*m_DataIt == 't')
  99. {
  100. // Read in texture coordinate (2D)
  101. ++m_DataIt;
  102. getVector2(m_pModel->m_TextureCoord);
  103. }
  104. else if (*m_DataIt == 'n')
  105. {
  106. // Read in normal vector definition
  107. ++m_DataIt;
  108. getVector3( m_pModel->m_Normals );
  109. }
  110. }
  111. break;
  112. case 'f': // Parse a face
  113. {
  114. getFace();
  115. }
  116. break;
  117. case '#': // Parse a comment
  118. {
  119. getComment();
  120. }
  121. break;
  122. case 'u': // Parse a material desc. setter
  123. {
  124. getMaterialDesc();
  125. }
  126. break;
  127. case 'm': // Parse a material library
  128. {
  129. getMaterialLib();
  130. }
  131. break;
  132. case 'g': // Parse group name
  133. {
  134. getGroupName();
  135. }
  136. break;
  137. case 's': // Parse group number
  138. {
  139. getGroupNumber();
  140. }
  141. break;
  142. case 'o': // Parse object name
  143. {
  144. getObjectName();
  145. }
  146. break;
  147. default:
  148. {
  149. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  150. }
  151. break;
  152. }
  153. }
  154. }
  155. // -------------------------------------------------------------------
  156. // Copy the next word in a temporary buffer
  157. void ObjFileParser::copyNextWord(char *pBuffer, size_t length)
  158. {
  159. size_t index = 0;
  160. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  161. while ( !isSeparator(*m_DataIt) && m_DataIt != m_DataItEnd )
  162. {
  163. pBuffer[index] = *m_DataIt;
  164. index++;
  165. if (index == length-1)
  166. break;
  167. ++m_DataIt;
  168. }
  169. pBuffer[index] = '\0';
  170. }
  171. // -------------------------------------------------------------------
  172. // Copy the next line into a temporary buffer
  173. void ObjFileParser::copyNextLine(char *pBuffer, size_t length)
  174. {
  175. size_t index = 0;
  176. while (m_DataIt != m_DataItEnd)
  177. {
  178. if (*m_DataIt == '\n' || *m_DataIt == '\r')
  179. break;
  180. assert (index+1 <= length);
  181. pBuffer[ index ] = *m_DataIt;
  182. ++index;
  183. ++m_DataIt;
  184. }
  185. pBuffer[ index ] = '\0';
  186. }
  187. // -------------------------------------------------------------------
  188. // Get values for a new 3D vector instance
  189. void ObjFileParser::getVector3(std::vector<aiVector3D> &point3d_array)
  190. {
  191. float x, y, z;
  192. copyNextWord(m_buffer, BUFFERSIZE);
  193. x = (float) fast_atof(m_buffer);
  194. copyNextWord(m_buffer, BUFFERSIZE);
  195. y = (float) fast_atof(m_buffer);
  196. copyNextWord(m_buffer, BUFFERSIZE);
  197. z = (float) fast_atof(m_buffer);
  198. point3d_array.push_back( aiVector3D( x, y, z ) );
  199. //skipLine();
  200. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  201. }
  202. // -------------------------------------------------------------------
  203. // Get values for a new 2D vector instance
  204. void ObjFileParser::getVector2( std::vector<aiVector2D> &point2d_array )
  205. {
  206. float x, y;
  207. copyNextWord(m_buffer, BUFFERSIZE);
  208. x = (float) fast_atof(m_buffer);
  209. copyNextWord(m_buffer, BUFFERSIZE);
  210. y = (float) fast_atof(m_buffer);
  211. point2d_array.push_back(aiVector2D(x, y));
  212. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  213. }
  214. // -------------------------------------------------------------------
  215. // Get values for a new face instance
  216. void ObjFileParser::getFace()
  217. {
  218. copyNextLine(m_buffer, BUFFERSIZE);
  219. if (m_DataIt == m_DataItEnd)
  220. return;
  221. char *pPtr = m_buffer;
  222. char *pEnd = &pPtr[BUFFERSIZE];
  223. pPtr = getNextToken<char*>(pPtr, pEnd);
  224. if (pPtr == '\0')
  225. return;
  226. std::vector<unsigned int> *pIndices = new std::vector<unsigned int>;
  227. std::vector<unsigned int> *pTexID = new std::vector<unsigned int>;
  228. std::vector<unsigned int> *pNormalID = new std::vector<unsigned int>;
  229. bool hasNormal = false;
  230. bool vt = (!m_pModel->m_TextureCoord.empty());
  231. bool vn = (!m_pModel->m_Normals.empty());
  232. int iStep = 0, iPos = 0;
  233. while (pPtr != pEnd)
  234. {
  235. iStep = 1;
  236. if (*pPtr == '\0')
  237. break;
  238. if (*pPtr=='\r')
  239. break;
  240. if (*pPtr=='/' )
  241. {
  242. if (iPos == 0)
  243. {
  244. //if there are no texturecoordinates in the obj file but normals
  245. if (!vt && vn) {
  246. iPos = 1;
  247. iStep++;
  248. }
  249. }
  250. iPos++;
  251. }
  252. else if ( isSeparator(*pPtr) )
  253. {
  254. iPos = 0;
  255. }
  256. else
  257. {
  258. //OBJ USES 1 Base ARRAYS!!!!
  259. const int iVal = atoi( pPtr );
  260. int tmp = iVal;
  261. while ( ( tmp = tmp / 10 )!=0 )
  262. ++iStep;
  263. if ( iVal > 0 )
  264. {
  265. // Store parsed index
  266. if ( 0 == iPos )
  267. {
  268. pIndices->push_back( iVal-1 );
  269. }
  270. else if ( 1 == iPos )
  271. {
  272. pTexID->push_back( iVal-1 );
  273. }
  274. else if ( 2 == iPos )
  275. {
  276. pNormalID->push_back( iVal-1 );
  277. hasNormal = true;
  278. }
  279. else
  280. {
  281. reportErrorTokenInFace();
  282. }
  283. }
  284. }
  285. for ( int i=0; i<iStep; i++ )
  286. ++pPtr;
  287. }
  288. ObjFile::Face *face = new ObjFile::Face(pIndices, pNormalID, pTexID);
  289. // Set active material, if one set
  290. if (NULL != m_pModel->m_pCurrentMaterial)
  291. face->m_pMaterial = m_pModel->m_pCurrentMaterial;
  292. else
  293. face->m_pMaterial = m_pModel->m_pDefaultMaterial;
  294. // Create a default object, if nothing there
  295. if ( NULL == m_pModel->m_pCurrent )
  296. createObject("defaultobject");
  297. // Store the new instance
  298. m_pModel->m_pCurrent->m_Faces.push_back(face);
  299. // Assign face to mesh
  300. if ( NULL == m_pModel->m_pCurrentMesh )
  301. {
  302. m_pModel->m_pCurrentMesh = new ObjFile::Mesh();
  303. m_pModel->m_Meshes.push_back( m_pModel->m_pCurrentMesh );
  304. }
  305. // Store the face
  306. m_pModel->m_pCurrentMesh->m_Faces.push_back( face );
  307. m_pModel->m_pCurrentMesh->m_uiNumIndices += (unsigned int)face->m_pVertices->size();
  308. m_pModel->m_pCurrentMesh->m_uiUVCoordinates[ 0 ] += (unsigned int)face->m_pTexturCoords[0].size();
  309. if(!m_pModel->m_pCurrentMesh->m_hasNormals && hasNormal) {
  310. m_pModel->m_pCurrentMesh->m_hasNormals = true;
  311. }
  312. // Skip the rest of the line
  313. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  314. }
  315. // -------------------------------------------------------------------
  316. // Get values for a new material description
  317. void ObjFileParser::getMaterialDesc()
  318. {
  319. // Get next data for material data
  320. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  321. if (m_DataIt == m_DataItEnd)
  322. return;
  323. char *pStart = &(*m_DataIt);
  324. while ( !isSeparator(*m_DataIt) && m_DataIt != m_DataItEnd )
  325. ++m_DataIt;
  326. // Get name
  327. std::string strName(pStart, &(*m_DataIt));
  328. if ( strName.empty())
  329. return;
  330. // Search for material
  331. std::map<std::string, ObjFile::Material*>::iterator it = m_pModel->m_MaterialMap.find( strName );
  332. if ( it == m_pModel->m_MaterialMap.end() )
  333. {
  334. // Not found, use default material
  335. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  336. m_pModel->m_pCurrentMesh = new ObjFile::Mesh();
  337. m_pModel->m_Meshes.push_back( m_pModel->m_pCurrentMesh );
  338. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex( DEFAULT_MATERIAL );
  339. }
  340. else
  341. {
  342. // Found, using detected material
  343. m_pModel->m_pCurrentMaterial = (*it).second;
  344. // Create a new mesh for a new material
  345. m_pModel->m_pCurrentMesh = new ObjFile::Mesh();
  346. m_pModel->m_Meshes.push_back( m_pModel->m_pCurrentMesh );
  347. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex( strName );
  348. }
  349. // Skip rest of line
  350. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  351. }
  352. // -------------------------------------------------------------------
  353. // Get a comment, values will be skipped
  354. void ObjFileParser::getComment()
  355. {
  356. bool running = true;
  357. while (running)
  358. {
  359. if ( '\n' == (*m_DataIt) || m_DataIt == m_DataItEnd )
  360. {
  361. ++m_DataIt;
  362. break;
  363. }
  364. else
  365. {
  366. ++m_DataIt;
  367. }
  368. }
  369. }
  370. // -------------------------------------------------------------------
  371. // Get material library from file.
  372. void ObjFileParser::getMaterialLib()
  373. {
  374. // Translate tuple
  375. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  376. if (m_DataIt == m_DataItEnd)
  377. return;
  378. char *pStart = &(*m_DataIt);
  379. while (!isNewLine(*m_DataIt))
  380. m_DataIt++;
  381. // Check for existence
  382. std::string strMatName(pStart, &(*m_DataIt));
  383. std::string absName = m_strAbsPath + io->getOsSeparator() + strMatName;
  384. IOStream *pFile = io->Open(absName.c_str());
  385. if (!pFile )
  386. {
  387. DefaultLogger::get()->error("OBJ: Unable to locate material file " + absName);
  388. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  389. return;
  390. }
  391. // Import material library data from file
  392. size_t size = pFile->FileSize();
  393. std::vector<char> buffer( size + 1 );
  394. buffer[ size ] = '\0';
  395. pFile->Read( &buffer[ 0 ], sizeof( char ), size );
  396. io->Close( pFile );
  397. // Importing the material library
  398. ObjFileMtlImporter mtlImporter( buffer, absName, m_pModel );
  399. }
  400. // -------------------------------------------------------------------
  401. // Set a new material definition as the current material.
  402. void ObjFileParser::getNewMaterial()
  403. {
  404. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  405. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  406. if ( m_DataIt == m_DataItEnd )
  407. return;
  408. char *pStart = &(*m_DataIt);
  409. std::string strMat(pStart, *m_DataIt);
  410. while ( isSeparator( *m_DataIt ) )
  411. m_DataIt++;
  412. std::map<std::string, ObjFile::Material*>::iterator it = m_pModel->m_MaterialMap.find( strMat );
  413. if (it == m_pModel->m_MaterialMap.end())
  414. {
  415. // Show a warning, if material was not found
  416. DefaultLogger::get()->warn("OBJ: Unsupported material requested: " + strMat);
  417. m_pModel->m_pCurrentMaterial = m_pModel->m_pDefaultMaterial;
  418. }
  419. else
  420. {
  421. // Set new material
  422. m_pModel->m_pCurrentMaterial = (*it).second;
  423. m_pModel->m_pCurrentMesh->m_uiMaterialIndex = getMaterialIndex( strMat );
  424. }
  425. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  426. }
  427. // -------------------------------------------------------------------
  428. int ObjFileParser::getMaterialIndex( const std::string &strMaterialName )
  429. {
  430. int mat_index = -1;
  431. if ( strMaterialName.empty() )
  432. return mat_index;
  433. for (size_t index = 0; index < m_pModel->m_MaterialLib.size(); ++index)
  434. {
  435. if ( strMaterialName == m_pModel->m_MaterialLib[ index ])
  436. {
  437. mat_index = (int)index;
  438. break;
  439. }
  440. }
  441. return mat_index;
  442. }
  443. // -------------------------------------------------------------------
  444. // Getter for a group name.
  445. void ObjFileParser::getGroupName()
  446. {
  447. // Get next word from data buffer
  448. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  449. m_DataIt = getNextWord<DataArrayIt>(m_DataIt, m_DataItEnd);
  450. if ( isEndOfBuffer( m_DataIt, m_DataItEnd ) )
  451. return;
  452. // Store groupname in group library
  453. char *pStart = &(*m_DataIt);
  454. while ( !isSeparator(*m_DataIt) )
  455. m_DataIt++;
  456. std::string strGroupName(pStart, &(*m_DataIt));
  457. // Change active group, if necessary
  458. if (m_pModel->m_strActiveGroup != strGroupName)
  459. {
  460. // Search for already existing entry
  461. ObjFile::Model::ConstGroupMapIt it = m_pModel->m_Groups.find(&strGroupName);
  462. // New group name, creating a new entry
  463. //ObjFile::Object *pObject = m_pModel->m_pCurrent;
  464. if (it == m_pModel->m_Groups.end())
  465. {
  466. std::vector<unsigned int> *pFaceIDArray = new std::vector<unsigned int>;
  467. m_pModel->m_Groups[ &strGroupName ] = pFaceIDArray;
  468. m_pModel->m_pGroupFaceIDs = (pFaceIDArray);
  469. }
  470. else
  471. {
  472. m_pModel->m_pGroupFaceIDs = (*it).second;
  473. }
  474. m_pModel->m_strActiveGroup = strGroupName;
  475. }
  476. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  477. }
  478. // -------------------------------------------------------------------
  479. // Not supported
  480. void ObjFileParser::getGroupNumber()
  481. {
  482. // Not used
  483. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  484. }
  485. // -------------------------------------------------------------------
  486. // Stores values for a new object instance, name will be used to
  487. // identify it.
  488. void ObjFileParser::getObjectName()
  489. {
  490. m_DataIt = getNextToken<DataArrayIt>(m_DataIt, m_DataItEnd);
  491. if (m_DataIt == m_DataItEnd)
  492. return;
  493. char *pStart = &(*m_DataIt);
  494. while (!isSeparator(*m_DataIt))
  495. m_DataIt++;
  496. std::string strObjectName(pStart, &(*m_DataIt));
  497. if (!strObjectName.empty())
  498. {
  499. // Reset current object
  500. m_pModel->m_pCurrent = NULL;
  501. // Search for actual object
  502. for (std::vector<ObjFile::Object*>::const_iterator it = m_pModel->m_Objects.begin();
  503. it != m_pModel->m_Objects.end();
  504. ++it)
  505. {
  506. if ((*it)->m_strObjName == strObjectName)
  507. {
  508. m_pModel->m_pCurrent = *it;
  509. break;
  510. }
  511. }
  512. // Allocate a new object, if current one wasn´t found before
  513. if ( NULL == m_pModel->m_pCurrent )
  514. createObject(strObjectName);
  515. }
  516. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  517. }
  518. // -------------------------------------------------------------------
  519. // Creates a new object instance
  520. void ObjFileParser::createObject(const std::string &strObjectName)
  521. {
  522. ai_assert (NULL != m_pModel);
  523. ai_assert (!strObjectName.empty());
  524. m_pModel->m_pCurrent = new ObjFile::Object();
  525. m_pModel->m_pCurrent->m_strObjName = strObjectName;
  526. m_pModel->m_Objects.push_back(m_pModel->m_pCurrent);
  527. }
  528. // -------------------------------------------------------------------
  529. // Shows an error in parsing process.
  530. void ObjFileParser::reportErrorTokenInFace()
  531. {
  532. m_DataIt = skipLine<DataArrayIt>( m_DataIt, m_DataItEnd, m_uiLine );
  533. DefaultLogger::get()->error("OBJ: Not supported token in face description detected");
  534. }
  535. // -------------------------------------------------------------------
  536. } // Namespace Assimp
  537. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER