glTF2Importer.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  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 "glTF2/glTF2Importer.h"
  35. #include "glTF2/glTF2Asset.h"
  36. #include "glTF2/glTF2AssetWriter.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 <assimp/CreateAnimMesh.h>
  46. #include <memory>
  47. #include <unordered_map>
  48. #include <rapidjson/document.h>
  49. #include <rapidjson/rapidjson.h>
  50. using namespace Assimp;
  51. using namespace glTF2;
  52. namespace {
  53. // generate bi-tangents from normals and tangents according to spec
  54. struct Tangent {
  55. aiVector3D xyz;
  56. ai_real w;
  57. };
  58. } // namespace
  59. //
  60. // glTF2Importer
  61. //
  62. static const aiImporterDesc desc = {
  63. "glTF2 Importer",
  64. "",
  65. "",
  66. "",
  67. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  68. 0,
  69. 0,
  70. 0,
  71. 0,
  72. "gltf glb"
  73. };
  74. glTF2Importer::glTF2Importer()
  75. : BaseImporter()
  76. , meshOffsets()
  77. , embeddedTexIdxs()
  78. , mScene( NULL ) {
  79. // empty
  80. }
  81. glTF2Importer::~glTF2Importer() {
  82. // empty
  83. }
  84. const aiImporterDesc* glTF2Importer::GetInfo() const
  85. {
  86. return &desc;
  87. }
  88. bool glTF2Importer::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool /* checkSig */) const
  89. {
  90. const std::string &extension = GetExtension(pFile);
  91. if (extension != "gltf" && extension != "glb")
  92. return false;
  93. if (pIOHandler) {
  94. glTF2::Asset asset(pIOHandler);
  95. asset.Load(pFile, extension == "glb");
  96. std::string version = asset.asset.version;
  97. return !version.empty() && version[0] == '2';
  98. }
  99. return false;
  100. }
  101. static aiTextureMapMode ConvertWrappingMode(SamplerWrap gltfWrapMode)
  102. {
  103. switch (gltfWrapMode) {
  104. case SamplerWrap::Mirrored_Repeat:
  105. return aiTextureMapMode_Mirror;
  106. case SamplerWrap::Clamp_To_Edge:
  107. return aiTextureMapMode_Clamp;
  108. case SamplerWrap::UNSET:
  109. case SamplerWrap::Repeat:
  110. default:
  111. return aiTextureMapMode_Wrap;
  112. }
  113. }
  114. static void CopyValue(const glTF2::vec3& v, aiColor3D& out)
  115. {
  116. out.r = v[0]; out.g = v[1]; out.b = v[2];
  117. }
  118. static void CopyValue(const glTF2::vec4& v, aiColor4D& out)
  119. {
  120. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = v[3];
  121. }
  122. /*static void CopyValue(const glTF2::vec4& v, aiColor3D& out)
  123. {
  124. out.r = v[0]; out.g = v[1]; out.b = v[2];
  125. }*/
  126. static void CopyValue(const glTF2::vec3& v, aiColor4D& out)
  127. {
  128. out.r = v[0]; out.g = v[1]; out.b = v[2]; out.a = 1.0;
  129. }
  130. static void CopyValue(const glTF2::vec3& v, aiVector3D& out)
  131. {
  132. out.x = v[0]; out.y = v[1]; out.z = v[2];
  133. }
  134. static void CopyValue(const glTF2::vec4& v, aiQuaternion& out)
  135. {
  136. out.x = v[0]; out.y = v[1]; out.z = v[2]; out.w = v[3];
  137. }
  138. static void CopyValue(const glTF2::mat4& v, aiMatrix4x4& o)
  139. {
  140. o.a1 = v[ 0]; o.b1 = v[ 1]; o.c1 = v[ 2]; o.d1 = v[ 3];
  141. o.a2 = v[ 4]; o.b2 = v[ 5]; o.c2 = v[ 6]; o.d2 = v[ 7];
  142. o.a3 = v[ 8]; o.b3 = v[ 9]; o.c3 = v[10]; o.d3 = v[11];
  143. o.a4 = v[12]; o.b4 = v[13]; o.c4 = v[14]; o.d4 = v[15];
  144. }
  145. inline void SetMaterialColorProperty(Asset& /*r*/, vec4& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx)
  146. {
  147. aiColor4D col;
  148. CopyValue(prop, col);
  149. mat->AddProperty(&col, 1, pKey, type, idx);
  150. }
  151. inline void SetMaterialColorProperty(Asset& /*r*/, vec3& prop, aiMaterial* mat, const char* pKey, unsigned int type, unsigned int idx)
  152. {
  153. aiColor4D col;
  154. CopyValue(prop, col);
  155. mat->AddProperty(&col, 1, pKey, type, idx);
  156. }
  157. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& /*r*/, glTF2::TextureInfo prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  158. {
  159. if (prop.texture && prop.texture->source) {
  160. aiString uri(prop.texture->source->uri);
  161. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  162. if (texIdx != -1) { // embedded
  163. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  164. uri.data[0] = '*';
  165. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, MAXLEN - 1, texIdx);
  166. }
  167. mat->AddProperty(&uri, AI_MATKEY_TEXTURE(texType, texSlot));
  168. mat->AddProperty(&prop.texCoord, 1, _AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, texType, texSlot);
  169. if (prop.texture->sampler) {
  170. Ref<Sampler> sampler = prop.texture->sampler;
  171. aiString name(sampler->name);
  172. aiString id(sampler->id);
  173. mat->AddProperty(&name, AI_MATKEY_GLTF_MAPPINGNAME(texType, texSlot));
  174. mat->AddProperty(&id, AI_MATKEY_GLTF_MAPPINGID(texType, texSlot));
  175. aiTextureMapMode wrapS = ConvertWrappingMode(sampler->wrapS);
  176. aiTextureMapMode wrapT = ConvertWrappingMode(sampler->wrapT);
  177. mat->AddProperty(&wrapS, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot));
  178. mat->AddProperty(&wrapT, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot));
  179. if (sampler->magFilter != SamplerMagFilter::UNSET) {
  180. mat->AddProperty(&sampler->magFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(texType, texSlot));
  181. }
  182. if (sampler->minFilter != SamplerMinFilter::UNSET) {
  183. mat->AddProperty(&sampler->minFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(texType, texSlot));
  184. }
  185. }
  186. }
  187. }
  188. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& r, glTF2::NormalTextureInfo& prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  189. {
  190. SetMaterialTextureProperty( embeddedTexIdxs, r, (glTF2::TextureInfo) prop, mat, texType, texSlot );
  191. if (prop.texture && prop.texture->source) {
  192. mat->AddProperty(&prop.scale, 1, AI_MATKEY_GLTF_TEXTURE_SCALE(texType, texSlot));
  193. }
  194. }
  195. inline void SetMaterialTextureProperty(std::vector<int>& embeddedTexIdxs, Asset& r, glTF2::OcclusionTextureInfo& prop, aiMaterial* mat, aiTextureType texType, unsigned int texSlot = 0)
  196. {
  197. SetMaterialTextureProperty( embeddedTexIdxs, r, (glTF2::TextureInfo) prop, mat, texType, texSlot );
  198. if (prop.texture && prop.texture->source) {
  199. mat->AddProperty(&prop.strength, 1, AI_MATKEY_GLTF_TEXTURE_STRENGTH(texType, texSlot));
  200. }
  201. }
  202. static aiMaterial* ImportMaterial(std::vector<int>& embeddedTexIdxs, Asset& r, Material& mat)
  203. {
  204. aiMaterial* aimat = new aiMaterial();
  205. if (!mat.name.empty()) {
  206. aiString str(mat.name);
  207. aimat->AddProperty(&str, AI_MATKEY_NAME);
  208. }
  209. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  210. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR);
  211. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_DIFFUSE);
  212. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE);
  213. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE);
  214. aimat->AddProperty(&mat.pbrMetallicRoughness.metallicFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR);
  215. aimat->AddProperty(&mat.pbrMetallicRoughness.roughnessFactor, 1, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR);
  216. float roughnessAsShininess = 1 - mat.pbrMetallicRoughness.roughnessFactor;
  217. roughnessAsShininess *= roughnessAsShininess * 1000;
  218. aimat->AddProperty(&roughnessAsShininess, 1, AI_MATKEY_SHININESS);
  219. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.normalTexture, aimat, aiTextureType_NORMALS);
  220. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.occlusionTexture, aimat, aiTextureType_LIGHTMAP);
  221. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.emissiveTexture, aimat, aiTextureType_EMISSIVE);
  222. SetMaterialColorProperty(r, mat.emissiveFactor, aimat, AI_MATKEY_COLOR_EMISSIVE);
  223. aimat->AddProperty(&mat.doubleSided, 1, AI_MATKEY_TWOSIDED);
  224. aiString alphaMode(mat.alphaMode);
  225. aimat->AddProperty(&alphaMode, AI_MATKEY_GLTF_ALPHAMODE);
  226. aimat->AddProperty(&mat.alphaCutoff, 1, AI_MATKEY_GLTF_ALPHACUTOFF);
  227. //pbrSpecularGlossiness
  228. if (mat.pbrSpecularGlossiness.isPresent) {
  229. PbrSpecularGlossiness &pbrSG = mat.pbrSpecularGlossiness.value;
  230. aimat->AddProperty(&mat.pbrSpecularGlossiness.isPresent, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS);
  231. SetMaterialColorProperty(r, pbrSG.diffuseFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  232. SetMaterialColorProperty(r, pbrSG.specularFactor, aimat, AI_MATKEY_COLOR_SPECULAR);
  233. float glossinessAsShininess = pbrSG.glossinessFactor * 1000.0f;
  234. aimat->AddProperty(&glossinessAsShininess, 1, AI_MATKEY_SHININESS);
  235. aimat->AddProperty(&pbrSG.glossinessFactor, 1, AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS_GLOSSINESS_FACTOR);
  236. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.diffuseTexture, aimat, aiTextureType_DIFFUSE);
  237. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.specularGlossinessTexture, aimat, aiTextureType_SPECULAR);
  238. }
  239. if (mat.unlit) {
  240. aimat->AddProperty(&mat.unlit, 1, AI_MATKEY_GLTF_UNLIT);
  241. }
  242. return aimat;
  243. }
  244. void glTF2Importer::ImportMaterials(glTF2::Asset& r)
  245. {
  246. const unsigned int numImportedMaterials = unsigned(r.materials.Size());
  247. Material defaultMaterial;
  248. mScene->mNumMaterials = numImportedMaterials + 1;
  249. mScene->mMaterials = new aiMaterial*[mScene->mNumMaterials];
  250. mScene->mMaterials[numImportedMaterials] = ImportMaterial(embeddedTexIdxs, r, defaultMaterial);
  251. for (unsigned int i = 0; i < numImportedMaterials; ++i) {
  252. mScene->mMaterials[i] = ImportMaterial(embeddedTexIdxs, r, r.materials[i]);
  253. }
  254. }
  255. static inline void SetFace(aiFace& face, int a)
  256. {
  257. face.mNumIndices = 1;
  258. face.mIndices = new unsigned int[1];
  259. face.mIndices[0] = a;
  260. }
  261. static inline void SetFace(aiFace& face, int a, int b)
  262. {
  263. face.mNumIndices = 2;
  264. face.mIndices = new unsigned int[2];
  265. face.mIndices[0] = a;
  266. face.mIndices[1] = b;
  267. }
  268. static inline void SetFace(aiFace& face, int a, int b, int c)
  269. {
  270. face.mNumIndices = 3;
  271. face.mIndices = new unsigned int[3];
  272. face.mIndices[0] = a;
  273. face.mIndices[1] = b;
  274. face.mIndices[2] = c;
  275. }
  276. #ifdef ASSIMP_BUILD_DEBUG
  277. static inline bool CheckValidFacesIndices(aiFace* faces, unsigned nFaces, unsigned nVerts)
  278. {
  279. for (unsigned i = 0; i < nFaces; ++i) {
  280. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  281. unsigned idx = faces[i].mIndices[j];
  282. if (idx >= nVerts)
  283. return false;
  284. }
  285. }
  286. return true;
  287. }
  288. #endif // ASSIMP_BUILD_DEBUG
  289. void glTF2Importer::ImportMeshes(glTF2::Asset& r)
  290. {
  291. std::vector<aiMesh*> meshes;
  292. unsigned int k = 0;
  293. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  294. Mesh& mesh = r.meshes[m];
  295. meshOffsets.push_back(k);
  296. k += unsigned(mesh.primitives.size());
  297. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  298. Mesh::Primitive& prim = mesh.primitives[p];
  299. aiMesh* aim = new aiMesh();
  300. meshes.push_back(aim);
  301. aim->mName = mesh.name.empty() ? mesh.id : mesh.name;
  302. if (mesh.primitives.size() > 1) {
  303. size_t& len = aim->mName.length;
  304. aim->mName.data[len] = '-';
  305. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(MAXLEN - len - 1), p);
  306. }
  307. switch (prim.mode) {
  308. case PrimitiveMode_POINTS:
  309. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  310. break;
  311. case PrimitiveMode_LINES:
  312. case PrimitiveMode_LINE_LOOP:
  313. case PrimitiveMode_LINE_STRIP:
  314. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  315. break;
  316. case PrimitiveMode_TRIANGLES:
  317. case PrimitiveMode_TRIANGLE_STRIP:
  318. case PrimitiveMode_TRIANGLE_FAN:
  319. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  320. break;
  321. }
  322. Mesh::Primitive::Attributes& attr = prim.attributes;
  323. if (attr.position.size() > 0 && attr.position[0]) {
  324. aim->mNumVertices = static_cast<unsigned int>(attr.position[0]->count);
  325. attr.position[0]->ExtractData(aim->mVertices);
  326. }
  327. if (attr.normal.size() > 0 && attr.normal[0]) {
  328. attr.normal[0]->ExtractData(aim->mNormals);
  329. // only extract tangents if normals are present
  330. if (attr.tangent.size() > 0 && attr.tangent[0]) {
  331. // generate bitangents from normals and tangents according to spec
  332. Tangent *tangents = nullptr;
  333. attr.tangent[0]->ExtractData(tangents);
  334. aim->mTangents = new aiVector3D[aim->mNumVertices];
  335. aim->mBitangents = new aiVector3D[aim->mNumVertices];
  336. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  337. aim->mTangents[i] = tangents[i].xyz;
  338. aim->mBitangents[i] = (aim->mNormals[i] ^ tangents[i].xyz) * tangents[i].w;
  339. }
  340. delete [] tangents;
  341. }
  342. }
  343. for (size_t c = 0; c < attr.color.size() && c < AI_MAX_NUMBER_OF_COLOR_SETS; ++c) {
  344. if (attr.color[c]->count != aim->mNumVertices) {
  345. DefaultLogger::get()->warn("Color stream size in mesh \"" + mesh.name +
  346. "\" does not match the vertex count");
  347. continue;
  348. }
  349. aim->mColors[c] = new aiColor4D[attr.color[c]->count];
  350. attr.color[c]->ExtractData(aim->mColors[c]);
  351. }
  352. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  353. if (attr.texcoord[tc]->count != aim->mNumVertices) {
  354. DefaultLogger::get()->warn("Texcoord stream size in mesh \"" + mesh.name +
  355. "\" does not match the vertex count");
  356. continue;
  357. }
  358. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc]);
  359. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  360. aiVector3D* values = aim->mTextureCoords[tc];
  361. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  362. values[i].y = 1 - values[i].y; // Flip Y coords
  363. }
  364. }
  365. std::vector<Mesh::Primitive::Target>& targets = prim.targets;
  366. if (targets.size() > 0) {
  367. aim->mNumAnimMeshes = (unsigned int)targets.size();
  368. aim->mAnimMeshes = new aiAnimMesh*[aim->mNumAnimMeshes];
  369. for (size_t i = 0; i < targets.size(); i++) {
  370. aim->mAnimMeshes[i] = aiCreateAnimMesh(aim);
  371. aiAnimMesh& aiAnimMesh = *(aim->mAnimMeshes[i]);
  372. Mesh::Primitive::Target& target = targets[i];
  373. if (target.position.size() > 0) {
  374. aiVector3D *positionDiff = nullptr;
  375. target.position[0]->ExtractData(positionDiff);
  376. for(unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  377. aiAnimMesh.mVertices[vertexId] += positionDiff[vertexId];
  378. }
  379. delete [] positionDiff;
  380. }
  381. if (target.normal.size() > 0) {
  382. aiVector3D *normalDiff = nullptr;
  383. target.normal[0]->ExtractData(normalDiff);
  384. for(unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  385. aiAnimMesh.mNormals[vertexId] += normalDiff[vertexId];
  386. }
  387. delete [] normalDiff;
  388. }
  389. if (target.tangent.size() > 0) {
  390. Tangent *tangent = nullptr;
  391. attr.tangent[0]->ExtractData(tangent);
  392. aiVector3D *tangentDiff = nullptr;
  393. target.tangent[0]->ExtractData(tangentDiff);
  394. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; ++vertexId) {
  395. tangent[vertexId].xyz += tangentDiff[vertexId];
  396. aiAnimMesh.mTangents[vertexId] = tangent[vertexId].xyz;
  397. aiAnimMesh.mBitangents[vertexId] = (aiAnimMesh.mNormals[vertexId] ^ tangent[vertexId].xyz) * tangent[vertexId].w;
  398. }
  399. delete [] tangent;
  400. delete [] tangentDiff;
  401. }
  402. if (mesh.weights.size() > i) {
  403. aiAnimMesh.mWeight = mesh.weights[i];
  404. }
  405. }
  406. }
  407. aiFace* faces = 0;
  408. size_t nFaces = 0;
  409. if (prim.indices) {
  410. size_t count = prim.indices->count;
  411. Accessor::Indexer data = prim.indices->GetIndexer();
  412. ai_assert(data.IsValid());
  413. switch (prim.mode) {
  414. case PrimitiveMode_POINTS: {
  415. nFaces = count;
  416. faces = new aiFace[nFaces];
  417. for (unsigned int i = 0; i < count; ++i) {
  418. SetFace(faces[i], data.GetUInt(i));
  419. }
  420. break;
  421. }
  422. case PrimitiveMode_LINES: {
  423. nFaces = count / 2;
  424. faces = new aiFace[nFaces];
  425. for (unsigned int i = 0; i < count; i += 2) {
  426. SetFace(faces[i / 2], data.GetUInt(i), data.GetUInt(i + 1));
  427. }
  428. break;
  429. }
  430. case PrimitiveMode_LINE_LOOP:
  431. case PrimitiveMode_LINE_STRIP: {
  432. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  433. faces = new aiFace[nFaces];
  434. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1));
  435. for (unsigned int i = 2; i < count; ++i) {
  436. SetFace(faces[i - 1], faces[i - 2].mIndices[1], data.GetUInt(i));
  437. }
  438. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  439. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  440. }
  441. break;
  442. }
  443. case PrimitiveMode_TRIANGLES: {
  444. nFaces = count / 3;
  445. faces = new aiFace[nFaces];
  446. for (unsigned int i = 0; i < count; i += 3) {
  447. SetFace(faces[i / 3], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  448. }
  449. break;
  450. }
  451. case PrimitiveMode_TRIANGLE_STRIP: {
  452. nFaces = count - 2;
  453. faces = new aiFace[nFaces];
  454. for (unsigned int i = 0; i < nFaces; ++i) {
  455. //The ordering is to ensure that the triangles are all drawn with the same orientation
  456. if ((i + 1) % 2 == 0)
  457. {
  458. //For even n, vertices n + 1, n, and n + 2 define triangle n
  459. SetFace(faces[i], data.GetUInt(i + 1), data.GetUInt(i), data.GetUInt(i + 2));
  460. }
  461. else
  462. {
  463. //For odd n, vertices n, n+1, and n+2 define triangle n
  464. SetFace(faces[i], data.GetUInt(i), data.GetUInt(i + 1), data.GetUInt(i + 2));
  465. }
  466. }
  467. break;
  468. }
  469. case PrimitiveMode_TRIANGLE_FAN:
  470. nFaces = count - 2;
  471. faces = new aiFace[nFaces];
  472. SetFace(faces[0], data.GetUInt(0), data.GetUInt(1), data.GetUInt(2));
  473. for (unsigned int i = 1; i < nFaces; ++i) {
  474. SetFace(faces[i], faces[0].mIndices[0], faces[i - 1].mIndices[2], data.GetUInt(i + 2));
  475. }
  476. break;
  477. }
  478. }
  479. else { // no indices provided so directly generate from counts
  480. // use the already determined count as it includes checks
  481. unsigned int count = aim->mNumVertices;
  482. switch (prim.mode) {
  483. case PrimitiveMode_POINTS: {
  484. nFaces = count;
  485. faces = new aiFace[nFaces];
  486. for (unsigned int i = 0; i < count; ++i) {
  487. SetFace(faces[i], i);
  488. }
  489. break;
  490. }
  491. case PrimitiveMode_LINES: {
  492. nFaces = count / 2;
  493. faces = new aiFace[nFaces];
  494. for (unsigned int i = 0; i < count; i += 2) {
  495. SetFace(faces[i / 2], i, i + 1);
  496. }
  497. break;
  498. }
  499. case PrimitiveMode_LINE_LOOP:
  500. case PrimitiveMode_LINE_STRIP: {
  501. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  502. faces = new aiFace[nFaces];
  503. SetFace(faces[0], 0, 1);
  504. for (unsigned int i = 2; i < count; ++i) {
  505. SetFace(faces[i - 1], faces[i - 2].mIndices[1], i);
  506. }
  507. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  508. SetFace(faces[count - 1], faces[count - 2].mIndices[1], faces[0].mIndices[0]);
  509. }
  510. break;
  511. }
  512. case PrimitiveMode_TRIANGLES: {
  513. nFaces = count / 3;
  514. faces = new aiFace[nFaces];
  515. for (unsigned int i = 0; i < count; i += 3) {
  516. SetFace(faces[i / 3], i, i + 1, i + 2);
  517. }
  518. break;
  519. }
  520. case PrimitiveMode_TRIANGLE_STRIP: {
  521. nFaces = count - 2;
  522. faces = new aiFace[nFaces];
  523. for (unsigned int i = 0; i < nFaces; ++i) {
  524. //The ordering is to ensure that the triangles are all drawn with the same orientation
  525. if ((i+1) % 2 == 0)
  526. {
  527. //For even n, vertices n + 1, n, and n + 2 define triangle n
  528. SetFace(faces[i], i+1, i, i+2);
  529. }
  530. else
  531. {
  532. //For odd n, vertices n, n+1, and n+2 define triangle n
  533. SetFace(faces[i], i, i+1, i+2);
  534. }
  535. }
  536. break;
  537. }
  538. case PrimitiveMode_TRIANGLE_FAN:
  539. nFaces = count - 2;
  540. faces = new aiFace[nFaces];
  541. SetFace(faces[0], 0, 1, 2);
  542. for (unsigned int i = 1; i < nFaces; ++i) {
  543. SetFace(faces[i], faces[0].mIndices[0], faces[i - 1].mIndices[2], i + 2);
  544. }
  545. break;
  546. }
  547. }
  548. if (faces) {
  549. aim->mFaces = faces;
  550. aim->mNumFaces = static_cast<unsigned int>(nFaces);
  551. ai_assert(CheckValidFacesIndices(faces, static_cast<unsigned>(nFaces), aim->mNumVertices));
  552. }
  553. if (prim.material) {
  554. aim->mMaterialIndex = prim.material.GetIndex();
  555. }
  556. else {
  557. aim->mMaterialIndex = mScene->mNumMaterials - 1;
  558. }
  559. }
  560. }
  561. meshOffsets.push_back(k);
  562. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  563. }
  564. void glTF2Importer::ImportCameras(glTF2::Asset& r)
  565. {
  566. if (!r.cameras.Size()) return;
  567. mScene->mNumCameras = r.cameras.Size();
  568. mScene->mCameras = new aiCamera*[r.cameras.Size()];
  569. for (size_t i = 0; i < r.cameras.Size(); ++i) {
  570. Camera& cam = r.cameras[i];
  571. aiCamera* aicam = mScene->mCameras[i] = new aiCamera();
  572. // cameras point in -Z by default, rest is specified in node transform
  573. aicam->mLookAt = aiVector3D(0.f,0.f,-1.f);
  574. if (cam.type == Camera::Perspective) {
  575. aicam->mAspect = cam.cameraProperties.perspective.aspectRatio;
  576. aicam->mHorizontalFOV = cam.cameraProperties.perspective.yfov * aicam->mAspect;
  577. aicam->mClipPlaneFar = cam.cameraProperties.perspective.zfar;
  578. aicam->mClipPlaneNear = cam.cameraProperties.perspective.znear;
  579. }
  580. else {
  581. // assimp does not support orthographic cameras
  582. }
  583. }
  584. }
  585. void glTF2Importer::ImportLights(glTF2::Asset& r)
  586. {
  587. if (!r.lights.Size())
  588. return;
  589. mScene->mNumLights = r.lights.Size();
  590. mScene->mLights = new aiLight*[r.lights.Size()];
  591. for (size_t i = 0; i < r.lights.Size(); ++i) {
  592. Light& light = r.lights[i];
  593. aiLight* ail = mScene->mLights[i] = new aiLight();
  594. switch (light.type)
  595. {
  596. case Light::Directional:
  597. ail->mType = aiLightSource_DIRECTIONAL; break;
  598. case Light::Point:
  599. ail->mType = aiLightSource_POINT; break;
  600. case Light::Spot:
  601. ail->mType = aiLightSource_SPOT; break;
  602. }
  603. if (ail->mType != aiLightSource_POINT)
  604. {
  605. ail->mDirection = aiVector3D(0.0f, 0.0f, -1.0f);
  606. ail->mUp = aiVector3D(0.0f, 1.0f, 0.0f);
  607. }
  608. vec3 colorWithIntensity = { light.color[0] * light.intensity, light.color[1] * light.intensity, light.color[2] * light.intensity };
  609. CopyValue(colorWithIntensity, ail->mColorAmbient);
  610. CopyValue(colorWithIntensity, ail->mColorDiffuse);
  611. CopyValue(colorWithIntensity, ail->mColorSpecular);
  612. if (ail->mType == aiLightSource_DIRECTIONAL)
  613. {
  614. ail->mAttenuationConstant = 1.0;
  615. ail->mAttenuationLinear = 0.0;
  616. ail->mAttenuationQuadratic = 0.0;
  617. }
  618. else
  619. {
  620. //in PBR attenuation is calculated using inverse square law which can be expressed
  621. //using assimps equation: 1/(att0 + att1 * d + att2 * d*d) with the following parameters
  622. //this is correct equation for the case when range (see
  623. //https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual)
  624. //is not present. When range is not present it is assumed that it is infinite and so numerator is 1.
  625. //When range is present then numerator might be any value in range [0,1] and then assimps equation
  626. //will not suffice. In this case range is added into metadata in ImportNode function
  627. //and its up to implementation to read it when it wants to
  628. ail->mAttenuationConstant = 0.0;
  629. ail->mAttenuationLinear = 0.0;
  630. ail->mAttenuationQuadratic = 1.0;
  631. }
  632. if (ail->mType == aiLightSource_SPOT)
  633. {
  634. ail->mAngleInnerCone = light.innerConeAngle;
  635. ail->mAngleOuterCone = light.outerConeAngle;
  636. }
  637. }
  638. }
  639. static void GetNodeTransform(aiMatrix4x4& matrix, const glTF2::Node& node) {
  640. if (node.matrix.isPresent) {
  641. CopyValue(node.matrix.value, matrix);
  642. }
  643. else {
  644. if (node.translation.isPresent) {
  645. aiVector3D trans;
  646. CopyValue(node.translation.value, trans);
  647. aiMatrix4x4 t;
  648. aiMatrix4x4::Translation(trans, t);
  649. matrix = matrix * t;
  650. }
  651. if (node.rotation.isPresent) {
  652. aiQuaternion rot;
  653. CopyValue(node.rotation.value, rot);
  654. matrix = matrix * aiMatrix4x4(rot.GetMatrix());
  655. }
  656. if (node.scale.isPresent) {
  657. aiVector3D scal(1.f);
  658. CopyValue(node.scale.value, scal);
  659. aiMatrix4x4 s;
  660. aiMatrix4x4::Scaling(scal, s);
  661. matrix = matrix * s;
  662. }
  663. }
  664. }
  665. static void BuildVertexWeightMapping(Mesh::Primitive& primitive, std::vector<std::vector<aiVertexWeight>>& map)
  666. {
  667. Mesh::Primitive::Attributes& attr = primitive.attributes;
  668. if (attr.weight.empty() || attr.joint.empty()) {
  669. return;
  670. }
  671. if (attr.weight[0]->count != attr.joint[0]->count) {
  672. return;
  673. }
  674. size_t num_vertices = attr.weight[0]->count;
  675. struct Weights { float values[4]; };
  676. Weights* weights = nullptr;
  677. attr.weight[0]->ExtractData(weights);
  678. struct Indices8 { uint8_t values[4]; };
  679. struct Indices16 { uint16_t values[4]; };
  680. Indices8* indices8 = nullptr;
  681. Indices16* indices16 = nullptr;
  682. if (attr.joint[0]->GetElementSize() == 4) {
  683. attr.joint[0]->ExtractData(indices8);
  684. }else {
  685. attr.joint[0]->ExtractData(indices16);
  686. }
  687. //
  688. if (nullptr == indices8 && nullptr == indices16) {
  689. // Something went completely wrong!
  690. ai_assert(false);
  691. return;
  692. }
  693. for (size_t i = 0; i < num_vertices; ++i) {
  694. for (int j = 0; j < 4; ++j) {
  695. const unsigned int bone = (indices8!=nullptr) ? indices8[i].values[j] : indices16[i].values[j];
  696. const float weight = weights[i].values[j];
  697. if (weight > 0 && bone < map.size()) {
  698. map[bone].reserve(8);
  699. map[bone].emplace_back(static_cast<unsigned int>(i), weight);
  700. }
  701. }
  702. }
  703. delete[] weights;
  704. delete[] indices8;
  705. delete[] indices16;
  706. }
  707. static std::string GetNodeName(const Node& node)
  708. {
  709. return node.name.empty() ? node.id : node.name;
  710. }
  711. aiNode* ImportNode(aiScene* pScene, glTF2::Asset& r, std::vector<unsigned int>& meshOffsets, glTF2::Ref<glTF2::Node>& ptr)
  712. {
  713. Node& node = *ptr;
  714. aiNode* ainode = new aiNode(GetNodeName(node));
  715. if (!node.children.empty()) {
  716. ainode->mNumChildren = unsigned(node.children.size());
  717. ainode->mChildren = new aiNode*[ainode->mNumChildren];
  718. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  719. aiNode* child = ImportNode(pScene, r, meshOffsets, node.children[i]);
  720. child->mParent = ainode;
  721. ainode->mChildren[i] = child;
  722. }
  723. }
  724. GetNodeTransform(ainode->mTransformation, node);
  725. if (!node.meshes.empty()) {
  726. // GLTF files contain at most 1 mesh per node.
  727. assert(node.meshes.size() == 1);
  728. int mesh_idx = node.meshes[0].GetIndex();
  729. int count = meshOffsets[mesh_idx + 1] - meshOffsets[mesh_idx];
  730. ainode->mNumMeshes = count;
  731. ainode->mMeshes = new unsigned int[count];
  732. if (node.skin) {
  733. for (int primitiveNo = 0; primitiveNo < count; ++primitiveNo) {
  734. aiMesh* mesh = pScene->mMeshes[meshOffsets[mesh_idx]+primitiveNo];
  735. mesh->mNumBones = static_cast<unsigned int>(node.skin->jointNames.size());
  736. mesh->mBones = new aiBone*[mesh->mNumBones];
  737. // GLTF and Assimp choose to store bone weights differently.
  738. // GLTF has each vertex specify which bones influence the vertex.
  739. // Assimp has each bone specify which vertices it has influence over.
  740. // To convert this data, we first read over the vertex data and pull
  741. // out the bone-to-vertex mapping. Then, when creating the aiBones,
  742. // we copy the bone-to-vertex mapping into the bone. This is unfortunate
  743. // both because it's somewhat slow and because, for many applications,
  744. // we then need to reconvert the data back into the vertex-to-bone
  745. // mapping which makes things doubly-slow.
  746. std::vector<std::vector<aiVertexWeight>> weighting(mesh->mNumBones);
  747. BuildVertexWeightMapping(node.meshes[0]->primitives[primitiveNo], weighting);
  748. for (uint32_t i = 0; i < mesh->mNumBones; ++i) {
  749. aiBone* bone = new aiBone();
  750. Ref<Node> joint = node.skin->jointNames[i];
  751. if (!joint->name.empty()) {
  752. bone->mName = joint->name;
  753. } else {
  754. // Assimp expects each bone to have a unique name.
  755. static const std::string kDefaultName = "bone_";
  756. char postfix[10] = {0};
  757. ASSIMP_itoa10(postfix, i);
  758. bone->mName = (kDefaultName + postfix);
  759. }
  760. GetNodeTransform(bone->mOffsetMatrix, *joint);
  761. std::vector<aiVertexWeight>& weights = weighting[i];
  762. bone->mNumWeights = static_cast<uint32_t>(weights.size());
  763. if (bone->mNumWeights > 0) {
  764. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  765. memcpy(bone->mWeights, weights.data(), bone->mNumWeights * sizeof(aiVertexWeight));
  766. } else {
  767. // Assimp expects all bones to have at least 1 weight.
  768. bone->mWeights = new aiVertexWeight[1];
  769. bone->mNumWeights = 1;
  770. bone->mWeights->mVertexId = 0;
  771. bone->mWeights->mWeight = 0.f;
  772. }
  773. mesh->mBones[i] = bone;
  774. }
  775. }
  776. }
  777. int k = 0;
  778. for (unsigned int j = meshOffsets[mesh_idx]; j < meshOffsets[mesh_idx + 1]; ++j, ++k) {
  779. ainode->mMeshes[k] = j;
  780. }
  781. }
  782. if (node.camera) {
  783. pScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  784. }
  785. if (node.light) {
  786. pScene->mLights[node.light.GetIndex()]->mName = ainode->mName;
  787. //range is optional - see https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  788. //it is added to meta data of parent node, because there is no other place to put it
  789. if (node.light->range.isPresent)
  790. {
  791. ainode->mMetaData = aiMetadata::Alloc(1);
  792. ainode->mMetaData->Set(0, "PBR_LightRange", node.light->range.value);
  793. }
  794. }
  795. return ainode;
  796. }
  797. void glTF2Importer::ImportNodes(glTF2::Asset& r)
  798. {
  799. if (!r.scene) return;
  800. std::vector< Ref<Node> > rootNodes = r.scene->nodes;
  801. // The root nodes
  802. unsigned int numRootNodes = unsigned(rootNodes.size());
  803. if (numRootNodes == 1) { // a single root node: use it
  804. mScene->mRootNode = ImportNode(mScene, r, meshOffsets, rootNodes[0]);
  805. }
  806. else if (numRootNodes > 1) { // more than one root node: create a fake root
  807. aiNode* root = new aiNode("ROOT");
  808. root->mChildren = new aiNode*[numRootNodes];
  809. for (unsigned int i = 0; i < numRootNodes; ++i) {
  810. aiNode* node = ImportNode(mScene, r, meshOffsets, rootNodes[i]);
  811. node->mParent = root;
  812. root->mChildren[root->mNumChildren++] = node;
  813. }
  814. mScene->mRootNode = root;
  815. }
  816. //if (!mScene->mRootNode) {
  817. // mScene->mRootNode = new aiNode("EMPTY");
  818. //}
  819. }
  820. struct AnimationSamplers {
  821. AnimationSamplers() : translation(nullptr), rotation(nullptr), scale(nullptr) {}
  822. Animation::Sampler* translation;
  823. Animation::Sampler* rotation;
  824. Animation::Sampler* scale;
  825. };
  826. aiNodeAnim* CreateNodeAnim(glTF2::Asset& r, Node& node, AnimationSamplers& samplers)
  827. {
  828. aiNodeAnim* anim = new aiNodeAnim();
  829. anim->mNodeName = GetNodeName(node);
  830. static const float kMillisecondsFromSeconds = 1000.f;
  831. if (samplers.translation) {
  832. float* times = nullptr;
  833. samplers.translation->input->ExtractData(times);
  834. aiVector3D* values = nullptr;
  835. samplers.translation->output->ExtractData(values);
  836. anim->mNumPositionKeys = static_cast<uint32_t>(samplers.translation->input->count);
  837. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  838. for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) {
  839. anim->mPositionKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  840. anim->mPositionKeys[i].mValue = values[i];
  841. }
  842. delete[] times;
  843. delete[] values;
  844. } else if (node.translation.isPresent) {
  845. anim->mNumPositionKeys = 1;
  846. anim->mPositionKeys = new aiVectorKey();
  847. anim->mPositionKeys->mTime = 0.f;
  848. anim->mPositionKeys->mValue.x = node.translation.value[0];
  849. anim->mPositionKeys->mValue.y = node.translation.value[1];
  850. anim->mPositionKeys->mValue.z = node.translation.value[2];
  851. }
  852. if (samplers.rotation) {
  853. float* times = nullptr;
  854. samplers.rotation->input->ExtractData(times);
  855. aiQuaternion* values = nullptr;
  856. samplers.rotation->output->ExtractData(values);
  857. anim->mNumRotationKeys = static_cast<uint32_t>(samplers.rotation->input->count);
  858. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  859. for (unsigned int i = 0; i < anim->mNumRotationKeys; ++i) {
  860. anim->mRotationKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  861. anim->mRotationKeys[i].mValue.x = values[i].w;
  862. anim->mRotationKeys[i].mValue.y = values[i].x;
  863. anim->mRotationKeys[i].mValue.z = values[i].y;
  864. anim->mRotationKeys[i].mValue.w = values[i].z;
  865. }
  866. delete[] times;
  867. delete[] values;
  868. } else if (node.rotation.isPresent) {
  869. anim->mNumRotationKeys = 1;
  870. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  871. anim->mRotationKeys->mTime = 0.f;
  872. anim->mRotationKeys->mValue.x = node.rotation.value[0];
  873. anim->mRotationKeys->mValue.y = node.rotation.value[1];
  874. anim->mRotationKeys->mValue.z = node.rotation.value[2];
  875. anim->mRotationKeys->mValue.w = node.rotation.value[3];
  876. }
  877. if (samplers.scale) {
  878. float* times = nullptr;
  879. samplers.scale->input->ExtractData(times);
  880. aiVector3D* values = nullptr;
  881. samplers.scale->output->ExtractData(values);
  882. anim->mNumScalingKeys = static_cast<uint32_t>(samplers.scale->input->count);
  883. anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys];
  884. for (unsigned int i = 0; i < anim->mNumScalingKeys; ++i) {
  885. anim->mScalingKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  886. anim->mScalingKeys[i].mValue = values[i];
  887. }
  888. delete[] times;
  889. delete[] values;
  890. } else if (node.scale.isPresent) {
  891. anim->mNumScalingKeys = 1;
  892. anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys];
  893. anim->mScalingKeys->mTime = 0.f;
  894. anim->mScalingKeys->mValue.x = node.scale.value[0];
  895. anim->mScalingKeys->mValue.y = node.scale.value[1];
  896. anim->mScalingKeys->mValue.z = node.scale.value[2];
  897. }
  898. return anim;
  899. }
  900. std::unordered_map<unsigned int, AnimationSamplers> GatherSamplers(Animation& anim)
  901. {
  902. std::unordered_map<unsigned int, AnimationSamplers> samplers;
  903. for (unsigned int c = 0; c < anim.channels.size(); ++c) {
  904. Animation::Channel& channel = anim.channels[c];
  905. if (channel.sampler >= static_cast<int>(anim.samplers.size())) {
  906. continue;
  907. }
  908. const unsigned int node_index = channel.target.node.GetIndex();
  909. AnimationSamplers& sampler = samplers[node_index];
  910. if (channel.target.path == AnimationPath_TRANSLATION) {
  911. sampler.translation = &anim.samplers[channel.sampler];
  912. } else if (channel.target.path == AnimationPath_ROTATION) {
  913. sampler.rotation = &anim.samplers[channel.sampler];
  914. } else if (channel.target.path == AnimationPath_SCALE) {
  915. sampler.scale = &anim.samplers[channel.sampler];
  916. }
  917. }
  918. return samplers;
  919. }
  920. void glTF2Importer::ImportAnimations(glTF2::Asset& r)
  921. {
  922. if (!r.scene) return;
  923. mScene->mNumAnimations = r.animations.Size();
  924. if (mScene->mNumAnimations == 0) {
  925. return;
  926. }
  927. mScene->mAnimations = new aiAnimation*[mScene->mNumAnimations];
  928. for (unsigned int i = 0; i < r.animations.Size(); ++i) {
  929. Animation& anim = r.animations[i];
  930. aiAnimation* ai_anim = new aiAnimation();
  931. ai_anim->mName = anim.name;
  932. ai_anim->mDuration = 0;
  933. ai_anim->mTicksPerSecond = 0;
  934. std::unordered_map<unsigned int, AnimationSamplers> samplers = GatherSamplers(anim);
  935. ai_anim->mNumChannels = static_cast<uint32_t>(samplers.size());
  936. if (ai_anim->mNumChannels > 0) {
  937. ai_anim->mChannels = new aiNodeAnim*[ai_anim->mNumChannels];
  938. int j = 0;
  939. for (auto& iter : samplers) {
  940. ai_anim->mChannels[j] = CreateNodeAnim(r, r.nodes[iter.first], iter.second);
  941. ++j;
  942. }
  943. }
  944. // Use the latest keyframe for the duration of the animation
  945. double maxDuration = 0;
  946. unsigned int maxNumberOfKeys = 0;
  947. for (unsigned int j = 0; j < ai_anim->mNumChannels; ++j) {
  948. auto chan = ai_anim->mChannels[j];
  949. if (chan->mNumPositionKeys) {
  950. auto lastPosKey = chan->mPositionKeys[chan->mNumPositionKeys - 1];
  951. if (lastPosKey.mTime > maxDuration) {
  952. maxDuration = lastPosKey.mTime;
  953. }
  954. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumPositionKeys);
  955. }
  956. if (chan->mNumRotationKeys) {
  957. auto lastRotKey = chan->mRotationKeys[chan->mNumRotationKeys - 1];
  958. if (lastRotKey.mTime > maxDuration) {
  959. maxDuration = lastRotKey.mTime;
  960. }
  961. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumRotationKeys);
  962. }
  963. if (chan->mNumScalingKeys) {
  964. auto lastScaleKey = chan->mScalingKeys[chan->mNumScalingKeys - 1];
  965. if (lastScaleKey.mTime > maxDuration) {
  966. maxDuration = lastScaleKey.mTime;
  967. }
  968. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumScalingKeys);
  969. }
  970. }
  971. ai_anim->mDuration = maxDuration;
  972. ai_anim->mTicksPerSecond = (maxNumberOfKeys > 0 && maxDuration > 0) ? (maxNumberOfKeys / (maxDuration/1000)) : 30;
  973. mScene->mAnimations[i] = ai_anim;
  974. }
  975. }
  976. void glTF2Importer::ImportEmbeddedTextures(glTF2::Asset& r)
  977. {
  978. embeddedTexIdxs.resize(r.images.Size(), -1);
  979. int numEmbeddedTexs = 0;
  980. for (size_t i = 0; i < r.images.Size(); ++i) {
  981. if (r.images[i].HasData())
  982. numEmbeddedTexs += 1;
  983. }
  984. if (numEmbeddedTexs == 0)
  985. return;
  986. mScene->mTextures = new aiTexture*[numEmbeddedTexs];
  987. // Add the embedded textures
  988. for (size_t i = 0; i < r.images.Size(); ++i) {
  989. Image &img = r.images[i];
  990. if (!img.HasData()) continue;
  991. int idx = mScene->mNumTextures++;
  992. embeddedTexIdxs[i] = idx;
  993. aiTexture* tex = mScene->mTextures[idx] = new aiTexture();
  994. size_t length = img.GetDataLength();
  995. void* data = img.StealData();
  996. tex->mWidth = static_cast<unsigned int>(length);
  997. tex->mHeight = 0;
  998. tex->pcData = reinterpret_cast<aiTexel*>(data);
  999. if (!img.mimeType.empty()) {
  1000. const char* ext = strchr(img.mimeType.c_str(), '/') + 1;
  1001. if (ext) {
  1002. if (strcmp(ext, "jpeg") == 0) ext = "jpg";
  1003. size_t len = strlen(ext);
  1004. if (len <= 3) {
  1005. strcpy(tex->achFormatHint, ext);
  1006. }
  1007. }
  1008. }
  1009. }
  1010. }
  1011. void glTF2Importer::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  1012. {
  1013. // clean all member arrays
  1014. meshOffsets.clear();
  1015. embeddedTexIdxs.clear();
  1016. this->mScene = pScene;
  1017. // read the asset file
  1018. glTF2::Asset asset(pIOHandler);
  1019. asset.Load(pFile, GetExtension(pFile) == "glb");
  1020. //
  1021. // Copy the data out
  1022. //
  1023. ImportEmbeddedTextures(asset);
  1024. ImportMaterials(asset);
  1025. ImportMeshes(asset);
  1026. ImportCameras(asset);
  1027. ImportLights(asset);
  1028. ImportNodes(asset);
  1029. ImportAnimations(asset);
  1030. if (pScene->mNumMeshes == 0) {
  1031. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  1032. }
  1033. }
  1034. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER