glTF2Importer.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2017, 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 "glTF2Importer.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 <assimp/importerdesc.h>
  42. #include <memory>
  43. #include "MakeVerboseFormat.h"
  44. #include "glTF2Asset.h"
  45. // This is included here so WriteLazyDict<T>'s definition is found.
  46. #include "glTF2AssetWriter.h"
  47. #include <rapidjson/document.h>
  48. #include <rapidjson/rapidjson.h>
  49. using namespace Assimp;
  50. using namespace glTF2;
  51. //
  52. // glTF2Importer
  53. //
  54. static const aiImporterDesc desc = {
  55. "glTF2 Importer",
  56. "",
  57. "",
  58. "",
  59. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  60. 0,
  61. 0,
  62. 0,
  63. 0,
  64. "gltf glb"
  65. };
  66. glTF2Importer::glTF2Importer()
  67. : BaseImporter()
  68. , meshOffsets()
  69. , embeddedTexIdxs()
  70. , mScene( NULL ) {
  71. // empty
  72. }
  73. glTF2Importer::~glTF2Importer() {
  74. // empty
  75. }
  76. const aiImporterDesc* glTF2Importer::GetInfo() const
  77. {
  78. return &desc;
  79. }
  80. bool glTF2Importer::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  81. {
  82. const std::string &extension = GetExtension(pFile);
  83. if (extension != "gltf" && extension != "glb")
  84. return false;
  85. if (checkSig && pIOHandler) {
  86. glTF2::Asset asset(pIOHandler);
  87. try {
  88. asset.Load(pFile, extension == "glb");
  89. std::string version = asset.asset.version;
  90. return !version.empty() && version[0] == '2';
  91. } catch (...) {
  92. return false;
  93. }
  94. }
  95. return false;
  96. }
  97. //static void CopyValue(const glTF2::vec3& v, aiColor3D& out)
  98. //{
  99. // out.r = v[0]; out.g = v[1]; out.b = v[2];
  100. //}
  101. static void CopyValue(const glTF2::vec4& v, aiColor4D& out)
  102. {
  103. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = v[3];
  104. }
  105. /*static void CopyValue(const glTF2::vec4& v, aiColor3D& out)
  106. {
  107. out.r = v[0]; out.g = v[1]; out.b = v[2];
  108. }*/
  109. static void CopyValue(const glTF2::vec3& v, aiColor4D& out)
  110. {
  111. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = 1.0;
  112. }
  113. static void CopyValue(const glTF2::vec3& v, aiVector3D& out)
  114. {
  115. out.x = v[0]; out.y = v[1]; out.z = v[2];
  116. }
  117. static void CopyValue(const glTF2::vec4& v, aiQuaternion& out)
  118. {
  119. out.x = v[0]; out.y = v[1]; out.z = v[2]; out.w = v[3];
  120. }
  121. static void CopyValue(const glTF2::mat4& v, aiMatrix4x4& o)
  122. {
  123. o.a1 = v[ 0]; o.b1 = v[ 1]; o.c1 = v[ 2]; o.d1 = v[ 3];
  124. o.a2 = v[ 4]; o.b2 = v[ 5]; o.c2 = v[ 6]; o.d2 = v[ 7];
  125. o.a3 = v[ 8]; o.b3 = v[ 9]; o.c3 = v[10]; o.d3 = v[11];
  126. o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15];
  127. }
  128. inline void SetMaterialColorProperty(Asset& /*r*/, vec4& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx)
  129. {
  130. aiColor4D col;
  131. CopyValue(prop, col);
  132. mat->AddProperty(&col, 1, pKey, type, idx);
  133. }
  134. inline void SetMaterialColorProperty(Asset& /*r*/, vec3& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx)
  135. {
  136. aiColor4D col;
  137. CopyValue(prop, col);
  138. mat->AddProperty(&col, 1, pKey, type, idx);
  139. }
  140. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& /*r*/, glTF2::TextureInfo prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  141. {
  142. if (prop.texture && prop.texture->source) {
  143. aiString uri(prop.texture->source->uri);
  144. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  145. if (texIdx != -1) { // embedded
  146. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  147. uri.data[0] = '*';
  148. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
  149. }
  150. mat->AddProperty(&uri, AI_MATKEY_TEXTURE(texType, texSlot));
  151. mat->AddProperty(&prop.texCoord, 1, _AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, texType, texSlot);
  152. if (prop.texture->sampler) {
  153. Ref<Sampler> sampler = prop.texture->sampler;
  154. aiString name(sampler->name);
  155. aiString id(sampler->id);
  156. mat->AddProperty(&name, AI_MATKEY_GLTF_MAPPINGNAME(texType, texSlot));
  157. mat->AddProperty(&id, AI_MATKEY_GLTF_MAPPINGID(texType, texSlot));
  158. mat->AddProperty(&sampler->wrapS, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot));
  159. mat->AddProperty(&sampler->wrapT, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot));
  160. if (sampler->magFilter != SamplerMagFilter::UNSET) {
  161. mat->AddProperty(&sampler->magFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(texType, texSlot));
  162. }
  163. if (sampler->minFilter != SamplerMinFilter::UNSET) {
  164. mat->AddProperty(&sampler->minFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(texType, texSlot));
  165. }
  166. }
  167. }
  168. }
  169. void glTF2Importer::ImportMaterials(glTF2::Asset& r)
  170. {
  171. mScene->mNumMaterials = unsigned(r.materials.Size());
  172. mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials];
  173. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  174. aiMaterial* aimat = mScene->mMaterials[i] = new aiMaterial();
  175. Material& mat = r.materials[i];
  176. if (!mat.name.empty()) {
  177. aiString str(mat.name);
  178. aimat->AddProperty(&str, AI_MATKEY_NAME);
  179. }
  180. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  181. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR);
  182. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_DIFFUSE);
  183. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE);
  184. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE);
  185. aimat->AddProperty(&mat.pbrMetallicRoughness.metallicFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR);
  186. aimat->AddProperty(&mat.pbrMetallicRoughness.roughnessFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR);
  187. float roughnessAsShininess = (1 - mat.pbrMetallicRoughness.roughnessFactor) * 1000;
  188. aimat->AddProperty(&roughnessAsShininess, 1, AI_MATKEY_SHININESS);
  189. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.normalTexture, aimat, aiTextureType_NORMALS);
  190. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.occlusionTexture, aimat, aiTextureType_LIGHTMAP);
  191. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.emissiveTexture, aimat, aiTextureType_EMISSIVE);
  192. SetMaterialColorProperty(r, mat.emissiveFactor, aimat, AI_MATKEY_COLOR_EMISSIVE);
  193. aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED);
  194. aiString alphaMode(mat.alphaMode);
  195. aimat->AddProperty(&alphaMode, AI_MATKEY_GLTF_ALPHAMODE);
  196. aimat->AddProperty(&mat.alphaCutoff, 1, AI_MATKEY_GLTF_ALPHACUTOFF);
  197. //pbrSpecularGlossiness
  198. if (mat.pbrSpecularGlossiness.isPresent) {
  199. PbrSpecularGlossiness &pbrSG = mat.pbrSpecularGlossiness.value;
  200. aimat->AddProperty(&mat.pbrSpecularGlossiness.isPresent, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS);
  201. SetMaterialColorProperty(r, pbrSG.diffuseFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  202. SetMaterialColorProperty(r, pbrSG.specularFactor, aimat, AI_MATKEY_COLOR_SPECULAR);
  203. float glossinessAsShininess = pbrSG.glossinessFactor * 1000.0f;
  204. aimat->AddProperty(&glossinessAsShininess, 1, AI_MATKEY_SHININESS);
  205. aimat->AddProperty(&pbrSG.glossinessFactor, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS_GLOSSINESS_FACTOR);
  206. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.diffuseTexture, aimat, aiTextureType_DIFFUSE);
  207. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.specularGlossinessTexture, aimat, aiTextureType_SPECULAR);
  208. }
  209. }
  210. }
  211. static inline void SetFace(aiFace& face, int a)
  212. {
  213. face.mNumIndices = 1;
  214. face.mIndices = new unsigned int[1];
  215. face.mIndices[0] = a;
  216. }
  217. static inline void SetFace(aiFace& face, int a, int b)
  218. {
  219. face.mNumIndices = 2;
  220. face.mIndices = new unsigned int[2];
  221. face.mIndices[0] = a;
  222. face.mIndices[1] = b;
  223. }
  224. static inline void SetFace(aiFace& face, int a, int b, int c)
  225. {
  226. face.mNumIndices = 3;
  227. face.mIndices = new unsigned int[3];
  228. face.mIndices[0] = a;
  229. face.mIndices[1] = b;
  230. face.mIndices[2] = c;
  231. }
  232. #ifdef ASSIMP_BUILD_DEBUG
  233. static inline bool CheckValidFacesIndices(aiFace* faces, unsigned nFaces, unsigned nVerts)
  234. {
  235. for (unsigned i = 0; i < nFaces; ++i) {
  236. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  237. unsigned idx = faces[i].mIndices[j];
  238. if (idx >= nVerts)
  239. return false;
  240. }
  241. }
  242. return true;
  243. }
  244. #endif // ASSIMP_BUILD_DEBUG
  245. void glTF2Importer::ImportMeshes(glTF2::Asset& r)
  246. {
  247. std::vector<aiMesh*> meshes;
  248. unsigned int k = 0;
  249. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  250. Mesh& mesh = r.meshes[m];
  251. meshOffsets.push_back(k);
  252. k += unsigned(mesh.primitives.size());
  253. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  254. Mesh::Primitive& prim = mesh.primitives[p];
  255. aiMesh* aim = new aiMesh();
  256. meshes.push_back(aim);
  257. aim->mName = mesh.name.empty() ? mesh.id : mesh.name;
  258. if (mesh.primitives.size() > 1) {
  259. size_t& len = aim->mName.length;
  260. aim->mName.data[len] = '-';
  261. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
  262. }
  263. switch (prim.mode) {
  264. case PrimitiveMode_POINTS:
  265. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  266. break;
  267. case PrimitiveMode_LINES:
  268. case PrimitiveMode_LINE_LOOP:
  269. case PrimitiveMode_LINE_STRIP:
  270. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  271. break;
  272. case PrimitiveMode_TRIANGLES:
  273. case PrimitiveMode_TRIANGLE_STRIP:
  274. case PrimitiveMode_TRIANGLE_FAN:
  275. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  276. break;
  277. }
  278. Mesh::Primitive::Attributes& attr = prim.attributes;
  279. if (attr.position.size() > 0 && attr.position[0]) {
  280. aim->mNumVertices = attr.position[0]->count;
  281. attr.position[0]->ExtractData(aim->mVertices);
  282. }
  283. if (attr.normal.size() > 0 && attr.normal[0]) {
  284. attr.normal[0]->ExtractData(aim->mNormals);
  285. // only extract tangents if normals are present
  286. if (attr.tangent.size() > 0 && attr.tangent[0]) {
  287. // generate bitangents from normals and tangents according to spec
  288. struct Tangent
  289. {
  290. aiVector3D xyz;
  291. ai_real w;
  292. } *tangents = nullptr;
  293. attr.tangent[0]->ExtractData(tangents);
  294. aim->mTangents = new aiVector3D[aim->mNumVertices];
  295. aim->mBitangents = new aiVector3D[aim->mNumVertices];
  296. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  297. aim->mTangents[i] = tangents[i].xyz;
  298. aim->mBitangents[i] = (aim->mNormals[i] ^ tangents[i].xyz) * tangents[i].w;
  299. }
  300. delete tangents;
  301. }
  302. }
  303. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  304. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
  305. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  306. aiVector3D* values = aim->mTextureCoords[tc];
  307. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  308. values[i].y = 1 - values[i].y; // Flip Y coords
  309. }
  310. }
  311. if (prim.indices) {
  312. aiFace* faces = 0;
  313. unsigned int nFaces = 0;
  314. unsigned int count = prim.indices->count;
  315. Accessor::Indexer data = prim.indices->GetIndexer();
  316. ai_assert(data.IsValid());
  317. switch (prim.mode) {
  318. case PrimitiveMode_POINTS: {
  319. nFaces = count;
  320. faces = new aiFace[nFaces];
  321. for (unsigned int i = 0; i < count; ++i) {
  322. SetFace(faces[i], data.GetUInt(i));
  323. }
  324. break;
  325. }
  326. case PrimitiveMode_LINES: {
  327. nFaces = count / 2;
  328. faces = new aiFace[nFaces];
  329. for (unsigned int i = 0; i < count; i += 2) {
  330. SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
  331. }
  332. break;
  333. }
  334. case PrimitiveMode_LINE_LOOP:
  335. case PrimitiveMode_LINE_STRIP: {
  336. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  337. faces = new aiFace[nFaces];
  338. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
  339. for (unsigned int i = 2; i < count; ++i) {
  340. SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
  341. }
  342. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  343. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  344. }
  345. break;
  346. }
  347. case PrimitiveMode_TRIANGLES: {
  348. nFaces = count / 3;
  349. faces = new aiFace[nFaces];
  350. for (unsigned int i = 0; i < count; i += 3) {
  351. SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  352. }
  353. break;
  354. }
  355. case PrimitiveMode_TRIANGLE_STRIP: {
  356. nFaces = count - 2;
  357. faces = new aiFace[nFaces];
  358. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  359. for (unsigned int i = 3; i < count; ++i) {
  360. SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], data.GetUInt(i));
  361. }
  362. break;
  363. }
  364. case PrimitiveMode_TRIANGLE_FAN:
  365. nFaces = count - 2;
  366. faces = new aiFace[nFaces];
  367. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  368. for (unsigned int i = 3; i < count; ++i) {
  369. SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i));
  370. }
  371. break;
  372. }
  373. if (faces) {
  374. aim->mFaces = faces;
  375. aim->mNumFaces = nFaces;
  376. ai_assert(CheckValidFacesIndices(faces, nFaces, aim->mNumVertices));
  377. }
  378. }
  379. if (prim.material) {
  380. aim->mMaterialIndex = prim.material.GetIndex();
  381. }
  382. }
  383. }
  384. meshOffsets.push_back(k);
  385. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  386. }
  387. void glTF2Importer::ImportCameras(glTF2::Asset& r)
  388. {
  389. if (!r.cameras.Size()) return;
  390. mScene->mNumCameras = r.cameras.Size();
  391. mScene->mCameras = new aiCamera*[r.cameras.Size()];
  392. for (size_t i = 0; i < r.cameras.Size(); ++i) {
  393. Camera& cam = r.cameras[i];
  394. aiCamera* aicam = mScene->mCameras[i] = new aiCamera();
  395. if (cam.type == Camera::Perspective) {
  396. aicam->mAspect = cam.cameraProperties.perspective.aspectRatio;
  397. aicam->mHorizontalFOV = cam.cameraProperties.perspective.yfov * aicam->mAspect;
  398. aicam->mClipPlaneFar = cam.cameraProperties.perspective.zfar;
  399. aicam->mClipPlaneNear = cam.cameraProperties.perspective.znear;
  400. }
  401. else {
  402. // assimp does not support orthographic cameras
  403. }
  404. }
  405. }
  406. aiNode* ImportNode(aiScene* pScene, glTF2::Asset& r, std::vector<unsigned int>& meshOffsets, glTF2::Ref<glTF2::Node>& ptr)
  407. {
  408. Node& node = *ptr;
  409. std::string nameOrId = node.name.empty() ? node.id : node.name;
  410. aiNode* ainode = new aiNode(nameOrId);
  411. if (!node.children.empty()) {
  412. ainode->mNumChildren = unsigned(node.children.size());
  413. ainode->mChildren = new aiNode*[ainode->mNumChildren];
  414. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  415. aiNode* child = ImportNode(pScene, r, meshOffsets, node.children[i]);
  416. child->mParent = ainode;
  417. ainode->mChildren[i] = child;
  418. }
  419. }
  420. aiMatrix4x4& matrix = ainode->mTransformation;
  421. if (node.matrix.isPresent) {
  422. CopyValue(node.matrix.value, matrix);
  423. }
  424. else {
  425. if (node.translation.isPresent) {
  426. aiVector3D trans;
  427. CopyValue(node.translation.value, trans);
  428. aiMatrix4x4 t;
  429. aiMatrix4x4::Translation(trans, t);
  430. matrix = matrix * t;
  431. }
  432. if (node.rotation.isPresent) {
  433. aiQuaternion rot;
  434. CopyValue(node.rotation.value, rot);
  435. matrix = matrix * aiMatrix4x4(rot.GetMatrix());
  436. }
  437. if (node.scale.isPresent) {
  438. aiVector3D scal(1.f);
  439. CopyValue(node.scale.value, scal);
  440. aiMatrix4x4 s;
  441. aiMatrix4x4::Scaling(scal, s);
  442. matrix = matrix * s;
  443. }
  444. }
  445. if (!node.meshes.empty()) {
  446. int count = 0;
  447. for (size_t i = 0; i < node.meshes.size(); ++i) {
  448. int idx = node.meshes[i].GetIndex();
  449. count += meshOffsets[idx + 1] - meshOffsets[idx];
  450. }
  451. ainode->mNumMeshes = count;
  452. ainode->mMeshes = new unsigned int[count];
  453. int k = 0;
  454. for (size_t i = 0; i < node.meshes.size(); ++i) {
  455. int idx = node.meshes[i].GetIndex();
  456. for (unsigned int j = meshOffsets[idx]; j < meshOffsets[idx + 1]; ++j, ++k) {
  457. ainode->mMeshes[k] = j;
  458. }
  459. }
  460. }
  461. if (node.camera) {
  462. pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  463. }
  464. return ainode;
  465. }
  466. void glTF2Importer::ImportNodes(glTF2::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 glTF2Importer::ImportEmbeddedTextures(glTF2::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 glTF2Importer::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler) {
  525. this->mScene = pScene;
  526. // read the asset file
  527. glTF2::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. ImportNodes(asset);
  537. // TODO: it does not split the loaded vertices, should it?
  538. //pScene->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
  539. MakeVerboseFormatProcess process;
  540. process.Execute(pScene);
  541. if (pScene->mNumMeshes == 0) {
  542. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  543. }
  544. }
  545. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER