ObjFileImporter.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  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 "ObjFileImporter.h"
  36. #include "ObjFileData.h"
  37. #include "ObjFileParser.h"
  38. #include <assimp/DefaultIOSystem.h>
  39. #include <assimp/IOStreamBuffer.h>
  40. #include <assimp/ai_assert.h>
  41. #include <assimp/importerdesc.h>
  42. #include <assimp/scene.h>
  43. #include <assimp/DefaultLogger.hpp>
  44. #include <assimp/Importer.hpp>
  45. #include <assimp/ObjMaterial.h>
  46. #include <memory>
  47. static constexpr aiImporterDesc desc = {
  48. "Wavefront Object Importer",
  49. "",
  50. "",
  51. "surfaces not supported",
  52. aiImporterFlags_SupportTextFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "obj"
  58. };
  59. static constexpr unsigned int ObjMinSize = 16u;
  60. namespace Assimp {
  61. using namespace std;
  62. // ------------------------------------------------------------------------------------------------
  63. // Default constructor
  64. ObjFileImporter::ObjFileImporter() :
  65. m_Buffer(),
  66. m_pRootObject(nullptr),
  67. m_strAbsPath(std::string(1, DefaultIOSystem().getOsSeparator())) {
  68. // empty
  69. }
  70. // ------------------------------------------------------------------------------------------------
  71. // Destructor.
  72. ObjFileImporter::~ObjFileImporter() {
  73. delete m_pRootObject;
  74. }
  75. // ------------------------------------------------------------------------------------------------
  76. // Returns true if file is an obj file.
  77. bool ObjFileImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  78. static const char *tokens[] = { "mtllib", "usemtl", "v ", "vt ", "vn ", "o ", "g ", "s ", "f " };
  79. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens), 200, false, true);
  80. }
  81. // ------------------------------------------------------------------------------------------------
  82. const aiImporterDesc *ObjFileImporter::GetInfo() const {
  83. return &desc;
  84. }
  85. // ------------------------------------------------------------------------------------------------
  86. // Obj-file import implementation
  87. void ObjFileImporter::InternReadFile(const std::string &file, aiScene *pScene, IOSystem *pIOHandler) {
  88. if (m_pRootObject != nullptr) {
  89. delete m_pRootObject;
  90. m_pRootObject = nullptr;
  91. }
  92. // Read file into memory
  93. static constexpr char mode[] = "rb";
  94. auto streamCloser = [&](IOStream *pStream) {
  95. pIOHandler->Close(pStream);
  96. };
  97. std::unique_ptr<IOStream, decltype(streamCloser)> fileStream(pIOHandler->Open(file, mode), streamCloser);
  98. if (!fileStream) {
  99. throw DeadlyImportError("Failed to open file ", file, ".");
  100. }
  101. // Get the file-size and validate it, throwing an exception when fails
  102. size_t fileSize = fileStream->FileSize();
  103. if (fileSize < ObjMinSize) {
  104. throw DeadlyImportError("OBJ-file is too small.");
  105. }
  106. IOStreamBuffer<char> streamedBuffer;
  107. streamedBuffer.open(fileStream.get());
  108. // Allocate buffer and read file into it
  109. //TextFileToBuffer( fileStream.get(),m_Buffer);
  110. // Get the model name
  111. std::string modelName, folderName;
  112. std::string::size_type pos = file.find_last_of("\\/");
  113. if (pos != std::string::npos) {
  114. modelName = file.substr(pos + 1, file.size() - pos - 1);
  115. folderName = file.substr(0, pos);
  116. if (!folderName.empty()) {
  117. pIOHandler->PushDirectory(folderName);
  118. }
  119. } else {
  120. modelName = file;
  121. }
  122. // parse the file into a temporary representation
  123. ObjFileParser parser(streamedBuffer, modelName, pIOHandler, m_progress, file);
  124. // And create the proper return structures out of it
  125. CreateDataFromImport(parser.GetModel(), pScene);
  126. streamedBuffer.close();
  127. // Clean up allocated storage for the next import
  128. m_Buffer.clear();
  129. // Pop directory stack
  130. if (pIOHandler->StackSize() > 0) {
  131. pIOHandler->PopDirectory();
  132. }
  133. }
  134. // ------------------------------------------------------------------------------------------------
  135. // Create the data from parsed obj-file
  136. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model *pModel, aiScene *pScene) {
  137. if (pModel == nullptr) {
  138. return;
  139. }
  140. // Create the root node of the scene
  141. pScene->mRootNode = new aiNode;
  142. if (!pModel->mModelName.empty()) {
  143. // Set the name of the scene
  144. pScene->mRootNode->mName.Set(pModel->mModelName);
  145. } else {
  146. // This is a fatal error, so break down the application
  147. ai_assert(false);
  148. }
  149. if (!pModel->mObjects.empty()) {
  150. unsigned int meshCount = 0;
  151. unsigned int childCount = 0;
  152. for (auto object : pModel->mObjects) {
  153. if (object) {
  154. ++childCount;
  155. meshCount += (unsigned int)object->m_Meshes.size();
  156. }
  157. }
  158. // Allocate space for the child nodes on the root node
  159. pScene->mRootNode->mChildren = new aiNode *[childCount];
  160. // Create nodes for the whole scene
  161. std::vector<std::unique_ptr<aiMesh>> MeshArray;
  162. MeshArray.reserve(meshCount);
  163. for (size_t index = 0; index < pModel->mObjects.size(); ++index) {
  164. createNodes(pModel, pModel->mObjects[index], pScene->mRootNode, pScene, MeshArray);
  165. }
  166. ai_assert(pScene->mRootNode->mNumChildren == childCount);
  167. // Create mesh pointer buffer for this scene
  168. if (pScene->mNumMeshes > 0) {
  169. pScene->mMeshes = new aiMesh *[MeshArray.size()];
  170. for (size_t index = 0; index < MeshArray.size(); ++index) {
  171. pScene->mMeshes[index] = MeshArray[index].release();
  172. }
  173. }
  174. // Create all materials
  175. createMaterials(pModel, pScene);
  176. } else {
  177. if (pModel->mVertices.empty()) {
  178. return;
  179. }
  180. std::unique_ptr<aiMesh> mesh(new aiMesh);
  181. mesh->mPrimitiveTypes = aiPrimitiveType_POINT;
  182. unsigned int n = (unsigned int)pModel->mVertices.size();
  183. mesh->mNumVertices = n;
  184. mesh->mVertices = new aiVector3D[n];
  185. memcpy(mesh->mVertices, pModel->mVertices.data(), n * sizeof(aiVector3D));
  186. if (!pModel->mNormals.empty()) {
  187. mesh->mNormals = new aiVector3D[n];
  188. if (pModel->mNormals.size() < n) {
  189. throw DeadlyImportError("OBJ: vertex normal index out of range");
  190. }
  191. memcpy(mesh->mNormals, pModel->mNormals.data(), n * sizeof(aiVector3D));
  192. }
  193. if (!pModel->mVertexColors.empty()) {
  194. mesh->mColors[0] = new aiColor4D[mesh->mNumVertices];
  195. for (unsigned int i = 0; i < n; ++i) {
  196. if (i < pModel->mVertexColors.size()) {
  197. const aiVector3D &color = pModel->mVertexColors[i];
  198. mesh->mColors[0][i] = aiColor4D(color.x, color.y, color.z, 1.0);
  199. } else {
  200. throw DeadlyImportError("OBJ: vertex color index out of range");
  201. }
  202. }
  203. }
  204. pScene->mRootNode->mNumMeshes = 1;
  205. pScene->mRootNode->mMeshes = new unsigned int[1];
  206. pScene->mRootNode->mMeshes[0] = 0;
  207. pScene->mMeshes = new aiMesh *[1];
  208. pScene->mNumMeshes = 1;
  209. pScene->mMeshes[0] = mesh.release();
  210. }
  211. }
  212. // ------------------------------------------------------------------------------------------------
  213. // Creates all nodes of the model
  214. aiNode *ObjFileImporter::createNodes(const ObjFile::Model *pModel, const ObjFile::Object *pObject,
  215. aiNode *pParent, aiScene *pScene,
  216. std::vector<std::unique_ptr<aiMesh>> &MeshArray) {
  217. if (nullptr == pObject || pModel == nullptr) {
  218. return nullptr;
  219. }
  220. // Store older mesh size to be able to computes mesh offsets for new mesh instances
  221. const size_t oldMeshSize = MeshArray.size();
  222. aiNode *pNode = new aiNode;
  223. pNode->mName = pObject->m_strObjName;
  224. // If we have a parent node, store it
  225. ai_assert(nullptr != pParent);
  226. appendChildToParentNode(pParent, pNode);
  227. for (size_t i = 0; i < pObject->m_Meshes.size(); ++i) {
  228. unsigned int meshId = pObject->m_Meshes[i];
  229. std::unique_ptr<aiMesh> pMesh = createTopology(pModel, pObject, meshId);
  230. if (pMesh != nullptr) {
  231. if (pMesh->mNumFaces > 0) {
  232. MeshArray.push_back(std::move(pMesh));
  233. }
  234. }
  235. }
  236. // Create all nodes from the sub-objects stored in the current object
  237. if (!pObject->m_SubObjects.empty()) {
  238. size_t numChilds = pObject->m_SubObjects.size();
  239. pNode->mNumChildren = static_cast<unsigned int>(numChilds);
  240. pNode->mChildren = new aiNode *[numChilds];
  241. pNode->mNumMeshes = 1;
  242. pNode->mMeshes = new unsigned int[1];
  243. }
  244. // Set mesh instances into scene- and node-instances
  245. const size_t meshSizeDiff = MeshArray.size() - oldMeshSize;
  246. if (meshSizeDiff > 0) {
  247. pNode->mMeshes = new unsigned int[meshSizeDiff];
  248. pNode->mNumMeshes = static_cast<unsigned int>(meshSizeDiff);
  249. size_t index = 0;
  250. for (size_t i = oldMeshSize; i < MeshArray.size(); ++i) {
  251. pNode->mMeshes[index] = pScene->mNumMeshes;
  252. pScene->mNumMeshes++;
  253. ++index;
  254. }
  255. }
  256. return pNode;
  257. }
  258. // ------------------------------------------------------------------------------------------------
  259. // Create topology data
  260. std::unique_ptr<aiMesh> ObjFileImporter::createTopology(const ObjFile::Model *pModel, const ObjFile::Object *pData, unsigned int meshIndex) {
  261. if (nullptr == pData || pModel == nullptr) {
  262. return nullptr;
  263. }
  264. // Create faces
  265. ObjFile::Mesh *pObjMesh = pModel->mMeshes[meshIndex];
  266. if (pObjMesh == nullptr) {
  267. return nullptr;
  268. }
  269. if (pObjMesh->m_Faces.empty()) {
  270. return nullptr;
  271. }
  272. std::unique_ptr<aiMesh> pMesh(new aiMesh);
  273. if (!pObjMesh->m_name.empty()) {
  274. pMesh->mName.Set(pObjMesh->m_name);
  275. }
  276. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++) {
  277. const ObjFile::Face *inp = pObjMesh->m_Faces[index];
  278. if (inp == nullptr) {
  279. continue;
  280. }
  281. if (inp->mPrimitiveType == aiPrimitiveType_LINE) {
  282. pMesh->mNumFaces += static_cast<unsigned int>(inp->m_vertices.size() - 1);
  283. pMesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  284. } else if (inp->mPrimitiveType == aiPrimitiveType_POINT) {
  285. pMesh->mNumFaces += static_cast<unsigned int>(inp->m_vertices.size());
  286. pMesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  287. } else {
  288. ++pMesh->mNumFaces;
  289. if (inp->m_vertices.size() > 3) {
  290. pMesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  291. } else {
  292. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  293. }
  294. }
  295. }
  296. unsigned int uiIdxCount = 0u;
  297. if (pMesh->mNumFaces > 0) {
  298. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  299. if (pObjMesh->m_uiMaterialIndex != ObjFile::Mesh::NoMaterial) {
  300. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  301. }
  302. unsigned int outIndex = 0u;
  303. // Copy all data from all stored meshes
  304. for (auto &face : pObjMesh->m_Faces) {
  305. const ObjFile::Face *inp = face;
  306. if (inp->mPrimitiveType == aiPrimitiveType_LINE) {
  307. for (size_t i = 0; i < inp->m_vertices.size() - 1; ++i) {
  308. aiFace &f = pMesh->mFaces[outIndex++];
  309. uiIdxCount += f.mNumIndices = 2;
  310. f.mIndices = new unsigned int[2];
  311. }
  312. continue;
  313. } else if (inp->mPrimitiveType == aiPrimitiveType_POINT) {
  314. for (size_t i = 0; i < inp->m_vertices.size(); ++i) {
  315. aiFace &f = pMesh->mFaces[outIndex++];
  316. uiIdxCount += f.mNumIndices = 1;
  317. f.mIndices = new unsigned int[1];
  318. }
  319. continue;
  320. }
  321. aiFace *pFace = &pMesh->mFaces[outIndex++];
  322. const unsigned int uiNumIndices = (unsigned int)face->m_vertices.size();
  323. uiIdxCount += pFace->mNumIndices = (unsigned int)uiNumIndices;
  324. if (pFace->mNumIndices > 0) {
  325. pFace->mIndices = new unsigned int[uiNumIndices];
  326. }
  327. }
  328. }
  329. // Create mesh vertices
  330. createVertexArray(pModel, pData, meshIndex, pMesh.get(), uiIdxCount);
  331. return pMesh;
  332. }
  333. // ------------------------------------------------------------------------------------------------
  334. // Creates a vertex array
  335. void ObjFileImporter::createVertexArray(const ObjFile::Model *pModel,
  336. const ObjFile::Object *pCurrentObject,
  337. unsigned int uiMeshIndex,
  338. aiMesh *pMesh,
  339. unsigned int numIndices) {
  340. // Checking preconditions
  341. if (pCurrentObject == nullptr || pModel == nullptr || pMesh == nullptr) {
  342. return;
  343. }
  344. // Break, if no faces are stored in object
  345. if (pCurrentObject->m_Meshes.empty()) {
  346. return;
  347. }
  348. // Get current mesh
  349. ObjFile::Mesh *pObjMesh = pModel->mMeshes[uiMeshIndex];
  350. if (nullptr == pObjMesh || pObjMesh->m_uiNumIndices < 1) {
  351. return;
  352. }
  353. // Copy vertices of this mesh instance
  354. pMesh->mNumVertices = numIndices;
  355. if (pMesh->mNumVertices == 0) {
  356. throw DeadlyImportError("OBJ: no vertices");
  357. } else if (pMesh->mNumVertices > AI_MAX_VERTICES) {
  358. throw DeadlyImportError("OBJ: Too many vertices");
  359. }
  360. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  361. // Allocate buffer for normal vectors
  362. if (!pModel->mNormals.empty() && pObjMesh->m_hasNormals)
  363. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  364. // Allocate buffer for vertex-color vectors
  365. if (!pModel->mVertexColors.empty())
  366. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  367. // Allocate buffer for texture coordinates
  368. if (!pModel->mTextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0]) {
  369. pMesh->mNumUVComponents[0] = pModel->mTextureCoordDim;
  370. pMesh->mTextureCoords[0] = new aiVector3D[pMesh->mNumVertices];
  371. }
  372. // Copy vertices, normals and textures into aiMesh instance
  373. bool normalsok = true, uvok = true;
  374. unsigned int newIndex = 0, outIndex = 0;
  375. for (auto sourceFace : pObjMesh->m_Faces) {
  376. // Copy all index arrays
  377. for (size_t vertexIndex = 0, outVertexIndex = 0; vertexIndex < sourceFace->m_vertices.size(); vertexIndex++) {
  378. const unsigned int vertex = sourceFace->m_vertices.at(vertexIndex);
  379. if (vertex >= pModel->mVertices.size()) {
  380. throw DeadlyImportError("OBJ: vertex index out of range");
  381. }
  382. if (pMesh->mNumVertices <= newIndex) {
  383. throw DeadlyImportError("OBJ: bad vertex index");
  384. }
  385. pMesh->mVertices[newIndex] = pModel->mVertices[vertex];
  386. // Copy all normals
  387. if (normalsok && !pModel->mNormals.empty() && vertexIndex < sourceFace->m_normals.size()) {
  388. const unsigned int normal = sourceFace->m_normals.at(vertexIndex);
  389. if (normal >= pModel->mNormals.size()) {
  390. normalsok = false;
  391. } else {
  392. pMesh->mNormals[newIndex] = pModel->mNormals[normal];
  393. }
  394. }
  395. // Copy all vertex colors
  396. if (vertex < pModel->mVertexColors.size()) {
  397. const aiVector3D &color = pModel->mVertexColors[vertex];
  398. pMesh->mColors[0][newIndex] = aiColor4D(color.x, color.y, color.z, 1.0);
  399. }
  400. // Copy all texture coordinates
  401. if (uvok && !pModel->mTextureCoord.empty() && vertexIndex < sourceFace->m_texturCoords.size()) {
  402. const unsigned int tex = sourceFace->m_texturCoords.at(vertexIndex);
  403. if (tex >= pModel->mTextureCoord.size()) {
  404. uvok = false;
  405. } else {
  406. const aiVector3D &coord3d = pModel->mTextureCoord[tex];
  407. pMesh->mTextureCoords[0][newIndex] = aiVector3D(coord3d.x, coord3d.y, coord3d.z);
  408. }
  409. }
  410. // Get destination face
  411. aiFace *pDestFace = &pMesh->mFaces[outIndex];
  412. const bool last = (vertexIndex == sourceFace->m_vertices.size() - 1);
  413. if (sourceFace->mPrimitiveType != aiPrimitiveType_LINE || !last) {
  414. pDestFace->mIndices[outVertexIndex] = newIndex;
  415. outVertexIndex++;
  416. }
  417. if (sourceFace->mPrimitiveType == aiPrimitiveType_POINT) {
  418. outIndex++;
  419. outVertexIndex = 0;
  420. } else if (sourceFace->mPrimitiveType == aiPrimitiveType_LINE) {
  421. outVertexIndex = 0;
  422. if (!last)
  423. outIndex++;
  424. if (vertexIndex) {
  425. if (!last) {
  426. if (pMesh->mNumVertices <= newIndex + 1) {
  427. throw DeadlyImportError("OBJ: bad vertex index");
  428. }
  429. pMesh->mVertices[newIndex + 1] = pMesh->mVertices[newIndex];
  430. if (!sourceFace->m_normals.empty() && !pModel->mNormals.empty()) {
  431. pMesh->mNormals[newIndex + 1] = pMesh->mNormals[newIndex];
  432. }
  433. if (!pModel->mTextureCoord.empty()) {
  434. for (size_t i = 0; i < pMesh->GetNumUVChannels(); i++) {
  435. pMesh->mTextureCoords[i][newIndex + 1] = pMesh->mTextureCoords[i][newIndex];
  436. }
  437. }
  438. ++newIndex;
  439. }
  440. pDestFace[-1].mIndices[1] = newIndex;
  441. }
  442. } else if (last) {
  443. outIndex++;
  444. }
  445. ++newIndex;
  446. }
  447. }
  448. if (!normalsok) {
  449. delete[] pMesh->mNormals;
  450. pMesh->mNormals = nullptr;
  451. }
  452. if (!uvok) {
  453. delete[] pMesh->mTextureCoords[0];
  454. pMesh->mTextureCoords[0] = nullptr;
  455. }
  456. }
  457. // ------------------------------------------------------------------------------------------------
  458. // Counts all stored meshes
  459. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object *> &rObjects, int &iNumMeshes) {
  460. iNumMeshes = 0;
  461. if (rObjects.empty())
  462. return;
  463. iNumMeshes += static_cast<unsigned int>(rObjects.size());
  464. for (auto object : rObjects) {
  465. if (!object->m_SubObjects.empty()) {
  466. countObjects(object->m_SubObjects, iNumMeshes);
  467. }
  468. }
  469. }
  470. // ------------------------------------------------------------------------------------------------
  471. // Add clamp mode property to material if necessary
  472. void ObjFileImporter::addTextureMappingModeProperty(aiMaterial *mat, aiTextureType type, int clampMode, int index) {
  473. if (nullptr == mat) {
  474. return;
  475. }
  476. mat->AddProperty<int>(&clampMode, 1, AI_MATKEY_MAPPINGMODE_U(type, index));
  477. mat->AddProperty<int>(&clampMode, 1, AI_MATKEY_MAPPINGMODE_V(type, index));
  478. }
  479. // ------------------------------------------------------------------------------------------------
  480. // Creates the material
  481. void ObjFileImporter::createMaterials(const ObjFile::Model *pModel, aiScene *pScene) {
  482. if (nullptr == pScene) {
  483. return;
  484. }
  485. const unsigned int numMaterials = (unsigned int)pModel->mMaterialLib.size();
  486. pScene->mNumMaterials = 0;
  487. if (pModel->mMaterialLib.empty()) {
  488. ASSIMP_LOG_DEBUG("OBJ: no materials specified");
  489. return;
  490. }
  491. pScene->mMaterials = new aiMaterial *[numMaterials];
  492. for (unsigned int matIndex = 0; matIndex < numMaterials; matIndex++) {
  493. // Store material name
  494. std::map<std::string, ObjFile::Material *>::const_iterator it;
  495. it = pModel->mMaterialMap.find(pModel->mMaterialLib[matIndex]);
  496. // No material found, use the default material
  497. if (pModel->mMaterialMap.end() == it) {
  498. continue;
  499. }
  500. aiMaterial *mat = new aiMaterial;
  501. ObjFile::Material *pCurrentMaterial = it->second;
  502. mat->AddProperty(&pCurrentMaterial->MaterialName, AI_MATKEY_NAME);
  503. // convert illumination model
  504. int sm = 0;
  505. switch (pCurrentMaterial->illumination_model) {
  506. case 0:
  507. sm = aiShadingMode_NoShading;
  508. break;
  509. case 1:
  510. sm = aiShadingMode_Gouraud;
  511. break;
  512. case 2:
  513. sm = aiShadingMode_Phong;
  514. break;
  515. default:
  516. sm = aiShadingMode_Gouraud;
  517. ASSIMP_LOG_ERROR("OBJ: unexpected illumination model (0-2 recognized)");
  518. }
  519. mat->AddProperty<int>(&sm, 1, AI_MATKEY_SHADING_MODEL);
  520. // Preserve the original illum value
  521. mat->AddProperty<int>(&pCurrentMaterial->illumination_model, 1, AI_MATKEY_OBJ_ILLUM);
  522. // Adding material colors
  523. mat->AddProperty(&pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT);
  524. mat->AddProperty(&pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  525. mat->AddProperty(&pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR);
  526. mat->AddProperty(&pCurrentMaterial->emissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  527. mat->AddProperty(&pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS);
  528. mat->AddProperty(&pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY);
  529. mat->AddProperty(&pCurrentMaterial->transparent, 1, AI_MATKEY_COLOR_TRANSPARENT);
  530. if (pCurrentMaterial->roughness)
  531. mat->AddProperty(&pCurrentMaterial->roughness.Get(), 1, AI_MATKEY_ROUGHNESS_FACTOR);
  532. if (pCurrentMaterial->metallic)
  533. mat->AddProperty(&pCurrentMaterial->metallic.Get(), 1, AI_MATKEY_METALLIC_FACTOR);
  534. if (pCurrentMaterial->sheen)
  535. mat->AddProperty(&pCurrentMaterial->sheen.Get(), 1, AI_MATKEY_SHEEN_COLOR_FACTOR);
  536. if (pCurrentMaterial->clearcoat_thickness)
  537. mat->AddProperty(&pCurrentMaterial->clearcoat_thickness.Get(), 1, AI_MATKEY_CLEARCOAT_FACTOR);
  538. if (pCurrentMaterial->clearcoat_roughness)
  539. mat->AddProperty(&pCurrentMaterial->clearcoat_roughness.Get(), 1, AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR);
  540. mat->AddProperty(&pCurrentMaterial->anisotropy, 1, AI_MATKEY_ANISOTROPY_FACTOR);
  541. // Adding refraction index
  542. mat->AddProperty(&pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI);
  543. // Adding textures
  544. const int uvwIndex = 0;
  545. if (0 != pCurrentMaterial->texture.length) {
  546. mat->AddProperty(&pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  547. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_DIFFUSE(0));
  548. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDiffuseType]) {
  549. addTextureMappingModeProperty(mat, aiTextureType_DIFFUSE);
  550. }
  551. }
  552. if (0 != pCurrentMaterial->textureAmbient.length) {
  553. mat->AddProperty(&pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  554. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_AMBIENT(0));
  555. if (pCurrentMaterial->clamp[ObjFile::Material::TextureAmbientType]) {
  556. addTextureMappingModeProperty(mat, aiTextureType_AMBIENT);
  557. }
  558. }
  559. if (0 != pCurrentMaterial->textureEmissive.length) {
  560. mat->AddProperty(&pCurrentMaterial->textureEmissive, AI_MATKEY_TEXTURE_EMISSIVE(0));
  561. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_EMISSIVE(0));
  562. }
  563. if (0 != pCurrentMaterial->textureSpecular.length) {
  564. mat->AddProperty(&pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  565. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_SPECULAR(0));
  566. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularType]) {
  567. addTextureMappingModeProperty(mat, aiTextureType_SPECULAR);
  568. }
  569. }
  570. if (0 != pCurrentMaterial->textureBump.length) {
  571. mat->AddProperty(&pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  572. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_HEIGHT(0));
  573. if (pCurrentMaterial->bump_multiplier != 1.0) {
  574. mat->AddProperty(&pCurrentMaterial->bump_multiplier, 1, AI_MATKEY_OBJ_BUMPMULT_HEIGHT(0));
  575. }
  576. if (pCurrentMaterial->clamp[ObjFile::Material::TextureBumpType]) {
  577. addTextureMappingModeProperty(mat, aiTextureType_HEIGHT);
  578. }
  579. }
  580. if (0 != pCurrentMaterial->textureNormal.length) {
  581. mat->AddProperty(&pCurrentMaterial->textureNormal, AI_MATKEY_TEXTURE_NORMALS(0));
  582. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_NORMALS(0));
  583. if (pCurrentMaterial->bump_multiplier != 1.0) {
  584. mat->AddProperty(&pCurrentMaterial->bump_multiplier, 1, AI_MATKEY_OBJ_BUMPMULT_NORMALS(0));
  585. }
  586. if (pCurrentMaterial->clamp[ObjFile::Material::TextureNormalType]) {
  587. addTextureMappingModeProperty(mat, aiTextureType_NORMALS);
  588. }
  589. }
  590. if (0 != pCurrentMaterial->textureReflection[0].length) {
  591. ObjFile::Material::TextureType type = 0 != pCurrentMaterial->textureReflection[1].length ?
  592. ObjFile::Material::TextureReflectionCubeTopType :
  593. ObjFile::Material::TextureReflectionSphereType;
  594. unsigned count = type == ObjFile::Material::TextureReflectionSphereType ? 1 : 6;
  595. for (unsigned i = 0; i < count; i++) {
  596. mat->AddProperty(&pCurrentMaterial->textureReflection[i], AI_MATKEY_TEXTURE_REFLECTION(i));
  597. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_REFLECTION(i));
  598. if (pCurrentMaterial->clamp[type])
  599. addTextureMappingModeProperty(mat, aiTextureType_REFLECTION, 1, i);
  600. }
  601. }
  602. if (0 != pCurrentMaterial->textureDisp.length) {
  603. mat->AddProperty(&pCurrentMaterial->textureDisp, AI_MATKEY_TEXTURE_DISPLACEMENT(0));
  604. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_DISPLACEMENT(0));
  605. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDispType]) {
  606. addTextureMappingModeProperty(mat, aiTextureType_DISPLACEMENT);
  607. }
  608. }
  609. if (0 != pCurrentMaterial->textureOpacity.length) {
  610. mat->AddProperty(&pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  611. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_OPACITY(0));
  612. if (pCurrentMaterial->clamp[ObjFile::Material::TextureOpacityType]) {
  613. addTextureMappingModeProperty(mat, aiTextureType_OPACITY);
  614. }
  615. }
  616. if (0 != pCurrentMaterial->textureSpecularity.length) {
  617. mat->AddProperty(&pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  618. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_SHININESS(0));
  619. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularityType]) {
  620. addTextureMappingModeProperty(mat, aiTextureType_SHININESS);
  621. }
  622. }
  623. if (0 != pCurrentMaterial->textureRoughness.length) {
  624. mat->AddProperty(&pCurrentMaterial->textureRoughness, _AI_MATKEY_TEXTURE_BASE, aiTextureType_DIFFUSE_ROUGHNESS, 0);
  625. mat->AddProperty(&uvwIndex, 1, _AI_MATKEY_UVWSRC_BASE, aiTextureType_DIFFUSE_ROUGHNESS, 0 );
  626. if (pCurrentMaterial->clamp[ObjFile::Material::TextureRoughnessType]) {
  627. addTextureMappingModeProperty(mat, aiTextureType_DIFFUSE_ROUGHNESS);
  628. }
  629. }
  630. if (0 != pCurrentMaterial->textureMetallic.length) {
  631. mat->AddProperty(&pCurrentMaterial->textureMetallic, _AI_MATKEY_TEXTURE_BASE, aiTextureType_METALNESS, 0);
  632. mat->AddProperty(&uvwIndex, 1, _AI_MATKEY_UVWSRC_BASE, aiTextureType_METALNESS, 0 );
  633. if (pCurrentMaterial->clamp[ObjFile::Material::TextureMetallicType]) {
  634. addTextureMappingModeProperty(mat, aiTextureType_METALNESS);
  635. }
  636. }
  637. if (0 != pCurrentMaterial->textureSheen.length) {
  638. mat->AddProperty(&pCurrentMaterial->textureSheen, _AI_MATKEY_TEXTURE_BASE, aiTextureType_SHEEN, 0);
  639. mat->AddProperty(&uvwIndex, 1, _AI_MATKEY_UVWSRC_BASE, aiTextureType_SHEEN, 0 );
  640. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSheenType]) {
  641. addTextureMappingModeProperty(mat, aiTextureType_SHEEN);
  642. }
  643. }
  644. if (0 != pCurrentMaterial->textureRMA.length) {
  645. // NOTE: glTF importer places Rough/Metal/AO texture in Unknown so doing the same here for consistency.
  646. mat->AddProperty(&pCurrentMaterial->textureRMA, _AI_MATKEY_TEXTURE_BASE, aiTextureType_UNKNOWN, 0);
  647. mat->AddProperty(&uvwIndex, 1, _AI_MATKEY_UVWSRC_BASE, aiTextureType_UNKNOWN, 0 );
  648. if (pCurrentMaterial->clamp[ObjFile::Material::TextureRMAType]) {
  649. addTextureMappingModeProperty(mat, aiTextureType_UNKNOWN);
  650. }
  651. }
  652. // Store material property info in material array in scene
  653. pScene->mMaterials[pScene->mNumMaterials] = mat;
  654. pScene->mNumMaterials++;
  655. }
  656. // Test number of created materials.
  657. ai_assert(pScene->mNumMaterials == numMaterials);
  658. }
  659. // ------------------------------------------------------------------------------------------------
  660. // Appends this node to the parent node
  661. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild) {
  662. // Checking preconditions
  663. if (pParent == nullptr || pChild == nullptr) {
  664. ai_assert(nullptr != pParent);
  665. ai_assert(nullptr != pChild);
  666. return;
  667. }
  668. // Assign parent to child
  669. pChild->mParent = pParent;
  670. // Copy node instances into parent node
  671. pParent->mNumChildren++;
  672. pParent->mChildren[pParent->mNumChildren - 1] = pChild;
  673. }
  674. // ------------------------------------------------------------------------------------------------
  675. } // Namespace Assimp
  676. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER