glTF2Importer.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2024, 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_GLTF2_IMPORTER)
  34. #include "AssetLib/glTF2/glTF2Importer.h"
  35. #include "AssetLib/glTF2/glTF2Asset.h"
  36. #include "PostProcessing/MakeVerboseFormat.h"
  37. #if !defined(ASSIMP_BUILD_NO_EXPORT)
  38. # include "AssetLib/glTF2/glTF2AssetWriter.h"
  39. #endif
  40. #include <assimp/CreateAnimMesh.h>
  41. #include <assimp/DefaultIOSystem.h>
  42. #include <assimp/StringComparison.h>
  43. #include <assimp/StringUtils.h>
  44. #include <assimp/ai_assert.h>
  45. #include <assimp/commonMetaData.h>
  46. #include <assimp/importerdesc.h>
  47. #include <assimp/scene.h>
  48. #include <assimp/DefaultLogger.hpp>
  49. #include <assimp/Importer.hpp>
  50. #include <memory>
  51. #include <unordered_map>
  52. #include <rapidjson/document.h>
  53. #include <rapidjson/rapidjson.h>
  54. using namespace Assimp;
  55. using namespace glTF2;
  56. using namespace glTFCommon;
  57. namespace {
  58. // generate bi-tangents from normals and tangents according to spec
  59. struct Tangent {
  60. aiVector3D xyz;
  61. ai_real w;
  62. };
  63. } // namespace
  64. //
  65. // glTF2Importer
  66. //
  67. static constexpr aiImporterDesc desc = {
  68. "glTF2 Importer",
  69. "",
  70. "",
  71. "",
  72. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  73. 0,
  74. 0,
  75. 0,
  76. 0,
  77. "gltf glb vrm"
  78. };
  79. glTF2Importer::glTF2Importer() :
  80. mScene(nullptr) {
  81. // empty
  82. }
  83. const aiImporterDesc *glTF2Importer::GetInfo() const {
  84. return &desc;
  85. }
  86. bool glTF2Importer::CanRead(const std::string &filename, IOSystem *pIOHandler, bool checkSig) const {
  87. const std::string extension = GetExtension(filename);
  88. if (!checkSig && (extension != "gltf") && (extension != "glb") && (extension != "vrm")) {
  89. return false;
  90. }
  91. if (pIOHandler) {
  92. glTF2::Asset asset(pIOHandler);
  93. return asset.CanRead(
  94. filename,
  95. CheckMagicToken(
  96. pIOHandler, filename, AI_GLB_MAGIC_NUMBER, 1, 0,
  97. static_cast<unsigned int>(strlen(AI_GLB_MAGIC_NUMBER))));
  98. }
  99. return false;
  100. }
  101. static inline aiTextureMapMode ConvertWrappingMode(SamplerWrap gltfWrapMode) {
  102. switch (gltfWrapMode) {
  103. case SamplerWrap::Mirrored_Repeat:
  104. return aiTextureMapMode_Mirror;
  105. case SamplerWrap::Clamp_To_Edge:
  106. return aiTextureMapMode_Clamp;
  107. case SamplerWrap::UNSET:
  108. case SamplerWrap::Repeat:
  109. default:
  110. return aiTextureMapMode_Wrap;
  111. }
  112. }
  113. static inline void SetMaterialColorProperty(Asset & /*r*/, vec4 &prop, aiMaterial *mat,
  114. const char *pKey, unsigned int type, unsigned int idx) {
  115. aiColor4D col;
  116. CopyValue(prop, col);
  117. mat->AddProperty(&col, 1, pKey, type, idx);
  118. }
  119. static inline void SetMaterialColorProperty(Asset & /*r*/, vec3 &prop, aiMaterial *mat,
  120. const char *pKey, unsigned int type, unsigned int idx) {
  121. aiColor4D col;
  122. glTFCommon::CopyValue(prop, col);
  123. mat->AddProperty(&col, 1, pKey, type, idx);
  124. }
  125. static void SetMaterialTextureProperty(std::vector<int> &embeddedTexIdxs, Asset & /*r*/,
  126. glTF2::TextureInfo prop, aiMaterial *mat, aiTextureType texType,
  127. unsigned int texSlot = 0) {
  128. if (prop.texture && prop.texture->source) {
  129. aiString uri(prop.texture->source->uri);
  130. int texIdx = embeddedTexIdxs[prop.texture->source.GetIndex()];
  131. if (texIdx != -1) { // embedded
  132. // setup texture reference string (copied from ColladaLoader::FindFilenameForEffectTexture)
  133. uri.data[0] = '*';
  134. uri.length = 1 + ASSIMP_itoa10(uri.data + 1, AI_MAXLEN - 1, texIdx);
  135. }
  136. mat->AddProperty(&uri, AI_MATKEY_TEXTURE(texType, texSlot));
  137. const int uvIndex = static_cast<int>(prop.texCoord);
  138. mat->AddProperty(&uvIndex, 1, AI_MATKEY_UVWSRC(texType, texSlot));
  139. if (prop.textureTransformSupported) {
  140. aiUVTransform transform;
  141. transform.mScaling.x = prop.TextureTransformExt_t.scale[0];
  142. transform.mScaling.y = prop.TextureTransformExt_t.scale[1];
  143. transform.mRotation = -prop.TextureTransformExt_t.rotation; // must be negated
  144. // A change of coordinates is required to map glTF UV transformations into the space used by
  145. // Assimp. In glTF all UV origins are at 0,1 (top left of texture) in Assimp space. In Assimp
  146. // rotation occurs around the image center (0.5,0.5) where as in glTF rotation is around the
  147. // texture origin. All three can be corrected for solely by a change of the translation since
  148. // the transformations available are shape preserving. Note the importer already flips the V
  149. // coordinate of the actual meshes during import.
  150. const ai_real rcos(cos(-transform.mRotation));
  151. const ai_real rsin(sin(-transform.mRotation));
  152. transform.mTranslation.x = (static_cast<ai_real>(0.5) * transform.mScaling.x) * (-rcos + rsin + 1) + prop.TextureTransformExt_t.offset[0];
  153. transform.mTranslation.y = ((static_cast<ai_real>(0.5) * transform.mScaling.y) * (rsin + rcos - 1)) + 1 - transform.mScaling.y - prop.TextureTransformExt_t.offset[1];
  154. mat->AddProperty(&transform, 1, _AI_MATKEY_UVTRANSFORM_BASE, texType, texSlot);
  155. }
  156. if (prop.texture->sampler) {
  157. Ref<Sampler> sampler = prop.texture->sampler;
  158. aiString name(sampler->name);
  159. aiString id(sampler->id);
  160. mat->AddProperty(&name, AI_MATKEY_GLTF_MAPPINGNAME(texType, texSlot));
  161. mat->AddProperty(&id, AI_MATKEY_GLTF_MAPPINGID(texType, texSlot));
  162. aiTextureMapMode wrapS = ConvertWrappingMode(sampler->wrapS);
  163. aiTextureMapMode wrapT = ConvertWrappingMode(sampler->wrapT);
  164. mat->AddProperty(&wrapS, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot));
  165. mat->AddProperty(&wrapT, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot));
  166. if (sampler->magFilter != SamplerMagFilter::UNSET) {
  167. mat->AddProperty(&sampler->magFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(texType, texSlot));
  168. }
  169. if (sampler->minFilter != SamplerMinFilter::UNSET) {
  170. mat->AddProperty(&sampler->minFilter, 1, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(texType, texSlot));
  171. }
  172. } else {
  173. // Use glTFv2 default sampler
  174. const aiTextureMapMode default_wrap = aiTextureMapMode_Wrap;
  175. mat->AddProperty(&default_wrap, 1, AI_MATKEY_MAPPINGMODE_U(texType, texSlot));
  176. mat->AddProperty(&default_wrap, 1, AI_MATKEY_MAPPINGMODE_V(texType, texSlot));
  177. }
  178. }
  179. }
  180. inline void SetMaterialTextureProperty(std::vector<int> &embeddedTexIdxs, Asset &r,
  181. NormalTextureInfo &prop, aiMaterial *mat, aiTextureType texType,
  182. unsigned int texSlot = 0) {
  183. SetMaterialTextureProperty(embeddedTexIdxs, r, (glTF2::TextureInfo)prop, mat, texType, texSlot);
  184. if (prop.texture && prop.texture->source) {
  185. mat->AddProperty(&prop.scale, 1, AI_MATKEY_GLTF_TEXTURE_SCALE(texType, texSlot));
  186. }
  187. }
  188. inline void SetMaterialTextureProperty(std::vector<int> &embeddedTexIdxs, Asset &r,
  189. OcclusionTextureInfo &prop, aiMaterial *mat, aiTextureType texType,
  190. unsigned int texSlot = 0) {
  191. SetMaterialTextureProperty(embeddedTexIdxs, r, (glTF2::TextureInfo)prop, mat, texType, texSlot);
  192. if (prop.texture && prop.texture->source) {
  193. std::string textureStrengthKey = std::string(_AI_MATKEY_TEXTURE_BASE) + "." + "strength";
  194. mat->AddProperty(&prop.strength, 1, textureStrengthKey.c_str(), texType, texSlot);
  195. }
  196. }
  197. static aiMaterial *ImportMaterial(std::vector<int> &embeddedTexIdxs, Asset &r, Material &mat) {
  198. aiMaterial *aimat = new aiMaterial();
  199. try {
  200. if (!mat.name.empty()) {
  201. aiString str(mat.name);
  202. aimat->AddProperty(&str, AI_MATKEY_NAME);
  203. }
  204. // Set Assimp DIFFUSE and BASE COLOR to the pbrMetallicRoughness base color and texture for backwards compatibility
  205. // Technically should not load any pbrMetallicRoughness if extensionsRequired contains KHR_materials_pbrSpecularGlossiness
  206. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  207. SetMaterialColorProperty(r, mat.pbrMetallicRoughness.baseColorFactor, aimat, AI_MATKEY_BASE_COLOR);
  208. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_DIFFUSE);
  209. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.baseColorTexture, aimat, aiTextureType_BASE_COLOR);
  210. // Keep AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE for backwards compatibility
  211. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE);
  212. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, aiTextureType_METALNESS);
  213. SetMaterialTextureProperty(embeddedTexIdxs, r, mat.pbrMetallicRoughness.metallicRoughnessTexture, aimat, aiTextureType_DIFFUSE_ROUGHNESS);
  214. aimat->AddProperty(&mat.pbrMetallicRoughness.metallicFactor, 1, AI_MATKEY_METALLIC_FACTOR);
  215. aimat->AddProperty(&mat.pbrMetallicRoughness.roughnessFactor, 1, AI_MATKEY_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. aimat->AddProperty(&mat.pbrMetallicRoughness.baseColorFactor[3], 1, AI_MATKEY_OPACITY);
  225. aiString alphaMode(mat.alphaMode);
  226. aimat->AddProperty(&alphaMode, AI_MATKEY_GLTF_ALPHAMODE);
  227. aimat->AddProperty(&mat.alphaCutoff, 1, AI_MATKEY_GLTF_ALPHACUTOFF);
  228. // KHR_materials_specular
  229. if (mat.materialSpecular.isPresent) {
  230. MaterialSpecular &specular = mat.materialSpecular.value;
  231. // Default values of zero disables Specular
  232. if (std::memcmp(specular.specularColorFactor, defaultSpecularColorFactor, sizeof(glTFCommon::vec3)) != 0 || specular.specularFactor != 0.0f) {
  233. SetMaterialColorProperty(r, specular.specularColorFactor, aimat, AI_MATKEY_COLOR_SPECULAR);
  234. aimat->AddProperty(&specular.specularFactor, 1, AI_MATKEY_SPECULAR_FACTOR);
  235. SetMaterialTextureProperty(embeddedTexIdxs, r, specular.specularTexture, aimat, aiTextureType_SPECULAR, 0);
  236. SetMaterialTextureProperty(embeddedTexIdxs, r, specular.specularColorTexture, aimat, aiTextureType_SPECULAR, 1);
  237. }
  238. }
  239. // pbrSpecularGlossiness
  240. else if (mat.pbrSpecularGlossiness.isPresent) {
  241. PbrSpecularGlossiness &pbrSG = mat.pbrSpecularGlossiness.value;
  242. SetMaterialColorProperty(r, pbrSG.diffuseFactor, aimat, AI_MATKEY_COLOR_DIFFUSE);
  243. SetMaterialColorProperty(r, pbrSG.specularFactor, aimat, AI_MATKEY_COLOR_SPECULAR);
  244. float glossinessAsShininess = pbrSG.glossinessFactor * 1000.0f;
  245. aimat->AddProperty(&glossinessAsShininess, 1, AI_MATKEY_SHININESS);
  246. aimat->AddProperty(&pbrSG.glossinessFactor, 1, AI_MATKEY_GLOSSINESS_FACTOR);
  247. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.diffuseTexture, aimat, aiTextureType_DIFFUSE);
  248. SetMaterialTextureProperty(embeddedTexIdxs, r, pbrSG.specularGlossinessTexture, aimat, aiTextureType_SPECULAR);
  249. }
  250. // glTFv2 is either PBR or Unlit
  251. aiShadingMode shadingMode = aiShadingMode_PBR_BRDF;
  252. if (mat.unlit) {
  253. aimat->AddProperty(&mat.unlit, 1, "$mat.gltf.unlit", 0, 0); // TODO: Remove this property, it is kept for backwards compatibility with assimp 5.0.1
  254. shadingMode = aiShadingMode_Unlit;
  255. }
  256. aimat->AddProperty(&shadingMode, 1, AI_MATKEY_SHADING_MODEL);
  257. // KHR_materials_sheen
  258. if (mat.materialSheen.isPresent) {
  259. MaterialSheen &sheen = mat.materialSheen.value;
  260. // Default value {0,0,0} disables Sheen
  261. if (std::memcmp(sheen.sheenColorFactor, defaultSheenFactor, sizeof(glTFCommon::vec3)) != 0) {
  262. SetMaterialColorProperty(r, sheen.sheenColorFactor, aimat, AI_MATKEY_SHEEN_COLOR_FACTOR);
  263. aimat->AddProperty(&sheen.sheenRoughnessFactor, 1, AI_MATKEY_SHEEN_ROUGHNESS_FACTOR);
  264. SetMaterialTextureProperty(embeddedTexIdxs, r, sheen.sheenColorTexture, aimat, AI_MATKEY_SHEEN_COLOR_TEXTURE);
  265. SetMaterialTextureProperty(embeddedTexIdxs, r, sheen.sheenRoughnessTexture, aimat, AI_MATKEY_SHEEN_ROUGHNESS_TEXTURE);
  266. }
  267. }
  268. // KHR_materials_clearcoat
  269. if (mat.materialClearcoat.isPresent) {
  270. MaterialClearcoat &clearcoat = mat.materialClearcoat.value;
  271. // Default value 0.0 disables clearcoat
  272. if (clearcoat.clearcoatFactor != 0.0f) {
  273. aimat->AddProperty(&clearcoat.clearcoatFactor, 1, AI_MATKEY_CLEARCOAT_FACTOR);
  274. aimat->AddProperty(&clearcoat.clearcoatRoughnessFactor, 1, AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR);
  275. SetMaterialTextureProperty(embeddedTexIdxs, r, clearcoat.clearcoatTexture, aimat, AI_MATKEY_CLEARCOAT_TEXTURE);
  276. SetMaterialTextureProperty(embeddedTexIdxs, r, clearcoat.clearcoatRoughnessTexture, aimat, AI_MATKEY_CLEARCOAT_ROUGHNESS_TEXTURE);
  277. SetMaterialTextureProperty(embeddedTexIdxs, r, clearcoat.clearcoatNormalTexture, aimat, AI_MATKEY_CLEARCOAT_NORMAL_TEXTURE);
  278. }
  279. }
  280. // KHR_materials_transmission
  281. if (mat.materialTransmission.isPresent) {
  282. MaterialTransmission &transmission = mat.materialTransmission.value;
  283. aimat->AddProperty(&transmission.transmissionFactor, 1, AI_MATKEY_TRANSMISSION_FACTOR);
  284. SetMaterialTextureProperty(embeddedTexIdxs, r, transmission.transmissionTexture, aimat, AI_MATKEY_TRANSMISSION_TEXTURE);
  285. }
  286. // KHR_materials_volume
  287. if (mat.materialVolume.isPresent) {
  288. MaterialVolume &volume = mat.materialVolume.value;
  289. aimat->AddProperty(&volume.thicknessFactor, 1, AI_MATKEY_VOLUME_THICKNESS_FACTOR);
  290. SetMaterialTextureProperty(embeddedTexIdxs, r, volume.thicknessTexture, aimat, AI_MATKEY_VOLUME_THICKNESS_TEXTURE);
  291. aimat->AddProperty(&volume.attenuationDistance, 1, AI_MATKEY_VOLUME_ATTENUATION_DISTANCE);
  292. SetMaterialColorProperty(r, volume.attenuationColor, aimat, AI_MATKEY_VOLUME_ATTENUATION_COLOR);
  293. }
  294. // KHR_materials_ior
  295. if (mat.materialIOR.isPresent) {
  296. MaterialIOR &ior = mat.materialIOR.value;
  297. aimat->AddProperty(&ior.ior, 1, AI_MATKEY_REFRACTI);
  298. }
  299. // KHR_materials_emissive_strength
  300. if (mat.materialEmissiveStrength.isPresent) {
  301. MaterialEmissiveStrength &emissiveStrength = mat.materialEmissiveStrength.value;
  302. aimat->AddProperty(&emissiveStrength.emissiveStrength, 1, AI_MATKEY_EMISSIVE_INTENSITY);
  303. }
  304. return aimat;
  305. } catch (...) {
  306. delete aimat;
  307. throw;
  308. }
  309. }
  310. void glTF2Importer::ImportMaterials(Asset &r) {
  311. const unsigned int numImportedMaterials = unsigned(r.materials.Size());
  312. ASSIMP_LOG_DEBUG("Importing ", numImportedMaterials, " materials");
  313. Material defaultMaterial;
  314. mScene->mNumMaterials = numImportedMaterials + 1;
  315. mScene->mMaterials = new aiMaterial *[mScene->mNumMaterials];
  316. std::fill(mScene->mMaterials, mScene->mMaterials + mScene->mNumMaterials, nullptr);
  317. mScene->mMaterials[numImportedMaterials] = ImportMaterial(mEmbeddedTexIdxs, r, defaultMaterial);
  318. for (unsigned int i = 0; i < numImportedMaterials; ++i) {
  319. mScene->mMaterials[i] = ImportMaterial(mEmbeddedTexIdxs, r, r.materials[i]);
  320. }
  321. }
  322. static inline void SetFaceAndAdvance1(aiFace *&face, unsigned int numVertices, unsigned int a) {
  323. if (a >= numVertices) {
  324. return;
  325. }
  326. face->mNumIndices = 1;
  327. face->mIndices = new unsigned int[1];
  328. face->mIndices[0] = a;
  329. ++face;
  330. }
  331. static inline void SetFaceAndAdvance2(aiFace *&face, unsigned int numVertices,
  332. unsigned int a, unsigned int b) {
  333. if ((a >= numVertices) || (b >= numVertices)) {
  334. return;
  335. }
  336. face->mNumIndices = 2;
  337. face->mIndices = new unsigned int[2];
  338. face->mIndices[0] = a;
  339. face->mIndices[1] = b;
  340. ++face;
  341. }
  342. static inline void SetFaceAndAdvance3(aiFace *&face, unsigned int numVertices, unsigned int a,
  343. unsigned int b, unsigned int c) {
  344. if ((a >= numVertices) || (b >= numVertices) || (c >= numVertices)) {
  345. return;
  346. }
  347. face->mNumIndices = 3;
  348. face->mIndices = new unsigned int[3];
  349. face->mIndices[0] = a;
  350. face->mIndices[1] = b;
  351. face->mIndices[2] = c;
  352. ++face;
  353. }
  354. #ifdef ASSIMP_BUILD_DEBUG
  355. static inline bool CheckValidFacesIndices(aiFace *faces, unsigned nFaces, unsigned nVerts) {
  356. for (unsigned i = 0; i < nFaces; ++i) {
  357. for (unsigned j = 0; j < faces[i].mNumIndices; ++j) {
  358. unsigned idx = faces[i].mIndices[j];
  359. if (idx >= nVerts) {
  360. return false;
  361. }
  362. }
  363. }
  364. return true;
  365. }
  366. #endif // ASSIMP_BUILD_DEBUG
  367. template <typename T>
  368. aiColor4D *GetVertexColorsForType(Ref<Accessor> input, std::vector<unsigned int> *vertexRemappingTable) {
  369. constexpr float max = std::numeric_limits<T>::max();
  370. aiColor4t<T> *colors;
  371. input->ExtractData(colors, vertexRemappingTable);
  372. auto output = new aiColor4D[input->count];
  373. for (size_t i = 0; i < input->count; i++) {
  374. output[i] = aiColor4D(
  375. colors[i].r / max, colors[i].g / max,
  376. colors[i].b / max, colors[i].a / max);
  377. }
  378. delete[] colors;
  379. return output;
  380. }
  381. void glTF2Importer::ImportMeshes(glTF2::Asset &r) {
  382. ASSIMP_LOG_DEBUG("Importing ", r.meshes.Size(), " meshes");
  383. std::vector<std::unique_ptr<aiMesh>> meshes;
  384. meshOffsets.clear();
  385. meshOffsets.reserve(r.meshes.Size() + 1);
  386. mVertexRemappingTables.clear();
  387. // Count the number of aiMeshes
  388. unsigned int num_aiMeshes = 0;
  389. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  390. meshOffsets.push_back(num_aiMeshes);
  391. num_aiMeshes += unsigned(r.meshes[m].primitives.size());
  392. }
  393. meshOffsets.push_back(num_aiMeshes); // add a last element so we can always do meshOffsets[n+1] - meshOffsets[n]
  394. std::vector<unsigned int> reverseMappingIndices;
  395. std::vector<unsigned int> indexBuffer;
  396. meshes.reserve(num_aiMeshes);
  397. mVertexRemappingTables.resize(num_aiMeshes);
  398. for (unsigned int m = 0; m < r.meshes.Size(); ++m) {
  399. Mesh &mesh = r.meshes[m];
  400. for (unsigned int p = 0; p < mesh.primitives.size(); ++p) {
  401. Mesh::Primitive &prim = mesh.primitives[p];
  402. Mesh::Primitive::Attributes &attr = prim.attributes;
  403. // Find out the maximum number of vertices:
  404. size_t numAllVertices = 0;
  405. if (!attr.position.empty() && attr.position[0]) {
  406. numAllVertices = attr.position[0]->count;
  407. }
  408. // Extract used vertices:
  409. bool useIndexBuffer = prim.indices;
  410. std::vector<unsigned int> *vertexRemappingTable = nullptr;
  411. if (useIndexBuffer) {
  412. size_t count = prim.indices->count;
  413. indexBuffer.resize(count);
  414. reverseMappingIndices.clear();
  415. vertexRemappingTable = &mVertexRemappingTables[meshes.size()];
  416. vertexRemappingTable->reserve(count / 3); // this is a very rough heuristic to reduce re-allocations
  417. Accessor::Indexer data = prim.indices->GetIndexer();
  418. if (!data.IsValid()) {
  419. throw DeadlyImportError("GLTF: Invalid accessor without data in mesh ", getContextForErrorMessages(mesh.id, mesh.name));
  420. }
  421. // Build the vertex remapping table and the modified index buffer (used later instead of the original one)
  422. // In case no index buffer is used, the original vertex arrays are being used so no remapping is required in the first place.
  423. const unsigned int unusedIndex = ~0u;
  424. for (unsigned int i = 0; i < count; ++i) {
  425. unsigned int index = data.GetUInt(i);
  426. if (index >= numAllVertices) {
  427. // Out-of-range indices will be filtered out when adding the faces and then lead to a warning. At this stage, we just keep them.
  428. indexBuffer[i] = index;
  429. continue;
  430. }
  431. if (index >= reverseMappingIndices.size()) {
  432. reverseMappingIndices.resize(index + 1, unusedIndex);
  433. }
  434. if (reverseMappingIndices[index] == unusedIndex) {
  435. reverseMappingIndices[index] = static_cast<unsigned int>(vertexRemappingTable->size());
  436. vertexRemappingTable->push_back(index);
  437. }
  438. indexBuffer[i] = reverseMappingIndices[index];
  439. }
  440. }
  441. aiMesh *aim = new aiMesh();
  442. meshes.push_back(std::unique_ptr<aiMesh>(aim));
  443. aim->mName = mesh.name.empty() ? mesh.id : mesh.name;
  444. if (mesh.primitives.size() > 1) {
  445. ai_uint32 &len = aim->mName.length;
  446. aim->mName.data[len] = '-';
  447. len += 1 + ASSIMP_itoa10(aim->mName.data + len + 1, unsigned(AI_MAXLEN - len - 1), p);
  448. }
  449. switch (prim.mode) {
  450. case PrimitiveMode_POINTS:
  451. aim->mPrimitiveTypes |= aiPrimitiveType_POINT;
  452. break;
  453. case PrimitiveMode_LINES:
  454. case PrimitiveMode_LINE_LOOP:
  455. case PrimitiveMode_LINE_STRIP:
  456. aim->mPrimitiveTypes |= aiPrimitiveType_LINE;
  457. break;
  458. case PrimitiveMode_TRIANGLES:
  459. case PrimitiveMode_TRIANGLE_STRIP:
  460. case PrimitiveMode_TRIANGLE_FAN:
  461. aim->mPrimitiveTypes |= aiPrimitiveType_TRIANGLE;
  462. break;
  463. }
  464. if (!attr.position.empty() && attr.position[0]) {
  465. aim->mNumVertices = static_cast<unsigned int>(attr.position[0]->ExtractData(aim->mVertices, vertexRemappingTable));
  466. }
  467. if (!attr.normal.empty() && attr.normal[0]) {
  468. if (attr.normal[0]->count != numAllVertices) {
  469. DefaultLogger::get()->warn("Normal count in mesh \"", mesh.name, "\" does not match the vertex count, normals ignored.");
  470. } else {
  471. attr.normal[0]->ExtractData(aim->mNormals, vertexRemappingTable);
  472. // only extract tangents if normals are present
  473. if (!attr.tangent.empty() && attr.tangent[0]) {
  474. if (attr.tangent[0]->count != numAllVertices) {
  475. DefaultLogger::get()->warn("Tangent count in mesh \"", mesh.name, "\" does not match the vertex count, tangents ignored.");
  476. } else {
  477. // generate bitangents from normals and tangents according to spec
  478. Tangent *tangents = nullptr;
  479. attr.tangent[0]->ExtractData(tangents, vertexRemappingTable);
  480. aim->mTangents = new aiVector3D[aim->mNumVertices];
  481. aim->mBitangents = new aiVector3D[aim->mNumVertices];
  482. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  483. aim->mTangents[i] = tangents[i].xyz;
  484. aim->mBitangents[i] = (aim->mNormals[i] ^ tangents[i].xyz) * tangents[i].w;
  485. }
  486. delete[] tangents;
  487. }
  488. }
  489. }
  490. }
  491. for (size_t c = 0; c < attr.color.size() && c < AI_MAX_NUMBER_OF_COLOR_SETS; ++c) {
  492. if (attr.color[c]->count != numAllVertices) {
  493. DefaultLogger::get()->warn("Color stream size in mesh \"", mesh.name,
  494. "\" does not match the vertex count");
  495. continue;
  496. }
  497. auto componentType = attr.color[c]->componentType;
  498. if (componentType == glTF2::ComponentType_FLOAT) {
  499. attr.color[c]->ExtractData(aim->mColors[c], vertexRemappingTable);
  500. } else {
  501. if (componentType == glTF2::ComponentType_UNSIGNED_BYTE) {
  502. aim->mColors[c] = GetVertexColorsForType<unsigned char>(attr.color[c], vertexRemappingTable);
  503. } else if (componentType == glTF2::ComponentType_UNSIGNED_SHORT) {
  504. aim->mColors[c] = GetVertexColorsForType<unsigned short>(attr.color[c], vertexRemappingTable);
  505. }
  506. }
  507. }
  508. for (size_t tc = 0; tc < attr.texcoord.size() && tc < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++tc) {
  509. if (!attr.texcoord[tc]) {
  510. DefaultLogger::get()->warn("Texture coordinate accessor not found or non-contiguous texture coordinate sets.");
  511. continue;
  512. }
  513. if (attr.texcoord[tc]->count != numAllVertices) {
  514. DefaultLogger::get()->warn("Texcoord stream size in mesh \"", mesh.name,
  515. "\" does not match the vertex count");
  516. continue;
  517. }
  518. attr.texcoord[tc]->ExtractData(aim->mTextureCoords[tc], vertexRemappingTable);
  519. aim->mNumUVComponents[tc] = attr.texcoord[tc]->GetNumComponents();
  520. aiVector3D *values = aim->mTextureCoords[tc];
  521. for (unsigned int i = 0; i < aim->mNumVertices; ++i) {
  522. values[i].y = 1 - values[i].y; // Flip Y coords
  523. }
  524. }
  525. std::vector<Mesh::Primitive::Target> &targets = prim.targets;
  526. if (!targets.empty()) {
  527. aim->mNumAnimMeshes = (unsigned int)targets.size();
  528. aim->mAnimMeshes = new aiAnimMesh *[aim->mNumAnimMeshes];
  529. std::fill(aim->mAnimMeshes, aim->mAnimMeshes + aim->mNumAnimMeshes, nullptr);
  530. for (size_t i = 0; i < targets.size(); i++) {
  531. bool needPositions = targets[i].position.size() > 0;
  532. bool needNormals = (targets[i].normal.size() > 0) && aim->HasNormals();
  533. bool needTangents = (targets[i].tangent.size() > 0) && aim->HasTangentsAndBitangents();
  534. // GLTF morph does not support colors and texCoords
  535. aim->mAnimMeshes[i] = aiCreateAnimMesh(aim,
  536. needPositions, needNormals, needTangents, false, false);
  537. aiAnimMesh &aiAnimMesh = *(aim->mAnimMeshes[i]);
  538. Mesh::Primitive::Target &target = targets[i];
  539. if (needPositions) {
  540. if (target.position[0]->count != numAllVertices) {
  541. ASSIMP_LOG_WARN("Positions of target ", i, " in mesh \"", mesh.name, "\" does not match the vertex count");
  542. } else {
  543. aiVector3D *positionDiff = nullptr;
  544. target.position[0]->ExtractData(positionDiff, vertexRemappingTable);
  545. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  546. aiAnimMesh.mVertices[vertexId] += positionDiff[vertexId];
  547. }
  548. delete[] positionDiff;
  549. }
  550. }
  551. if (needNormals) {
  552. if (target.normal[0]->count != numAllVertices) {
  553. ASSIMP_LOG_WARN("Normals of target ", i, " in mesh \"", mesh.name, "\" does not match the vertex count");
  554. } else {
  555. aiVector3D *normalDiff = nullptr;
  556. target.normal[0]->ExtractData(normalDiff, vertexRemappingTable);
  557. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; vertexId++) {
  558. aiAnimMesh.mNormals[vertexId] += normalDiff[vertexId];
  559. }
  560. delete[] normalDiff;
  561. }
  562. }
  563. if (needTangents) {
  564. if (!aiAnimMesh.HasNormals()) {
  565. // prevent nullptr access to aiAnimMesh.mNormals below when no normals are available
  566. ASSIMP_LOG_WARN("Bitangents of target ", i, " in mesh \"", mesh.name, "\" can't be computed, because mesh has no normals.");
  567. } else if (target.tangent[0]->count != numAllVertices) {
  568. ASSIMP_LOG_WARN("Tangents of target ", i, " in mesh \"", mesh.name, "\" does not match the vertex count");
  569. } else {
  570. Tangent *tangent = nullptr;
  571. attr.tangent[0]->ExtractData(tangent, vertexRemappingTable);
  572. aiVector3D *tangentDiff = nullptr;
  573. target.tangent[0]->ExtractData(tangentDiff, vertexRemappingTable);
  574. for (unsigned int vertexId = 0; vertexId < aim->mNumVertices; ++vertexId) {
  575. tangent[vertexId].xyz += tangentDiff[vertexId];
  576. aiAnimMesh.mTangents[vertexId] = tangent[vertexId].xyz;
  577. aiAnimMesh.mBitangents[vertexId] = (aiAnimMesh.mNormals[vertexId] ^ tangent[vertexId].xyz) * tangent[vertexId].w;
  578. }
  579. delete[] tangent;
  580. delete[] tangentDiff;
  581. }
  582. }
  583. if (mesh.weights.size() > i) {
  584. aiAnimMesh.mWeight = mesh.weights[i];
  585. }
  586. if (mesh.targetNames.size() > i) {
  587. aiAnimMesh.mName = mesh.targetNames[i];
  588. }
  589. }
  590. }
  591. aiFace *faces = nullptr;
  592. aiFace *facePtr = nullptr;
  593. size_t nFaces = 0;
  594. if (useIndexBuffer) {
  595. size_t count = indexBuffer.size();
  596. switch (prim.mode) {
  597. case PrimitiveMode_POINTS: {
  598. nFaces = count;
  599. facePtr = faces = new aiFace[nFaces];
  600. for (unsigned int i = 0; i < count; ++i) {
  601. SetFaceAndAdvance1(facePtr, aim->mNumVertices, indexBuffer[i]);
  602. }
  603. break;
  604. }
  605. case PrimitiveMode_LINES: {
  606. nFaces = count / 2;
  607. if (nFaces * 2 != count) {
  608. ASSIMP_LOG_WARN("The number of vertices was not compatible with the LINES mode. Some vertices were dropped.");
  609. count = nFaces * 2;
  610. }
  611. facePtr = faces = new aiFace[nFaces];
  612. for (unsigned int i = 0; i < count; i += 2) {
  613. SetFaceAndAdvance2(facePtr, aim->mNumVertices, indexBuffer[i], indexBuffer[i + 1]);
  614. }
  615. break;
  616. }
  617. case PrimitiveMode_LINE_LOOP:
  618. case PrimitiveMode_LINE_STRIP: {
  619. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  620. facePtr = faces = new aiFace[nFaces];
  621. SetFaceAndAdvance2(facePtr, aim->mNumVertices, indexBuffer[0], indexBuffer[1]);
  622. for (unsigned int i = 2; i < count; ++i) {
  623. SetFaceAndAdvance2(facePtr, aim->mNumVertices, indexBuffer[i - 1], indexBuffer[i]);
  624. }
  625. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  626. SetFaceAndAdvance2(facePtr, aim->mNumVertices, indexBuffer[static_cast<int>(count) - 1], faces[0].mIndices[0]);
  627. }
  628. break;
  629. }
  630. case PrimitiveMode_TRIANGLES: {
  631. nFaces = count / 3;
  632. if (nFaces * 3 != count) {
  633. ASSIMP_LOG_WARN("The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.");
  634. count = nFaces * 3;
  635. }
  636. facePtr = faces = new aiFace[nFaces];
  637. for (unsigned int i = 0; i < count; i += 3) {
  638. SetFaceAndAdvance3(facePtr, aim->mNumVertices, indexBuffer[i], indexBuffer[i + 1], indexBuffer[i + 2]);
  639. }
  640. break;
  641. }
  642. case PrimitiveMode_TRIANGLE_STRIP: {
  643. nFaces = count - 2;
  644. facePtr = faces = new aiFace[nFaces];
  645. for (unsigned int i = 0; i < nFaces; ++i) {
  646. // The ordering is to ensure that the triangles are all drawn with the same orientation
  647. if ((i + 1) % 2 == 0) {
  648. // For even n, vertices n + 1, n, and n + 2 define triangle n
  649. SetFaceAndAdvance3(facePtr, aim->mNumVertices, indexBuffer[i + 1], indexBuffer[i], indexBuffer[i + 2]);
  650. } else {
  651. // For odd n, vertices n, n+1, and n+2 define triangle n
  652. SetFaceAndAdvance3(facePtr, aim->mNumVertices, indexBuffer[i], indexBuffer[i + 1], indexBuffer[i + 2]);
  653. }
  654. }
  655. break;
  656. }
  657. case PrimitiveMode_TRIANGLE_FAN:
  658. nFaces = count - 2;
  659. facePtr = faces = new aiFace[nFaces];
  660. SetFaceAndAdvance3(facePtr, aim->mNumVertices, indexBuffer[0], indexBuffer[1], indexBuffer[2]);
  661. for (unsigned int i = 1; i < nFaces; ++i) {
  662. SetFaceAndAdvance3(facePtr, aim->mNumVertices, indexBuffer[0], indexBuffer[i + 1], indexBuffer[i + 2]);
  663. }
  664. break;
  665. }
  666. } else { // no indices provided so directly generate from counts
  667. // use the already determined count as it includes checks
  668. unsigned int count = aim->mNumVertices;
  669. switch (prim.mode) {
  670. case PrimitiveMode_POINTS: {
  671. nFaces = count;
  672. facePtr = faces = new aiFace[nFaces];
  673. for (unsigned int i = 0; i < count; ++i) {
  674. SetFaceAndAdvance1(facePtr, aim->mNumVertices, i);
  675. }
  676. break;
  677. }
  678. case PrimitiveMode_LINES: {
  679. nFaces = count / 2;
  680. if (nFaces * 2 != count) {
  681. ASSIMP_LOG_WARN("The number of vertices was not compatible with the LINES mode. Some vertices were dropped.");
  682. count = (unsigned int)nFaces * 2;
  683. }
  684. facePtr = faces = new aiFace[nFaces];
  685. for (unsigned int i = 0; i < count; i += 2) {
  686. SetFaceAndAdvance2(facePtr, aim->mNumVertices, i, i + 1);
  687. }
  688. break;
  689. }
  690. case PrimitiveMode_LINE_LOOP:
  691. case PrimitiveMode_LINE_STRIP: {
  692. nFaces = count - ((prim.mode == PrimitiveMode_LINE_STRIP) ? 1 : 0);
  693. facePtr = faces = new aiFace[nFaces];
  694. SetFaceAndAdvance2(facePtr, aim->mNumVertices, 0, 1);
  695. for (unsigned int i = 2; i < count; ++i) {
  696. SetFaceAndAdvance2(facePtr, aim->mNumVertices, i - 1, i);
  697. }
  698. if (prim.mode == PrimitiveMode_LINE_LOOP) { // close the loop
  699. SetFaceAndAdvance2(facePtr, aim->mNumVertices, count - 1, 0);
  700. }
  701. break;
  702. }
  703. case PrimitiveMode_TRIANGLES: {
  704. nFaces = count / 3;
  705. if (nFaces * 3 != count) {
  706. ASSIMP_LOG_WARN("The number of vertices was not compatible with the TRIANGLES mode. Some vertices were dropped.");
  707. count = (unsigned int)nFaces * 3;
  708. }
  709. facePtr = faces = new aiFace[nFaces];
  710. for (unsigned int i = 0; i < count; i += 3) {
  711. SetFaceAndAdvance3(facePtr, aim->mNumVertices, i, i + 1, i + 2);
  712. }
  713. break;
  714. }
  715. case PrimitiveMode_TRIANGLE_STRIP: {
  716. nFaces = count - 2;
  717. facePtr = faces = new aiFace[nFaces];
  718. for (unsigned int i = 0; i < nFaces; ++i) {
  719. // The ordering is to ensure that the triangles are all drawn with the same orientation
  720. if ((i + 1) % 2 == 0) {
  721. // For even n, vertices n + 1, n, and n + 2 define triangle n
  722. SetFaceAndAdvance3(facePtr, aim->mNumVertices, i + 1, i, i + 2);
  723. } else {
  724. // For odd n, vertices n, n+1, and n+2 define triangle n
  725. SetFaceAndAdvance3(facePtr, aim->mNumVertices, i, i + 1, i + 2);
  726. }
  727. }
  728. break;
  729. }
  730. case PrimitiveMode_TRIANGLE_FAN:
  731. nFaces = count - 2;
  732. facePtr = faces = new aiFace[nFaces];
  733. SetFaceAndAdvance3(facePtr, aim->mNumVertices, 0, 1, 2);
  734. for (unsigned int i = 1; i < nFaces; ++i) {
  735. SetFaceAndAdvance3(facePtr, aim->mNumVertices, 0, i + 1, i + 2);
  736. }
  737. break;
  738. }
  739. }
  740. if (faces) {
  741. aim->mFaces = faces;
  742. const unsigned int actualNumFaces = static_cast<unsigned int>(facePtr - faces);
  743. if (actualNumFaces < nFaces) {
  744. ASSIMP_LOG_WARN("Some faces had out-of-range indices. Those faces were dropped.");
  745. }
  746. if (actualNumFaces == 0) {
  747. throw DeadlyImportError("Mesh \"", aim->mName.C_Str(), "\" has no faces");
  748. }
  749. aim->mNumFaces = actualNumFaces;
  750. ai_assert(CheckValidFacesIndices(faces, actualNumFaces, aim->mNumVertices));
  751. }
  752. if (prim.material) {
  753. aim->mMaterialIndex = prim.material.GetIndex();
  754. } else {
  755. aim->mMaterialIndex = mScene->mNumMaterials - 1;
  756. }
  757. }
  758. }
  759. CopyVector(meshes, mScene->mMeshes, mScene->mNumMeshes);
  760. }
  761. void glTF2Importer::ImportCameras(glTF2::Asset &r) {
  762. if (!r.cameras.Size()) {
  763. return;
  764. }
  765. const unsigned int numCameras = r.cameras.Size();
  766. ASSIMP_LOG_DEBUG("Importing ", numCameras, " cameras");
  767. mScene->mNumCameras = numCameras;
  768. mScene->mCameras = new aiCamera *[numCameras];
  769. std::fill(mScene->mCameras, mScene->mCameras + numCameras, nullptr);
  770. for (size_t i = 0; i < numCameras; ++i) {
  771. Camera &cam = r.cameras[i];
  772. aiCamera *aicam = mScene->mCameras[i] = new aiCamera();
  773. // cameras point in -Z by default, rest is specified in node transform
  774. aicam->mLookAt = aiVector3D(0.f, 0.f, -1.f);
  775. if (cam.type == Camera::Perspective) {
  776. aicam->mAspect = cam.cameraProperties.perspective.aspectRatio;
  777. aicam->mHorizontalFOV = 2.0f * std::atan(std::tan(cam.cameraProperties.perspective.yfov * 0.5f) * ((aicam->mAspect == 0.f) ? 1.f : aicam->mAspect));
  778. aicam->mClipPlaneFar = cam.cameraProperties.perspective.zfar;
  779. aicam->mClipPlaneNear = cam.cameraProperties.perspective.znear;
  780. } else {
  781. aicam->mClipPlaneFar = cam.cameraProperties.ortographic.zfar;
  782. aicam->mClipPlaneNear = cam.cameraProperties.ortographic.znear;
  783. aicam->mHorizontalFOV = 0.0;
  784. aicam->mOrthographicWidth = cam.cameraProperties.ortographic.xmag;
  785. aicam->mAspect = 1.0f;
  786. if (0.f != cam.cameraProperties.ortographic.ymag) {
  787. aicam->mAspect = cam.cameraProperties.ortographic.xmag / cam.cameraProperties.ortographic.ymag;
  788. }
  789. }
  790. }
  791. }
  792. void glTF2Importer::ImportLights(glTF2::Asset &r) {
  793. if (!r.lights.Size()) {
  794. return;
  795. }
  796. const unsigned int numLights = r.lights.Size();
  797. ASSIMP_LOG_DEBUG("Importing ", numLights, " lights");
  798. mScene->mNumLights = numLights;
  799. mScene->mLights = new aiLight *[numLights];
  800. std::fill(mScene->mLights, mScene->mLights + numLights, nullptr);
  801. for (size_t i = 0; i < numLights; ++i) {
  802. Light &light = r.lights[i];
  803. aiLight *ail = mScene->mLights[i] = new aiLight();
  804. switch (light.type) {
  805. case Light::Directional:
  806. ail->mType = aiLightSource_DIRECTIONAL;
  807. break;
  808. case Light::Point:
  809. ail->mType = aiLightSource_POINT;
  810. break;
  811. case Light::Spot:
  812. ail->mType = aiLightSource_SPOT;
  813. break;
  814. }
  815. if (ail->mType != aiLightSource_POINT) {
  816. ail->mDirection = aiVector3D(0.0f, 0.0f, -1.0f);
  817. ail->mUp = aiVector3D(0.0f, 1.0f, 0.0f);
  818. }
  819. vec3 colorWithIntensity = { light.color[0] * light.intensity, light.color[1] * light.intensity, light.color[2] * light.intensity };
  820. CopyValue(colorWithIntensity, ail->mColorAmbient);
  821. CopyValue(colorWithIntensity, ail->mColorDiffuse);
  822. CopyValue(colorWithIntensity, ail->mColorSpecular);
  823. if (ail->mType == aiLightSource_DIRECTIONAL) {
  824. ail->mAttenuationConstant = 1.0;
  825. ail->mAttenuationLinear = 0.0;
  826. ail->mAttenuationQuadratic = 0.0;
  827. } else {
  828. // in PBR attenuation is calculated using inverse square law which can be expressed
  829. // using assimps equation: 1/(att0 + att1 * d + att2 * d*d) with the following parameters
  830. // this is correct equation for the case when range (see
  831. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual)
  832. // is not present. When range is not present it is assumed that it is infinite and so numerator is 1.
  833. // When range is present then numerator might be any value in range [0,1] and then assimps equation
  834. // will not suffice. In this case range is added into metadata in ImportNode function
  835. // and its up to implementation to read it when it wants to
  836. ail->mAttenuationConstant = 0.0;
  837. ail->mAttenuationLinear = 0.0;
  838. ail->mAttenuationQuadratic = 1.0;
  839. }
  840. if (ail->mType == aiLightSource_SPOT) {
  841. ail->mAngleInnerCone = light.innerConeAngle;
  842. ail->mAngleOuterCone = light.outerConeAngle;
  843. }
  844. }
  845. }
  846. static void GetNodeTransform(aiMatrix4x4 &matrix, const glTF2::Node &node) {
  847. if (node.matrix.isPresent) {
  848. CopyValue(node.matrix.value, matrix);
  849. return;
  850. }
  851. if (node.translation.isPresent) {
  852. aiVector3D trans;
  853. CopyValue(node.translation.value, trans);
  854. aiMatrix4x4 t;
  855. aiMatrix4x4::Translation(trans, t);
  856. matrix = matrix * t;
  857. }
  858. if (node.rotation.isPresent) {
  859. aiQuaternion rot;
  860. CopyValue(node.rotation.value, rot);
  861. matrix = matrix * aiMatrix4x4(rot.GetMatrix());
  862. }
  863. if (node.scale.isPresent) {
  864. aiVector3D scal(1.f);
  865. CopyValue(node.scale.value, scal);
  866. aiMatrix4x4 s;
  867. aiMatrix4x4::Scaling(scal, s);
  868. matrix = matrix * s;
  869. }
  870. }
  871. static void BuildVertexWeightMapping(Mesh::Primitive &primitive, std::vector<std::vector<aiVertexWeight>> &map, std::vector<unsigned int>* vertexRemappingTablePtr) {
  872. Mesh::Primitive::Attributes &attr = primitive.attributes;
  873. if (attr.weight.empty() || attr.joint.empty()) {
  874. return;
  875. }
  876. if (attr.weight[0]->count != attr.joint[0]->count) {
  877. return;
  878. }
  879. size_t num_vertices = 0;
  880. struct Weights {
  881. float values[4];
  882. };
  883. Weights **weights = new Weights*[attr.weight.size()];
  884. for (size_t w = 0; w < attr.weight.size(); ++w) {
  885. num_vertices = attr.weight[w]->ExtractData(weights[w], vertexRemappingTablePtr);
  886. }
  887. struct Indices8 {
  888. uint8_t values[4];
  889. };
  890. struct Indices16 {
  891. uint16_t values[4];
  892. };
  893. Indices8 **indices8 = nullptr;
  894. Indices16 **indices16 = nullptr;
  895. if (attr.joint[0]->GetElementSize() == 4) {
  896. indices8 = new Indices8*[attr.joint.size()];
  897. for (size_t j = 0; j < attr.joint.size(); ++j) {
  898. attr.joint[j]->ExtractData(indices8[j], vertexRemappingTablePtr);
  899. }
  900. } else {
  901. indices16 = new Indices16 *[attr.joint.size()];
  902. for (size_t j = 0; j < attr.joint.size(); ++j) {
  903. attr.joint[j]->ExtractData(indices16[j], vertexRemappingTablePtr);
  904. }
  905. }
  906. // No indices are an invalid usecase
  907. if (nullptr == indices8 && nullptr == indices16) {
  908. // Something went completely wrong!
  909. ai_assert(false);
  910. return;
  911. }
  912. for (size_t w = 0; w < attr.weight.size(); ++w) {
  913. for (size_t i = 0; i < num_vertices; ++i) {
  914. for (int j = 0; j < 4; ++j) {
  915. const unsigned int bone = (indices8 != nullptr) ? indices8[w][i].values[j] : indices16[w][i].values[j];
  916. const float weight = weights[w][i].values[j];
  917. if (weight > 0 && bone < map.size()) {
  918. map[bone].reserve(8);
  919. map[bone].emplace_back(static_cast<unsigned int>(i), weight);
  920. }
  921. }
  922. }
  923. }
  924. for (size_t w = 0; w < attr.weight.size(); ++w) {
  925. delete[] weights[w];
  926. if(indices8)
  927. delete[] indices8[w];
  928. if (indices16)
  929. delete[] indices16[w];
  930. }
  931. delete[] weights;
  932. delete[] indices8;
  933. delete[] indices16;
  934. }
  935. static std::string GetNodeName(const Node &node) {
  936. return node.name.empty() ? node.id : node.name;
  937. }
  938. void ParseExtensions(aiMetadata *metadata, const CustomExtension &extension) {
  939. if (extension.mStringValue.isPresent) {
  940. metadata->Add(extension.name, aiString(extension.mStringValue.value));
  941. } else if (extension.mDoubleValue.isPresent) {
  942. metadata->Add(extension.name, extension.mDoubleValue.value);
  943. } else if (extension.mUint64Value.isPresent) {
  944. metadata->Add(extension.name, extension.mUint64Value.value);
  945. } else if (extension.mInt64Value.isPresent) {
  946. metadata->Add(extension.name, static_cast<int32_t>(extension.mInt64Value.value));
  947. } else if (extension.mBoolValue.isPresent) {
  948. metadata->Add(extension.name, extension.mBoolValue.value);
  949. } else if (extension.mValues.isPresent) {
  950. aiMetadata val;
  951. for (auto const &subExtension : extension.mValues.value) {
  952. ParseExtensions(&val, subExtension);
  953. }
  954. metadata->Add(extension.name, val);
  955. }
  956. }
  957. void ParseExtras(aiMetadata* metadata, const Extras& extras) {
  958. for (auto const &value : extras.mValues) {
  959. ParseExtensions(metadata, value);
  960. }
  961. }
  962. aiNode *glTF2Importer::ImportNode(glTF2::Asset &r, glTF2::Ref<glTF2::Node> &ptr) {
  963. Node &node = *ptr;
  964. aiNode *ainode = new aiNode(GetNodeName(node));
  965. try {
  966. if (!node.children.empty()) {
  967. ainode->mNumChildren = unsigned(node.children.size());
  968. ainode->mChildren = new aiNode *[ainode->mNumChildren];
  969. std::fill(ainode->mChildren, ainode->mChildren + ainode->mNumChildren, nullptr);
  970. for (unsigned int i = 0; i < ainode->mNumChildren; ++i) {
  971. aiNode *child = ImportNode(r, node.children[i]);
  972. child->mParent = ainode;
  973. ainode->mChildren[i] = child;
  974. }
  975. }
  976. if (node.customExtensions || node.extras.HasExtras()) {
  977. ainode->mMetaData = new aiMetadata;
  978. if (node.customExtensions) {
  979. ParseExtensions(ainode->mMetaData, node.customExtensions);
  980. }
  981. if (node.extras.HasExtras()) {
  982. ParseExtras(ainode->mMetaData, node.extras);
  983. }
  984. }
  985. GetNodeTransform(ainode->mTransformation, node);
  986. if (!node.meshes.empty()) {
  987. // GLTF files contain at most 1 mesh per node.
  988. if (node.meshes.size() > 1) {
  989. throw DeadlyImportError("GLTF: Invalid input, found ", node.meshes.size(),
  990. " meshes in ", getContextForErrorMessages(node.id, node.name),
  991. ", but only 1 mesh per node allowed.");
  992. }
  993. int mesh_idx = node.meshes[0].GetIndex();
  994. int count = meshOffsets[mesh_idx + 1] - meshOffsets[mesh_idx];
  995. ainode->mNumMeshes = count;
  996. ainode->mMeshes = new unsigned int[count];
  997. if (node.skin) {
  998. for (int primitiveNo = 0; primitiveNo < count; ++primitiveNo) {
  999. unsigned int aiMeshIdx = meshOffsets[mesh_idx] + primitiveNo;
  1000. aiMesh *mesh = mScene->mMeshes[aiMeshIdx];
  1001. unsigned int numBones = static_cast<unsigned int>(node.skin->jointNames.size());
  1002. std::vector<unsigned int> *vertexRemappingTablePtr = mVertexRemappingTables[aiMeshIdx].empty() ? nullptr : &mVertexRemappingTables[aiMeshIdx];
  1003. std::vector<std::vector<aiVertexWeight>> weighting(numBones);
  1004. BuildVertexWeightMapping(node.meshes[0]->primitives[primitiveNo], weighting, vertexRemappingTablePtr);
  1005. mesh->mNumBones = static_cast<unsigned int>(numBones);
  1006. mesh->mBones = new aiBone *[mesh->mNumBones];
  1007. std::fill(mesh->mBones, mesh->mBones + mesh->mNumBones, nullptr);
  1008. // GLTF and Assimp choose to store bone weights differently.
  1009. // GLTF has each vertex specify which bones influence the vertex.
  1010. // Assimp has each bone specify which vertices it has influence over.
  1011. // To convert this data, we first read over the vertex data and pull
  1012. // out the bone-to-vertex mapping. Then, when creating the aiBones,
  1013. // we copy the bone-to-vertex mapping into the bone. This is unfortunate
  1014. // both because it's somewhat slow and because, for many applications,
  1015. // we then need to reconvert the data back into the vertex-to-bone
  1016. // mapping which makes things doubly-slow.
  1017. mat4 *pbindMatrices = nullptr;
  1018. node.skin->inverseBindMatrices->ExtractData(pbindMatrices, nullptr);
  1019. for (uint32_t i = 0; i < numBones; ++i) {
  1020. const std::vector<aiVertexWeight> &weights = weighting[i];
  1021. aiBone *bone = new aiBone();
  1022. Ref<Node> joint = node.skin->jointNames[i];
  1023. if (!joint->name.empty()) {
  1024. bone->mName = joint->name;
  1025. } else {
  1026. // Assimp expects each bone to have a unique name.
  1027. static const std::string kDefaultName = "bone_";
  1028. char postfix[10] = { 0 };
  1029. ASSIMP_itoa10(postfix, i);
  1030. bone->mName = (kDefaultName + postfix);
  1031. }
  1032. GetNodeTransform(bone->mOffsetMatrix, *joint);
  1033. CopyValue(pbindMatrices[i], bone->mOffsetMatrix);
  1034. bone->mNumWeights = static_cast<uint32_t>(weights.size());
  1035. if (bone->mNumWeights > 0) {
  1036. bone->mWeights = new aiVertexWeight[bone->mNumWeights];
  1037. memcpy(bone->mWeights, weights.data(), bone->mNumWeights * sizeof(aiVertexWeight));
  1038. } else {
  1039. // Assimp expects all bones to have at least 1 weight.
  1040. bone->mWeights = new aiVertexWeight[1];
  1041. bone->mNumWeights = 1;
  1042. bone->mWeights->mVertexId = 0;
  1043. bone->mWeights->mWeight = 0.f;
  1044. }
  1045. mesh->mBones[i] = bone;
  1046. }
  1047. if (pbindMatrices) {
  1048. delete[] pbindMatrices;
  1049. }
  1050. }
  1051. }
  1052. int k = 0;
  1053. for (unsigned int j = meshOffsets[mesh_idx]; j < meshOffsets[mesh_idx + 1]; ++j, ++k) {
  1054. ainode->mMeshes[k] = j;
  1055. }
  1056. }
  1057. if (node.camera) {
  1058. mScene->mCameras[node.camera.GetIndex()]->mName = ainode->mName;
  1059. }
  1060. if (node.light) {
  1061. mScene->mLights[node.light.GetIndex()]->mName = ainode->mName;
  1062. // range is optional - see https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  1063. // it is added to meta data of parent node, because there is no other place to put it
  1064. if (node.light->range.isPresent) {
  1065. if (!ainode->mMetaData) {
  1066. ainode->mMetaData = aiMetadata::Alloc(1);
  1067. ainode->mMetaData->Set(0, "PBR_LightRange", node.light->range.value);
  1068. } else {
  1069. ainode->mMetaData->Add("PBR_LightRange", node.light->range.value);
  1070. }
  1071. }
  1072. }
  1073. return ainode;
  1074. } catch (...) {
  1075. delete ainode;
  1076. throw;
  1077. }
  1078. }
  1079. void glTF2Importer::ImportNodes(glTF2::Asset &r) {
  1080. if (!r.scene) {
  1081. throw DeadlyImportError("GLTF: No scene");
  1082. }
  1083. ASSIMP_LOG_DEBUG("Importing nodes");
  1084. std::vector<Ref<Node>> rootNodes = r.scene->nodes;
  1085. // The root nodes
  1086. unsigned int numRootNodes = unsigned(rootNodes.size());
  1087. if (numRootNodes == 1) { // a single root node: use it
  1088. mScene->mRootNode = ImportNode(r, rootNodes[0]);
  1089. } else if (numRootNodes > 1) { // more than one root node: create a fake root
  1090. aiNode *root = mScene->mRootNode = new aiNode("ROOT");
  1091. root->mChildren = new aiNode *[numRootNodes];
  1092. std::fill(root->mChildren, root->mChildren + numRootNodes, nullptr);
  1093. for (unsigned int i = 0; i < numRootNodes; ++i) {
  1094. aiNode *node = ImportNode(r, rootNodes[i]);
  1095. node->mParent = root;
  1096. root->mChildren[root->mNumChildren++] = node;
  1097. }
  1098. } else {
  1099. mScene->mRootNode = new aiNode("ROOT");
  1100. }
  1101. }
  1102. struct AnimationSamplers {
  1103. AnimationSamplers() :
  1104. translation(nullptr),
  1105. rotation(nullptr),
  1106. scale(nullptr),
  1107. weight(nullptr) {
  1108. // empty
  1109. }
  1110. Animation::Sampler *translation;
  1111. Animation::Sampler *rotation;
  1112. Animation::Sampler *scale;
  1113. Animation::Sampler *weight;
  1114. };
  1115. aiNodeAnim *CreateNodeAnim(glTF2::Asset &, Node &node, AnimationSamplers &samplers) {
  1116. aiNodeAnim *anim = new aiNodeAnim();
  1117. try {
  1118. anim->mNodeName = GetNodeName(node);
  1119. static const float kMillisecondsFromSeconds = 1000.f;
  1120. if (samplers.translation && samplers.translation->input && samplers.translation->output) {
  1121. float *times = nullptr;
  1122. samplers.translation->input->ExtractData(times);
  1123. aiVector3D *values = nullptr;
  1124. samplers.translation->output->ExtractData(values);
  1125. anim->mNumPositionKeys = static_cast<uint32_t>(samplers.translation->input->count);
  1126. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  1127. unsigned int ii = (samplers.translation->interpolation == Interpolation_CUBICSPLINE) ? 1 : 0;
  1128. for (unsigned int i = 0; i < anim->mNumPositionKeys; ++i) {
  1129. anim->mPositionKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  1130. anim->mPositionKeys[i].mValue = values[ii];
  1131. ii += (samplers.translation->interpolation == Interpolation_CUBICSPLINE) ? 3 : 1;
  1132. }
  1133. delete[] times;
  1134. delete[] values;
  1135. } else if (node.translation.isPresent) {
  1136. anim->mNumPositionKeys = 1;
  1137. anim->mPositionKeys = new aiVectorKey[anim->mNumPositionKeys];
  1138. anim->mPositionKeys->mTime = 0.f;
  1139. anim->mPositionKeys->mValue.x = node.translation.value[0];
  1140. anim->mPositionKeys->mValue.y = node.translation.value[1];
  1141. anim->mPositionKeys->mValue.z = node.translation.value[2];
  1142. }
  1143. if (samplers.rotation && samplers.rotation->input && samplers.rotation->output) {
  1144. float *times = nullptr;
  1145. samplers.rotation->input->ExtractData(times);
  1146. aiQuaternion *values = nullptr;
  1147. samplers.rotation->output->ExtractData(values);
  1148. anim->mNumRotationKeys = static_cast<uint32_t>(samplers.rotation->input->count);
  1149. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  1150. unsigned int ii = (samplers.rotation->interpolation == Interpolation_CUBICSPLINE) ? 1 : 0;
  1151. for (unsigned int i = 0; i < anim->mNumRotationKeys; ++i) {
  1152. anim->mRotationKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  1153. anim->mRotationKeys[i].mValue.x = values[ii].w;
  1154. anim->mRotationKeys[i].mValue.y = values[ii].x;
  1155. anim->mRotationKeys[i].mValue.z = values[ii].y;
  1156. anim->mRotationKeys[i].mValue.w = values[ii].z;
  1157. ii += (samplers.rotation->interpolation == Interpolation_CUBICSPLINE) ? 3 : 1;
  1158. }
  1159. delete[] times;
  1160. delete[] values;
  1161. } else if (node.rotation.isPresent) {
  1162. anim->mNumRotationKeys = 1;
  1163. anim->mRotationKeys = new aiQuatKey[anim->mNumRotationKeys];
  1164. anim->mRotationKeys->mTime = 0.f;
  1165. anim->mRotationKeys->mValue.x = node.rotation.value[0];
  1166. anim->mRotationKeys->mValue.y = node.rotation.value[1];
  1167. anim->mRotationKeys->mValue.z = node.rotation.value[2];
  1168. anim->mRotationKeys->mValue.w = node.rotation.value[3];
  1169. }
  1170. if (samplers.scale && samplers.scale->input && samplers.scale->output) {
  1171. float *times = nullptr;
  1172. samplers.scale->input->ExtractData(times);
  1173. aiVector3D *values = nullptr;
  1174. samplers.scale->output->ExtractData(values);
  1175. anim->mNumScalingKeys = static_cast<uint32_t>(samplers.scale->input->count);
  1176. anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys];
  1177. unsigned int ii = (samplers.scale->interpolation == Interpolation_CUBICSPLINE) ? 1 : 0;
  1178. for (unsigned int i = 0; i < anim->mNumScalingKeys; ++i) {
  1179. anim->mScalingKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  1180. anim->mScalingKeys[i].mValue = values[ii];
  1181. ii += (samplers.scale->interpolation == Interpolation_CUBICSPLINE) ? 3 : 1;
  1182. }
  1183. delete[] times;
  1184. delete[] values;
  1185. } else if (node.scale.isPresent) {
  1186. anim->mNumScalingKeys = 1;
  1187. anim->mScalingKeys = new aiVectorKey[anim->mNumScalingKeys];
  1188. anim->mScalingKeys->mTime = 0.f;
  1189. anim->mScalingKeys->mValue.x = node.scale.value[0];
  1190. anim->mScalingKeys->mValue.y = node.scale.value[1];
  1191. anim->mScalingKeys->mValue.z = node.scale.value[2];
  1192. }
  1193. return anim;
  1194. } catch (...) {
  1195. delete anim;
  1196. throw;
  1197. }
  1198. }
  1199. aiMeshMorphAnim *CreateMeshMorphAnim(glTF2::Asset &, Node &node, AnimationSamplers &samplers) {
  1200. auto *anim = new aiMeshMorphAnim();
  1201. try {
  1202. anim->mName = GetNodeName(node);
  1203. static const float kMillisecondsFromSeconds = 1000.f;
  1204. if (samplers.weight && samplers.weight->input && samplers.weight->output) {
  1205. float *times = nullptr;
  1206. samplers.weight->input->ExtractData(times);
  1207. float *values = nullptr;
  1208. samplers.weight->output->ExtractData(values);
  1209. anim->mNumKeys = static_cast<uint32_t>(samplers.weight->input->count);
  1210. // for Interpolation_CUBICSPLINE can have more outputs
  1211. const unsigned int weightStride = (unsigned int)samplers.weight->output->count / anim->mNumKeys;
  1212. const unsigned int numMorphs = (samplers.weight->interpolation == Interpolation_CUBICSPLINE) ? weightStride - 2 : weightStride;
  1213. anim->mKeys = new aiMeshMorphKey[anim->mNumKeys];
  1214. unsigned int ii = (samplers.weight->interpolation == Interpolation_CUBICSPLINE) ? 1 : 0;
  1215. for (unsigned int i = 0u; i < anim->mNumKeys; ++i) {
  1216. unsigned int k = weightStride * i + ii;
  1217. anim->mKeys[i].mTime = times[i] * kMillisecondsFromSeconds;
  1218. anim->mKeys[i].mNumValuesAndWeights = numMorphs;
  1219. anim->mKeys[i].mValues = new unsigned int[numMorphs];
  1220. anim->mKeys[i].mWeights = new double[numMorphs];
  1221. for (unsigned int j = 0u; j < numMorphs; ++j, ++k) {
  1222. anim->mKeys[i].mValues[j] = j;
  1223. anim->mKeys[i].mWeights[j] = (0.f > values[k]) ? 0.f : values[k];
  1224. }
  1225. }
  1226. delete[] times;
  1227. delete[] values;
  1228. }
  1229. return anim;
  1230. } catch (...) {
  1231. delete anim;
  1232. throw;
  1233. }
  1234. }
  1235. std::unordered_map<unsigned int, AnimationSamplers> GatherSamplers(Animation &anim) {
  1236. std::unordered_map<unsigned int, AnimationSamplers> samplers;
  1237. for (unsigned int c = 0; c < anim.channels.size(); ++c) {
  1238. Animation::Channel &channel = anim.channels[c];
  1239. if (channel.sampler < 0 || channel.sampler >= static_cast<int>(anim.samplers.size())) {
  1240. continue;
  1241. }
  1242. auto &animsampler = anim.samplers[channel.sampler];
  1243. if (!animsampler.input) {
  1244. ASSIMP_LOG_WARN("Animation ", anim.name, ": Missing sampler input. Skipping.");
  1245. continue;
  1246. }
  1247. if (!animsampler.output) {
  1248. ASSIMP_LOG_WARN("Animation ", anim.name, ": Missing sampler output. Skipping.");
  1249. continue;
  1250. }
  1251. if (animsampler.input->count > animsampler.output->count) {
  1252. ASSIMP_LOG_WARN("Animation ", anim.name, ": Number of keyframes in sampler input ", animsampler.input->count,
  1253. " exceeds number of keyframes in sampler output ", animsampler.output->count);
  1254. continue;
  1255. }
  1256. const unsigned int node_index = channel.target.node.GetIndex();
  1257. AnimationSamplers &sampler = samplers[node_index];
  1258. if (channel.target.path == AnimationPath_TRANSLATION) {
  1259. sampler.translation = &anim.samplers[channel.sampler];
  1260. } else if (channel.target.path == AnimationPath_ROTATION) {
  1261. sampler.rotation = &anim.samplers[channel.sampler];
  1262. } else if (channel.target.path == AnimationPath_SCALE) {
  1263. sampler.scale = &anim.samplers[channel.sampler];
  1264. } else if (channel.target.path == AnimationPath_WEIGHTS) {
  1265. sampler.weight = &anim.samplers[channel.sampler];
  1266. }
  1267. }
  1268. return samplers;
  1269. }
  1270. void glTF2Importer::ImportAnimations(glTF2::Asset &r) {
  1271. if (!r.scene) return;
  1272. const unsigned numAnimations = r.animations.Size();
  1273. ASSIMP_LOG_DEBUG("Importing ", numAnimations, " animations");
  1274. mScene->mNumAnimations = numAnimations;
  1275. if (mScene->mNumAnimations == 0) {
  1276. return;
  1277. }
  1278. mScene->mAnimations = new aiAnimation *[numAnimations];
  1279. std::fill(mScene->mAnimations, mScene->mAnimations + numAnimations, nullptr);
  1280. for (unsigned int i = 0; i < numAnimations; ++i) {
  1281. aiAnimation *ai_anim = mScene->mAnimations[i] = new aiAnimation();
  1282. Animation &anim = r.animations[i];
  1283. ai_anim->mName = anim.name;
  1284. ai_anim->mDuration = 0;
  1285. ai_anim->mTicksPerSecond = 0;
  1286. std::unordered_map<unsigned int, AnimationSamplers> samplers = GatherSamplers(anim);
  1287. uint32_t numChannels = 0u;
  1288. uint32_t numMorphMeshChannels = 0u;
  1289. for (auto &iter : samplers) {
  1290. if ((nullptr != iter.second.rotation) || (nullptr != iter.second.scale) || (nullptr != iter.second.translation)) {
  1291. ++numChannels;
  1292. }
  1293. if (nullptr != iter.second.weight) {
  1294. ++numMorphMeshChannels;
  1295. }
  1296. }
  1297. ai_anim->mNumChannels = numChannels;
  1298. if (ai_anim->mNumChannels > 0) {
  1299. ai_anim->mChannels = new aiNodeAnim *[ai_anim->mNumChannels];
  1300. std::fill(ai_anim->mChannels, ai_anim->mChannels + ai_anim->mNumChannels, nullptr);
  1301. int j = 0;
  1302. for (auto &iter : samplers) {
  1303. if ((nullptr != iter.second.rotation) || (nullptr != iter.second.scale) || (nullptr != iter.second.translation)) {
  1304. ai_anim->mChannels[j] = CreateNodeAnim(r, r.nodes[iter.first], iter.second);
  1305. ++j;
  1306. }
  1307. }
  1308. }
  1309. ai_anim->mNumMorphMeshChannels = numMorphMeshChannels;
  1310. if (ai_anim->mNumMorphMeshChannels > 0) {
  1311. ai_anim->mMorphMeshChannels = new aiMeshMorphAnim *[ai_anim->mNumMorphMeshChannels];
  1312. std::fill(ai_anim->mMorphMeshChannels, ai_anim->mMorphMeshChannels + ai_anim->mNumMorphMeshChannels, nullptr);
  1313. int j = 0;
  1314. for (auto &iter : samplers) {
  1315. if (nullptr != iter.second.weight) {
  1316. ai_anim->mMorphMeshChannels[j] = CreateMeshMorphAnim(r, r.nodes[iter.first], iter.second);
  1317. ++j;
  1318. }
  1319. }
  1320. }
  1321. // Use the latest key-frame for the duration of the animation
  1322. double maxDuration = 0;
  1323. unsigned int maxNumberOfKeys = 0;
  1324. for (unsigned int j = 0; j < ai_anim->mNumChannels; ++j) {
  1325. auto chan = ai_anim->mChannels[j];
  1326. if (chan->mNumPositionKeys) {
  1327. auto lastPosKey = chan->mPositionKeys[chan->mNumPositionKeys - 1];
  1328. if (lastPosKey.mTime > maxDuration) {
  1329. maxDuration = lastPosKey.mTime;
  1330. }
  1331. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumPositionKeys);
  1332. }
  1333. if (chan->mNumRotationKeys) {
  1334. auto lastRotKey = chan->mRotationKeys[chan->mNumRotationKeys - 1];
  1335. if (lastRotKey.mTime > maxDuration) {
  1336. maxDuration = lastRotKey.mTime;
  1337. }
  1338. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumRotationKeys);
  1339. }
  1340. if (chan->mNumScalingKeys) {
  1341. auto lastScaleKey = chan->mScalingKeys[chan->mNumScalingKeys - 1];
  1342. if (lastScaleKey.mTime > maxDuration) {
  1343. maxDuration = lastScaleKey.mTime;
  1344. }
  1345. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumScalingKeys);
  1346. }
  1347. }
  1348. for (unsigned int j = 0; j < ai_anim->mNumMorphMeshChannels; ++j) {
  1349. const auto *const chan = ai_anim->mMorphMeshChannels[j];
  1350. if (0u != chan->mNumKeys) {
  1351. const auto &lastKey = chan->mKeys[chan->mNumKeys - 1u];
  1352. if (lastKey.mTime > maxDuration) {
  1353. maxDuration = lastKey.mTime;
  1354. }
  1355. maxNumberOfKeys = std::max(maxNumberOfKeys, chan->mNumKeys);
  1356. }
  1357. }
  1358. ai_anim->mDuration = maxDuration;
  1359. ai_anim->mTicksPerSecond = 1000.0;
  1360. }
  1361. }
  1362. static unsigned int countEmbeddedTextures(glTF2::Asset &r) {
  1363. unsigned int numEmbeddedTexs = 0;
  1364. for (size_t i = 0; i < r.images.Size(); ++i) {
  1365. if (r.images[i].HasData()) {
  1366. numEmbeddedTexs += 1;
  1367. }
  1368. }
  1369. return numEmbeddedTexs;
  1370. }
  1371. void glTF2Importer::ImportEmbeddedTextures(glTF2::Asset &r) {
  1372. mEmbeddedTexIdxs.resize(r.images.Size(), -1);
  1373. const unsigned int numEmbeddedTexs = countEmbeddedTextures(r);
  1374. if (numEmbeddedTexs == 0) {
  1375. return;
  1376. }
  1377. ASSIMP_LOG_DEBUG("Importing ", numEmbeddedTexs, " embedded textures");
  1378. mScene->mTextures = new aiTexture *[numEmbeddedTexs];
  1379. std::fill(mScene->mTextures, mScene->mTextures + numEmbeddedTexs, nullptr);
  1380. // Add the embedded textures
  1381. for (size_t i = 0; i < r.images.Size(); ++i) {
  1382. Image &img = r.images[i];
  1383. if (!img.HasData()) {
  1384. continue;
  1385. }
  1386. int idx = mScene->mNumTextures++;
  1387. mEmbeddedTexIdxs[i] = idx;
  1388. aiTexture *tex = mScene->mTextures[idx] = new aiTexture();
  1389. size_t length = img.GetDataLength();
  1390. void *data = img.StealData();
  1391. tex->mFilename = img.name;
  1392. tex->mWidth = static_cast<unsigned int>(length);
  1393. tex->mHeight = 0;
  1394. tex->pcData = reinterpret_cast<aiTexel *>(data);
  1395. if (!img.mimeType.empty()) {
  1396. const char *ext = strchr(img.mimeType.c_str(), '/') + 1;
  1397. if (ext) {
  1398. if (strncmp(ext, "jpeg", 4) == 0) {
  1399. ext = "jpg";
  1400. } else if (strcmp(ext, "ktx2") == 0) { // basisu: ktx remains
  1401. ext = "kx2";
  1402. } else if (strcmp(ext, "basis") == 0) { // basisu
  1403. ext = "bu";
  1404. }
  1405. size_t len = strlen(ext);
  1406. if (len > 3) len = 3;
  1407. tex->achFormatHint[3] = '\0';
  1408. memcpy(tex->achFormatHint, ext, len);
  1409. }
  1410. }
  1411. }
  1412. }
  1413. void glTF2Importer::ImportCommonMetadata(glTF2::Asset &a) {
  1414. ASSIMP_LOG_DEBUG("Importing metadata");
  1415. ai_assert(mScene->mMetaData == nullptr);
  1416. const bool hasVersion = !a.asset.version.empty();
  1417. const bool hasGenerator = !a.asset.generator.empty();
  1418. const bool hasCopyright = !a.asset.copyright.empty();
  1419. const bool hasSceneMetadata = a.scene->customExtensions;
  1420. if (hasVersion || hasGenerator || hasCopyright || hasSceneMetadata) {
  1421. mScene->mMetaData = new aiMetadata;
  1422. if (hasVersion) {
  1423. mScene->mMetaData->Add(AI_METADATA_SOURCE_FORMAT_VERSION, aiString(a.asset.version));
  1424. }
  1425. if (hasGenerator) {
  1426. mScene->mMetaData->Add(AI_METADATA_SOURCE_GENERATOR, aiString(a.asset.generator));
  1427. }
  1428. if (hasCopyright) {
  1429. mScene->mMetaData->Add(AI_METADATA_SOURCE_COPYRIGHT, aiString(a.asset.copyright));
  1430. }
  1431. if (hasSceneMetadata) {
  1432. ParseExtensions(mScene->mMetaData, a.scene->customExtensions);
  1433. }
  1434. }
  1435. }
  1436. void glTF2Importer::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) {
  1437. ASSIMP_LOG_DEBUG("Reading GLTF2 file");
  1438. // clean all member arrays
  1439. meshOffsets.clear();
  1440. mVertexRemappingTables.clear();
  1441. mEmbeddedTexIdxs.clear();
  1442. this->mScene = pScene;
  1443. // read the asset file
  1444. glTF2::Asset asset(pIOHandler, static_cast<rapidjson::IRemoteSchemaDocumentProvider *>(mSchemaDocumentProvider));
  1445. asset.Load(pFile,
  1446. CheckMagicToken(
  1447. pIOHandler, pFile, AI_GLB_MAGIC_NUMBER, 1, 0,
  1448. static_cast<unsigned int>(strlen(AI_GLB_MAGIC_NUMBER))));
  1449. if (asset.scene) {
  1450. pScene->mName = asset.scene->name;
  1451. }
  1452. // Copy the data out
  1453. ImportEmbeddedTextures(asset);
  1454. ImportMaterials(asset);
  1455. ImportMeshes(asset);
  1456. ImportCameras(asset);
  1457. ImportLights(asset);
  1458. ImportNodes(asset);
  1459. ImportAnimations(asset);
  1460. ImportCommonMetadata(asset);
  1461. if (pScene->mNumMeshes == 0) {
  1462. pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  1463. }
  1464. }
  1465. void glTF2Importer::SetupProperties(const Importer *pImp) {
  1466. mSchemaDocumentProvider = static_cast<rapidjson::IRemoteSchemaDocumentProvider *>(pImp->GetPropertyPointer(AI_CONFIG_IMPORT_SCHEMA_DOCUMENT_PROVIDER));
  1467. }
  1468. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER