ObjFileParser.cpp 30 KB

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