2
0

glTFImporter.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2019, 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 "glTF/glTFImporter.h"
  35. #include "glTF/glTFAsset.h"
  36. #include "glTF/glTFAssetWriter.h"
  37. #include "PostProcessing/MakeVerboseFormat.h"
  38. #include <assimp/StringComparison.h>
  39. #include <assimp/StringUtils.h>
  40. #include <assimp/Importer.hpp>
  41. #include <assimp/scene.h>
  42. #include <assimp/ai_assert.h>
  43. #include <assimp/DefaultLogger.hpp>
  44. #include <assimp/importerdesc.h>
  45. #include <memory>
  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( nullptr ) {
  69. // empty
  70. }
  71. glTFImporter::~glTFImporter() {
  72. // empty
  73. }
  74. const aiImporterDesc* glTFImporter::GetInfo() const {
  75. return &desc;
  76. }
  77. bool glTFImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool /* checkSig */) const {
  78. const std::string &extension = GetExtension(pFile);
  79. if (extension != "gltf" && extension != "glb") {
  80. return false;
  81. }
  82. if (pIOHandler) {
  83. glTF::Asset asset(pIOHandler);
  84. try {
  85. asset.Load(pFile, extension == "glb");
  86. std::string version = asset.asset.version;
  87. return !version.empty() && version[0] == '1';
  88. } catch (...) {
  89. return false;
  90. }
  91. }
  92. return false;
  93. }
  94. inline
  95. void SetMaterialColorProperty(std::vector<int>& embeddedTexIdxs, Asset& /*r*/, glTF::TexProperty prop, aiMaterial* mat,
  96. aiTextureType texType, const char* pKey, unsigned int type, unsigned int idx) {
  97. if (prop.texture) {
  98. if (prop.texture->source) {
  99. aiString uri(prop.texture->source->uri);
  100. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  101. if (texIdx != -1) { // embedded
  102. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  103. uri.data[0] = '*';
  104. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
  105. }
  106. mat->AddProperty(&uri, _AI_MATKEY_TEXTURE_BASE, texType, 0);
  107. }
  108. } else {
  109. aiColor4D col;
  110. CopyValue(prop.color, col);
  111. mat->AddProperty(&col, 1, pKey, type, idx);
  112. }
  113. }
  114. void glTFImporter::ImportMaterials(glTF::Asset& r) {
  115. mScene->mNumMaterials = unsigned(r.materials.Size());
  116. mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials];
  117. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  118. aiMaterial* aimat = mScene->mMaterials[i] = new aiMaterial();
  119. Material& mat = r.materials[i];
  120. /*if (!mat.name.empty())*/ {
  121. aiString str(mat.id /*mat.name*/);
  122. aimat->AddProperty(&str, AI_MATKEY_NAME);
  123. }
  124. SetMaterialColorProperty(embeddedTexIdxs, r, mat.ambient, aimat, aiTextureType_AMBIENT, AI_MATKEY_COLOR_AMBIENT );
  125. SetMaterialColorProperty(embeddedTexIdxs, r, mat.diffuse, aimat, aiTextureType_DIFFUSE, AI_MATKEY_COLOR_DIFFUSE );
  126. SetMaterialColorProperty(embeddedTexIdxs, r, mat.specular, aimat, aiTextureType_SPECULAR, AI_MATKEY_COLOR_SPECULAR);
  127. SetMaterialColorProperty(embeddedTexIdxs, r, mat.emission, aimat, aiTextureType_EMISSIVE, AI_MATKEY_COLOR_EMISSIVE);
  128. aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED);
  129. if (mat.transparent && (mat.transparency != 1.0f)) {
  130. aimat->AddProperty(&mat.transparency, 1, AI_MATKEY_OPACITY);
  131. }
  132. if (mat.shininess > 0.f) {
  133. aimat->AddProperty(&mat.shininess, 1, AI_MATKEY_SHININESS);
  134. }
  135. }
  136. if (mScene->mNumMaterials == 0) {
  137. mScene->mNumMaterials = 1;
  138. mScene->mMaterials = new aiMaterial*[1];
  139. mScene->mMaterials[0] = new aiMaterial();
  140. }
  141. }
  142. static inline void SetFace(aiFace& face, int a)
  143. {
  144. face.mNumIndices = 1;
  145. face.mIndices = new unsigned int[1];
  146. face.mIndices[0] = a;
  147. }
  148. static inline void SetFace(aiFace& face, int a, int b)
  149. {
  150. face.mNumIndices = 2;
  151. face.mIndices = new unsigned int[2];
  152. face.mIndices[0] = a;
  153. face.mIndices[1] = b;
  154. }
  155. static inline void SetFace(aiFace& face, int a, int b, int c)
  156. {
  157. face.mNumIndices = 3;
  158. face.mIndices = new unsigned int[3];
  159. face.mIndices[0] = a;
  160. face.mIndices[1] = b;
  161. face.mIndices[2] = c;
  162. }
  163. #ifdef ASSIMP_BUILD_DEBUG
  164. static inline bool CheckValidFacesIndices(aiFace* faces, unsigned nFaces, unsigned nVerts)
  165. {
  166. for (unsigned i = 0; i < nFaces; ++i) {
  167. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  168. unsigned idx = faces[i].mIndices[j];
  169. if (idx >= nVerts)
  170. return false;
  171. }
  172. }
  173. return true;
  174. }
  175. #endif // ASSIMP_BUILD_DEBUG
  176. void glTFImporter::ImportMeshes(glTF::Asset& r)
  177. {
  178. std::vector<aiMesh*> meshes;
  179. unsigned int k = 0;
  180. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  181. Mesh& mesh = r.meshes[m];
  182. // Check if mesh extensions is used
  183. if(mesh.Extension.size() > 0)
  184. {
  185. for(Mesh::SExtension* cur_ext : mesh.Extension)
  186. {
  187. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  188. if(cur_ext->Type == Mesh::SExtension::EType::Compression_Open3DGC)
  189. {
  190. // Limitations for meshes when using Open3DGC-compression.
  191. // It's a current limitation of sp... Specification have not this part still - about mesh compression. Why only one primitive?
  192. // Because glTF is very flexibly. But in fact it ugly flexible. Every primitive can has own set of accessors and accessors can
  193. // point to a-a-a-a-any part of buffer (through bufferview of course) and even to another buffer. We know that "Open3DGC-compression"
  194. // is applicable only to part of buffer. As we can't guaranty continuity of the data for decoder, we will limit quantity of primitives.
  195. // Yes indices, coordinates etc. still can br stored in different buffers, but with current specification it's a exporter problem.
  196. // Also primitive can has only one of "POSITION", "NORMAL" and less then "AI_MAX_NUMBER_OF_TEXTURECOORDS" of "TEXCOORD". All accessor
  197. // of primitive must point to one continuous region of the buffer.
  198. if(mesh.primitives.size() > 2) throw DeadlyImportError("GLTF: When using Open3DGC compression then only one primitive per mesh are allowed.");
  199. Mesh::SCompression_Open3DGC* o3dgc_ext = (Mesh::SCompression_Open3DGC*)cur_ext;
  200. Ref<Buffer> buf = r.buffers.Get(o3dgc_ext->Buffer);
  201. buf->EncodedRegion_SetCurrent(mesh.id);
  202. }
  203. else
  204. #endif
  205. {
  206. throw DeadlyImportError("GLTF: Can not import mesh: unknown mesh extension (code: \"" + to_string(cur_ext->Type) +
  207. "\"), only Open3DGC is supported.");
  208. }
  209. }
  210. }// if(mesh.Extension.size() > 0)
  211. meshOffsets.push_back(k);
  212. k += unsigned(mesh.primitives.size());
  213. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  214. Mesh::Primitive& prim = mesh.primitives[p];
  215. aiMesh* aim = new aiMesh();
  216. meshes.push_back(aim);
  217. aim->mName = mesh.id;
  218. if (mesh.primitives.size() > 1) {
  219. ai_uint32& len = aim->mName.length;
  220. aim->mName.data[len] = '-';
  221. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
  222. }
  223. switch (prim.mode) {
  224. case PrimitiveMode_POINTS:
  225. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  226. break;
  227. case PrimitiveMode_LINES:
  228. case PrimitiveMode_LINE_LOOP:
  229. case PrimitiveMode_LINE_STRIP:
  230. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  231. break;
  232. case PrimitiveMode_TRIANGLES:
  233. case PrimitiveMode_TRIANGLE_STRIP:
  234. case PrimitiveMode_TRIANGLE_FAN:
  235. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  236. break;
  237. }
  238. Mesh::Primitive::Attributes& attr = prim.attributes;
  239. if (attr.position.size() > 0 && attr.position[0]) {
  240. aim->mNumVertices = attr.position[0]->count;
  241. attr.position[0]->ExtractData(aim->mVertices);
  242. }
  243. if (attr.normal.size() > 0 && attr.normal[0]) attr.normal[0]->ExtractData(aim->mNormals);
  244. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  245. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
  246. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  247. aiVector3D* values = aim->mTextureCoords[tc];
  248. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  249. values[i].y = 1 - values[i].y; // Flip Y coords
  250. }
  251. }
  252. aiFace* faces = 0;
  253. unsigned int nFaces = 0;
  254. if (prim.indices) {
  255. unsigned int count = prim.indices->count;
  256. Accessor::Indexer data = prim.indices->GetIndexer();
  257. ai_assert(data.IsValid());
  258. switch (prim.mode) {
  259. case PrimitiveMode_POINTS: {
  260. nFaces = count;
  261. faces = new aiFace[nFaces];
  262. for (unsigned int i = 0; i < count; ++i) {
  263. SetFace(faces[i], data.GetUInt(i));
  264. }
  265. break;
  266. }
  267. case PrimitiveMode_LINES: {
  268. nFaces = count / 2;
  269. faces = new aiFace[nFaces];
  270. for (unsigned int i = 0; i < count; i += 2) {
  271. SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
  272. }
  273. break;
  274. }
  275. case PrimitiveMode_LINE_LOOP:
  276. case PrimitiveMode_LINE_STRIP: {
  277. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  278. faces = new aiFace[nFaces];
  279. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
  280. for (unsigned int i = 2; i < count; ++i) {
  281. SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
  282. }
  283. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  284. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  285. }
  286. break;
  287. }
  288. case PrimitiveMode_TRIANGLES: {
  289. nFaces = count / 3;
  290. faces = new aiFace[nFaces];
  291. for (unsigned int i = 0; i < count; i += 3) {
  292. SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  293. }
  294. break;
  295. }
  296. case PrimitiveMode_TRIANGLE_STRIP: {
  297. nFaces = count - 2;
  298. faces = new aiFace[nFaces];
  299. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  300. for (unsigned int i = 3; i < count; ++i) {
  301. SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], data.GetUInt(i));
  302. }
  303. break;
  304. }
  305. case PrimitiveMode_TRIANGLE_FAN:
  306. nFaces = count - 2;
  307. faces = new aiFace[nFaces];
  308. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  309. for (unsigned int i = 3; i < count; ++i) {
  310. SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i));
  311. }
  312. break;
  313. }
  314. }
  315. else { // no indices provided so directly generate from counts
  316. // use the already determined count as it includes checks
  317. unsigned int count = aim->mNumVertices;
  318. switch (prim.mode) {
  319. case PrimitiveMode_POINTS: {
  320. nFaces = count;
  321. faces = new aiFace[nFaces];
  322. for (unsigned int i = 0; i < count; ++i) {
  323. SetFace(faces[i], i);
  324. }
  325. break;
  326. }
  327. case PrimitiveMode_LINES: {
  328. nFaces = count / 2;
  329. faces = new aiFace[nFaces];
  330. for (unsigned int i = 0; i < count; i += 2) {
  331. SetFace(faces[i / 2], i, i + 1);
  332. }
  333. break;
  334. }
  335. case PrimitiveMode_LINE_LOOP:
  336. case PrimitiveMode_LINE_STRIP: {
  337. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  338. faces = new aiFace[nFaces];
  339. SetFace(faces[0], 0, 1);
  340. for (unsigned int i = 2; i < count; ++i) {
  341. SetFace(faces[i - 1], faces[i - 2].mIndices[1], i);
  342. }
  343. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  344. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  345. }
  346. break;
  347. }
  348. case PrimitiveMode_TRIANGLES: {
  349. nFaces = count / 3;
  350. faces = new aiFace[nFaces];
  351. for (unsigned int i = 0; i < count; i += 3) {
  352. SetFace(faces[i / 3], i, i + 1, i + 2);
  353. }
  354. break;
  355. }
  356. case PrimitiveMode_TRIANGLE_STRIP: {
  357. nFaces = count - 2;
  358. faces = new aiFace[nFaces];
  359. SetFace(faces[0], 0, 1, 2);
  360. for (unsigned int i = 3; i < count; ++i) {
  361. SetFace(faces[i - 2], faces[i - 1].mIndices[1], faces[i - 1].mIndices[2], i);
  362. }
  363. break;
  364. }
  365. case PrimitiveMode_TRIANGLE_FAN:
  366. nFaces = count - 2;
  367. faces = new aiFace[nFaces];
  368. SetFace(faces[0], 0, 1, 2);
  369. for (unsigned int i = 3; i < count; ++i) {
  370. SetFace(faces[i - 2], faces[0].mIndices[0], faces[i - 1].mIndices[2], i);
  371. }
  372. break;
  373. }
  374. }
  375. if (faces) {
  376. aim->mFaces = faces;
  377. aim->mNumFaces = nFaces;
  378. ai_assert(CheckValidFacesIndices(faces, nFaces, aim->mNumVertices));
  379. }
  380. if (prim.material) {
  381. aim->mMaterialIndex = prim.material.GetIndex();
  382. }
  383. }
  384. }
  385. meshOffsets.push_back(k);
  386. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  387. }
  388. void glTFImporter::ImportCameras(glTF::Asset& r) {
  389. if (!r.cameras.Size()) {
  390. return;
  391. }
  392. mScene->mNumCameras = r.cameras.Size();
  393. mScene->mCameras = new aiCamera*[r.cameras.Size()];
  394. for (size_t i = 0; i < r.cameras.Size(); ++i) {
  395. Camera& cam = r.cameras[i];
  396. aiCamera* aicam = mScene->mCameras[i] = new aiCamera();
  397. if (cam.type == Camera::Perspective) {
  398. aicam->mAspect = cam.perspective.aspectRatio;
  399. aicam->mHorizontalFOV = cam.perspective.yfov * ((aicam->mAspect == 0.f) ? 1.f : aicam->mAspect);
  400. aicam->mClipPlaneFar = cam.perspective.zfar;
  401. aicam->mClipPlaneNear = cam.perspective.znear;
  402. } else {
  403. aicam->mClipPlaneFar = cam.ortographic.zfar;
  404. aicam->mClipPlaneNear = cam.ortographic.znear;
  405. aicam->mHorizontalFOV = 0.0;
  406. aicam->mAspect = 1.0f;
  407. if (0.f != cam.ortographic.ymag) {
  408. aicam->mAspect = cam.ortographic.xmag / cam.ortographic.ymag;
  409. }
  410. }
  411. }
  412. }
  413. void glTFImporter::ImportLights(glTF::Asset& r)
  414. {
  415. if (!r.lights.Size()) return;
  416. mScene->mNumLights = r.lights.Size();
  417. mScene->mLights = new aiLight*[r.lights.Size()];
  418. for (size_t i = 0; i < r.lights.Size(); ++i) {
  419. Light& l = r.lights[i];
  420. aiLight* ail = mScene->mLights[i] = new aiLight();
  421. switch (l.type) {
  422. case Light::Type_directional:
  423. ail->mType = aiLightSource_DIRECTIONAL; break;
  424. case Light::Type_spot:
  425. ail->mType = aiLightSource_SPOT; break;
  426. case Light::Type_ambient:
  427. ail->mType = aiLightSource_AMBIENT; break;
  428. default: // Light::Type_point
  429. ail->mType = aiLightSource_POINT; break;
  430. }
  431. CopyValue(l.color, ail->mColorAmbient);
  432. CopyValue(l.color, ail->mColorDiffuse);
  433. CopyValue(l.color, ail->mColorSpecular);
  434. ail->mAngleOuterCone = l.falloffAngle;
  435. ail->mAngleInnerCone = l.falloffExponent; // TODO fix this, it does not look right at all
  436. ail->mAttenuationConstant = l.constantAttenuation;
  437. ail->mAttenuationLinear = l.linearAttenuation;
  438. ail->mAttenuationQuadratic = l.quadraticAttenuation;
  439. }
  440. }
  441. aiNode* ImportNode(aiScene* pScene, glTF::Asset& r, std::vector<unsigned int>& meshOffsets, glTF::Ref<glTF::Node>& ptr)
  442. {
  443. Node& node = *ptr;
  444. aiNode* ainode = new aiNode(node.id);
  445. if (!node.children.empty()) {
  446. ainode->mNumChildren = unsigned(node.children.size());
  447. ainode->mChildren = new aiNode*[ainode->mNumChildren];
  448. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  449. aiNode* child = ImportNode(pScene, r, meshOffsets, node.children[i]);
  450. child->mParent = ainode;
  451. ainode->mChildren[i] = child;
  452. }
  453. }
  454. aiMatrix4x4& matrix = ainode->mTransformation;
  455. if (node.matrix.isPresent) {
  456. CopyValue(node.matrix.value, matrix);
  457. }
  458. else {
  459. if (node.translation.isPresent) {
  460. aiVector3D trans;
  461. CopyValue(node.translation.value, trans);
  462. aiMatrix4x4 t;
  463. aiMatrix4x4::Translation(trans, t);
  464. matrix = t * matrix;
  465. }
  466. if (node.scale.isPresent) {
  467. aiVector3D scal(1.f);
  468. CopyValue(node.scale.value, scal);
  469. aiMatrix4x4 s;
  470. aiMatrix4x4::Scaling(scal, s);
  471. matrix = s * matrix;
  472. }
  473. if (node.rotation.isPresent) {
  474. aiQuaternion rot;
  475. CopyValue(node.rotation.value, rot);
  476. matrix = aiMatrix4x4(rot.GetMatrix()) * matrix;
  477. }
  478. }
  479. if (!node.meshes.empty()) {
  480. int count = 0;
  481. for (size_t i = 0; i < node.meshes.size(); ++i) {
  482. int idx = node.meshes[i].GetIndex();
  483. count += meshOffsets[idx + 1] - meshOffsets[idx];
  484. }
  485. ainode->mNumMeshes = count;
  486. ainode->mMeshes = new unsigned int[count];
  487. int k = 0;
  488. for (size_t i = 0; i < node.meshes.size(); ++i) {
  489. int idx = node.meshes[i].GetIndex();
  490. for (unsigned int j = meshOffsets[idx]; j < meshOffsets[idx + 1]; ++j, ++k) {
  491. ainode->mMeshes[k] = j;
  492. }
  493. }
  494. }
  495. if (node.camera) {
  496. pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  497. }
  498. if (node.light) {
  499. pScene->mLights[node.light.GetIndex()]->mName = ainode->mName;
  500. }
  501. return ainode;
  502. }
  503. void glTFImporter::ImportNodes(glTF::Asset& r)
  504. {
  505. if (!r.scene) return;
  506. std::vector< Ref<Node> > rootNodes = r.scene->nodes;
  507. // The root nodes
  508. unsigned int numRootNodes = unsigned(rootNodes.size());
  509. if (numRootNodes == 1) { // a single root node: use it
  510. mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
  511. }
  512. else if (numRootNodes > 1) { // more than one root node: create a fake root
  513. aiNode* root = new aiNode("ROOT");
  514. root->mChildren = new aiNode*[numRootNodes];
  515. for (unsigned int i = 0; i < numRootNodes; ++i) {
  516. aiNode* node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
  517. node->mParent = root;
  518. root->mChildren[root->mNumChildren++] = node;
  519. }
  520. mScene->mRootNode = root;
  521. }
  522. //if (!mScene->mRootNode) {
  523. // mScene->mRootNode = new aiNode("EMPTY");
  524. //}
  525. }
  526. void glTFImporter::ImportEmbeddedTextures(glTF::Asset& r)
  527. {
  528. embeddedTexIdxs.resize(r.images.Size(), -1);
  529. int numEmbeddedTexs = 0;
  530. for (size_t i = 0; i < r.images.Size(); ++i) {
  531. if (r.images[i].HasData())
  532. numEmbeddedTexs += 1;
  533. }
  534. if (numEmbeddedTexs == 0)
  535. return;
  536. mScene->mTextures = new aiTexture*[numEmbeddedTexs];
  537. // Add the embedded textures
  538. for (size_t i = 0; i < r.images.Size(); ++i) {
  539. Image &img = r.images[i];
  540. if (!img.HasData()) continue;
  541. int idx = mScene->mNumTextures++;
  542. embeddedTexIdxs[i] = idx;
  543. aiTexture* tex = mScene->mTextures[idx] = new aiTexture();
  544. size_t length = img.GetDataLength();
  545. void* data = img.StealData();
  546. tex->mWidth = static_cast<unsigned int>(length);
  547. tex->mHeight = 0;
  548. tex->pcData = reinterpret_cast<aiTexel*>(data);
  549. if (!img.mimeType.empty()) {
  550. const char* ext = strchr(img.mimeType.c_str(), '/') + 1;
  551. if (ext) {
  552. if (strcmp(ext, "jpeg") == 0) ext = "jpg";
  553. size_t len = strlen(ext);
  554. if (len <= 3) {
  555. strcpy(tex->achFormatHint, ext);
  556. }
  557. }
  558. }
  559. }
  560. }
  561. void glTFImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  562. {
  563. // clean all member arrays
  564. meshOffsets.clear();
  565. embeddedTexIdxs.clear();
  566. this->mScene = pScene;
  567. // read the asset file
  568. glTF::Asset asset(pIOHandler);
  569. asset.Load(pFile, GetExtension(pFile) == "glb");
  570. //
  571. // Copy the data out
  572. //
  573. ImportEmbeddedTextures(asset);
  574. ImportMaterials(asset);
  575. ImportMeshes(asset);
  576. ImportCameras(asset);
  577. ImportLights(asset);
  578. ImportNodes(asset);
  579. if (pScene->mNumMeshes == 0) {
  580. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  581. }
  582. }
  583. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER