glTF2Exporter.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2021, 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_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER
  35. #include "AssetLib/glTF2/glTF2Exporter.h"
  36. #include "AssetLib/glTF2/glTF2AssetWriter.h"
  37. #include "PostProcessing/SplitLargeMeshes.h"
  38. #include <assimp/commonMetaData.h>
  39. #include <assimp/Exceptional.h>
  40. #include <assimp/StringComparison.h>
  41. #include <assimp/ByteSwapper.h>
  42. #include <assimp/SceneCombiner.h>
  43. #include <assimp/version.h>
  44. #include <assimp/IOSystem.hpp>
  45. #include <assimp/Exporter.hpp>
  46. #include <assimp/material.h>
  47. #include <assimp/scene.h>
  48. // Header files, standard library.
  49. #include <memory>
  50. #include <limits>
  51. #include <inttypes.h>
  52. using namespace rapidjson;
  53. using namespace Assimp;
  54. using namespace glTF2;
  55. namespace Assimp {
  56. // ------------------------------------------------------------------------------------------------
  57. // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
  58. void ExportSceneGLTF2(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  59. {
  60. // invoke the exporter
  61. glTF2Exporter exporter(pFile, pIOSystem, pScene, pProperties, false);
  62. }
  63. // ------------------------------------------------------------------------------------------------
  64. // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
  65. void ExportSceneGLB2(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  66. {
  67. // invoke the exporter
  68. glTF2Exporter exporter(pFile, pIOSystem, pScene, pProperties, true);
  69. }
  70. } // end of namespace Assimp
  71. glTF2Exporter::glTF2Exporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
  72. const ExportProperties* pProperties, bool isBinary)
  73. : mFilename(filename)
  74. , mIOSystem(pIOSystem)
  75. , mScene(pScene)
  76. , mProperties(pProperties)
  77. , mAsset(new Asset(pIOSystem))
  78. {
  79. // Always on as our triangulation process is aware of this type of encoding
  80. mAsset->extensionsUsed.FB_ngon_encoding = true;
  81. if (isBinary) {
  82. mAsset->SetAsBinary();
  83. }
  84. ExportMetadata();
  85. ExportMaterials();
  86. if (mScene->mRootNode) {
  87. ExportNodeHierarchy(mScene->mRootNode);
  88. }
  89. ExportMeshes();
  90. MergeMeshes();
  91. ExportScene();
  92. ExportAnimations();
  93. // export extras
  94. if(mProperties->HasPropertyCallback("extras"))
  95. {
  96. std::function<void*(void*)> ExportExtras = mProperties->GetPropertyCallback("extras");
  97. mAsset->extras = (rapidjson::Value*)ExportExtras(0);
  98. }
  99. AssetWriter writer(*mAsset);
  100. if (isBinary) {
  101. writer.WriteGLBFile(filename);
  102. } else {
  103. writer.WriteFile(filename);
  104. }
  105. }
  106. glTF2Exporter::~glTF2Exporter() {
  107. // empty
  108. }
  109. /*
  110. * Copy a 4x4 matrix from struct aiMatrix to typedef mat4.
  111. * Also converts from row-major to column-major storage.
  112. */
  113. static void CopyValue(const aiMatrix4x4& v, mat4& o) {
  114. o[ 0] = v.a1; o[ 1] = v.b1; o[ 2] = v.c1; o[ 3] = v.d1;
  115. o[ 4] = v.a2; o[ 5] = v.b2; o[ 6] = v.c2; o[ 7] = v.d2;
  116. o[ 8] = v.a3; o[ 9] = v.b3; o[10] = v.c3; o[11] = v.d3;
  117. o[12] = v.a4; o[13] = v.b4; o[14] = v.c4; o[15] = v.d4;
  118. }
  119. static void CopyValue(const aiMatrix4x4& v, aiMatrix4x4& o) {
  120. memcpy(&o, &v, sizeof(aiMatrix4x4));
  121. }
  122. static void IdentityMatrix4(mat4& o) {
  123. o[ 0] = 1; o[ 1] = 0; o[ 2] = 0; o[ 3] = 0;
  124. o[ 4] = 0; o[ 5] = 1; o[ 6] = 0; o[ 7] = 0;
  125. o[ 8] = 0; o[ 9] = 0; o[10] = 1; o[11] = 0;
  126. o[12] = 0; o[13] = 0; o[14] = 0; o[15] = 1;
  127. }
  128. template<typename T>
  129. void SetAccessorRange(Ref<Accessor> acc, void* data, size_t count,
  130. unsigned int numCompsIn, unsigned int numCompsOut)
  131. {
  132. ai_assert(numCompsOut <= numCompsIn);
  133. // Allocate and initialize with large values.
  134. for (unsigned int i = 0 ; i < numCompsOut ; i++) {
  135. acc->min.push_back( std::numeric_limits<double>::max());
  136. acc->max.push_back(-std::numeric_limits<double>::max());
  137. }
  138. size_t totalComps = count * numCompsIn;
  139. T* buffer_ptr = static_cast<T*>(data);
  140. T* buffer_end = buffer_ptr + totalComps;
  141. // Search and set extreme values.
  142. for (; buffer_ptr < buffer_end ; buffer_ptr += numCompsIn) {
  143. for (unsigned int j = 0 ; j < numCompsOut ; j++) {
  144. double valueTmp = buffer_ptr[j];
  145. // Gracefully tolerate rogue NaN's in buffer data
  146. // Any NaNs/Infs introduced in accessor bounds will end up in
  147. // document and prevent rapidjson from writing out valid JSON
  148. if (!std::isfinite(valueTmp)) {
  149. continue;
  150. }
  151. if (valueTmp < acc->min[j]) {
  152. acc->min[j] = valueTmp;
  153. }
  154. if (valueTmp > acc->max[j]) {
  155. acc->max[j] = valueTmp;
  156. }
  157. }
  158. }
  159. }
  160. inline void SetAccessorRange(ComponentType compType, Ref<Accessor> acc, void* data,
  161. size_t count, unsigned int numCompsIn, unsigned int numCompsOut)
  162. {
  163. switch (compType) {
  164. case ComponentType_SHORT:
  165. SetAccessorRange<short>(acc, data, count, numCompsIn, numCompsOut);
  166. return;
  167. case ComponentType_UNSIGNED_SHORT:
  168. SetAccessorRange<unsigned short>(acc, data, count, numCompsIn, numCompsOut);
  169. return;
  170. case ComponentType_UNSIGNED_INT:
  171. SetAccessorRange<unsigned int>(acc, data, count, numCompsIn, numCompsOut);
  172. return;
  173. case ComponentType_FLOAT:
  174. SetAccessorRange<float>(acc, data, count, numCompsIn, numCompsOut);
  175. return;
  176. case ComponentType_BYTE:
  177. SetAccessorRange<int8_t>(acc, data, count, numCompsIn, numCompsOut);
  178. return;
  179. case ComponentType_UNSIGNED_BYTE:
  180. SetAccessorRange<uint8_t>(acc, data, count, numCompsIn, numCompsOut);
  181. return;
  182. }
  183. }
  184. // compute the (data-dataBase), store the non-zero data items
  185. template <typename T>
  186. size_t NZDiff(void *data, void *dataBase, size_t count, unsigned int numCompsIn, unsigned int numCompsOut, void *&outputNZDiff, void *&outputNZIdx) {
  187. std::vector<T> vNZDiff;
  188. std::vector<unsigned short> vNZIdx;
  189. size_t totalComps = count * numCompsIn;
  190. T *bufferData_ptr = static_cast<T *>(data);
  191. T *bufferData_end = bufferData_ptr + totalComps;
  192. T *bufferBase_ptr = static_cast<T *>(dataBase);
  193. // Search and set extreme values.
  194. for (short idx = 0; bufferData_ptr < bufferData_end; idx += 1, bufferData_ptr += numCompsIn) {
  195. bool bNonZero = false;
  196. //for the data, check any component Non Zero
  197. for (unsigned int j = 0; j < numCompsOut; j++) {
  198. double valueData = bufferData_ptr[j];
  199. double valueBase = bufferBase_ptr ? bufferBase_ptr[j] : 0;
  200. if ((valueData - valueBase) != 0) {
  201. bNonZero = true;
  202. break;
  203. }
  204. }
  205. //all zeros, continue
  206. if (!bNonZero)
  207. continue;
  208. //non zero, store the data
  209. for (unsigned int j = 0; j < numCompsOut; j++) {
  210. T valueData = bufferData_ptr[j];
  211. T valueBase = bufferBase_ptr ? bufferBase_ptr[j] : 0;
  212. vNZDiff.push_back(valueData - valueBase);
  213. }
  214. vNZIdx.push_back(idx);
  215. }
  216. //avoid all-0, put 1 item
  217. if (vNZDiff.size() == 0) {
  218. for (unsigned int j = 0; j < numCompsOut; j++)
  219. vNZDiff.push_back(0);
  220. vNZIdx.push_back(0);
  221. }
  222. //process data
  223. outputNZDiff = new T[vNZDiff.size()];
  224. memcpy(outputNZDiff, vNZDiff.data(), vNZDiff.size() * sizeof(T));
  225. outputNZIdx = new unsigned short[vNZIdx.size()];
  226. memcpy(outputNZIdx, vNZIdx.data(), vNZIdx.size() * sizeof(unsigned short));
  227. return vNZIdx.size();
  228. }
  229. inline size_t NZDiff(ComponentType compType, void *data, void *dataBase, size_t count, unsigned int numCompsIn, unsigned int numCompsOut, void *&nzDiff, void *&nzIdx) {
  230. switch (compType) {
  231. case ComponentType_SHORT:
  232. return NZDiff<short>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  233. case ComponentType_UNSIGNED_SHORT:
  234. return NZDiff<unsigned short>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  235. case ComponentType_UNSIGNED_INT:
  236. return NZDiff<unsigned int>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  237. case ComponentType_FLOAT:
  238. return NZDiff<float>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  239. case ComponentType_BYTE:
  240. return NZDiff<int8_t>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  241. case ComponentType_UNSIGNED_BYTE:
  242. return NZDiff<uint8_t>(data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  243. }
  244. return 0;
  245. }
  246. inline Ref<Accessor> ExportDataSparse(Asset &a, std::string &meshName, Ref<Buffer> &buffer,
  247. size_t count, void *data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, BufferViewTarget target = BufferViewTarget_NONE, void *dataBase = 0) {
  248. if (!count || !data) {
  249. return Ref<Accessor>();
  250. }
  251. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  252. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  253. unsigned int bytesPerComp = ComponentTypeSize(compType);
  254. // accessor
  255. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  256. // if there is a basic data vector
  257. if (dataBase) {
  258. size_t base_offset = buffer->byteLength;
  259. size_t base_padding = base_offset % bytesPerComp;
  260. base_offset += base_padding;
  261. size_t base_length = count * numCompsOut * bytesPerComp;
  262. buffer->Grow(base_length + base_padding);
  263. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  264. bv->buffer = buffer;
  265. bv->byteOffset = base_offset;
  266. bv->byteLength = base_length; //! The target that the WebGL buffer should be bound to.
  267. bv->byteStride = 0;
  268. bv->target = target;
  269. acc->bufferView = bv;
  270. acc->WriteData(count, dataBase, numCompsIn * bytesPerComp);
  271. }
  272. acc->byteOffset = 0;
  273. acc->componentType = compType;
  274. acc->count = count;
  275. acc->type = typeOut;
  276. if (data) {
  277. void *nzDiff = 0, *nzIdx = 0;
  278. size_t nzCount = NZDiff(compType, data, dataBase, count, numCompsIn, numCompsOut, nzDiff, nzIdx);
  279. acc->sparse.reset(new Accessor::Sparse);
  280. acc->sparse->count = nzCount;
  281. //indices
  282. unsigned int bytesPerIdx = sizeof(unsigned short);
  283. size_t indices_offset = buffer->byteLength;
  284. size_t indices_padding = indices_offset % bytesPerIdx;
  285. indices_offset += indices_padding;
  286. size_t indices_length = nzCount * 1 * bytesPerIdx;
  287. buffer->Grow(indices_length + indices_padding);
  288. Ref<BufferView> indicesBV = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  289. indicesBV->buffer = buffer;
  290. indicesBV->byteOffset = indices_offset;
  291. indicesBV->byteLength = indices_length;
  292. indicesBV->byteStride = 0;
  293. acc->sparse->indices = indicesBV;
  294. acc->sparse->indicesType = ComponentType_UNSIGNED_SHORT;
  295. acc->sparse->indicesByteOffset = 0;
  296. acc->WriteSparseIndices(nzCount, nzIdx, 1 * bytesPerIdx);
  297. //values
  298. size_t values_offset = buffer->byteLength;
  299. size_t values_padding = values_offset % bytesPerComp;
  300. values_offset += values_padding;
  301. size_t values_length = nzCount * numCompsOut * bytesPerComp;
  302. buffer->Grow(values_length + values_padding);
  303. Ref<BufferView> valuesBV = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  304. valuesBV->buffer = buffer;
  305. valuesBV->byteOffset = values_offset;
  306. valuesBV->byteLength = values_length;
  307. valuesBV->byteStride = 0;
  308. acc->sparse->values = valuesBV;
  309. acc->sparse->valuesByteOffset = 0;
  310. acc->WriteSparseValues(nzCount, nzDiff, numCompsIn * bytesPerComp);
  311. //clear
  312. delete[] (char*)nzDiff;
  313. delete[] (char*)nzIdx;
  314. }
  315. return acc;
  316. }
  317. inline Ref<Accessor> ExportData(Asset& a, std::string& meshName, Ref<Buffer>& buffer,
  318. size_t count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, BufferViewTarget target = BufferViewTarget_NONE)
  319. {
  320. if (!count || !data) {
  321. return Ref<Accessor>();
  322. }
  323. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  324. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  325. unsigned int bytesPerComp = ComponentTypeSize(compType);
  326. size_t offset = buffer->byteLength;
  327. // make sure offset is correctly byte-aligned, as required by spec
  328. size_t padding = offset % bytesPerComp;
  329. offset += padding;
  330. size_t length = count * numCompsOut * bytesPerComp;
  331. buffer->Grow(length + padding);
  332. // bufferView
  333. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  334. bv->buffer = buffer;
  335. bv->byteOffset = offset;
  336. bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
  337. bv->byteStride = 0;
  338. bv->target = target;
  339. // accessor
  340. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  341. acc->bufferView = bv;
  342. acc->byteOffset = 0;
  343. acc->componentType = compType;
  344. acc->count = count;
  345. acc->type = typeOut;
  346. // calculate min and max values
  347. SetAccessorRange(compType, acc, data, count, numCompsIn, numCompsOut);
  348. // copy the data
  349. acc->WriteData(count, data, numCompsIn*bytesPerComp);
  350. return acc;
  351. }
  352. inline void SetSamplerWrap(SamplerWrap& wrap, aiTextureMapMode map)
  353. {
  354. switch (map) {
  355. case aiTextureMapMode_Clamp:
  356. wrap = SamplerWrap::Clamp_To_Edge;
  357. break;
  358. case aiTextureMapMode_Mirror:
  359. wrap = SamplerWrap::Mirrored_Repeat;
  360. break;
  361. case aiTextureMapMode_Wrap:
  362. case aiTextureMapMode_Decal:
  363. default:
  364. wrap = SamplerWrap::Repeat;
  365. break;
  366. };
  367. }
  368. void glTF2Exporter::GetTexSampler(const aiMaterial& mat, Ref<Texture> texture, aiTextureType tt, unsigned int slot)
  369. {
  370. aiString aId;
  371. std::string id;
  372. if (aiGetMaterialString(&mat, AI_MATKEY_GLTF_MAPPINGID(tt, slot), &aId) == AI_SUCCESS) {
  373. id = aId.C_Str();
  374. }
  375. if (Ref<Sampler> ref = mAsset->samplers.Get(id.c_str())) {
  376. texture->sampler = ref;
  377. } else {
  378. id = mAsset->FindUniqueID(id, "sampler");
  379. texture->sampler = mAsset->samplers.Create(id.c_str());
  380. aiTextureMapMode mapU, mapV;
  381. SamplerMagFilter filterMag;
  382. SamplerMinFilter filterMin;
  383. if (aiGetMaterialInteger(&mat, AI_MATKEY_MAPPINGMODE_U(tt, slot), (int*)&mapU) == AI_SUCCESS) {
  384. SetSamplerWrap(texture->sampler->wrapS, mapU);
  385. }
  386. if (aiGetMaterialInteger(&mat, AI_MATKEY_MAPPINGMODE_V(tt, slot), (int*)&mapV) == AI_SUCCESS) {
  387. SetSamplerWrap(texture->sampler->wrapT, mapV);
  388. }
  389. if (aiGetMaterialInteger(&mat, AI_MATKEY_GLTF_MAPPINGFILTER_MAG(tt, slot), (int*)&filterMag) == AI_SUCCESS) {
  390. texture->sampler->magFilter = filterMag;
  391. }
  392. if (aiGetMaterialInteger(&mat, AI_MATKEY_GLTF_MAPPINGFILTER_MIN(tt, slot), (int*)&filterMin) == AI_SUCCESS) {
  393. texture->sampler->minFilter = filterMin;
  394. }
  395. aiString name;
  396. if (aiGetMaterialString(&mat, AI_MATKEY_GLTF_MAPPINGNAME(tt, slot), &name) == AI_SUCCESS) {
  397. texture->sampler->name = name.C_Str();
  398. }
  399. }
  400. }
  401. void glTF2Exporter::GetMatTexProp(const aiMaterial& mat, unsigned int& prop, const char* propName, aiTextureType tt, unsigned int slot)
  402. {
  403. std::string textureKey = std::string(_AI_MATKEY_TEXTURE_BASE) + "." + propName;
  404. mat.Get(textureKey.c_str(), tt, slot, prop);
  405. }
  406. void glTF2Exporter::GetMatTexProp(const aiMaterial& mat, float& prop, const char* propName, aiTextureType tt, unsigned int slot)
  407. {
  408. std::string textureKey = std::string(_AI_MATKEY_TEXTURE_BASE) + "." + propName;
  409. mat.Get(textureKey.c_str(), tt, slot, prop);
  410. }
  411. void glTF2Exporter::GetMatTex(const aiMaterial& mat, Ref<Texture>& texture, unsigned int &texCoord, aiTextureType tt, unsigned int slot = 0)
  412. {
  413. if (mat.GetTextureCount(tt) > 0) {
  414. aiString tex;
  415. // Read texcoord (UV map index)
  416. mat.Get(AI_MATKEY_UVWSRC(tt, slot), texCoord);
  417. if (mat.Get(AI_MATKEY_TEXTURE(tt, slot), tex) == AI_SUCCESS) {
  418. std::string path = tex.C_Str();
  419. if (path.size() > 0) {
  420. std::map<std::string, unsigned int>::iterator it = mTexturesByPath.find(path);
  421. if (it != mTexturesByPath.end()) {
  422. texture = mAsset->textures.Get(it->second);
  423. }
  424. bool useBasisUniversal = false;
  425. if (!texture) {
  426. std::string texId = mAsset->FindUniqueID("", "texture");
  427. texture = mAsset->textures.Create(texId);
  428. mTexturesByPath[path] = texture.GetIndex();
  429. std::string imgId = mAsset->FindUniqueID("", "image");
  430. texture->source = mAsset->images.Create(imgId);
  431. const aiTexture* curTex = mScene->GetEmbeddedTexture(path.c_str());
  432. if (curTex != nullptr) { // embedded
  433. texture->source->name = curTex->mFilename.C_Str();
  434. //basisu: embedded ktx2, bu
  435. if (curTex->achFormatHint[0]) {
  436. std::string mimeType = "image/";
  437. if(memcmp(curTex->achFormatHint, "jpg", 3) == 0)
  438. mimeType += "jpeg";
  439. else if(memcmp(curTex->achFormatHint, "ktx", 3) == 0) {
  440. useBasisUniversal = true;
  441. mimeType += "ktx";
  442. }
  443. else if(memcmp(curTex->achFormatHint, "kx2", 3) == 0) {
  444. useBasisUniversal = true;
  445. mimeType += "ktx2";
  446. }
  447. else if(memcmp(curTex->achFormatHint, "bu", 2) == 0) {
  448. useBasisUniversal = true;
  449. mimeType += "basis";
  450. }
  451. else
  452. mimeType += curTex->achFormatHint;
  453. texture->source->mimeType = mimeType;
  454. }
  455. // The asset has its own buffer, see Image::SetData
  456. //basisu: "image/ktx2", "image/basis" as is
  457. texture->source->SetData(reinterpret_cast<uint8_t *>(curTex->pcData), curTex->mWidth, *mAsset);
  458. }
  459. else {
  460. texture->source->uri = path;
  461. if(texture->source->uri.find(".ktx")!=std::string::npos ||
  462. texture->source->uri.find(".basis")!=std::string::npos)
  463. {
  464. useBasisUniversal = true;
  465. }
  466. }
  467. //basisu
  468. if(useBasisUniversal) {
  469. mAsset->extensionsUsed.KHR_texture_basisu = true;
  470. mAsset->extensionsRequired.KHR_texture_basisu = true;
  471. }
  472. GetTexSampler(mat, texture, tt, slot);
  473. }
  474. }
  475. }
  476. }
  477. }
  478. void glTF2Exporter::GetMatTex(const aiMaterial& mat, TextureInfo& prop, aiTextureType tt, unsigned int slot = 0)
  479. {
  480. Ref<Texture>& texture = prop.texture;
  481. GetMatTex(mat, texture, prop.texCoord, tt, slot);
  482. //if (texture) {
  483. // GetMatTexProp(mat, prop.texCoord, "texCoord", tt, slot);
  484. //}
  485. }
  486. void glTF2Exporter::GetMatTex(const aiMaterial& mat, NormalTextureInfo& prop, aiTextureType tt, unsigned int slot = 0)
  487. {
  488. Ref<Texture>& texture = prop.texture;
  489. GetMatTex(mat, texture, prop.texCoord, tt, slot);
  490. if (texture) {
  491. //GetMatTexProp(mat, prop.texCoord, "texCoord", tt, slot);
  492. GetMatTexProp(mat, prop.scale, "scale", tt, slot);
  493. }
  494. }
  495. void glTF2Exporter::GetMatTex(const aiMaterial& mat, OcclusionTextureInfo& prop, aiTextureType tt, unsigned int slot = 0)
  496. {
  497. Ref<Texture>& texture = prop.texture;
  498. GetMatTex(mat, texture, prop.texCoord, tt, slot);
  499. if (texture) {
  500. //GetMatTexProp(mat, prop.texCoord, "texCoord", tt, slot);
  501. GetMatTexProp(mat, prop.strength, "strength", tt, slot);
  502. }
  503. }
  504. aiReturn glTF2Exporter::GetMatColor(const aiMaterial& mat, vec4& prop, const char* propName, int type, int idx) const
  505. {
  506. aiColor4D col;
  507. aiReturn result = mat.Get(propName, type, idx, col);
  508. if (result == AI_SUCCESS) {
  509. prop[0] = col.r; prop[1] = col.g; prop[2] = col.b; prop[3] = col.a;
  510. }
  511. return result;
  512. }
  513. aiReturn glTF2Exporter::GetMatColor(const aiMaterial& mat, vec3& prop, const char* propName, int type, int idx) const
  514. {
  515. aiColor3D col;
  516. aiReturn result = mat.Get(propName, type, idx, col);
  517. if (result == AI_SUCCESS) {
  518. prop[0] = col.r;
  519. prop[1] = col.g;
  520. prop[2] = col.b;
  521. }
  522. return result;
  523. }
  524. bool glTF2Exporter::GetMatSpecGloss(const aiMaterial &mat, glTF2::PbrSpecularGlossiness &pbrSG) {
  525. bool result = false;
  526. // If has Glossiness, a Specular Color or Specular Texture, use the KHR_materials_pbrSpecularGlossiness extension
  527. // NOTE: This extension is being considered for deprecation (Dec 2020), may be replaced by KHR_material_specular
  528. if (mat.Get(AI_MATKEY_GLOSSINESS_FACTOR, pbrSG.glossinessFactor) == AI_SUCCESS) {
  529. result = true;
  530. } else {
  531. // Don't have explicit glossiness, convert from pbr roughness or legacy shininess
  532. float shininess;
  533. if (mat.Get(AI_MATKEY_ROUGHNESS_FACTOR, shininess) == AI_SUCCESS) {
  534. pbrSG.glossinessFactor = 1.0f - shininess; // Extension defines this way
  535. } else if (mat.Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS) {
  536. pbrSG.glossinessFactor = shininess / 1000;
  537. }
  538. }
  539. if (GetMatColor(mat, pbrSG.specularFactor, AI_MATKEY_COLOR_SPECULAR) == AI_SUCCESS) {
  540. result = true;
  541. }
  542. // Add any appropriate textures
  543. GetMatTex(mat, pbrSG.specularGlossinessTexture, aiTextureType_SPECULAR);
  544. result = result || pbrSG.specularGlossinessTexture.texture;
  545. if (result) {
  546. // Likely to always have diffuse
  547. GetMatTex(mat, pbrSG.diffuseTexture, aiTextureType_DIFFUSE);
  548. GetMatColor(mat, pbrSG.diffuseFactor, AI_MATKEY_COLOR_DIFFUSE);
  549. }
  550. return result;
  551. }
  552. bool glTF2Exporter::GetMatSheen(const aiMaterial &mat, glTF2::MaterialSheen &sheen) {
  553. // Return true if got any valid Sheen properties or textures
  554. if (GetMatColor(mat, sheen.sheenColorFactor, AI_MATKEY_SHEEN_COLOR_FACTOR) != aiReturn_SUCCESS)
  555. return false;
  556. // Default Sheen color factor {0,0,0} disables Sheen, so do not export
  557. if (sheen.sheenColorFactor == defaultSheenFactor)
  558. return false;
  559. mat.Get(AI_MATKEY_SHEEN_ROUGHNESS_FACTOR, sheen.sheenRoughnessFactor);
  560. GetMatTex(mat, sheen.sheenColorTexture, AI_MATKEY_SHEEN_COLOR_TEXTURE);
  561. GetMatTex(mat, sheen.sheenRoughnessTexture, AI_MATKEY_SHEEN_ROUGHNESS_TEXTURE);
  562. return true;
  563. }
  564. bool glTF2Exporter::GetMatClearcoat(const aiMaterial &mat, glTF2::MaterialClearcoat &clearcoat) {
  565. if (mat.Get(AI_MATKEY_CLEARCOAT_FACTOR, clearcoat.clearcoatFactor) != aiReturn_SUCCESS) {
  566. return false;
  567. }
  568. // Clearcoat factor of zero disables Clearcoat, so do not export
  569. if (clearcoat.clearcoatFactor == 0.0f)
  570. return false;
  571. mat.Get(AI_MATKEY_CLEARCOAT_ROUGHNESS_FACTOR, clearcoat.clearcoatRoughnessFactor);
  572. GetMatTex(mat, clearcoat.clearcoatTexture, AI_MATKEY_CLEARCOAT_TEXTURE);
  573. GetMatTex(mat, clearcoat.clearcoatRoughnessTexture, AI_MATKEY_CLEARCOAT_ROUGHNESS_TEXTURE);
  574. GetMatTex(mat, clearcoat.clearcoatNormalTexture, AI_MATKEY_CLEARCOAT_NORMAL_TEXTURE);
  575. return true;
  576. }
  577. bool glTF2Exporter::GetMatTransmission(const aiMaterial &mat, glTF2::MaterialTransmission &transmission) {
  578. bool result = mat.Get(AI_MATKEY_TRANSMISSION_FACTOR, transmission.transmissionFactor) == aiReturn_SUCCESS;
  579. GetMatTex(mat, transmission.transmissionTexture, AI_MATKEY_TRANSMISSION_TEXTURE);
  580. return result || transmission.transmissionTexture.texture;
  581. }
  582. void glTF2Exporter::ExportMaterials()
  583. {
  584. aiString aiName;
  585. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  586. ai_assert(mScene->mMaterials[i] != nullptr);
  587. const aiMaterial & mat = *(mScene->mMaterials[i]);
  588. std::string id = "material_" + ai_to_string(i);
  589. Ref<Material> m = mAsset->materials.Create(id);
  590. std::string name;
  591. if (mat.Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
  592. name = aiName.C_Str();
  593. }
  594. name = mAsset->FindUniqueID(name, "material");
  595. m->name = name;
  596. GetMatTex(mat, m->pbrMetallicRoughness.baseColorTexture, aiTextureType_BASE_COLOR);
  597. if (!m->pbrMetallicRoughness.baseColorTexture.texture) {
  598. //if there wasn't a baseColorTexture defined in the source, fallback to any diffuse texture
  599. GetMatTex(mat, m->pbrMetallicRoughness.baseColorTexture, aiTextureType_DIFFUSE);
  600. }
  601. GetMatTex(mat, m->pbrMetallicRoughness.metallicRoughnessTexture, AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE);
  602. if (GetMatColor(mat, m->pbrMetallicRoughness.baseColorFactor, AI_MATKEY_BASE_COLOR) != AI_SUCCESS) {
  603. // if baseColorFactor wasn't defined, then the source is likely not a metallic roughness material.
  604. //a fallback to any diffuse color should be used instead
  605. GetMatColor(mat, m->pbrMetallicRoughness.baseColorFactor, AI_MATKEY_COLOR_DIFFUSE);
  606. }
  607. if (mat.Get(AI_MATKEY_METALLIC_FACTOR, m->pbrMetallicRoughness.metallicFactor) != AI_SUCCESS) {
  608. //if metallicFactor wasn't defined, then the source is likely not a PBR file, and the metallicFactor should be 0
  609. m->pbrMetallicRoughness.metallicFactor = 0;
  610. }
  611. // get roughness if source is gltf2 file
  612. if (mat.Get(AI_MATKEY_ROUGHNESS_FACTOR, m->pbrMetallicRoughness.roughnessFactor) != AI_SUCCESS) {
  613. // otherwise, try to derive and convert from specular + shininess values
  614. aiColor4D specularColor;
  615. ai_real shininess;
  616. if (
  617. mat.Get(AI_MATKEY_COLOR_SPECULAR, specularColor) == AI_SUCCESS &&
  618. mat.Get(AI_MATKEY_SHININESS, shininess) == AI_SUCCESS
  619. ) {
  620. // convert specular color to luminance
  621. float specularIntensity = specularColor[0] * 0.2125f + specularColor[1] * 0.7154f + specularColor[2] * 0.0721f;
  622. //normalize shininess (assuming max is 1000) with an inverse exponentional curve
  623. float normalizedShininess = std::sqrt(shininess / 1000);
  624. //clamp the shininess value between 0 and 1
  625. normalizedShininess = std::min(std::max(normalizedShininess, 0.0f), 1.0f);
  626. // low specular intensity values should produce a rough material even if shininess is high.
  627. normalizedShininess = normalizedShininess * specularIntensity;
  628. m->pbrMetallicRoughness.roughnessFactor = 1 - normalizedShininess;
  629. }
  630. }
  631. GetMatTex(mat, m->normalTexture, aiTextureType_NORMALS);
  632. GetMatTex(mat, m->occlusionTexture, aiTextureType_LIGHTMAP);
  633. GetMatTex(mat, m->emissiveTexture, aiTextureType_EMISSIVE);
  634. GetMatColor(mat, m->emissiveFactor, AI_MATKEY_COLOR_EMISSIVE);
  635. mat.Get(AI_MATKEY_TWOSIDED, m->doubleSided);
  636. mat.Get(AI_MATKEY_GLTF_ALPHACUTOFF, m->alphaCutoff);
  637. float opacity;
  638. aiString alphaMode;
  639. if (mat.Get(AI_MATKEY_OPACITY, opacity) == AI_SUCCESS) {
  640. if (opacity < 1) {
  641. m->alphaMode = "BLEND";
  642. m->pbrMetallicRoughness.baseColorFactor[3] *= opacity;
  643. }
  644. }
  645. if (mat.Get(AI_MATKEY_GLTF_ALPHAMODE, alphaMode) == AI_SUCCESS) {
  646. m->alphaMode = alphaMode.C_Str();
  647. }
  648. {
  649. // KHR_materials_pbrSpecularGlossiness extension
  650. // NOTE: This extension is being considered for deprecation (Dec 2020)
  651. PbrSpecularGlossiness pbrSG;
  652. if (GetMatSpecGloss(mat, pbrSG)) {
  653. mAsset->extensionsUsed.KHR_materials_pbrSpecularGlossiness = true;
  654. m->pbrSpecularGlossiness = Nullable<PbrSpecularGlossiness>(pbrSG);
  655. }
  656. }
  657. // glTFv2 is either PBR or Unlit
  658. aiShadingMode shadingMode = aiShadingMode_PBR_BRDF;
  659. mat.Get(AI_MATKEY_SHADING_MODEL, shadingMode);
  660. if (shadingMode == aiShadingMode_Unlit) {
  661. mAsset->extensionsUsed.KHR_materials_unlit = true;
  662. m->unlit = true;
  663. } else {
  664. // These extensions are not compatible with KHR_materials_unlit or KHR_materials_pbrSpecularGlossiness
  665. if (!m->pbrSpecularGlossiness.isPresent) {
  666. // Sheen
  667. MaterialSheen sheen;
  668. if (GetMatSheen(mat, sheen)) {
  669. mAsset->extensionsUsed.KHR_materials_sheen = true;
  670. m->materialSheen = Nullable<MaterialSheen>(sheen);
  671. }
  672. MaterialClearcoat clearcoat;
  673. if (GetMatClearcoat(mat, clearcoat)) {
  674. mAsset->extensionsUsed.KHR_materials_clearcoat = true;
  675. m->materialClearcoat = Nullable<MaterialClearcoat>(clearcoat);
  676. }
  677. MaterialTransmission transmission;
  678. if (GetMatTransmission(mat, transmission)) {
  679. mAsset->extensionsUsed.KHR_materials_transmission = true;
  680. m->materialTransmission = Nullable<MaterialTransmission>(transmission);
  681. }
  682. }
  683. }
  684. }
  685. }
  686. /*
  687. * Search through node hierarchy and find the node containing the given meshID.
  688. * Returns true on success, and false otherwise.
  689. */
  690. bool FindMeshNode(Ref<Node> &nodeIn, Ref<Node> &meshNode, const std::string &meshID) {
  691. for (unsigned int i = 0; i < nodeIn->meshes.size(); ++i) {
  692. if (meshID.compare(nodeIn->meshes[i]->id) == 0) {
  693. meshNode = nodeIn;
  694. return true;
  695. }
  696. }
  697. for (unsigned int i = 0; i < nodeIn->children.size(); ++i) {
  698. if(FindMeshNode(nodeIn->children[i], meshNode, meshID)) {
  699. return true;
  700. }
  701. }
  702. return false;
  703. }
  704. /*
  705. * Find the root joint of the skeleton.
  706. * Starts will any joint node and traces up the tree,
  707. * until a parent is found that does not have a jointName.
  708. * Returns the first parent Ref<Node> found that does not have a jointName.
  709. */
  710. Ref<Node> FindSkeletonRootJoint(Ref<Skin>& skinRef)
  711. {
  712. Ref<Node> startNodeRef;
  713. Ref<Node> parentNodeRef;
  714. // Arbitrarily use the first joint to start the search.
  715. startNodeRef = skinRef->jointNames[0];
  716. parentNodeRef = skinRef->jointNames[0];
  717. do {
  718. startNodeRef = parentNodeRef;
  719. parentNodeRef = startNodeRef->parent;
  720. } while (!parentNodeRef->jointName.empty());
  721. return parentNodeRef;
  722. }
  723. void ExportSkin(Asset& mAsset, const aiMesh* aimesh, Ref<Mesh>& meshRef, Ref<Buffer>& bufferRef, Ref<Skin>& skinRef, std::vector<aiMatrix4x4>& inverseBindMatricesData)
  724. {
  725. if (aimesh->mNumBones < 1) {
  726. return;
  727. }
  728. // Store the vertex joint and weight data.
  729. const size_t NumVerts( aimesh->mNumVertices );
  730. vec4* vertexJointData = new vec4[ NumVerts ];
  731. vec4* vertexWeightData = new vec4[ NumVerts ];
  732. int* jointsPerVertex = new int[ NumVerts ];
  733. for (size_t i = 0; i < NumVerts; ++i) {
  734. jointsPerVertex[i] = 0;
  735. for (size_t j = 0; j < 4; ++j) {
  736. vertexJointData[i][j] = 0;
  737. vertexWeightData[i][j] = 0;
  738. }
  739. }
  740. for (unsigned int idx_bone = 0; idx_bone < aimesh->mNumBones; ++idx_bone) {
  741. const aiBone* aib = aimesh->mBones[idx_bone];
  742. // aib->mName =====> skinRef->jointNames
  743. // Find the node with id = mName.
  744. Ref<Node> nodeRef = mAsset.nodes.Get(aib->mName.C_Str());
  745. nodeRef->jointName = nodeRef->name;
  746. unsigned int jointNamesIndex = 0;
  747. bool addJointToJointNames = true;
  748. for ( unsigned int idx_joint = 0; idx_joint < skinRef->jointNames.size(); ++idx_joint) {
  749. if (skinRef->jointNames[idx_joint]->jointName.compare(nodeRef->jointName) == 0) {
  750. addJointToJointNames = false;
  751. jointNamesIndex = idx_joint;
  752. }
  753. }
  754. if (addJointToJointNames) {
  755. skinRef->jointNames.push_back(nodeRef);
  756. // aib->mOffsetMatrix =====> skinRef->inverseBindMatrices
  757. aiMatrix4x4 tmpMatrix4;
  758. CopyValue(aib->mOffsetMatrix, tmpMatrix4);
  759. inverseBindMatricesData.push_back(tmpMatrix4);
  760. jointNamesIndex = static_cast<unsigned int>(inverseBindMatricesData.size() - 1);
  761. }
  762. // aib->mWeights =====> vertexWeightData
  763. for (unsigned int idx_weights = 0; idx_weights < aib->mNumWeights; ++idx_weights) {
  764. unsigned int vertexId = aib->mWeights[idx_weights].mVertexId;
  765. float vertWeight = aib->mWeights[idx_weights].mWeight;
  766. // A vertex can only have at most four joint weights. Ignore all others.
  767. if (jointsPerVertex[vertexId] > 3) {
  768. continue;
  769. }
  770. vertexJointData[vertexId][jointsPerVertex[vertexId]] = static_cast<float>(jointNamesIndex);
  771. vertexWeightData[vertexId][jointsPerVertex[vertexId]] = vertWeight;
  772. jointsPerVertex[vertexId] += 1;
  773. }
  774. } // End: for-loop mNumMeshes
  775. Mesh::Primitive& p = meshRef->primitives.back();
  776. Ref<Accessor> vertexJointAccessor = ExportData(mAsset, skinRef->id, bufferRef, aimesh->mNumVertices, vertexJointData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  777. if ( vertexJointAccessor ) {
  778. size_t offset = vertexJointAccessor->bufferView->byteOffset;
  779. size_t bytesLen = vertexJointAccessor->bufferView->byteLength;
  780. unsigned int s_bytesPerComp= ComponentTypeSize(ComponentType_UNSIGNED_SHORT);
  781. unsigned int bytesPerComp = ComponentTypeSize(vertexJointAccessor->componentType);
  782. size_t s_bytesLen = bytesLen * s_bytesPerComp / bytesPerComp;
  783. Ref<Buffer> buf = vertexJointAccessor->bufferView->buffer;
  784. uint8_t* arrys = new uint8_t[bytesLen];
  785. unsigned int i = 0;
  786. for ( unsigned int j = 0; j <= bytesLen; j += bytesPerComp ){
  787. size_t len_p = offset + j;
  788. float f_value = *(float *)&buf->GetPointer()[len_p];
  789. unsigned short c = static_cast<unsigned short>(f_value);
  790. memcpy(&arrys[i*s_bytesPerComp], &c, s_bytesPerComp);
  791. ++i;
  792. }
  793. buf->ReplaceData_joint(offset, bytesLen, arrys, bytesLen);
  794. vertexJointAccessor->componentType = ComponentType_UNSIGNED_SHORT;
  795. vertexJointAccessor->bufferView->byteLength = s_bytesLen;
  796. p.attributes.joint.push_back( vertexJointAccessor );
  797. delete[] arrys;
  798. }
  799. Ref<Accessor> vertexWeightAccessor = ExportData(mAsset, skinRef->id, bufferRef, aimesh->mNumVertices,
  800. vertexWeightData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  801. if ( vertexWeightAccessor ) {
  802. p.attributes.weight.push_back( vertexWeightAccessor );
  803. }
  804. delete[] jointsPerVertex;
  805. delete[] vertexWeightData;
  806. delete[] vertexJointData;
  807. }
  808. void glTF2Exporter::ExportMeshes()
  809. {
  810. typedef decltype(aiFace::mNumIndices) IndicesType;
  811. std::string fname = std::string(mFilename);
  812. std::string bufferIdPrefix = fname.substr(0, fname.rfind(".gltf"));
  813. std::string bufferId = mAsset->FindUniqueID("", bufferIdPrefix.c_str());
  814. Ref<Buffer> b = mAsset->GetBodyBuffer();
  815. if (!b) {
  816. b = mAsset->buffers.Create(bufferId);
  817. }
  818. //----------------------------------------
  819. // Initialize variables for the skin
  820. bool createSkin = false;
  821. for (unsigned int idx_mesh = 0; idx_mesh < mScene->mNumMeshes; ++idx_mesh) {
  822. const aiMesh* aim = mScene->mMeshes[idx_mesh];
  823. if(aim->HasBones()) {
  824. createSkin = true;
  825. break;
  826. }
  827. }
  828. Ref<Skin> skinRef;
  829. std::string skinName = mAsset->FindUniqueID("skin", "skin");
  830. std::vector<aiMatrix4x4> inverseBindMatricesData;
  831. if(createSkin) {
  832. skinRef = mAsset->skins.Create(skinName);
  833. skinRef->name = skinName;
  834. }
  835. //----------------------------------------
  836. for (unsigned int idx_mesh = 0; idx_mesh < mScene->mNumMeshes; ++idx_mesh) {
  837. const aiMesh* aim = mScene->mMeshes[idx_mesh];
  838. std::string name = aim->mName.C_Str();
  839. std::string meshId = mAsset->FindUniqueID(name, "mesh");
  840. Ref<Mesh> m = mAsset->meshes.Create(meshId);
  841. m->primitives.resize(1);
  842. Mesh::Primitive& p = m->primitives.back();
  843. m->name = name;
  844. p.material = mAsset->materials.Get(aim->mMaterialIndex);
  845. p.ngonEncoded = (aim->mPrimitiveTypes & aiPrimitiveType_NGONEncodingFlag) != 0;
  846. /******************* Vertices ********************/
  847. Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  848. if (v) p.attributes.position.push_back(v);
  849. /******************** Normals ********************/
  850. // Normalize all normals as the validator can emit a warning otherwise
  851. if ( nullptr != aim->mNormals) {
  852. for ( auto i = 0u; i < aim->mNumVertices; ++i ) {
  853. aim->mNormals[ i ].NormalizeSafe();
  854. }
  855. }
  856. Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  857. if (n) p.attributes.normal.push_back(n);
  858. /************** Texture coordinates **************/
  859. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  860. if (!aim->HasTextureCoords(i))
  861. continue;
  862. // Flip UV y coords
  863. if (aim -> mNumUVComponents[i] > 1) {
  864. for (unsigned int j = 0; j < aim->mNumVertices; ++j) {
  865. aim->mTextureCoords[i][j].y = 1 - aim->mTextureCoords[i][j].y;
  866. }
  867. }
  868. if (aim->mNumUVComponents[i] > 0) {
  869. AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
  870. Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i], AttribType::VEC3, type, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  871. if (tc) p.attributes.texcoord.push_back(tc);
  872. }
  873. }
  874. /*************** Vertex colors ****************/
  875. for (unsigned int indexColorChannel = 0; indexColorChannel < aim->GetNumColorChannels(); ++indexColorChannel) {
  876. Ref<Accessor> c = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mColors[indexColorChannel], AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT, BufferViewTarget_ARRAY_BUFFER);
  877. if (c)
  878. p.attributes.color.push_back(c);
  879. }
  880. /*************** Vertices indices ****************/
  881. if (aim->mNumFaces > 0) {
  882. std::vector<IndicesType> indices;
  883. unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
  884. indices.resize(aim->mNumFaces * nIndicesPerFace);
  885. for (size_t i = 0; i < aim->mNumFaces; ++i) {
  886. for (size_t j = 0; j < nIndicesPerFace; ++j) {
  887. indices[i*nIndicesPerFace + j] = IndicesType(aim->mFaces[i].mIndices[j]);
  888. }
  889. }
  890. p.indices = ExportData(*mAsset, meshId, b, indices.size(), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_INT, BufferViewTarget_ELEMENT_ARRAY_BUFFER);
  891. }
  892. switch (aim->mPrimitiveTypes) {
  893. case aiPrimitiveType_POLYGON:
  894. p.mode = PrimitiveMode_TRIANGLES; break; // TODO implement this
  895. case aiPrimitiveType_LINE:
  896. p.mode = PrimitiveMode_LINES; break;
  897. case aiPrimitiveType_POINT:
  898. p.mode = PrimitiveMode_POINTS; break;
  899. default: // aiPrimitiveType_TRIANGLE
  900. p.mode = PrimitiveMode_TRIANGLES;
  901. }
  902. /*************** Skins ****************/
  903. if(aim->HasBones()) {
  904. ExportSkin(*mAsset, aim, m, b, skinRef, inverseBindMatricesData);
  905. }
  906. /*************** Targets for blendshapes ****************/
  907. if (aim->mNumAnimMeshes > 0) {
  908. bool bUseSparse = this->mProperties->HasPropertyBool("GLTF2_SPARSE_ACCESSOR_EXP") &&
  909. this->mProperties->GetPropertyBool("GLTF2_SPARSE_ACCESSOR_EXP");
  910. bool bIncludeNormal = this->mProperties->HasPropertyBool("GLTF2_TARGET_NORMAL_EXP") &&
  911. this->mProperties->GetPropertyBool("GLTF2_TARGET_NORMAL_EXP");
  912. bool bExportTargetNames = this->mProperties->HasPropertyBool("GLTF2_TARGETNAMES_EXP") &&
  913. this->mProperties->GetPropertyBool("GLTF2_TARGETNAMES_EXP");
  914. p.targets.resize(aim->mNumAnimMeshes);
  915. for (unsigned int am = 0; am < aim->mNumAnimMeshes; ++am) {
  916. aiAnimMesh *pAnimMesh = aim->mAnimMeshes[am];
  917. if (bExportTargetNames)
  918. m->targetNames.push_back(pAnimMesh->mName.data);
  919. // position
  920. if (pAnimMesh->HasPositions()) {
  921. // NOTE: in gltf it is the diff stored
  922. aiVector3D *pPositionDiff = new aiVector3D[pAnimMesh->mNumVertices];
  923. for (unsigned int vt = 0; vt < pAnimMesh->mNumVertices; ++vt) {
  924. pPositionDiff[vt] = pAnimMesh->mVertices[vt] - aim->mVertices[vt];
  925. }
  926. Ref<Accessor> vec;
  927. if (bUseSparse) {
  928. vec = ExportDataSparse(*mAsset, meshId, b,
  929. pAnimMesh->mNumVertices, pPositionDiff,
  930. AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  931. } else {
  932. vec = ExportData(*mAsset, meshId, b,
  933. pAnimMesh->mNumVertices, pPositionDiff,
  934. AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  935. }
  936. if (vec) {
  937. p.targets[am].position.push_back(vec);
  938. }
  939. delete[] pPositionDiff;
  940. }
  941. // normal
  942. if (pAnimMesh->HasNormals() && bIncludeNormal) {
  943. aiVector3D *pNormalDiff = new aiVector3D[pAnimMesh->mNumVertices];
  944. for (unsigned int vt = 0; vt < pAnimMesh->mNumVertices; ++vt) {
  945. pNormalDiff[vt] = pAnimMesh->mNormals[vt] - aim->mNormals[vt];
  946. }
  947. Ref<Accessor> vec;
  948. if (bUseSparse) {
  949. vec = ExportDataSparse(*mAsset, meshId, b,
  950. pAnimMesh->mNumVertices, pNormalDiff,
  951. AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  952. } else {
  953. vec = ExportData(*mAsset, meshId, b,
  954. pAnimMesh->mNumVertices, pNormalDiff,
  955. AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  956. }
  957. if (vec) {
  958. p.targets[am].normal.push_back(vec);
  959. }
  960. delete[] pNormalDiff;
  961. }
  962. // tangent?
  963. }
  964. }
  965. }
  966. //----------------------------------------
  967. // Finish the skin
  968. // Create the Accessor for skinRef->inverseBindMatrices
  969. bool bAddCustomizedProperty = this->mProperties->HasPropertyBool("GLTF2_CUSTOMIZE_PROPERTY");
  970. if (createSkin) {
  971. mat4* invBindMatrixData = new mat4[inverseBindMatricesData.size()];
  972. for ( unsigned int idx_joint = 0; idx_joint < inverseBindMatricesData.size(); ++idx_joint) {
  973. CopyValue(inverseBindMatricesData[idx_joint], invBindMatrixData[idx_joint]);
  974. }
  975. Ref<Accessor> invBindMatrixAccessor = ExportData(*mAsset, skinName, b,
  976. static_cast<unsigned int>(inverseBindMatricesData.size()),
  977. invBindMatrixData, AttribType::MAT4, AttribType::MAT4, ComponentType_FLOAT);
  978. if (invBindMatrixAccessor) {
  979. skinRef->inverseBindMatrices = invBindMatrixAccessor;
  980. }
  981. // Identity Matrix =====> skinRef->bindShapeMatrix
  982. // Temporary. Hard-coded identity matrix here
  983. skinRef->bindShapeMatrix.isPresent = bAddCustomizedProperty;
  984. IdentityMatrix4(skinRef->bindShapeMatrix.value);
  985. // Find nodes that contain a mesh with bones and add "skeletons" and "skin" attributes to those nodes.
  986. Ref<Node> rootNode = mAsset->nodes.Get(unsigned(0));
  987. Ref<Node> meshNode;
  988. for (unsigned int meshIndex = 0; meshIndex < mAsset->meshes.Size(); ++meshIndex) {
  989. Ref<Mesh> mesh = mAsset->meshes.Get(meshIndex);
  990. bool hasBones = false;
  991. for (unsigned int i = 0; i < mesh->primitives.size(); ++i) {
  992. if (!mesh->primitives[i].attributes.weight.empty()) {
  993. hasBones = true;
  994. break;
  995. }
  996. }
  997. if (!hasBones) {
  998. continue;
  999. }
  1000. std::string meshID = mesh->id;
  1001. FindMeshNode(rootNode, meshNode, meshID);
  1002. Ref<Node> rootJoint = FindSkeletonRootJoint(skinRef);
  1003. if(bAddCustomizedProperty)
  1004. meshNode->skeletons.push_back(rootJoint);
  1005. meshNode->skin = skinRef;
  1006. }
  1007. delete[] invBindMatrixData;
  1008. }
  1009. }
  1010. // Merges a node's multiple meshes (with one primitive each) into one mesh with multiple primitives
  1011. void glTF2Exporter::MergeMeshes()
  1012. {
  1013. for (unsigned int n = 0; n < mAsset->nodes.Size(); ++n) {
  1014. Ref<Node> node = mAsset->nodes.Get(n);
  1015. unsigned int nMeshes = static_cast<unsigned int>(node->meshes.size());
  1016. //skip if it's 1 or less meshes per node
  1017. if (nMeshes > 1) {
  1018. Ref<Mesh> firstMesh = node->meshes.at(0);
  1019. //loop backwards to allow easy removal of a mesh from a node once it's merged
  1020. for (unsigned int m = nMeshes - 1; m >= 1; --m) {
  1021. Ref<Mesh> mesh = node->meshes.at(m);
  1022. //append this mesh's primitives to the first mesh's primitives
  1023. firstMesh->primitives.insert(
  1024. firstMesh->primitives.end(),
  1025. mesh->primitives.begin(),
  1026. mesh->primitives.end()
  1027. );
  1028. //remove the mesh from the list of meshes
  1029. unsigned int removedIndex = mAsset->meshes.Remove(mesh->id.c_str());
  1030. //find the presence of the removed mesh in other nodes
  1031. for (unsigned int nn = 0; nn < mAsset->nodes.Size(); ++nn) {
  1032. Ref<Node> curNode = mAsset->nodes.Get(nn);
  1033. for (unsigned int mm = 0; mm < curNode->meshes.size(); ++mm) {
  1034. Ref<Mesh> &meshRef = curNode->meshes.at(mm);
  1035. unsigned int meshIndex = meshRef.GetIndex();
  1036. if (meshIndex == removedIndex) {
  1037. curNode->meshes.erase(curNode->meshes.begin() + mm);
  1038. } else if (meshIndex > removedIndex) {
  1039. Ref<Mesh> newMeshRef = mAsset->meshes.Get(meshIndex - 1);
  1040. meshRef = newMeshRef;
  1041. }
  1042. }
  1043. }
  1044. }
  1045. //since we were looping backwards, reverse the order of merged primitives to their original order
  1046. std::reverse(firstMesh->primitives.begin() + 1, firstMesh->primitives.end());
  1047. }
  1048. }
  1049. }
  1050. /*
  1051. * Export the root node of the node hierarchy.
  1052. * Calls ExportNode for all children.
  1053. */
  1054. unsigned int glTF2Exporter::ExportNodeHierarchy(const aiNode* n)
  1055. {
  1056. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  1057. node->name = n->mName.C_Str();
  1058. if (!n->mTransformation.IsIdentity()) {
  1059. node->matrix.isPresent = true;
  1060. CopyValue(n->mTransformation, node->matrix.value);
  1061. }
  1062. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  1063. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  1064. }
  1065. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  1066. unsigned int idx = ExportNode(n->mChildren[i], node);
  1067. node->children.push_back(mAsset->nodes.Get(idx));
  1068. }
  1069. return node.GetIndex();
  1070. }
  1071. /*
  1072. * Export node and recursively calls ExportNode for all children.
  1073. * Since these nodes are not the root node, we also export the parent Ref<Node>
  1074. */
  1075. unsigned int glTF2Exporter::ExportNode(const aiNode* n, Ref<Node>& parent)
  1076. {
  1077. std::string name = mAsset->FindUniqueID(n->mName.C_Str(), "node");
  1078. Ref<Node> node = mAsset->nodes.Create(name);
  1079. node->parent = parent;
  1080. node->name = name;
  1081. if (!n->mTransformation.IsIdentity()) {
  1082. if (mScene->mNumAnimations > 0 || (mProperties && mProperties->HasPropertyBool("GLTF2_NODE_IN_TRS"))) {
  1083. aiQuaternion quaternion;
  1084. n->mTransformation.Decompose(*reinterpret_cast<aiVector3D *>(&node->scale.value), quaternion, *reinterpret_cast<aiVector3D *>(&node->translation.value));
  1085. aiVector3D vector(static_cast<ai_real>(1.0f), static_cast<ai_real>(1.0f), static_cast<ai_real>(1.0f));
  1086. if (!reinterpret_cast<aiVector3D *>(&node->scale.value)->Equal(vector)) {
  1087. node->scale.isPresent = true;
  1088. }
  1089. if (!reinterpret_cast<aiVector3D *>(&node->translation.value)->Equal(vector)) {
  1090. node->translation.isPresent = true;
  1091. }
  1092. node->rotation.isPresent = true;
  1093. node->rotation.value[0] = quaternion.x;
  1094. node->rotation.value[1] = quaternion.y;
  1095. node->rotation.value[2] = quaternion.z;
  1096. node->rotation.value[3] = quaternion.w;
  1097. node->matrix.isPresent = false;
  1098. } else {
  1099. node->matrix.isPresent = true;
  1100. CopyValue(n->mTransformation, node->matrix.value);
  1101. }
  1102. }
  1103. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  1104. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  1105. }
  1106. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  1107. unsigned int idx = ExportNode(n->mChildren[i], node);
  1108. node->children.push_back(mAsset->nodes.Get(idx));
  1109. }
  1110. return node.GetIndex();
  1111. }
  1112. void glTF2Exporter::ExportScene()
  1113. {
  1114. // Use the name of the scene if specified
  1115. const std::string sceneName = (mScene->mName.length > 0) ? mScene->mName.C_Str() : "defaultScene";
  1116. // Ensure unique
  1117. Ref<Scene> scene = mAsset->scenes.Create(mAsset->FindUniqueID(sceneName, ""));
  1118. // root node will be the first one exported (idx 0)
  1119. if (mAsset->nodes.Size() > 0) {
  1120. scene->nodes.push_back(mAsset->nodes.Get(0u));
  1121. }
  1122. // set as the default scene
  1123. mAsset->scene = scene;
  1124. }
  1125. void glTF2Exporter::ExportMetadata()
  1126. {
  1127. AssetMetadata& asset = mAsset->asset;
  1128. asset.version = "2.0";
  1129. char buffer[256];
  1130. ai_snprintf(buffer, 256, "Open Asset Import Library (assimp v%d.%d.%x)",
  1131. aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
  1132. asset.generator = buffer;
  1133. // Copyright
  1134. aiString copyright_str;
  1135. if (mScene->mMetaData != nullptr && mScene->mMetaData->Get(AI_METADATA_SOURCE_COPYRIGHT, copyright_str)) {
  1136. asset.copyright = copyright_str.C_Str();
  1137. }
  1138. }
  1139. inline Ref<Accessor> GetSamplerInputRef(Asset& asset, std::string& animId, Ref<Buffer>& buffer, std::vector<float>& times)
  1140. {
  1141. return ExportData(asset, animId, buffer, (unsigned int)times.size(), &times[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_FLOAT);
  1142. }
  1143. inline void ExtractTranslationSampler(Asset& asset, std::string& animId, Ref<Buffer>& buffer, const aiNodeAnim* nodeChannel, float ticksPerSecond, Animation::Sampler& sampler)
  1144. {
  1145. const unsigned int numKeyframes = nodeChannel->mNumPositionKeys;
  1146. std::vector<float> times(numKeyframes);
  1147. std::vector<float> values(numKeyframes * 3);
  1148. for (unsigned int i = 0; i < numKeyframes; ++i) {
  1149. const aiVectorKey& key = nodeChannel->mPositionKeys[i];
  1150. // mTime is measured in ticks, but GLTF time is measured in seconds, so convert.
  1151. times[i] = static_cast<float>(key.mTime / ticksPerSecond);
  1152. values[(i * 3) + 0] = key.mValue.x;
  1153. values[(i * 3) + 1] = key.mValue.y;
  1154. values[(i * 3) + 2] = key.mValue.z;
  1155. }
  1156. sampler.input = GetSamplerInputRef(asset, animId, buffer, times);
  1157. sampler.output = ExportData(asset, animId, buffer, numKeyframes, &values[0], AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  1158. sampler.interpolation = Interpolation_LINEAR;
  1159. }
  1160. inline void ExtractScaleSampler(Asset& asset, std::string& animId, Ref<Buffer>& buffer, const aiNodeAnim* nodeChannel, float ticksPerSecond, Animation::Sampler& sampler)
  1161. {
  1162. const unsigned int numKeyframes = nodeChannel->mNumScalingKeys;
  1163. std::vector<float> times(numKeyframes);
  1164. std::vector<float> values(numKeyframes * 3);
  1165. for (unsigned int i = 0; i < numKeyframes; ++i) {
  1166. const aiVectorKey& key = nodeChannel->mScalingKeys[i];
  1167. // mTime is measured in ticks, but GLTF time is measured in seconds, so convert.
  1168. times[i] = static_cast<float>(key.mTime / ticksPerSecond);
  1169. values[(i * 3) + 0] = key.mValue.x;
  1170. values[(i * 3) + 1] = key.mValue.y;
  1171. values[(i * 3) + 2] = key.mValue.z;
  1172. }
  1173. sampler.input = GetSamplerInputRef(asset, animId, buffer, times);
  1174. sampler.output = ExportData(asset, animId, buffer, numKeyframes, &values[0], AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  1175. sampler.interpolation = Interpolation_LINEAR;
  1176. }
  1177. inline void ExtractRotationSampler(Asset& asset, std::string& animId, Ref<Buffer>& buffer, const aiNodeAnim* nodeChannel, float ticksPerSecond, Animation::Sampler& sampler)
  1178. {
  1179. const unsigned int numKeyframes = nodeChannel->mNumRotationKeys;
  1180. std::vector<float> times(numKeyframes);
  1181. std::vector<float> values(numKeyframes * 4);
  1182. for (unsigned int i = 0; i < numKeyframes; ++i) {
  1183. const aiQuatKey& key = nodeChannel->mRotationKeys[i];
  1184. // mTime is measured in ticks, but GLTF time is measured in seconds, so convert.
  1185. times[i] = static_cast<float>(key.mTime / ticksPerSecond);
  1186. values[(i * 4) + 0] = key.mValue.x;
  1187. values[(i * 4) + 1] = key.mValue.y;
  1188. values[(i * 4) + 2] = key.mValue.z;
  1189. values[(i * 4) + 3] = key.mValue.w;
  1190. }
  1191. sampler.input = GetSamplerInputRef(asset, animId, buffer, times);
  1192. sampler.output = ExportData(asset, animId, buffer, numKeyframes, &values[0], AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  1193. sampler.interpolation = Interpolation_LINEAR;
  1194. }
  1195. static void AddSampler(Ref<Animation>& animRef, Ref<Node>& nodeRef, Animation::Sampler& sampler, AnimationPath path)
  1196. {
  1197. Animation::Channel channel;
  1198. channel.sampler = static_cast<int>(animRef->samplers.size());
  1199. channel.target.path = path;
  1200. channel.target.node = nodeRef;
  1201. animRef->channels.push_back(channel);
  1202. animRef->samplers.push_back(sampler);
  1203. }
  1204. void glTF2Exporter::ExportAnimations()
  1205. {
  1206. Ref<Buffer> bufferRef = mAsset->buffers.Get(unsigned (0));
  1207. for (unsigned int i = 0; i < mScene->mNumAnimations; ++i) {
  1208. const aiAnimation* anim = mScene->mAnimations[i];
  1209. const float ticksPerSecond = static_cast<float>(anim->mTicksPerSecond);
  1210. std::string nameAnim = "anim";
  1211. if (anim->mName.length > 0) {
  1212. nameAnim = anim->mName.C_Str();
  1213. }
  1214. Ref<Animation> animRef = mAsset->animations.Create(nameAnim);
  1215. animRef->name = nameAnim;
  1216. for (unsigned int channelIndex = 0; channelIndex < anim->mNumChannels; ++channelIndex) {
  1217. const aiNodeAnim* nodeChannel = anim->mChannels[channelIndex];
  1218. std::string name = nameAnim + "_" + ai_to_string(channelIndex);
  1219. name = mAsset->FindUniqueID(name, "animation");
  1220. Ref<Node> animNode = mAsset->nodes.Get(nodeChannel->mNodeName.C_Str());
  1221. if (nodeChannel->mNumPositionKeys > 0)
  1222. {
  1223. Animation::Sampler translationSampler;
  1224. ExtractTranslationSampler(*mAsset, name, bufferRef, nodeChannel, ticksPerSecond, translationSampler);
  1225. AddSampler(animRef, animNode, translationSampler, AnimationPath_TRANSLATION);
  1226. }
  1227. if (nodeChannel->mNumRotationKeys > 0)
  1228. {
  1229. Animation::Sampler rotationSampler;
  1230. ExtractRotationSampler(*mAsset, name, bufferRef, nodeChannel, ticksPerSecond, rotationSampler);
  1231. AddSampler(animRef, animNode, rotationSampler, AnimationPath_ROTATION);
  1232. }
  1233. if (nodeChannel->mNumScalingKeys > 0)
  1234. {
  1235. Animation::Sampler scaleSampler;
  1236. ExtractScaleSampler(*mAsset, name, bufferRef, nodeChannel, ticksPerSecond, scaleSampler);
  1237. AddSampler(animRef, animNode, scaleSampler, AnimationPath_SCALE);
  1238. }
  1239. }
  1240. // Assimp documentation staes this is not used (not implemented)
  1241. // for (unsigned int channelIndex = 0; channelIndex < anim->mNumMeshChannels; ++channelIndex) {
  1242. // const aiMeshAnim* meshChannel = anim->mMeshChannels[channelIndex];
  1243. // }
  1244. } // End: for-loop mNumAnimations
  1245. }
  1246. #endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
  1247. #endif // ASSIMP_BUILD_NO_EXPORT