glTFImporter.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2016, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
  34. #include "glTFImporter.h"
  35. #include "StringComparison.h"
  36. #include "StringUtils.h"
  37. #include <assimp/Importer.hpp>
  38. #include <assimp/scene.h>
  39. #include <assimp/ai_assert.h>
  40. #include <assimp/DefaultLogger.hpp>
  41. #include <memory>
  42. #include "MakeVerboseFormat.h"
  43. #include "glTFAsset.h"
  44. // This is included here so WriteLazyDict<T>'s definition is found.
  45. #include "glTFAssetWriter.h"
  46. using namespace Assimp;
  47. using namespace glTF;
  48. //
  49. // glTFImporter
  50. //
  51. static const aiImporterDesc desc = {
  52. "glTF Importer",
  53. "",
  54. "",
  55. "",
  56. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportCompressedFlavour
  57. | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  58. 0,
  59. 0,
  60. 0,
  61. 0,
  62. "gltf glb"
  63. };
  64. glTFImporter::glTFImporter()
  65. : BaseImporter()
  66. , meshOffsets()
  67. , embeddedTexIdxs()
  68. , mScene( NULL ) {
  69. // empty
  70. }
  71. glTFImporter::~glTFImporter() {
  72. // empty
  73. }
  74. const aiImporterDesc* glTFImporter::GetInfo() const
  75. {
  76. return &desc;
  77. }
  78. bool glTFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  79. {
  80. const std::string& extension = GetExtension(pFile);
  81. if (extension == "gltf" || extension == "glb")
  82. return true;
  83. if ((checkSig || !extension.length()) && pIOHandler) {
  84. char buffer[4];
  85. std::unique_ptr<IOStream> pStream(pIOHandler->Open(pFile));
  86. if (pStream && pStream->Read(buffer, sizeof(buffer), 1) == 1) {
  87. if (memcmp(buffer, AI_GLB_MAGIC_NUMBER, sizeof(buffer)) == 0) {
  88. return true; // Has GLB header
  89. }
  90. else if (memcmp(buffer, "{\r\n ", sizeof(buffer)) == 0
  91. || memcmp(buffer, "{\n ", sizeof(buffer)) == 0) {
  92. // seems a JSON file, and we're the only format that can read them
  93. return true;
  94. }
  95. }
  96. }
  97. return false;
  98. }
  99. //static void CopyValue(const glTF::vec3& v, aiColor3D& out)
  100. //{
  101. // out.r = v[0]; out.g = v[1]; out.b = v[2];
  102. //}
  103. static void CopyValue(const glTF::vec4& v, aiColor4D& out)
  104. {
  105. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = v[3];
  106. }
  107. static void CopyValue(const glTF::vec4& v, aiColor3D& out)
  108. {
  109. out.r = v[0]; out.g = v[1]; out.b = v[2];
  110. }
  111. static void CopyValue(const glTF::vec3& v, aiVector3D& out)
  112. {
  113. out.x = v[0]; out.y = v[1]; out.z = v[2];
  114. }
  115. static void CopyValue(const glTF::vec4& v, aiQuaternion& out)
  116. {
  117. out.x = v[0]; out.y = v[1]; out.z = v[2]; out.w = v[3];
  118. }
  119. static void CopyValue(const glTF::mat4& v, aiMatrix4x4& o)
  120. {
  121. o.a1 = v[ 0]; o.b1 = v[ 1]; o.c1 = v[ 2]; o.d1 = v[ 3];
  122. o.a2 = v[ 4]; o.b2 = v[ 5]; o.c2 = v[ 6]; o.d2 = v[ 7];
  123. o.a3 = v[ 8]; o.b3 = v[ 9]; o.c3 = v[10]; o.d3 = v[11];
  124. o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15];
  125. }
  126. inline void SetMaterialColorProperty(std::vector<int>& embeddedTexIdxs, Asset& r, glTF::TexProperty prop, aiMaterial* mat,
  127. aiTextureType texType, const char* pKey, unsigned int type, unsigned int idx)
  128. {
  129. if (prop.texture) {
  130. if (prop.texture->source) {
  131. aiString uri(prop.texture->source->uri);
  132. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  133. if (texIdx != -1) { // embedded
  134. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  135. uri.data[0] = '*';
  136. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
  137. }
  138. mat->AddProperty(&uri, _AI_MATKEY_TEXTURE_BASE, texType, 0);
  139. }
  140. }
  141. else {
  142. aiColor4D col;
  143. CopyValue(prop.color, col);
  144. if (col.r != 1.f || col.g != 1.f || col.b != 1.f || col.a != 1.f) {
  145. mat->AddProperty(&col, 1, pKey, type, idx);
  146. }
  147. }
  148. }
  149. void glTFImporter::ImportMaterials(glTF::Asset& r)
  150. {
  151. mScene->mNumMaterials = unsigned(r.materials.Size());
  152. mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials];
  153. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  154. aiMaterial* aimat = mScene->mMaterials[i] = new aiMaterial();
  155. Material& mat = r.materials[i];
  156. /*if (!mat.name.empty())*/ {
  157. aiString str(mat.id /*mat.name*/);
  158. aimat->AddProperty(&str, AI_MATKEY_NAME);
  159. }
  160. SetMaterialColorProperty(embeddedTexIdxs, r, mat.diffuse, aimat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE);
  161. SetMaterialColorProperty(embeddedTexIdxs, r, mat.specular, aimat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
  162. SetMaterialColorProperty(embeddedTexIdxs, r, mat.ambient, aimat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT);
  163. if (mat.shininess > 0.f) {
  164. aimat->AddProperty(&mat.shininess, 1, AI_MATKEY_SHININESS);
  165. }
  166. }
  167. if (mScene->mNumMaterials == 0) {
  168. mScene->mNumMaterials = 1;
  169. mScene->mMaterials = new aiMaterial*[1];
  170. mScene->mMaterials[0] = new aiMaterial();
  171. }
  172. }
  173. static inline void SetFace(aiFace& face, int a)
  174. {
  175. face.mNumIndices = 1;
  176. face.mIndices = new unsigned int[1];
  177. face.mIndices[0] = a;
  178. }
  179. static inline void SetFace(aiFace& face, int a, int b)
  180. {
  181. face.mNumIndices = 2;
  182. face.mIndices = new unsigned int[2];
  183. face.mIndices[0] = a;
  184. face.mIndices[1] = b;
  185. }
  186. static inline void SetFace(aiFace& face, int a, int b, int c)
  187. {
  188. face.mNumIndices = 3;
  189. face.mIndices = new unsigned int[3];
  190. face.mIndices[0] = a;
  191. face.mIndices[1] = b;
  192. face.mIndices[2] = c;
  193. }
  194. static inline bool CheckValidFacesIndices(aiFace* faces, unsigned nFaces, unsigned nVerts)
  195. {
  196. for (unsigned i = 0; i < nFaces; ++i) {
  197. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  198. unsigned idx = faces[i].mIndices[j];
  199. if (idx >= nVerts)
  200. return false;
  201. }
  202. }
  203. return true;
  204. }
  205. void glTFImporter::ImportMeshes(glTF::Asset& r)
  206. {
  207. std::vector<aiMesh*> meshes;
  208. unsigned int k = 0;
  209. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  210. Mesh& mesh = r.meshes[m];
  211. // Check if mesh extensions is used
  212. if(mesh.Extension.size() > 0)
  213. {
  214. for(Mesh::SExtension* cur_ext : mesh.Extension)
  215. {
  216. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  217. if(cur_ext->Type == Mesh::SExtension::EType::Compression_Open3DGC)
  218. {
  219. // Limitations for meshes when using Open3DGC-compression.
  220. // It's a current limitation of sp... Specification have not this part still - about mesh compression. Why only one primitive?
  221. // Because glTF is very flexibly. But in fact it ugly flexible. Every primitive can has own set of accessors and accessors can
  222. // point to a-a-a-a-any part of buffer (thru bufferview ofcourse) and even to another buffer. We know that "Open3DGC-compression"
  223. // is applicable only to part of buffer. As we can't guaranty continuity of the data for decoder, we will limit quantity of primitives.
  224. // Yes indices, coordinates etc. still can br stored in different buffers, but with current specification it's a exporter problem.
  225. // Also primitive can has only one of "POSITION", "NORMAL" and less then "AI_MAX_NUMBER_OF_TEXTURECOORDS" of "TEXCOORD". All accessor
  226. // of primitive must point to one continuous region of the buffer.
  227. if(mesh.primitives.size() > 2) throw DeadlyImportError("GLTF: When using Open3DGC compression then only one primitive per mesh are allowed.");
  228. Mesh::SCompression_Open3DGC* o3dgc_ext = (Mesh::SCompression_Open3DGC*)cur_ext;
  229. Ref<Buffer> buf = r.buffers.Get(o3dgc_ext->Buffer);
  230. buf->EncodedRegion_SetCurrent(mesh.id);
  231. }
  232. else
  233. #endif
  234. {
  235. throw DeadlyImportError("GLTF: Can not import mesh: unknown mesh extension (code: \"" + to_string(cur_ext->Type) +
  236. "\"), only Open3DGC is supported.");
  237. }
  238. }
  239. }// if(mesh.Extension.size() > 0)
  240. meshOffsets.push_back(k);
  241. k += unsigned(mesh.primitives.size());
  242. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  243. Mesh::Primitive& prim = mesh.primitives[p];
  244. aiMesh* aim = new aiMesh();
  245. meshes.push_back(aim);
  246. aim->mName = mesh.id;
  247. if (mesh.primitives.size() > 1) {
  248. size_t& len = aim->mName.length;
  249. aim->mName.data[len] = '-';
  250. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
  251. }
  252. switch (prim.mode) {
  253. case PrimitiveMode_POINTS:
  254. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  255. break;
  256. case PrimitiveMode_LINES:
  257. case PrimitiveMode_LINE_LOOP:
  258. case PrimitiveMode_LINE_STRIP:
  259. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  260. break;
  261. case PrimitiveMode_TRIANGLES:
  262. case PrimitiveMode_TRIANGLE_STRIP:
  263. case PrimitiveMode_TRIANGLE_FAN:
  264. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  265. break;
  266. }
  267. Mesh::Primitive::Attributes& attr = prim.attributes;
  268. if (attr.position.size() > 0 && attr.position[0]) {
  269. aim->mNumVertices = attr.position[0]->count;
  270. attr.position[0]->ExtractData(aim->mVertices);
  271. }
  272. if (attr.normal.size() > 0 && attr.normal[0]) attr.normal[0]->ExtractData(aim->mNormals);
  273. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  274. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
  275. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  276. aiVector3D* values = aim->mTextureCoords[tc];
  277. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  278. values[i].y = 1 - values[i].y; // Flip Y coords
  279. }
  280. }
  281. if (prim.indices) {
  282. aiFace* faces = 0;
  283. unsigned int nFaces = 0;
  284. unsigned int count = prim.indices->count;
  285. Accessor::Indexer data = prim.indices->GetIndexer();
  286. ai_assert(data.IsValid());
  287. switch (prim.mode) {
  288. case PrimitiveMode_POINTS: {
  289. nFaces = count;
  290. faces = new aiFace[nFaces];
  291. for (unsigned int i = 0; i < count; ++i) {
  292. SetFace(faces[i], data.GetUInt(i));
  293. }
  294. break;
  295. }
  296. case PrimitiveMode_LINES: {
  297. nFaces = count / 2;
  298. faces = new aiFace[nFaces];
  299. for (unsigned int i = 0; i < count; i += 2) {
  300. SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
  301. }
  302. break;
  303. }
  304. case PrimitiveMode_LINE_LOOP:
  305. case PrimitiveMode_LINE_STRIP: {
  306. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  307. faces = new aiFace[nFaces];
  308. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
  309. for (unsigned int i = 2; i < count; ++i) {
  310. SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
  311. }
  312. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  313. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  314. }
  315. break;
  316. }
  317. case PrimitiveMode_TRIANGLES: {
  318. nFaces = count / 3;
  319. faces = new aiFace[nFaces];
  320. for (unsigned int i = 0; i < count; i += 3) {
  321. SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  322. }
  323. break;
  324. }
  325. case PrimitiveMode_TRIANGLE_STRIP: {
  326. nFaces = count - 2;
  327. faces = new aiFace[nFaces];
  328. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  329. for (unsigned int i = 3; i < count; ++i) {
  330. SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], data.GetUInt(i));
  331. }
  332. break;
  333. }
  334. case PrimitiveMode_TRIANGLE_FAN:
  335. nFaces = count - 2;
  336. faces = new aiFace[nFaces];
  337. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  338. for (unsigned int i = 3; i < count; ++i) {
  339. SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i));
  340. }
  341. break;
  342. }
  343. if (faces) {
  344. aim->mFaces = faces;
  345. aim->mNumFaces = nFaces;
  346. ai_assert(CheckValidFacesIndices(faces, nFaces, aim->mNumVertices));
  347. }
  348. }
  349. if (prim.material) {
  350. aim->mMaterialIndex = prim.material.GetIndex();
  351. }
  352. }
  353. }
  354. meshOffsets.push_back(k);
  355. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  356. }
  357. void glTFImporter::ImportCameras(glTF::Asset& r)
  358. {
  359. if (!r.cameras.Size()) return;
  360. mScene->mNumCameras = r.cameras.Size();
  361. mScene->mCameras = new aiCamera*[r.cameras.Size()];
  362. for (size_t i = 0; i < r.cameras.Size(); ++i) {
  363. Camera& cam = r.cameras[i];
  364. aiCamera* aicam = mScene->mCameras[i] = new aiCamera();
  365. if (cam.type == Camera::Perspective) {
  366. aicam->mAspect = cam.perspective.aspectRatio;
  367. aicam->mHorizontalFOV = cam.perspective.yfov * aicam->mAspect;
  368. aicam->mClipPlaneFar = cam.perspective.zfar;
  369. aicam->mClipPlaneNear = cam.perspective.znear;
  370. }
  371. else {
  372. // assimp does not support orthographic cameras
  373. }
  374. }
  375. }
  376. void glTFImporter::ImportLights(glTF::Asset& r)
  377. {
  378. if (!r.lights.Size()) return;
  379. mScene->mNumLights = r.lights.Size();
  380. mScene->mLights = new aiLight*[r.lights.Size()];
  381. for (size_t i = 0; i < r.lights.Size(); ++i) {
  382. Light& l = r.lights[i];
  383. aiLight* ail = mScene->mLights[i] = new aiLight();
  384. switch (l.type) {
  385. case Light::Type_directional:
  386. ail->mType = aiLightSource_DIRECTIONAL; break;
  387. case Light::Type_spot:
  388. ail->mType = aiLightSource_SPOT; break;
  389. case Light::Type_ambient:
  390. ail->mType = aiLightSource_AMBIENT; break;
  391. default: // Light::Type_point
  392. ail->mType = aiLightSource_POINT; break;
  393. }
  394. CopyValue(l.color, ail->mColorAmbient);
  395. CopyValue(l.color, ail->mColorDiffuse);
  396. CopyValue(l.color, ail->mColorSpecular);
  397. ail->mAngleOuterCone = l.falloffAngle;
  398. ail->mAngleInnerCone = l.falloffExponent; // TODO fix this, it does not look right at all
  399. ail->mAttenuationConstant = l.constantAttenuation;
  400. ail->mAttenuationLinear = l.linearAttenuation;
  401. ail->mAttenuationQuadratic = l.quadraticAttenuation;
  402. }
  403. }
  404. aiNode* ImportNode(aiScene* pScene, glTF::Asset& r, std::vector<unsigned int>& meshOffsets, glTF::Ref<glTF::Node>& ptr)
  405. {
  406. Node& node = *ptr;
  407. aiNode* ainode = new aiNode(node.id);
  408. if (!node.children.empty()) {
  409. ainode->mNumChildren = unsigned(node.children.size());
  410. ainode->mChildren = new aiNode*[ainode->mNumChildren];
  411. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  412. aiNode* child = ImportNode(pScene, r, meshOffsets, node.children[i]);
  413. child->mParent = ainode;
  414. ainode->mChildren[i] = child;
  415. }
  416. }
  417. aiMatrix4x4& matrix = ainode->mTransformation;
  418. if (node.matrix.isPresent) {
  419. CopyValue(node.matrix.value, matrix);
  420. }
  421. else {
  422. if (node.translation.isPresent) {
  423. aiVector3D trans;
  424. CopyValue(node.translation.value, trans);
  425. aiMatrix4x4 t;
  426. aiMatrix4x4::Translation(trans, t);
  427. matrix = t * matrix;
  428. }
  429. if (node.scale.isPresent) {
  430. aiVector3D scal(1.f);
  431. CopyValue(node.scale.value, scal);
  432. aiMatrix4x4 s;
  433. aiMatrix4x4::Scaling(scal, s);
  434. matrix = s * matrix;
  435. }
  436. if (node.rotation.isPresent) {
  437. aiQuaternion rot;
  438. CopyValue(node.rotation.value, rot);
  439. matrix = aiMatrix4x4(rot.GetMatrix()) * matrix;
  440. }
  441. }
  442. if (!node.meshes.empty()) {
  443. int count = 0;
  444. for (size_t i = 0; i < node.meshes.size(); ++i) {
  445. int idx = node.meshes[i].GetIndex();
  446. count += meshOffsets[idx + 1] - meshOffsets[idx];
  447. }
  448. ainode->mNumMeshes = count;
  449. ainode->mMeshes = new unsigned int[count];
  450. int k = 0;
  451. for (size_t i = 0; i < node.meshes.size(); ++i) {
  452. int idx = node.meshes[i].GetIndex();
  453. for (unsigned int j = meshOffsets[idx]; j < meshOffsets[idx + 1]; ++j, ++k) {
  454. ainode->mMeshes[k] = j;
  455. }
  456. }
  457. }
  458. if (node.camera) {
  459. pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  460. }
  461. if (node.light) {
  462. pScene->mLights[node.light.GetIndex()]->mName = ainode->mName;
  463. }
  464. return ainode;
  465. }
  466. void glTFImporter::ImportNodes(glTF::Asset& r)
  467. {
  468. if (!r.scene) return;
  469. std::vector< Ref<Node> > rootNodes = r.scene->nodes;
  470. // The root nodes
  471. unsigned int numRootNodes = unsigned(rootNodes.size());
  472. if (numRootNodes == 1) { // a single root node: use it
  473. mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
  474. }
  475. else if (numRootNodes > 1) { // more than one root node: create a fake root
  476. aiNode* root = new aiNode("ROOT");
  477. root->mChildren = new aiNode*[numRootNodes];
  478. for (unsigned int i = 0; i < numRootNodes; ++i) {
  479. aiNode* node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
  480. node->mParent = root;
  481. root->mChildren[root->mNumChildren++] = node;
  482. }
  483. mScene->mRootNode = root;
  484. }
  485. //if (!mScene->mRootNode) {
  486. // mScene->mRootNode = new aiNode("EMPTY");
  487. //}
  488. }
  489. void glTFImporter::ImportEmbeddedTextures(glTF::Asset& r)
  490. {
  491. embeddedTexIdxs.resize(r.images.Size(), -1);
  492. int numEmbeddedTexs = 0;
  493. for (size_t i = 0; i < r.images.Size(); ++i) {
  494. if (r.images[i].HasData())
  495. numEmbeddedTexs += 1;
  496. }
  497. if (numEmbeddedTexs == 0)
  498. return;
  499. mScene->mTextures = new aiTexture*[numEmbeddedTexs];
  500. // Add the embedded textures
  501. for (size_t i = 0; i < r.images.Size(); ++i) {
  502. Image img = r.images[i];
  503. if (!img.HasData()) continue;
  504. int idx = mScene->mNumTextures++;
  505. embeddedTexIdxs[i] = idx;
  506. aiTexture* tex = mScene->mTextures[idx] = new aiTexture();
  507. size_t length = img.GetDataLength();
  508. void* data = img.StealData();
  509. tex->mWidth = static_cast<unsigned int>(length);
  510. tex->mHeight = 0;
  511. tex->pcData = reinterpret_cast<aiTexel*>(data);
  512. if (!img.mimeType.empty()) {
  513. const char* ext = strchr(img.mimeType.c_str(), '/') + 1;
  514. if (ext) {
  515. if (strcmp(ext, "jpeg") == 0) ext = "jpg";
  516. size_t len = strlen(ext);
  517. if (len <= 3) {
  518. strcpy(tex->achFormatHint, ext);
  519. }
  520. }
  521. }
  522. }
  523. }
  524. void glTFImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) {
  525. this->mScene = pScene;
  526. // read the asset file
  527. glTF::Asset asset(pIOHandler);
  528. asset.Load(pFile, GetExtension(pFile) == "glb");
  529. //
  530. // Copy the data out
  531. //
  532. ImportEmbeddedTextures(asset);
  533. ImportMaterials(asset);
  534. ImportMeshes(asset);
  535. ImportCameras(asset);
  536. ImportLights(asset);
  537. ImportNodes(asset);
  538. // TODO: it does not split the loaded vertices, should it?
  539. //pScene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
  540. MakeVerboseFormatProcess process;
  541. process.Execute(pScene);
  542. if (pScene->mNumMeshes == 0) {
  543. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  544. }
  545. }
  546. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER