glTF2Exporter.cpp 60 KB

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