glTFImporter.cpp 26 KB

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