ObjFileParser.cpp 30 KB

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