ObjFileImporter.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. #ifndef ASSIMP_BUILD_NO_OBJ_IMPORTER
  35. #include "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 <memory>
  46. static const aiImporterDesc desc = {
  47. "Wavefront Object Importer",
  48. "",
  49. "",
  50. "surfaces not supported",
  51. aiImporterFlags_SupportTextFlavour,
  52. 0,
  53. 0,
  54. 0,
  55. 0,
  56. "obj"
  57. };
  58. static const unsigned int ObjMinSize = 16;
  59. namespace Assimp {
  60. using namespace std;
  61. // ------------------------------------------------------------------------------------------------
  62. // Default constructor
  63. ObjFileImporter::ObjFileImporter() :
  64. m_Buffer(), m_pRootObject(nullptr), m_strAbsPath(std::string(1, DefaultIOSystem().getOsSeparator())) {}
  65. // ------------------------------------------------------------------------------------------------
  66. // Destructor.
  67. ObjFileImporter::~ObjFileImporter() {
  68. delete m_pRootObject;
  69. m_pRootObject = nullptr;
  70. }
  71. // ------------------------------------------------------------------------------------------------
  72. // Returns true, if file is an obj file.
  73. bool ObjFileImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
  74. if (!checkSig) {
  75. //Check File Extension
  76. return SimpleExtensionCheck(pFile, "obj");
  77. } else {
  78. // Check file Header
  79. static const char *pTokens[] = { "mtllib", "usemtl", "v ", "vt ", "vn ", "o ", "g ", "s ", "f " };
  80. return BaseImporter::SearchFileHeaderForToken(pIOHandler, pFile, pTokens, 9, 200, false, true);
  81. }
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. const aiImporterDesc *ObjFileImporter::GetInfo() const {
  85. return &desc;
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. // Obj-file import implementation
  89. void ObjFileImporter::InternReadFile(const std::string &file, aiScene *pScene, IOSystem *pIOHandler) {
  90. // Read file into memory
  91. static const std::string mode = "rb";
  92. IOStream *pFileStream = pIOHandler->Open(file, mode);
  93. if (!pFileStream) {
  94. throw DeadlyImportError("Failed to open file " + file + ".");
  95. }
  96. // Get the file-size and validate it, throwing an exception when fails
  97. size_t fileSize = pFileStream->FileSize();
  98. if (fileSize < ObjMinSize) {
  99. throw DeadlyImportError("OBJ-file is too small.");
  100. }
  101. IOStreamBuffer<char> streamedBuffer;
  102. streamedBuffer.open(pFileStream);
  103. // Allocate buffer and read file into it
  104. //TextFileToBuffer( pFileStream,m_Buffer);
  105. // Get the model name
  106. std::string modelName, folderName;
  107. std::string::size_type pos = file.find_last_of("\\/");
  108. if (pos != std::string::npos) {
  109. modelName = file.substr(pos + 1, file.size() - pos - 1);
  110. folderName = file.substr(0, pos);
  111. if (!folderName.empty()) {
  112. pIOHandler->PushDirectory(folderName);
  113. }
  114. } else {
  115. modelName = file;
  116. }
  117. // parse the file into a temporary representation
  118. ObjFileParser parser(streamedBuffer, modelName, pIOHandler, m_progress, file);
  119. // And create the proper return structures out of it
  120. CreateDataFromImport(parser.GetModel(), pScene);
  121. streamedBuffer.close();
  122. pIOHandler->Close(pFileStream);
  123. // Clean up allocated storage for the next import
  124. m_Buffer.clear();
  125. // Pop directory stack
  126. if (pIOHandler->StackSize() > 0) {
  127. pIOHandler->PopDirectory();
  128. }
  129. }
  130. // ------------------------------------------------------------------------------------------------
  131. // Create the data from parsed obj-file
  132. void ObjFileImporter::CreateDataFromImport(const ObjFile::Model *pModel, aiScene *pScene) {
  133. if (0L == pModel) {
  134. return;
  135. }
  136. // Create the root node of the scene
  137. pScene->mRootNode = new aiNode;
  138. if (!pModel->m_ModelName.empty()) {
  139. // Set the name of the scene
  140. pScene->mRootNode->mName.Set(pModel->m_ModelName);
  141. } else {
  142. // This is a fatal error, so break down the application
  143. ai_assert(false);
  144. }
  145. if (!pModel->m_Objects.empty()) {
  146. unsigned int meshCount = 0;
  147. unsigned int childCount = 0;
  148. for (auto object : pModel->m_Objects) {
  149. if (object) {
  150. ++childCount;
  151. meshCount += (unsigned int)object->m_Meshes.size();
  152. }
  153. }
  154. // Allocate space for the child nodes on the root node
  155. pScene->mRootNode->mChildren = new aiNode *[childCount];
  156. // Create nodes for the whole scene
  157. std::vector<aiMesh *> MeshArray;
  158. MeshArray.reserve(meshCount);
  159. for (size_t index = 0; index < pModel->m_Objects.size(); ++index) {
  160. createNodes(pModel, pModel->m_Objects[index], pScene->mRootNode, pScene, MeshArray);
  161. }
  162. ai_assert(pScene->mRootNode->mNumChildren == childCount);
  163. // Create mesh pointer buffer for this scene
  164. if (pScene->mNumMeshes > 0) {
  165. pScene->mMeshes = new aiMesh *[MeshArray.size()];
  166. for (size_t index = 0; index < MeshArray.size(); ++index) {
  167. pScene->mMeshes[index] = MeshArray[index];
  168. }
  169. }
  170. // Create all materials
  171. createMaterials(pModel, pScene);
  172. } else {
  173. if (pModel->m_Vertices.empty()) {
  174. return;
  175. }
  176. std::unique_ptr<aiMesh> mesh(new aiMesh);
  177. mesh->mPrimitiveTypes = aiPrimitiveType_POINT;
  178. unsigned int n = (unsigned int)pModel->m_Vertices.size();
  179. mesh->mNumVertices = n;
  180. mesh->mVertices = new aiVector3D[n];
  181. memcpy(mesh->mVertices, pModel->m_Vertices.data(), n * sizeof(aiVector3D));
  182. if (!pModel->m_Normals.empty()) {
  183. mesh->mNormals = new aiVector3D[n];
  184. if (pModel->m_Normals.size() < n) {
  185. throw DeadlyImportError("OBJ: vertex normal index out of range");
  186. }
  187. memcpy(mesh->mNormals, pModel->m_Normals.data(), n * sizeof(aiVector3D));
  188. }
  189. if (!pModel->m_VertexColors.empty()) {
  190. mesh->mColors[0] = new aiColor4D[mesh->mNumVertices];
  191. for (unsigned int i = 0; i < n; ++i) {
  192. if (i < pModel->m_VertexColors.size()) {
  193. const aiVector3D &color = pModel->m_VertexColors[i];
  194. mesh->mColors[0][i] = aiColor4D(color.x, color.y, color.z, 1.0);
  195. } else {
  196. throw DeadlyImportError("OBJ: vertex color index out of range");
  197. }
  198. }
  199. }
  200. pScene->mRootNode->mNumMeshes = 1;
  201. pScene->mRootNode->mMeshes = new unsigned int[1];
  202. pScene->mRootNode->mMeshes[0] = 0;
  203. pScene->mMeshes = new aiMesh *[1];
  204. pScene->mNumMeshes = 1;
  205. pScene->mMeshes[0] = mesh.release();
  206. }
  207. }
  208. // ------------------------------------------------------------------------------------------------
  209. // Creates all nodes of the model
  210. aiNode *ObjFileImporter::createNodes(const ObjFile::Model *pModel, const ObjFile::Object *pObject,
  211. aiNode *pParent, aiScene *pScene,
  212. std::vector<aiMesh *> &MeshArray) {
  213. ai_assert(nullptr != pModel);
  214. if (nullptr == pObject) {
  215. return nullptr;
  216. }
  217. // Store older mesh size to be able to computes mesh offsets for new mesh instances
  218. const size_t oldMeshSize = MeshArray.size();
  219. aiNode *pNode = new aiNode;
  220. pNode->mName = pObject->m_strObjName;
  221. // If we have a parent node, store it
  222. ai_assert(nullptr != pParent);
  223. appendChildToParentNode(pParent, pNode);
  224. for (size_t i = 0; i < pObject->m_Meshes.size(); ++i) {
  225. unsigned int meshId = pObject->m_Meshes[i];
  226. aiMesh *pMesh = createTopology(pModel, pObject, meshId);
  227. if (pMesh) {
  228. if (pMesh->mNumFaces > 0) {
  229. MeshArray.push_back(pMesh);
  230. } else {
  231. delete pMesh;
  232. }
  233. }
  234. }
  235. // Create all nodes from the sub-objects stored in the current object
  236. if (!pObject->m_SubObjects.empty()) {
  237. size_t numChilds = pObject->m_SubObjects.size();
  238. pNode->mNumChildren = static_cast<unsigned int>(numChilds);
  239. pNode->mChildren = new aiNode *[numChilds];
  240. pNode->mNumMeshes = 1;
  241. pNode->mMeshes = new unsigned int[1];
  242. }
  243. // Set mesh instances into scene- and node-instances
  244. const size_t meshSizeDiff = MeshArray.size() - oldMeshSize;
  245. if (meshSizeDiff > 0) {
  246. pNode->mMeshes = new unsigned int[meshSizeDiff];
  247. pNode->mNumMeshes = static_cast<unsigned int>(meshSizeDiff);
  248. size_t index = 0;
  249. for (size_t i = oldMeshSize; i < MeshArray.size(); ++i) {
  250. pNode->mMeshes[index] = pScene->mNumMeshes;
  251. pScene->mNumMeshes++;
  252. ++index;
  253. }
  254. }
  255. return pNode;
  256. }
  257. // ------------------------------------------------------------------------------------------------
  258. // Create topology data
  259. aiMesh *ObjFileImporter::createTopology(const ObjFile::Model *pModel, const ObjFile::Object *pData, unsigned int meshIndex) {
  260. // Checking preconditions
  261. ai_assert(nullptr != pModel);
  262. if (nullptr == pData) {
  263. return nullptr;
  264. }
  265. // Create faces
  266. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[meshIndex];
  267. if (!pObjMesh) {
  268. return nullptr;
  269. }
  270. if (pObjMesh->m_Faces.empty()) {
  271. return nullptr;
  272. }
  273. std::unique_ptr<aiMesh> pMesh(new aiMesh);
  274. if (!pObjMesh->m_name.empty()) {
  275. pMesh->mName.Set(pObjMesh->m_name);
  276. }
  277. for (size_t index = 0; index < pObjMesh->m_Faces.size(); index++) {
  278. ObjFile::Face *const inp = pObjMesh->m_Faces[index];
  279. ai_assert(nullptr != inp);
  280. if (inp->m_PrimitiveType == aiPrimitiveType_LINE) {
  281. pMesh->mNumFaces += static_cast<unsigned int>(inp->m_vertices.size() - 1);
  282. pMesh->mPrimitiveTypes |= aiPrimitiveType_LINE;
  283. } else if (inp->m_PrimitiveType == aiPrimitiveType_POINT) {
  284. pMesh->mNumFaces += static_cast<unsigned int>(inp->m_vertices.size());
  285. pMesh->mPrimitiveTypes |= aiPrimitiveType_POINT;
  286. } else {
  287. ++pMesh->mNumFaces;
  288. if (inp->m_vertices.size() > 3) {
  289. pMesh->mPrimitiveTypes |= aiPrimitiveType_POLYGON;
  290. } else {
  291. pMesh->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  292. }
  293. }
  294. }
  295. unsigned int uiIdxCount(0u);
  296. if (pMesh->mNumFaces > 0) {
  297. pMesh->mFaces = new aiFace[pMesh->mNumFaces];
  298. if (pObjMesh->m_uiMaterialIndex != ObjFile::Mesh::NoMaterial) {
  299. pMesh->mMaterialIndex = pObjMesh->m_uiMaterialIndex;
  300. }
  301. unsigned int outIndex(0);
  302. // Copy all data from all stored meshes
  303. for (auto &face : pObjMesh->m_Faces) {
  304. ObjFile::Face *const inp = face;
  305. if (inp->m_PrimitiveType == aiPrimitiveType_LINE) {
  306. for (size_t i = 0; i < inp->m_vertices.size() - 1; ++i) {
  307. aiFace &f = pMesh->mFaces[outIndex++];
  308. uiIdxCount += f.mNumIndices = 2;
  309. f.mIndices = new unsigned int[2];
  310. }
  311. continue;
  312. } else if (inp->m_PrimitiveType == aiPrimitiveType_POINT) {
  313. for (size_t i = 0; i < inp->m_vertices.size(); ++i) {
  314. aiFace &f = pMesh->mFaces[outIndex++];
  315. uiIdxCount += f.mNumIndices = 1;
  316. f.mIndices = new unsigned int[1];
  317. }
  318. continue;
  319. }
  320. aiFace *pFace = &pMesh->mFaces[outIndex++];
  321. const unsigned int uiNumIndices = (unsigned int)face->m_vertices.size();
  322. uiIdxCount += pFace->mNumIndices = (unsigned int)uiNumIndices;
  323. if (pFace->mNumIndices > 0) {
  324. pFace->mIndices = new unsigned int[uiNumIndices];
  325. }
  326. }
  327. }
  328. // Create mesh vertices
  329. createVertexArray(pModel, pData, meshIndex, pMesh.get(), uiIdxCount);
  330. return pMesh.release();
  331. }
  332. // ------------------------------------------------------------------------------------------------
  333. // Creates a vertex array
  334. void ObjFileImporter::createVertexArray(const ObjFile::Model *pModel,
  335. const ObjFile::Object *pCurrentObject,
  336. unsigned int uiMeshIndex,
  337. aiMesh *pMesh,
  338. unsigned int numIndices) {
  339. // Checking preconditions
  340. ai_assert(nullptr != pCurrentObject);
  341. // Break, if no faces are stored in object
  342. if (pCurrentObject->m_Meshes.empty())
  343. return;
  344. // Get current mesh
  345. ObjFile::Mesh *pObjMesh = pModel->m_Meshes[uiMeshIndex];
  346. if (nullptr == pObjMesh || pObjMesh->m_uiNumIndices < 1) {
  347. return;
  348. }
  349. // Copy vertices of this mesh instance
  350. pMesh->mNumVertices = numIndices;
  351. if (pMesh->mNumVertices == 0) {
  352. throw DeadlyImportError("OBJ: no vertices");
  353. } else if (pMesh->mNumVertices > AI_MAX_VERTICES) {
  354. throw DeadlyImportError("OBJ: Too many vertices");
  355. }
  356. pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
  357. // Allocate buffer for normal vectors
  358. if (!pModel->m_Normals.empty() && pObjMesh->m_hasNormals)
  359. pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
  360. // Allocate buffer for vertex-color vectors
  361. if (!pModel->m_VertexColors.empty())
  362. pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
  363. // Allocate buffer for texture coordinates
  364. if (!pModel->m_TextureCoord.empty() && pObjMesh->m_uiUVCoordinates[0]) {
  365. pMesh->mNumUVComponents[0] = pModel->m_TextureCoordDim;
  366. pMesh->mTextureCoords[0] = new aiVector3D[pMesh->mNumVertices];
  367. }
  368. // Copy vertices, normals and textures into aiMesh instance
  369. bool normalsok = true, uvok = true;
  370. unsigned int newIndex = 0, outIndex = 0;
  371. for (auto sourceFace : pObjMesh->m_Faces) {
  372. // Copy all index arrays
  373. for (size_t vertexIndex = 0, outVertexIndex = 0; vertexIndex < sourceFace->m_vertices.size(); vertexIndex++) {
  374. const unsigned int vertex = sourceFace->m_vertices.at(vertexIndex);
  375. if (vertex >= pModel->m_Vertices.size()) {
  376. throw DeadlyImportError("OBJ: vertex index out of range");
  377. }
  378. if (pMesh->mNumVertices <= newIndex) {
  379. throw DeadlyImportError("OBJ: bad vertex index");
  380. }
  381. pMesh->mVertices[newIndex] = pModel->m_Vertices[vertex];
  382. // Copy all normals
  383. if (normalsok && !pModel->m_Normals.empty() && vertexIndex < sourceFace->m_normals.size()) {
  384. const unsigned int normal = sourceFace->m_normals.at(vertexIndex);
  385. if (normal >= pModel->m_Normals.size()) {
  386. normalsok = false;
  387. } else {
  388. pMesh->mNormals[newIndex] = pModel->m_Normals[normal];
  389. }
  390. }
  391. // Copy all vertex colors
  392. if (!pModel->m_VertexColors.empty()) {
  393. const aiVector3D &color = pModel->m_VertexColors[vertex];
  394. pMesh->mColors[0][newIndex] = aiColor4D(color.x, color.y, color.z, 1.0);
  395. }
  396. // Copy all texture coordinates
  397. if (uvok && !pModel->m_TextureCoord.empty() && vertexIndex < sourceFace->m_texturCoords.size()) {
  398. const unsigned int tex = sourceFace->m_texturCoords.at(vertexIndex);
  399. if (tex >= pModel->m_TextureCoord.size()) {
  400. uvok = false;
  401. } else {
  402. const aiVector3D &coord3d = pModel->m_TextureCoord[tex];
  403. pMesh->mTextureCoords[0][newIndex] = aiVector3D(coord3d.x, coord3d.y, coord3d.z);
  404. }
  405. }
  406. // Get destination face
  407. aiFace *pDestFace = &pMesh->mFaces[outIndex];
  408. const bool last = (vertexIndex == sourceFace->m_vertices.size() - 1);
  409. if (sourceFace->m_PrimitiveType != aiPrimitiveType_LINE || !last) {
  410. pDestFace->mIndices[outVertexIndex] = newIndex;
  411. outVertexIndex++;
  412. }
  413. if (sourceFace->m_PrimitiveType == aiPrimitiveType_POINT) {
  414. outIndex++;
  415. outVertexIndex = 0;
  416. } else if (sourceFace->m_PrimitiveType == aiPrimitiveType_LINE) {
  417. outVertexIndex = 0;
  418. if (!last)
  419. outIndex++;
  420. if (vertexIndex) {
  421. if (!last) {
  422. pMesh->mVertices[newIndex + 1] = pMesh->mVertices[newIndex];
  423. if (!sourceFace->m_normals.empty() && !pModel->m_Normals.empty()) {
  424. pMesh->mNormals[newIndex + 1] = pMesh->mNormals[newIndex];
  425. }
  426. if (!pModel->m_TextureCoord.empty()) {
  427. for (size_t i = 0; i < pMesh->GetNumUVChannels(); i++) {
  428. pMesh->mTextureCoords[i][newIndex + 1] = pMesh->mTextureCoords[i][newIndex];
  429. }
  430. }
  431. ++newIndex;
  432. }
  433. pDestFace[-1].mIndices[1] = newIndex;
  434. }
  435. } else if (last) {
  436. outIndex++;
  437. }
  438. ++newIndex;
  439. }
  440. }
  441. if (!normalsok) {
  442. delete[] pMesh->mNormals;
  443. pMesh->mNormals = nullptr;
  444. }
  445. if (!uvok) {
  446. delete[] pMesh->mTextureCoords[0];
  447. pMesh->mTextureCoords[0] = nullptr;
  448. }
  449. }
  450. // ------------------------------------------------------------------------------------------------
  451. // Counts all stored meshes
  452. void ObjFileImporter::countObjects(const std::vector<ObjFile::Object *> &rObjects, int &iNumMeshes) {
  453. iNumMeshes = 0;
  454. if (rObjects.empty())
  455. return;
  456. iNumMeshes += static_cast<unsigned int>(rObjects.size());
  457. for (auto object : rObjects) {
  458. if (!object->m_SubObjects.empty()) {
  459. countObjects(object->m_SubObjects, iNumMeshes);
  460. }
  461. }
  462. }
  463. // ------------------------------------------------------------------------------------------------
  464. // Add clamp mode property to material if necessary
  465. void ObjFileImporter::addTextureMappingModeProperty(aiMaterial *mat, aiTextureType type, int clampMode, int index) {
  466. if (nullptr == mat) {
  467. return;
  468. }
  469. mat->AddProperty<int>(&clampMode, 1, AI_MATKEY_MAPPINGMODE_U(type, index));
  470. mat->AddProperty<int>(&clampMode, 1, AI_MATKEY_MAPPINGMODE_V(type, index));
  471. }
  472. // ------------------------------------------------------------------------------------------------
  473. // Creates the material
  474. void ObjFileImporter::createMaterials(const ObjFile::Model *pModel, aiScene *pScene) {
  475. if (nullptr == pScene) {
  476. return;
  477. }
  478. const unsigned int numMaterials = (unsigned int)pModel->m_MaterialLib.size();
  479. pScene->mNumMaterials = 0;
  480. if (pModel->m_MaterialLib.empty()) {
  481. ASSIMP_LOG_DEBUG("OBJ: no materials specified");
  482. return;
  483. }
  484. pScene->mMaterials = new aiMaterial *[numMaterials];
  485. for (unsigned int matIndex = 0; matIndex < numMaterials; matIndex++) {
  486. // Store material name
  487. std::map<std::string, ObjFile::Material *>::const_iterator it;
  488. it = pModel->m_MaterialMap.find(pModel->m_MaterialLib[matIndex]);
  489. // No material found, use the default material
  490. if (pModel->m_MaterialMap.end() == it)
  491. continue;
  492. aiMaterial *mat = new aiMaterial;
  493. ObjFile::Material *pCurrentMaterial = (*it).second;
  494. mat->AddProperty(&pCurrentMaterial->MaterialName, AI_MATKEY_NAME);
  495. // convert illumination model
  496. int sm = 0;
  497. switch (pCurrentMaterial->illumination_model) {
  498. case 0:
  499. sm = aiShadingMode_NoShading;
  500. break;
  501. case 1:
  502. sm = aiShadingMode_Gouraud;
  503. break;
  504. case 2:
  505. sm = aiShadingMode_Phong;
  506. break;
  507. default:
  508. sm = aiShadingMode_Gouraud;
  509. ASSIMP_LOG_ERROR("OBJ: unexpected illumination model (0-2 recognized)");
  510. }
  511. mat->AddProperty<int>(&sm, 1, AI_MATKEY_SHADING_MODEL);
  512. // Adding material colors
  513. mat->AddProperty(&pCurrentMaterial->ambient, 1, AI_MATKEY_COLOR_AMBIENT);
  514. mat->AddProperty(&pCurrentMaterial->diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  515. mat->AddProperty(&pCurrentMaterial->specular, 1, AI_MATKEY_COLOR_SPECULAR);
  516. mat->AddProperty(&pCurrentMaterial->emissive, 1, AI_MATKEY_COLOR_EMISSIVE);
  517. mat->AddProperty(&pCurrentMaterial->shineness, 1, AI_MATKEY_SHININESS);
  518. mat->AddProperty(&pCurrentMaterial->alpha, 1, AI_MATKEY_OPACITY);
  519. mat->AddProperty(&pCurrentMaterial->transparent, 1, AI_MATKEY_COLOR_TRANSPARENT);
  520. // Adding refraction index
  521. mat->AddProperty(&pCurrentMaterial->ior, 1, AI_MATKEY_REFRACTI);
  522. // Adding textures
  523. const int uvwIndex = 0;
  524. if (0 != pCurrentMaterial->texture.length) {
  525. mat->AddProperty(&pCurrentMaterial->texture, AI_MATKEY_TEXTURE_DIFFUSE(0));
  526. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_DIFFUSE(0));
  527. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDiffuseType]) {
  528. addTextureMappingModeProperty(mat, aiTextureType_DIFFUSE);
  529. }
  530. }
  531. if (0 != pCurrentMaterial->textureAmbient.length) {
  532. mat->AddProperty(&pCurrentMaterial->textureAmbient, AI_MATKEY_TEXTURE_AMBIENT(0));
  533. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_AMBIENT(0));
  534. if (pCurrentMaterial->clamp[ObjFile::Material::TextureAmbientType]) {
  535. addTextureMappingModeProperty(mat, aiTextureType_AMBIENT);
  536. }
  537. }
  538. if (0 != pCurrentMaterial->textureEmissive.length) {
  539. mat->AddProperty(&pCurrentMaterial->textureEmissive, AI_MATKEY_TEXTURE_EMISSIVE(0));
  540. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_EMISSIVE(0));
  541. }
  542. if (0 != pCurrentMaterial->textureSpecular.length) {
  543. mat->AddProperty(&pCurrentMaterial->textureSpecular, AI_MATKEY_TEXTURE_SPECULAR(0));
  544. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_SPECULAR(0));
  545. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularType]) {
  546. addTextureMappingModeProperty(mat, aiTextureType_SPECULAR);
  547. }
  548. }
  549. if (0 != pCurrentMaterial->textureBump.length) {
  550. mat->AddProperty(&pCurrentMaterial->textureBump, AI_MATKEY_TEXTURE_HEIGHT(0));
  551. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_HEIGHT(0));
  552. if (pCurrentMaterial->clamp[ObjFile::Material::TextureBumpType]) {
  553. addTextureMappingModeProperty(mat, aiTextureType_HEIGHT);
  554. }
  555. }
  556. if (0 != pCurrentMaterial->textureNormal.length) {
  557. mat->AddProperty(&pCurrentMaterial->textureNormal, AI_MATKEY_TEXTURE_NORMALS(0));
  558. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_NORMALS(0));
  559. if (pCurrentMaterial->clamp[ObjFile::Material::TextureNormalType]) {
  560. addTextureMappingModeProperty(mat, aiTextureType_NORMALS);
  561. }
  562. }
  563. if (0 != pCurrentMaterial->textureReflection[0].length) {
  564. ObjFile::Material::TextureType type = 0 != pCurrentMaterial->textureReflection[1].length ?
  565. ObjFile::Material::TextureReflectionCubeTopType :
  566. ObjFile::Material::TextureReflectionSphereType;
  567. unsigned count = type == ObjFile::Material::TextureReflectionSphereType ? 1 : 6;
  568. for (unsigned i = 0; i < count; i++) {
  569. mat->AddProperty(&pCurrentMaterial->textureReflection[i], AI_MATKEY_TEXTURE_REFLECTION(i));
  570. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_REFLECTION(i));
  571. if (pCurrentMaterial->clamp[type])
  572. addTextureMappingModeProperty(mat, aiTextureType_REFLECTION, 1, i);
  573. }
  574. }
  575. if (0 != pCurrentMaterial->textureDisp.length) {
  576. mat->AddProperty(&pCurrentMaterial->textureDisp, AI_MATKEY_TEXTURE_DISPLACEMENT(0));
  577. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_DISPLACEMENT(0));
  578. if (pCurrentMaterial->clamp[ObjFile::Material::TextureDispType]) {
  579. addTextureMappingModeProperty(mat, aiTextureType_DISPLACEMENT);
  580. }
  581. }
  582. if (0 != pCurrentMaterial->textureOpacity.length) {
  583. mat->AddProperty(&pCurrentMaterial->textureOpacity, AI_MATKEY_TEXTURE_OPACITY(0));
  584. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_OPACITY(0));
  585. if (pCurrentMaterial->clamp[ObjFile::Material::TextureOpacityType]) {
  586. addTextureMappingModeProperty(mat, aiTextureType_OPACITY);
  587. }
  588. }
  589. if (0 != pCurrentMaterial->textureSpecularity.length) {
  590. mat->AddProperty(&pCurrentMaterial->textureSpecularity, AI_MATKEY_TEXTURE_SHININESS(0));
  591. mat->AddProperty(&uvwIndex, 1, AI_MATKEY_UVWSRC_SHININESS(0));
  592. if (pCurrentMaterial->clamp[ObjFile::Material::TextureSpecularityType]) {
  593. addTextureMappingModeProperty(mat, aiTextureType_SHININESS);
  594. }
  595. }
  596. // Store material property info in material array in scene
  597. pScene->mMaterials[pScene->mNumMaterials] = mat;
  598. pScene->mNumMaterials++;
  599. }
  600. // Test number of created materials.
  601. ai_assert(pScene->mNumMaterials == numMaterials);
  602. }
  603. // ------------------------------------------------------------------------------------------------
  604. // Appends this node to the parent node
  605. void ObjFileImporter::appendChildToParentNode(aiNode *pParent, aiNode *pChild) {
  606. // Checking preconditions
  607. ai_assert(nullptr != pParent);
  608. ai_assert(nullptr != pChild);
  609. // Assign parent to child
  610. pChild->mParent = pParent;
  611. // Copy node instances into parent node
  612. pParent->mNumChildren++;
  613. pParent->mChildren[pParent->mNumChildren - 1] = pChild;
  614. }
  615. // ------------------------------------------------------------------------------------------------
  616. } // Namespace Assimp
  617. #endif // !! ASSIMP_BUILD_NO_OBJ_IMPORTER