GltfImporter.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Importer/GltfImporter.h>
  6. #include <AnKi/Util/System.h>
  7. #include <AnKi/Util/ThreadJobManager.h>
  8. #include <AnKi/Util/StringList.h>
  9. #include <AnKi/Util/Xml.h>
  10. #if ANKI_COMPILER_GCC_COMPATIBLE
  11. # pragma GCC diagnostic push
  12. # pragma GCC diagnostic ignored "-Wconversion"
  13. #endif
  14. #define CGLTF_IMPLEMENTATION
  15. #include <Cgltf/cgltf.h>
  16. #if ANKI_COMPILER_GCC_COMPATIBLE
  17. # pragma GCC diagnostic pop
  18. #endif
  19. namespace anki {
  20. static F32 computeLightRadius(const Vec3 color)
  21. {
  22. // Based on the attenuation equation: att = 1 - fragLightDist^2 / lightRadius^2
  23. const F32 minAtt = 0.01f;
  24. const F32 maxIntensity = max(max(color.x, color.y), color.z);
  25. return sqrt(maxIntensity / minAtt);
  26. }
  27. #if 0
  28. static Error getUniformScale(const Mat4& m, F32& out)
  29. {
  30. const F32 SCALE_THRESHOLD = 0.01f; // 1 cm
  31. Vec3 xAxis = m.getColumn(0).xyz;
  32. Vec3 yAxis = m.getColumn(1).xyz;
  33. Vec3 zAxis = m.getColumn(2).xyz;
  34. const F32 scale = xAxis.getLength();
  35. if(absolute(scale - yAxis.getLength()) > SCALE_THRESHOLD || absolute(scale - zAxis.getLength()) > SCALE_THRESHOLD)
  36. {
  37. ANKI_IMPORTER_LOGE("No uniform scale in the matrix");
  38. return Error::kUserData;
  39. }
  40. out = scale;
  41. return Error::kNone;
  42. }
  43. #endif
  44. static void removeScale(Mat4& m)
  45. {
  46. Vec3 xAxis = m.getColumn(0).xyz;
  47. Vec3 yAxis = m.getColumn(1).xyz;
  48. Vec3 zAxis = m.getColumn(2).xyz;
  49. xAxis = xAxis.normalize();
  50. yAxis = yAxis.normalize();
  51. zAxis = zAxis.normalize();
  52. Mat3 rot;
  53. rot.setColumns(xAxis, yAxis, zAxis);
  54. m.setRotationPart(rot);
  55. }
  56. static void getNodeTransform(const cgltf_node& node, Vec3& tsl, Mat3& rot, Vec3& scale)
  57. {
  58. if(node.has_matrix)
  59. {
  60. Mat4 trf = Mat4(node.matrix);
  61. Vec3 xAxis = trf.getColumn(0).xyz;
  62. Vec3 yAxis = trf.getColumn(1).xyz;
  63. Vec3 zAxis = trf.getColumn(2).xyz;
  64. scale = Vec3(xAxis.length(), yAxis.length(), zAxis.length());
  65. removeScale(trf);
  66. rot = trf.getRotationPart();
  67. tsl = trf.getTranslationPart().xyz;
  68. }
  69. else
  70. {
  71. if(node.has_translation)
  72. {
  73. tsl = Vec3(node.translation[0], node.translation[1], node.translation[2]);
  74. }
  75. else
  76. {
  77. tsl = Vec3(0.0f);
  78. }
  79. if(node.has_rotation)
  80. {
  81. rot = Mat3(Quat(node.rotation[0], node.rotation[1], node.rotation[2], node.rotation[3]));
  82. }
  83. else
  84. {
  85. rot = Mat3::getIdentity();
  86. }
  87. if(node.has_scale)
  88. {
  89. ANKI_ASSERT(node.scale[0] > 0.0f);
  90. ANKI_ASSERT(node.scale[1] > 0.0f);
  91. ANKI_ASSERT(node.scale[2] > 0.0f);
  92. scale = Vec3(node.scale[0], node.scale[1], node.scale[2]);
  93. }
  94. else
  95. {
  96. scale = Vec3(1.0f);
  97. }
  98. }
  99. }
  100. static Error getNodeTransform(const cgltf_node& node, Transform& trf)
  101. {
  102. Vec3 tsl;
  103. Mat3 rot;
  104. Vec3 scale;
  105. getNodeTransform(node, tsl, rot, scale);
  106. trf.setOrigin(tsl.xyz0);
  107. trf.setRotation(Mat3x4(Vec3(0.0f), rot));
  108. trf.setScale(scale);
  109. return Error::kNone;
  110. }
  111. static Bool stringsExist(const ImporterHashMap<CString, ImporterString>& map, const std::initializer_list<CString>& list)
  112. {
  113. for(CString item : list)
  114. {
  115. if(map.find(item) != map.getEnd())
  116. {
  117. return true;
  118. }
  119. }
  120. return false;
  121. }
  122. static Error getExtra(const ImporterHashMap<CString, ImporterString>& extras, CString name, F32& val, Bool& found)
  123. {
  124. found = false;
  125. ImporterHashMap<CString, ImporterString>::ConstIterator it = extras.find(name);
  126. if(it != extras.getEnd())
  127. {
  128. const Error err = it->toNumber(val);
  129. if(err)
  130. {
  131. ANKI_IMPORTER_LOGE("Failed to parse %s with value: %s", name.cstr(), it->cstr());
  132. return err;
  133. }
  134. found = true;
  135. }
  136. return Error::kNone;
  137. }
  138. static Error getExtra(const ImporterHashMap<CString, ImporterString>& extras, CString name, ImporterString& val, Bool& found)
  139. {
  140. found = false;
  141. ImporterHashMap<CString, ImporterString>::ConstIterator it = extras.find(name);
  142. if(it != extras.getEnd())
  143. {
  144. val = *it;
  145. found = true;
  146. }
  147. return Error::kNone;
  148. }
  149. static Error getExtra(const ImporterHashMap<CString, ImporterString>& extras, CString name, Bool& val, Bool& found)
  150. {
  151. found = false;
  152. ImporterHashMap<CString, ImporterString>::ConstIterator it = extras.find(name);
  153. if(it != extras.getEnd())
  154. {
  155. if(*it == "true" || *it == "1")
  156. {
  157. val = true;
  158. }
  159. else if(*it == "false" || *it == "0")
  160. {
  161. val = false;
  162. }
  163. else
  164. {
  165. U32 valu;
  166. const Error err = it->toNumber(valu);
  167. if(err || valu != 0 || valu != 1)
  168. {
  169. ANKI_IMPORTER_LOGE("Failed to parse %s with value: %s", name.cstr(), it->cstr());
  170. return err;
  171. }
  172. val = valu != 0;
  173. }
  174. found = true;
  175. }
  176. return Error::kNone;
  177. }
  178. static Error getExtra(const ImporterHashMap<CString, ImporterString>& extras, CString name, Vec3& val, Bool& found)
  179. {
  180. found = false;
  181. ImporterHashMap<CString, ImporterString>::ConstIterator it = extras.find(name);
  182. if(it != extras.getEnd())
  183. {
  184. ImporterStringList tokens;
  185. tokens.splitString(*it, ' ');
  186. if(tokens.getSize() != 3)
  187. {
  188. ANKI_IMPORTER_LOGE("Error parsing %s with value: %s", name.cstr(), it->cstr());
  189. return Error::kUserData;
  190. }
  191. U count = 0;
  192. for(auto& token : tokens)
  193. {
  194. F32 f;
  195. const Error err = token.toNumber(f);
  196. if(err)
  197. {
  198. ANKI_IMPORTER_LOGE("Error parsing %s with value: %s", name.cstr(), it->cstr());
  199. return Error::kUserData;
  200. }
  201. val[count++] = f;
  202. }
  203. found = true;
  204. }
  205. return Error::kNone;
  206. }
  207. static Bool isNodeValid(const cgltf_node& node)
  208. {
  209. if(node.mesh == nullptr)
  210. {
  211. return false;
  212. }
  213. if(node.mesh->primitives_count == 0)
  214. {
  215. return false;
  216. }
  217. for(U32 i = 0; i < node.mesh->primitives_count; ++i)
  218. {
  219. if(node.mesh->primitives[i].material == nullptr)
  220. {
  221. return false;
  222. }
  223. }
  224. return true;
  225. }
  226. GltfImporter::GltfImporter()
  227. {
  228. }
  229. GltfImporter::~GltfImporter()
  230. {
  231. if(m_gltf)
  232. {
  233. cgltf_free(m_gltf);
  234. m_gltf = nullptr;
  235. }
  236. deleteInstance(ImporterMemoryPool::getSingleton(), m_jobManager);
  237. }
  238. Error GltfImporter::init(const GltfImporterInitInfo& initInfo)
  239. {
  240. m_inputFname = initInfo.m_inputFilename;
  241. m_outDir = initInfo.m_outDirectory;
  242. m_rpath = initInfo.m_rpath;
  243. m_texrpath = initInfo.m_texrpath;
  244. m_optimizeMeshes = initInfo.m_optimizeMeshes;
  245. m_optimizeAnimations = initInfo.m_optimizeAnimations;
  246. m_comment = initInfo.m_comment;
  247. m_lightIntensityScale = max(initInfo.m_lightIntensityScale, kEpsilonf);
  248. m_lodCount = clamp(initInfo.m_lodCount, 1u, 3u);
  249. m_lodFactor = clamp(initInfo.m_lodFactor, 0.0f, 1.0f);
  250. if(m_lodFactor * F32(m_lodCount - 1) > 0.7f)
  251. {
  252. ANKI_IMPORTER_LOGE("LOD factor is too high %f", m_lodFactor);
  253. return Error::kUserData;
  254. }
  255. if(m_lodFactor < kEpsilonf || m_lodCount == 1)
  256. {
  257. m_lodCount = 1;
  258. m_lodFactor = 0.0f;
  259. }
  260. ANKI_IMPORTER_LOGV("Having %u LODs with LOD factor %f", m_lodCount, m_lodFactor);
  261. cgltf_options options = {};
  262. cgltf_result res = cgltf_parse_file(&options, m_inputFname.cstr(), &m_gltf);
  263. if(res != cgltf_result_success)
  264. {
  265. ANKI_IMPORTER_LOGE("Failed to open the GLTF file. Code: %d", res);
  266. return Error::kFunctionFailed;
  267. }
  268. res = cgltf_load_buffers(&options, m_gltf, m_inputFname.cstr());
  269. if(res != cgltf_result_success)
  270. {
  271. ANKI_IMPORTER_LOGE("Failed to load GLTF data. Code: %d", res);
  272. return Error::kFunctionFailed;
  273. }
  274. if(initInfo.m_threadCount > 0)
  275. {
  276. const U32 threadCount = min(getCpuCoresCount(), initInfo.m_threadCount);
  277. m_jobManager = newInstance<ThreadJobManager>(ImporterMemoryPool::getSingleton(), threadCount, true);
  278. }
  279. m_importTextures = initInfo.m_importTextures;
  280. return Error::kNone;
  281. }
  282. Error GltfImporter::writeAll()
  283. {
  284. populateNodePtrToIdx();
  285. ImporterString sceneFname;
  286. sceneFname.sprintf("%sScene.lua", m_outDir.cstr());
  287. ANKI_CHECK(m_sceneFile.open(sceneFname.toCString(), FileOpenFlag::kWrite));
  288. ANKI_CHECK(m_sceneFile.writeTextf("-- Generated by: %s\n", m_comment.cstr()));
  289. ANKI_CHECK(m_sceneFile.writeText("local scene = getSceneGraph()\nlocal events = getEventManager()\n"));
  290. // Nodes
  291. for(const cgltf_scene* scene = m_gltf->scenes; scene < m_gltf->scenes + m_gltf->scenes_count; ++scene)
  292. {
  293. for(cgltf_node* const* node = scene->nodes; node < scene->nodes + scene->nodes_count; ++node)
  294. {
  295. ANKI_CHECK(visitNode(*(*node), Transform::getIdentity(), ImporterHashMap<CString, ImporterString>()));
  296. }
  297. }
  298. // Fire up all requests
  299. for(auto& req : m_meshImportRequests)
  300. {
  301. if(m_jobManager)
  302. {
  303. m_jobManager->dispatchTask([&req]([[maybe_unused]] U32 threadId) {
  304. Error err = req.m_importer->m_errorInThread.load();
  305. if(!err)
  306. {
  307. err = req.m_importer->writeMesh(*req.m_value);
  308. }
  309. if(err)
  310. {
  311. req.m_importer->m_errorInThread.store(err._getCode());
  312. }
  313. });
  314. }
  315. else
  316. {
  317. ANKI_CHECK(writeMesh(*req.m_value));
  318. }
  319. }
  320. for(auto& req : m_materialImportRequests)
  321. {
  322. if(m_jobManager)
  323. {
  324. m_jobManager->dispatchTask([&req]([[maybe_unused]] U32 threadId) {
  325. Error err = req.m_importer->m_errorInThread.load();
  326. if(!err)
  327. {
  328. err = req.m_importer->writeMaterial(*req.m_value.m_cgltfMaterial, req.m_value.m_writeRt);
  329. }
  330. if(err)
  331. {
  332. req.m_importer->m_errorInThread.store(err._getCode());
  333. }
  334. });
  335. }
  336. else
  337. {
  338. ANKI_CHECK(writeMaterial(*req.m_value.m_cgltfMaterial, req.m_value.m_writeRt));
  339. }
  340. }
  341. for(auto& req : m_skinImportRequests)
  342. {
  343. if(m_jobManager)
  344. {
  345. m_jobManager->dispatchTask([&req]([[maybe_unused]] U32 threadId) {
  346. Error err = req.m_importer->m_errorInThread.load();
  347. if(!err)
  348. {
  349. err = req.m_importer->writeSkeleton(*req.m_value);
  350. }
  351. if(err)
  352. {
  353. req.m_importer->m_errorInThread.store(err._getCode());
  354. }
  355. });
  356. }
  357. else
  358. {
  359. ANKI_CHECK(writeSkeleton(*req.m_value));
  360. }
  361. }
  362. if(m_jobManager)
  363. {
  364. m_jobManager->waitForAllTasksToFinish();
  365. const Error threadErr = m_errorInThread.load();
  366. if(threadErr)
  367. {
  368. ANKI_IMPORTER_LOGE("Error happened in a thread");
  369. return threadErr;
  370. }
  371. }
  372. // Animations
  373. for(const cgltf_animation* anim = m_gltf->animations; anim < m_gltf->animations + m_gltf->animations_count; ++anim)
  374. {
  375. ANKI_CHECK(writeAnimation(*anim));
  376. }
  377. ANKI_IMPORTER_LOGV("Importing GLTF has completed");
  378. return Error::kNone;
  379. }
  380. Error GltfImporter::appendExtras(const cgltf_extras& extras, ImporterHashMap<CString, ImporterString>& out) const
  381. {
  382. cgltf_size extrasSize;
  383. cgltf_copy_extras_json(m_gltf, &extras, nullptr, &extrasSize);
  384. if(extrasSize == 0)
  385. {
  386. return Error::kNone;
  387. }
  388. ImporterDynamicArrayLarge<char> json;
  389. json.resize(extrasSize + 1);
  390. cgltf_result res = cgltf_copy_extras_json(m_gltf, &extras, &json[0], &extrasSize);
  391. if(res != cgltf_result_success)
  392. {
  393. ANKI_IMPORTER_LOGE("cgltf_copy_extras_json failed: %d", res);
  394. return Error::kFunctionFailed;
  395. }
  396. json[json.getSize() - 1] = '\0';
  397. // Get token count
  398. CString jsonTxt(&json[0]);
  399. jsmn_parser parser;
  400. jsmn_init(&parser);
  401. const I tokenCount = jsmn_parse(&parser, jsonTxt.cstr(), jsonTxt.getLength(), nullptr, 0);
  402. if(tokenCount < 1)
  403. {
  404. return Error::kNone;
  405. }
  406. ImporterDynamicArray<jsmntok_t> tokens;
  407. tokens.resize(U32(tokenCount));
  408. // Get tokens
  409. jsmn_init(&parser);
  410. jsmn_parse(&parser, jsonTxt.cstr(), jsonTxt.getLength(), &tokens[0], tokens.getSize());
  411. ImporterStringList tokenStrings;
  412. for(const jsmntok_t& token : tokens)
  413. {
  414. if(token.type != JSMN_STRING && token.type != JSMN_PRIMITIVE)
  415. {
  416. continue;
  417. }
  418. ImporterString tokenStr(&jsonTxt[token.start], &jsonTxt[token.end]);
  419. tokenStrings.pushBack(tokenStr.toCString());
  420. }
  421. if((tokenStrings.getSize() % 2) != 0)
  422. {
  423. ANKI_IMPORTER_LOGV("Ignoring: %s", jsonTxt.cstr());
  424. return Error::kNone;
  425. }
  426. // Write them to the map
  427. auto it = tokenStrings.getBegin();
  428. while(it != tokenStrings.getEnd())
  429. {
  430. auto it2 = it;
  431. ++it2;
  432. out.emplace(it->toCString(), ImporterString(it2->toCString()));
  433. ++it;
  434. ++it;
  435. }
  436. return Error::kNone;
  437. }
  438. static void appendExtrasMap(const ImporterHashMap<CString, ImporterString>& in, ImporterHashMap<CString, ImporterString>& out)
  439. {
  440. auto& outs = out.getSparseArray();
  441. for(auto it = in.getBegin(); it != in.getEnd(); ++it)
  442. {
  443. outs.emplace(it.getKey(), *it);
  444. }
  445. }
  446. void GltfImporter::populateNodePtrToIdxInternal(const cgltf_node& node, U32& idx)
  447. {
  448. m_nodePtrToIdx.emplace(&node, idx++);
  449. for(cgltf_node* const* c = node.children; c < node.children + node.children_count; ++c)
  450. {
  451. populateNodePtrToIdxInternal(**c, idx);
  452. }
  453. }
  454. void GltfImporter::populateNodePtrToIdx()
  455. {
  456. U32 idx = 0;
  457. for(const cgltf_scene* scene = m_gltf->scenes; scene < m_gltf->scenes + m_gltf->scenes_count; ++scene)
  458. {
  459. for(cgltf_node* const* node = scene->nodes; node < scene->nodes + scene->nodes_count; ++node)
  460. {
  461. populateNodePtrToIdxInternal(**node, idx);
  462. }
  463. }
  464. }
  465. ImporterString GltfImporter::getNodeName(const cgltf_node& node) const
  466. {
  467. ImporterString out;
  468. if(node.name)
  469. {
  470. out = node.name;
  471. }
  472. else
  473. {
  474. auto it = m_nodePtrToIdx.find(&node);
  475. ANKI_ASSERT(it != m_nodePtrToIdx.getEnd());
  476. out.sprintf("unnamed_node_%u", *it);
  477. }
  478. return out;
  479. }
  480. Error GltfImporter::parseArrayOfNumbers(CString str, ImporterDynamicArray<F64>& out, const U32* expectedArraySize)
  481. {
  482. ImporterStringList list;
  483. list.splitString(str, ' ');
  484. out.resize(U32(list.getSize()));
  485. Error err = Error::kNone;
  486. auto it = list.getBegin();
  487. auto end = list.getEnd();
  488. U32 i = 0;
  489. while(it != end && !err)
  490. {
  491. err = it->toNumber(out[i++]);
  492. ++it;
  493. }
  494. if(err)
  495. {
  496. ANKI_IMPORTER_LOGE("Failed to parse floats: %s", str.cstr());
  497. }
  498. if(expectedArraySize && *expectedArraySize != out.getSize())
  499. {
  500. ANKI_IMPORTER_LOGE("Failed to parse floats. Expecting %u floats got %u: %s", *expectedArraySize, out.getSize(), str.cstr());
  501. }
  502. return Error::kNone;
  503. }
  504. Error GltfImporter::visitNode(const cgltf_node& node, const Transform& parentTrf, const ImporterHashMap<CString, ImporterString>& parentExtras)
  505. {
  506. // Check error from a thread
  507. const Error threadErr = m_errorInThread.load();
  508. if(threadErr)
  509. {
  510. ANKI_IMPORTER_LOGE("Error happened in a thread");
  511. return threadErr;
  512. }
  513. ImporterHashMap<CString, ImporterString> outExtras;
  514. if(node.light)
  515. {
  516. ImporterHashMap<CString, ImporterString> extras;
  517. ANKI_CHECK(appendExtras(node.light->extras, extras));
  518. ANKI_CHECK(appendExtras(node.extras, extras));
  519. appendExtrasMap(parentExtras, extras);
  520. ANKI_CHECK(writeLight(node, extras));
  521. Transform localTrf;
  522. ANKI_CHECK(getNodeTransform(node, localTrf));
  523. localTrf.setScale(Vec4(1.0f, 1.0f, 1.0f, 0.0f)); // Remove scale
  524. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  525. }
  526. else if(node.camera)
  527. {
  528. ImporterHashMap<CString, ImporterString> extras;
  529. ANKI_CHECK(appendExtras(node.camera->extras, extras));
  530. ANKI_CHECK(appendExtras(node.extras, extras));
  531. appendExtrasMap(parentExtras, extras);
  532. ANKI_CHECK(writeCamera(node, extras));
  533. Transform localTrf;
  534. ANKI_CHECK(getNodeTransform(node, localTrf));
  535. localTrf.setScale(Vec4(1.0f, 1.0f, 1.0f, 0.0f)); // Remove scale
  536. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  537. }
  538. else if(node.mesh)
  539. {
  540. // Handle special nodes
  541. ImporterHashMap<CString, ImporterString> extras;
  542. ANKI_CHECK(appendExtras(node.mesh->extras, extras));
  543. ANKI_CHECK(appendExtras(node.extras, extras));
  544. appendExtrasMap(parentExtras, extras);
  545. ImporterString extraValueStr;
  546. Bool extraValueBool = false;
  547. Vec3 extraValueVec3;
  548. F32 extraValuef = 0.0f;
  549. Bool extraFound = false;
  550. ANKI_CHECK(getExtra(extras, "particleEmitterResource", extraValueStr, extraFound));
  551. if(extraFound)
  552. {
  553. ImporterString materialFname;
  554. ANKI_CHECK(getExtra(extras, "materialResource", materialFname, extraFound));
  555. if(!extraFound)
  556. {
  557. ANKI_IMPORTER_LOGE("A \"particleEmitterResource\" also requires a \"materialResource\". Ignoring node");
  558. }
  559. else
  560. {
  561. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  562. ANKI_CHECK(m_sceneFile.writeTextf("comp = node:newParticleEmitter2Component()\n"));
  563. ANKI_CHECK(m_sceneFile.writeTextf("comp:setParticleEmitterFilename(\"%s\")\n", extraValueStr.cstr()));
  564. ANKI_CHECK(m_sceneFile.writeTextf("comp = node:newMaterialComponent()\n"));
  565. ANKI_CHECK(m_sceneFile.writeTextf("comp:setMaterialFilename(\"%s\")\n", materialFname.cstr()));
  566. Transform localTrf;
  567. ANKI_CHECK(getNodeTransform(node, localTrf));
  568. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  569. }
  570. }
  571. else if(stringsExist(extras, {"skybox_solid_color", "skybox_image", "fog_min_density", "fog_max_density", "fog_height_of_min_density",
  572. "fog_height_of_max_density", "fog_diffuse_color", "skybox_generated"}))
  573. {
  574. // Atmosphere
  575. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  576. ANKI_CHECK(m_sceneFile.writeText("comp = node:newSkyboxComponent()\n"));
  577. ANKI_CHECK(getExtra(extras, "skybox_solid_color", extraValueVec3, extraFound));
  578. if(extraFound)
  579. {
  580. ANKI_CHECK(
  581. m_sceneFile.writeTextf("comp:setSolidColor(Vec3.new(%f, %f, %f))\n", extraValueVec3.x, extraValueVec3.y, extraValueVec3.z));
  582. }
  583. ANKI_CHECK(getExtra(extras, "skybox_image", extraValueStr, extraFound));
  584. if(extraFound)
  585. {
  586. ANKI_CHECK(m_sceneFile.writeTextf("comp:loadImageResource(\"%s\")\n", extraValueStr.cstr()));
  587. }
  588. ANKI_CHECK(getExtra(extras, "skybox_image_scale", extraValueVec3, extraFound));
  589. if(extraFound)
  590. {
  591. ANKI_CHECK(
  592. m_sceneFile.writeTextf("comp:setImageScale(Vec3.new(%f, %f, %f))\n", extraValueVec3.x, extraValueVec3.y, extraValueVec3.z));
  593. }
  594. ANKI_CHECK(getExtra(extras, "fog_min_density", extraValuef, extraFound));
  595. if(extraFound)
  596. {
  597. ANKI_CHECK(m_sceneFile.writeTextf("comp:setMinFogDensity(%f)\n", extraValuef));
  598. }
  599. ANKI_CHECK(getExtra(extras, "fog_max_density", extraValuef, extraFound));
  600. if(extraFound)
  601. {
  602. ANKI_CHECK(m_sceneFile.writeTextf("comp:setMaxFogDensity(%f)\n", extraValuef));
  603. }
  604. ANKI_CHECK(getExtra(extras, "fog_height_of_min_density", extraValuef, extraFound));
  605. if(extraFound)
  606. {
  607. ANKI_CHECK(m_sceneFile.writeTextf("comp:setHeightOfMinFogDensity(%f)\n", extraValuef));
  608. }
  609. ANKI_CHECK(getExtra(extras, "fog_height_of_max_density", extraValuef, extraFound));
  610. if(extraFound)
  611. {
  612. ANKI_CHECK(m_sceneFile.writeTextf("comp:setHeightOfMaxFogDensity(%f)\n", extraValuef));
  613. }
  614. ANKI_CHECK(getExtra(extras, "fog_diffuse_color", extraValueVec3, extraFound));
  615. if(extraFound)
  616. {
  617. ANKI_CHECK(
  618. m_sceneFile.writeTextf("comp:setFogDiffuseColor(Vec3.new(%f, %f, %f))\n", extraValueVec3.x, extraValueVec3.y, extraValueVec3.z));
  619. }
  620. ANKI_CHECK(getExtra(extras, "skybox_generated", extraValueBool, extraFound));
  621. if(extraFound && extraValueBool)
  622. {
  623. ANKI_CHECK(m_sceneFile.writeTextf("comp:setGeneratedSky()\n"));
  624. }
  625. Transform localTrf;
  626. ANKI_CHECK(getNodeTransform(node, localTrf));
  627. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  628. }
  629. else if(stringsExist(extras, {"collision"}))
  630. {
  631. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  632. ANKI_CHECK(m_sceneFile.writeText("comp = scene:newBodyComponent()\n"));
  633. const ImporterString meshFname = computeMeshResourceFilename(*node.mesh);
  634. ANKI_CHECK(m_sceneFile.writeTextf("comp:loadMeshResource(\"%s%s\")\n", m_rpath.cstr(), meshFname.cstr()));
  635. Transform localTrf;
  636. ANKI_CHECK(getNodeTransform(node, localTrf));
  637. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  638. }
  639. else if(stringsExist(extras, {"reflection_probe"}))
  640. {
  641. Vec3 tsl;
  642. Mat3 rot;
  643. Vec3 scale;
  644. getNodeTransform(node, tsl, rot, scale);
  645. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  646. ANKI_CHECK(m_sceneFile.writeText("comp = node:newReflectionProbeComponent()\n"));
  647. const Transform localTrf = Transform(tsl, rot, scale);
  648. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  649. }
  650. else if(stringsExist(extras, {"gi_probe"}))
  651. {
  652. Vec3 tsl;
  653. Mat3 rot;
  654. Vec3 scale;
  655. getNodeTransform(node, tsl, rot, scale);
  656. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  657. ANKI_CHECK(m_sceneFile.writeText("comp = node:newGlobalIlluminationProbeComponent()\n"));
  658. ANKI_CHECK(getExtra(extras, "gi_probe_fade_distance", extraValuef, extraFound));
  659. if(extraFound && extraValuef > 0.0f)
  660. {
  661. ANKI_CHECK(m_sceneFile.writeTextf("comp:setFadeDistance(%f)\n", extraValuef));
  662. }
  663. ANKI_CHECK(getExtra(extras, "gi_probe_cell_size", extraValuef, extraFound));
  664. if(extraFound && extraValuef > 0.0f)
  665. {
  666. ANKI_CHECK(m_sceneFile.writeTextf("comp:setCellSize(%f)\n", extraValuef));
  667. }
  668. const Transform localTrf = Transform(tsl, rot, scale);
  669. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  670. }
  671. else if(stringsExist(extras, {"decal"}))
  672. {
  673. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  674. ANKI_CHECK(m_sceneFile.writeText("comp = node:newDecalComponent()\n"));
  675. ANKI_CHECK(getExtra(extras, "decal_diffuse", extraValueStr, extraFound));
  676. if(extraFound)
  677. {
  678. ANKI_CHECK(getExtra(extras, "decal_diffuse_factor", extraValuef, extraFound));
  679. ANKI_CHECK(
  680. m_sceneFile.writeTextf("comp:setDiffuseImageFilename(\"%s\", %f)\n", extraValueStr.cstr(), (extraFound) ? extraValuef : 1.0f));
  681. }
  682. ANKI_CHECK(getExtra(extras, "decal_metal_roughness", extraValueStr, extraFound));
  683. if(extraFound)
  684. {
  685. ANKI_CHECK(getExtra(extras, "decal_metal_roughness_factor", extraValuef, extraFound));
  686. ANKI_CHECK(m_sceneFile.writeTextf("comp:setMetalRoughnessImageFilename(\"%s\", %f)\n", extraValueStr.cstr(),
  687. (extraFound) ? extraValuef : 1.0f));
  688. }
  689. Vec3 tsl;
  690. Mat3 rot;
  691. Vec3 scale;
  692. getNodeTransform(node, tsl, rot, scale);
  693. const Transform localTrf = Transform(tsl, rot, scale);
  694. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  695. }
  696. else if(isNodeValid(node))
  697. {
  698. // Mesh+Material node
  699. ANKI_CHECK(getExtra(extras, "no_rt", extraValueBool, extraFound));
  700. const Bool skipRt = (extraFound) ? extraValueBool : false;
  701. Transform localTrf;
  702. const Error err = getNodeTransform(node, localTrf);
  703. if(err)
  704. {
  705. ANKI_IMPORTER_LOGE("Will skip node: %s", getNodeName(node).cstr());
  706. }
  707. else
  708. {
  709. addRequest<const cgltf_mesh*>(node.mesh, m_meshImportRequests);
  710. for(U32 i = 0; i < node.mesh->primitives_count; ++i)
  711. {
  712. const MaterialImportRequest req = {node.mesh->primitives[i].material, !skipRt};
  713. addRequest<MaterialImportRequest>(req, m_materialImportRequests);
  714. }
  715. if(node.skin)
  716. {
  717. addRequest<const cgltf_skin*>(node.skin, m_skinImportRequests);
  718. }
  719. ImporterHashMap<CString, ImporterString>::Iterator it2;
  720. const Bool selfCollision = (it2 = extras.find("collision_mesh")) != extras.getEnd() && *it2 == "self";
  721. ANKI_CHECK(writeMeshMaterialNode(node, parentExtras));
  722. ANKI_CHECK(writeTransform(parentTrf.combineTransformations(localTrf)));
  723. if(selfCollision)
  724. {
  725. ANKI_CHECK(m_sceneFile.writeText("comp = node:newBodyComponent()\n"));
  726. const ImporterString meshFname = computeMeshResourceFilename(*node.mesh);
  727. ANKI_CHECK(m_sceneFile.writeText("comp:setCollisionShapeType(BodyComponentCollisionShapeType.kFromMeshComponent)\n"));
  728. }
  729. }
  730. }
  731. else
  732. {
  733. ANKI_IMPORTER_LOGV("Ignoring invalid node: %s", getNodeName(node).cstr());
  734. }
  735. }
  736. else
  737. {
  738. ANKI_IMPORTER_LOGV("Ignoring node %s. Assuming transform node", getNodeName(node).cstr());
  739. ANKI_CHECK(appendExtras(node.extras, outExtras));
  740. }
  741. // Visit children
  742. Transform nodeTrf;
  743. {
  744. Vec3 tsl;
  745. Mat3 rot;
  746. Vec3 scale;
  747. getNodeTransform(node, tsl, rot, scale);
  748. nodeTrf = Transform(tsl.xyz0, Mat3x4(Vec3(0.0f), rot), scale.xyz0);
  749. }
  750. for(cgltf_node* const* c = node.children; c < node.children + node.children_count; ++c)
  751. {
  752. ANKI_CHECK(visitNode(*(*c), nodeTrf, outExtras));
  753. }
  754. return Error::kNone;
  755. }
  756. Error GltfImporter::writeTransform(const Transform& trf)
  757. {
  758. ANKI_CHECK(m_sceneFile.writeText("trf = Transform.new()\n"));
  759. ANKI_CHECK(m_sceneFile.writeTextf("trf:setOrigin(Vec3.new(%f, %f, %f))\n", trf.getOrigin().x, trf.getOrigin().y, trf.getOrigin().z));
  760. ANKI_CHECK(m_sceneFile.writeText("rot = Mat3.new()\n"));
  761. ANKI_CHECK(m_sceneFile.writeText("rot:setAll("));
  762. for(U i = 0; i < 9; i++)
  763. {
  764. ANKI_CHECK(m_sceneFile.writeTextf((i != 8) ? "%f, " : "%f)\n", trf.getRotation().getRotationPart()[i]));
  765. }
  766. ANKI_CHECK(m_sceneFile.writeText("trf:setRotation(rot)\n"));
  767. ANKI_CHECK(m_sceneFile.writeTextf("trf:setScale(Vec3.new(%f, %f, %f))\n", trf.getScale().x, trf.getScale().y, trf.getScale().z));
  768. ANKI_CHECK(m_sceneFile.writeText("node:setLocalTransform(trf)\n"));
  769. return Error::kNone;
  770. }
  771. Error GltfImporter::writeSkeleton(const cgltf_skin& skin) const
  772. {
  773. ImporterString fname;
  774. fname.sprintf("%s%s", m_outDir.cstr(), computeSkeletonResourceFilename(skin).cstr());
  775. ANKI_IMPORTER_LOGV("Importing skeleton %s", fname.cstr());
  776. // Get matrices
  777. ImporterDynamicArray<Mat4> boneMats;
  778. readAccessor(*skin.inverse_bind_matrices, boneMats);
  779. if(boneMats.getSize() != skin.joints_count)
  780. {
  781. ANKI_IMPORTER_LOGE("Bone matrices should match the joint count");
  782. return Error::kUserData;
  783. }
  784. // Write file
  785. File file;
  786. ANKI_CHECK(file.open(fname.toCString(), FileOpenFlag::kWrite));
  787. ANKI_CHECK(file.writeTextf("%s\n<skeleton>\n", XmlDocument<MemoryPoolPtrWrapper<BaseMemoryPool>>::kXmlHeader.cstr()));
  788. ANKI_CHECK(file.writeTextf("\t<bones>\n"));
  789. for(U32 i = 0; i < skin.joints_count; ++i)
  790. {
  791. const cgltf_node& boneNode = *skin.joints[i];
  792. ImporterString parent;
  793. // Name & parent
  794. ANKI_CHECK(file.writeTextf("\t\t<bone name=\"%s\" ", getNodeName(boneNode).cstr()));
  795. if(boneNode.parent && getNodeName(*boneNode.parent) != skin.name)
  796. {
  797. ANKI_CHECK(file.writeTextf("parent=\"%s\" ", getNodeName(*boneNode.parent).cstr()));
  798. }
  799. // Bone transform
  800. ANKI_CHECK(file.writeText("boneTransform=\""));
  801. Mat4 btrf(&boneMats[i][0]);
  802. btrf = btrf.transpose();
  803. const Mat3x4 btrf3x4(btrf);
  804. for(U32 j = 0; j < 12; j++)
  805. {
  806. ANKI_CHECK(file.writeTextf("%f ", btrf3x4[j]));
  807. }
  808. ANKI_CHECK(file.writeText("\" "));
  809. // Transform
  810. Transform trf;
  811. ANKI_CHECK(getNodeTransform(boneNode, trf));
  812. Mat3x4 mat(trf);
  813. ANKI_CHECK(file.writeText("transform=\""));
  814. for(U j = 0; j < 12; j++)
  815. {
  816. ANKI_CHECK(file.writeTextf("%f ", mat[j]));
  817. }
  818. ANKI_CHECK(file.writeText("\" "));
  819. ANKI_CHECK(file.writeText("/>\n"));
  820. }
  821. ANKI_CHECK(file.writeText("\t</bones>\n"));
  822. ANKI_CHECK(file.writeText("</skeleton>\n"));
  823. return Error::kNone;
  824. }
  825. Error GltfImporter::writeLight(const cgltf_node& node, const ImporterHashMap<CString, ImporterString>& parentExtras)
  826. {
  827. const cgltf_light& light = *node.light;
  828. ImporterString nodeName = getNodeName(node);
  829. ANKI_IMPORTER_LOGV("Importing light %s", nodeName.cstr());
  830. ImporterHashMap<CString, ImporterString> extras(parentExtras);
  831. ANKI_CHECK(appendExtras(light.extras, extras));
  832. ANKI_CHECK(appendExtras(node.extras, extras));
  833. CString lightTypeStr;
  834. switch(light.type)
  835. {
  836. case cgltf_light_type_point:
  837. lightTypeStr = "Point";
  838. break;
  839. case cgltf_light_type_spot:
  840. lightTypeStr = "Spot";
  841. break;
  842. case cgltf_light_type_directional:
  843. lightTypeStr = "Directional";
  844. break;
  845. default:
  846. ANKI_IMPORTER_LOGE("Unsupporter light type %d", light.type);
  847. return Error::kUserData;
  848. }
  849. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", nodeName.cstr()));
  850. ANKI_CHECK(m_sceneFile.writeText("lcomp = node:newLightComponent()\n"));
  851. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setLightComponentType(LightComponentType.k%s)\n", lightTypeStr.cstr()));
  852. Vec3 color(light.color[0], light.color[1], light.color[2]);
  853. color *= light.intensity;
  854. color *= m_lightIntensityScale;
  855. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setDiffuseColor(Vec4.new(%f, %f, %f, 1))\n", color.x, color.y, color.z));
  856. auto shadow = extras.find("shadow");
  857. if(shadow != extras.getEnd())
  858. {
  859. if(*shadow == "true" || *shadow == "1")
  860. {
  861. ANKI_CHECK(m_sceneFile.writeText("lcomp:setShadowEnabled(1)\n"));
  862. }
  863. else
  864. {
  865. ANKI_CHECK(m_sceneFile.writeText("lcomp:setShadowEnabled(0)\n"));
  866. }
  867. }
  868. if(light.type == cgltf_light_type_point)
  869. {
  870. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setRadius(%f)\n", (light.range > 0.0f) ? light.range : computeLightRadius(color)));
  871. }
  872. else if(light.type == cgltf_light_type_spot)
  873. {
  874. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setDistance(%f)\n", (light.range > 0.0f) ? light.range : computeLightRadius(color)));
  875. const F32 outer = light.spot_outer_cone_angle * 2.0f;
  876. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setOuterAngle(%f)\n", outer));
  877. auto angStr = extras.find("inner_cone_angle_factor");
  878. F32 inner;
  879. if(angStr != extras.getEnd())
  880. {
  881. F32 factor;
  882. ANKI_CHECK(angStr->toNumber(factor));
  883. inner = light.spot_inner_cone_angle * 2.0f * min(1.0f, factor);
  884. }
  885. else
  886. {
  887. inner = light.spot_inner_cone_angle * 2.0f;
  888. }
  889. if(inner >= 0.95f * outer)
  890. {
  891. inner = 0.75f * outer;
  892. }
  893. ANKI_CHECK(m_sceneFile.writeTextf("lcomp:setInnerAngle(%f)\n", inner));
  894. }
  895. auto lensFlaresFname = extras.find("lens_flare");
  896. if(lensFlaresFname != extras.getEnd())
  897. {
  898. ANKI_CHECK(m_sceneFile.writeTextf("lfcomp = node:newLensFlareComponent()\n"));
  899. ANKI_CHECK(m_sceneFile.writeTextf("lfcomp:loadImageResource(\"%s\")\n", lensFlaresFname->cstr()));
  900. auto lsSpriteSize = extras.find("lens_flare_first_sprite_size");
  901. auto lsColor = extras.find("lens_flare_color");
  902. if(lsSpriteSize != extras.getEnd())
  903. {
  904. ImporterDynamicArray<F64> numbers;
  905. const U32 count = 2;
  906. ANKI_CHECK(parseArrayOfNumbers(lsSpriteSize->toCString(), numbers, &count));
  907. ANKI_CHECK(m_sceneFile.writeTextf("lfcomp:setFirstFlareSize(Vec2.new(%f, %f))\n", numbers[0], numbers[1]));
  908. }
  909. if(lsColor != extras.getEnd())
  910. {
  911. ImporterDynamicArray<F64> numbers;
  912. const U32 count = 4;
  913. ANKI_CHECK(parseArrayOfNumbers(lsColor->toCString(), numbers, &count));
  914. ANKI_CHECK(
  915. m_sceneFile.writeTextf("lfcomp:setColorMultiplier(Vec4.new(%f, %f, %f, %f))\n", numbers[0], numbers[1], numbers[2], numbers[3]));
  916. }
  917. }
  918. auto lightEventIntensity = extras.find("light_event_intensity");
  919. auto lightEventFrequency = extras.find("light_event_frequency");
  920. if(lightEventIntensity != extras.getEnd() || lightEventFrequency != extras.getEnd())
  921. {
  922. ANKI_CHECK(m_sceneFile.writeText("event = events:newLightEvent(0.0, -1.0, node)\n"));
  923. if(lightEventIntensity != extras.getEnd())
  924. {
  925. ImporterDynamicArray<F64> numbers;
  926. const U32 count = 4;
  927. ANKI_CHECK(parseArrayOfNumbers(lightEventIntensity->toCString(), numbers, &count));
  928. ANKI_CHECK(
  929. m_sceneFile.writeTextf("event:setIntensityMultiplier(Vec4.new(%f, %f, %f, %f))\n", numbers[0], numbers[1], numbers[2], numbers[3]));
  930. }
  931. if(lightEventFrequency != extras.getEnd())
  932. {
  933. ImporterDynamicArray<F64> numbers;
  934. const U32 count = 2;
  935. ANKI_CHECK(parseArrayOfNumbers(lightEventFrequency->toCString(), numbers, &count));
  936. ANKI_CHECK(m_sceneFile.writeTextf("event:setFrequency(%f, %f)\n", numbers[0], numbers[1]));
  937. }
  938. }
  939. return Error::kNone;
  940. }
  941. Error GltfImporter::writeCamera(const cgltf_node& node, [[maybe_unused]] const ImporterHashMap<CString, ImporterString>& parentExtras)
  942. {
  943. if(node.camera->type != cgltf_camera_type_perspective)
  944. {
  945. ANKI_IMPORTER_LOGV("Unsupported camera type: %s", getNodeName(node).cstr());
  946. return Error::kNone;
  947. }
  948. const cgltf_camera_perspective& cam = node.camera->data.perspective;
  949. ANKI_IMPORTER_LOGV("Importing camera %s", getNodeName(node).cstr());
  950. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  951. ANKI_CHECK(m_sceneFile.writeText("scene:setActiveCameraNode(node)\n"));
  952. ANKI_CHECK(m_sceneFile.writeText("comp = node:newCameraComponent()\n"));
  953. ANKI_CHECK(
  954. m_sceneFile.writeTextf("comp:setPerspective(%f, %f, getRenderer():getAspectRatio() * %f, %f)\n", cam.znear, cam.zfar, cam.yfov, cam.yfov));
  955. return Error::kNone;
  956. }
  957. Error GltfImporter::writeMeshMaterialNode(const cgltf_node& node, const ImporterHashMap<CString, ImporterString>& parentExtras)
  958. {
  959. ANKI_IMPORTER_LOGV("Importing mesh&material node %s", getNodeName(node).cstr());
  960. ImporterHashMap<CString, ImporterString> extras(parentExtras);
  961. ANKI_CHECK(appendExtras(node.extras, extras));
  962. ANKI_CHECK(m_sceneFile.writeTextf("\nnode = scene:newSceneNode(\"%s\")\n", getNodeName(node).cstr()));
  963. const cgltf_mesh& mesh = *node.mesh;
  964. ANKI_CHECK(
  965. m_sceneFile.writeTextf("node:newMeshComponent():setMeshFilename(\"%s%s\")\n", m_rpath.cstr(), computeMeshResourceFilename(mesh).cstr()));
  966. for(U32 primIdx = 0; primIdx < mesh.primitives_count; ++primIdx)
  967. {
  968. ANKI_CHECK(m_sceneFile.writeTextf("node:newMaterialComponent():setMaterialFilename(\"%s%s\"):setSubmeshIndex(%u)\n", m_rpath.cstr(),
  969. computeMaterialResourceFilename(*mesh.primitives[primIdx].material).cstr(), primIdx));
  970. }
  971. if(node.skin)
  972. {
  973. ANKI_CHECK(m_sceneFile.writeTextf("node:newSkinComponent():setSkeletonFilename(\"%s%s\")\n", m_rpath.cstr(),
  974. computeSkeletonResourceFilename(*node.skin).cstr()));
  975. }
  976. return Error::kNone;
  977. }
  978. ImporterString GltfImporter::computeMeshResourceFilename(const cgltf_mesh& mesh) const
  979. {
  980. const U64 hash = computeHash(mesh.name, strlen(mesh.name));
  981. ImporterString out;
  982. out.sprintf("%.64s_%" PRIx64 ".ankimesh", mesh.name, hash); // Limit the filename size
  983. return out;
  984. }
  985. ImporterString GltfImporter::computeMaterialResourceFilename(const cgltf_material& mtl) const
  986. {
  987. const U64 hash = computeHash(mtl.name, strlen(mtl.name));
  988. ImporterString out;
  989. out.sprintf("%.64s_%" PRIx64 ".ankimtl", mtl.name, hash); // Limit the filename size
  990. return out;
  991. }
  992. ImporterString GltfImporter::computeAnimationResourceFilename(const cgltf_animation& anim) const
  993. {
  994. const U64 hash = computeHash(anim.name, strlen(anim.name));
  995. ImporterString out;
  996. out.sprintf("%.64s_%" PRIx64 ".ankianim", anim.name, hash); // Limit the filename size
  997. return out;
  998. }
  999. ImporterString GltfImporter::computeSkeletonResourceFilename(const cgltf_skin& skin) const
  1000. {
  1001. const U64 hash = computeHash(skin.name, strlen(skin.name));
  1002. ImporterString out;
  1003. out.sprintf("%.64s_%" PRIx64 ".ankiskel", skin.name, hash); // Limit the filename size
  1004. return out;
  1005. }
  1006. } // end namespace anki