ObjFileParser.cpp 28 KB

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