Exporter.cpp 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. // Copyright (C) 2009-2019, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include "Exporter.h"
  6. #include <iostream>
  7. static const char* XML_HEADER = R"(<?xml version="1.0" encoding="UTF-8" ?>)";
  8. static aiColor3D srgbToLinear(aiColor3D in)
  9. {
  10. const float p = 1.0 / 2.4;
  11. aiColor3D out;
  12. out[0] = pow(in[0], p);
  13. out[1] = pow(in[1], p);
  14. out[2] = pow(in[2], p);
  15. out[3] = in[3];
  16. return out;
  17. }
  18. /// Convert from sRGB to linear and preserve energy
  19. static aiColor3D computeLightColor(aiColor3D in)
  20. {
  21. float energy = std::max(std::max(in[0], in[1]), in[2]);
  22. if(energy > 1.0)
  23. {
  24. in[0] /= energy;
  25. in[1] /= energy;
  26. in[2] /= energy;
  27. }
  28. else
  29. {
  30. energy = 1.0;
  31. }
  32. in = srgbToLinear(in);
  33. in[0] *= energy;
  34. in[1] *= energy;
  35. in[2] *= energy;
  36. return in;
  37. }
  38. static std::string getMeshName(const aiMesh& mesh)
  39. {
  40. return std::string(mesh.mName.C_Str());
  41. }
  42. /// Walk the node hierarchy and find the node.
  43. static const aiNode* findNodeWithName(const std::string& name, const aiNode* node, unsigned* depth = nullptr)
  44. {
  45. if(node == nullptr || node->mName.C_Str() == name)
  46. {
  47. return node;
  48. }
  49. if(depth)
  50. {
  51. ++(*depth);
  52. }
  53. const aiNode* out = nullptr;
  54. // Go to children
  55. for(unsigned i = 0; i < node->mNumChildren; i++)
  56. {
  57. out = findNodeWithName(name, node->mChildren[i]);
  58. if(out)
  59. {
  60. break;
  61. }
  62. }
  63. return out;
  64. }
  65. static std::vector<std::string> tokenize(const std::string& source)
  66. {
  67. const char* delimiter = " ";
  68. bool keepEmpty = false;
  69. std::vector<std::string> results;
  70. size_t prev = 0;
  71. size_t next = 0;
  72. while((next = source.find_first_of(delimiter, prev)) != std::string::npos)
  73. {
  74. if(keepEmpty || (next - prev != 0))
  75. {
  76. results.push_back(source.substr(prev, next - prev));
  77. }
  78. prev = next + 1;
  79. }
  80. if(prev < source.size())
  81. {
  82. results.push_back(source.substr(prev));
  83. }
  84. return results;
  85. }
  86. template<int N, typename Arr>
  87. static void stringToFloatArray(const std::string& in, Arr& out)
  88. {
  89. std::vector<std::string> tokens = tokenize(in);
  90. if(tokens.size() != N)
  91. {
  92. ERROR("Failed to parse %s", in.c_str());
  93. }
  94. int count = 0;
  95. for(const std::string& s : tokens)
  96. {
  97. out[count] = std::stof(s);
  98. ++count;
  99. }
  100. }
  101. static void removeScale(aiMatrix4x4& m)
  102. {
  103. aiVector3D xAxis(m.a1, m.b1, m.c1);
  104. aiVector3D yAxis(m.a2, m.b2, m.c2);
  105. aiVector3D zAxis(m.a3, m.b3, m.c3);
  106. float scale = xAxis.Length();
  107. m.a1 /= scale;
  108. m.b1 /= scale;
  109. m.c1 /= scale;
  110. scale = yAxis.Length();
  111. m.a2 /= scale;
  112. m.b2 /= scale;
  113. m.c2 /= scale;
  114. scale = zAxis.Length();
  115. m.a3 /= scale;
  116. m.b3 /= scale;
  117. m.c3 /= scale;
  118. }
  119. static float getUniformScale(const aiMatrix4x4& m)
  120. {
  121. const float SCALE_THRESHOLD = 0.01; // 1 cm
  122. aiVector3D xAxis(m.a1, m.b1, m.c1);
  123. aiVector3D yAxis(m.a2, m.b2, m.c2);
  124. aiVector3D zAxis(m.a3, m.b3, m.c3);
  125. float scale = xAxis.Length();
  126. if(std::abs(scale - yAxis.Length()) > SCALE_THRESHOLD || std::abs(scale - zAxis.Length()) > SCALE_THRESHOLD)
  127. {
  128. ERROR("No uniform scale in the matrix");
  129. }
  130. return scale;
  131. }
  132. static aiVector3D getNonUniformScale(const aiMatrix4x4& m)
  133. {
  134. aiVector3D xAxis(m.a1, m.b1, m.c1);
  135. aiVector3D yAxis(m.a2, m.b2, m.c2);
  136. aiVector3D zAxis(m.a3, m.b3, m.c3);
  137. aiVector3D scale;
  138. scale[0] = xAxis.Length();
  139. scale[1] = yAxis.Length();
  140. scale[2] = zAxis.Length();
  141. return scale;
  142. }
  143. std::string Exporter::getMaterialName(const aiMaterial& mtl)
  144. {
  145. aiString ainame;
  146. std::string name;
  147. if(mtl.Get(AI_MATKEY_NAME, ainame) == AI_SUCCESS)
  148. {
  149. name = ainame.C_Str();
  150. }
  151. else
  152. {
  153. ERROR("Material's name is missing");
  154. }
  155. return name;
  156. }
  157. aiMatrix4x4 Exporter::toAnkiMatrix(const aiMatrix4x4& in) const
  158. {
  159. static const aiMatrix4x4 toLeftHanded(1, 0, 0, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1);
  160. static const aiMatrix4x4 toLeftHandedInv(1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1);
  161. if(m_flipyz)
  162. {
  163. return toLeftHanded * in * toLeftHandedInv;
  164. }
  165. else
  166. {
  167. return in;
  168. }
  169. }
  170. aiMatrix3x3 Exporter::toAnkiMatrix(const aiMatrix3x3& in) const
  171. {
  172. static const aiMatrix3x3 toLeftHanded(1, 0, 0, 0, 0, 1, 0, -1, 0);
  173. static const aiMatrix3x3 toLeftHandedInv(1, 0, 0, 0, 0, -1, 0, 1, 0);
  174. if(m_flipyz)
  175. {
  176. return toLeftHanded * in;
  177. }
  178. else
  179. {
  180. return in;
  181. }
  182. }
  183. void Exporter::writeTransform(const aiMatrix4x4& inmat)
  184. {
  185. aiMatrix4x4 mat = inmat;
  186. std::ofstream& file = m_sceneFile;
  187. float pos[3];
  188. pos[0] = mat[0][3];
  189. pos[1] = mat[1][3];
  190. pos[2] = mat[2][3];
  191. file << "trf = Transform.new()\n";
  192. file << "trf:setOrigin(Vec4.new(" << pos[0] << ", " << pos[1] << ", " << pos[2] << ", 0))\n";
  193. float scale = getUniformScale(mat);
  194. removeScale(mat);
  195. file << "rot = Mat3x4.new()\n";
  196. file << "rot:setAll(";
  197. for(unsigned j = 0; j < 3; j++)
  198. {
  199. for(unsigned i = 0; i < 4; i++)
  200. {
  201. if(i == 3)
  202. {
  203. file << "0";
  204. }
  205. else
  206. {
  207. file << mat[j][i];
  208. }
  209. if(!(i == 3 && j == 2))
  210. {
  211. file << ", ";
  212. }
  213. }
  214. }
  215. file << ")\n";
  216. file << "trf:setRotation(rot)\n";
  217. file << "trf:setScale(" << scale << ")\n";
  218. }
  219. void Exporter::writeNodeTransform(const std::string& node, const aiMatrix4x4& mat)
  220. {
  221. std::ofstream& file = m_sceneFile;
  222. writeTransform(mat);
  223. file << node << ":getSceneNodeBase():getMoveComponent():setLocalTransform(trf)\n";
  224. }
  225. const aiMesh& Exporter::getMeshAt(unsigned index) const
  226. {
  227. assert(index < m_scene->mNumMeshes);
  228. return *m_scene->mMeshes[index];
  229. }
  230. const aiMaterial& Exporter::getMaterialAt(unsigned index) const
  231. {
  232. assert(index < m_scene->mNumMaterials);
  233. return *m_scene->mMaterials[index];
  234. }
  235. std::string Exporter::getModelName(const Model& model) const
  236. {
  237. std::string name = getMeshName(getMeshAt(model.m_meshIndex));
  238. name += getMaterialName(getMaterialAt(model.m_materialIndex));
  239. return name;
  240. }
  241. void Exporter::exportSkeleton(const aiMesh& mesh) const
  242. {
  243. assert(mesh.HasBones());
  244. std::string name = mesh.mName.C_Str();
  245. std::fstream file;
  246. LOGI("Exporting skeleton %s", name.c_str());
  247. // Find the root bone
  248. unsigned minDepth = 0xFFFFFFFF;
  249. std::string rootBoneName;
  250. for(uint32_t i = 0; i < mesh.mNumBones; i++)
  251. {
  252. const aiBone& bone = *mesh.mBones[i];
  253. unsigned depth = 0;
  254. const aiNode* node = findNodeWithName(bone.mName.C_Str(), m_scene->mRootNode, &depth);
  255. if(!node)
  256. {
  257. ERROR("Bone \"%s\" was not found in the scene hierarchy", bone.mName.C_Str());
  258. }
  259. if(depth < minDepth)
  260. {
  261. minDepth = depth;
  262. rootBoneName = bone.mName.C_Str();
  263. }
  264. }
  265. assert(!rootBoneName.empty());
  266. // Open file
  267. file.open(m_outputDirectory + name + ".ankiskel", std::ios::out);
  268. file << XML_HEADER << "\n";
  269. file << "<skeleton>\n";
  270. file << "\t<bones>\n";
  271. for(uint32_t i = 0; i < mesh.mNumBones; i++)
  272. {
  273. const aiBone& bone = *mesh.mBones[i];
  274. file << "\t\t<bone>\n";
  275. // <name>
  276. file << "\t\t\t<name>" << bone.mName.C_Str() << "</name>\n";
  277. // <boneTransform>
  278. aiMatrix4x4 akMat = toAnkiMatrix(bone.mOffsetMatrix);
  279. file << "\t\t\t<boneTransform>";
  280. for(unsigned j = 0; j < 4; j++)
  281. {
  282. for(unsigned i = 0; i < 4; i++)
  283. {
  284. file << akMat[j][i] << " ";
  285. }
  286. }
  287. file << "</boneTransform>\n";
  288. // <transform>
  289. const aiNode* node = findNodeWithName(bone.mName.C_Str(), m_scene->mRootNode);
  290. assert(node);
  291. akMat = toAnkiMatrix(node->mTransformation);
  292. file << "\t\t\t<transform>";
  293. for(unsigned j = 0; j < 4; j++)
  294. {
  295. for(unsigned i = 0; i < 4; i++)
  296. {
  297. file << akMat[j][i] << " ";
  298. }
  299. }
  300. file << "</transform>\n";
  301. // <parent>
  302. if(bone.mName.C_Str() != rootBoneName)
  303. {
  304. file << "\t\t\t<parent>" << node->mParent->mName.C_Str() << "</parent>\n";
  305. }
  306. file << "\t\t</bone>\n";
  307. }
  308. file << "\t</bones>\n";
  309. file << "</skeleton>\n";
  310. }
  311. void Exporter::exportModel(const Model& model) const
  312. {
  313. std::string name = getModelName(model);
  314. LOGI("Exporting model %s", name.c_str());
  315. std::fstream file;
  316. file.open(m_outputDirectory + name + ".ankimdl", std::ios::out);
  317. file << XML_HEADER << '\n';
  318. file << "<model>\n";
  319. file << "\t<modelPatches>\n";
  320. // Start patches
  321. file << "\t\t<modelPatch>\n";
  322. // Write mesh
  323. file << "\t\t\t<mesh>" << m_rpath << getMeshName(getMeshAt(model.m_meshIndex)) << ".ankimesh</mesh>\n";
  324. // Write mesh1
  325. if(!model.m_lod1MeshName.empty())
  326. {
  327. bool found = false;
  328. for(unsigned i = 0; i < m_scene->mNumMeshes; i++)
  329. {
  330. if(m_scene->mMeshes[i]->mName.C_Str() == model.m_lod1MeshName)
  331. {
  332. file << "\t\t\t<mesh1>" << m_rpath << getMeshName(getMeshAt(i)) << ".ankimesh</mesh1>\n";
  333. found = true;
  334. break;
  335. }
  336. }
  337. if(!found)
  338. {
  339. ERROR("Couldn't find the LOD1 %s", model.m_lod1MeshName.c_str());
  340. }
  341. }
  342. // Write material
  343. const aiMaterial& mtl = *m_scene->mMaterials[model.m_materialIndex];
  344. if(mtl.mAnKiProperties.find("material_override") == mtl.mAnKiProperties.end())
  345. {
  346. file << "\t\t\t<material>" << m_rpath << getMaterialName(getMaterialAt(model.m_materialIndex))
  347. << ".ankimtl</material>\n";
  348. }
  349. else
  350. {
  351. file << "\t\t\t<material>" << mtl.mAnKiProperties.at("material_override") << "</material>\n";
  352. }
  353. // End patches
  354. file << "\t\t</modelPatch>\n";
  355. file << "\t</modelPatches>\n";
  356. // Skeleton
  357. const aiMesh& aimesh = *m_scene->mMeshes[model.m_meshIndex];
  358. if(aimesh.HasBones())
  359. {
  360. exportSkeleton(aimesh);
  361. file << "\t<skeleton>" << m_rpath << aimesh.mName.C_Str() << ".ankiskel</skeleton>\n";
  362. }
  363. file << "</model>\n";
  364. }
  365. void Exporter::exportLight(const aiLight& light)
  366. {
  367. std::ofstream& file = m_sceneFile;
  368. LOGI("Exporting light %s", light.mName.C_Str());
  369. if(light.mType != aiLightSource_POINT && light.mType != aiLightSource_SPOT
  370. && light.mType != aiLightSource_DIRECTIONAL)
  371. {
  372. LOGW("Skipping light %s. Unsupported type (0x%x)", light.mName.C_Str(), light.mType);
  373. return;
  374. }
  375. if(light.mAttenuationLinear != 0.0)
  376. {
  377. LOGW("Skipping light %s. Linear attenuation is not 0.0", light.mName.C_Str());
  378. return;
  379. }
  380. const char* lightType;
  381. switch(light.mType)
  382. {
  383. case aiLightSource_POINT:
  384. lightType = "Point";
  385. break;
  386. case aiLightSource_SPOT:
  387. lightType = "Spot";
  388. break;
  389. case aiLightSource_DIRECTIONAL:
  390. lightType = "Directional";
  391. break;
  392. default:
  393. lightType = nullptr;
  394. assert(0);
  395. }
  396. file << "\nnode = scene:new" << lightType << "LightNode(\"" << light.mName.C_Str() << "\")\n";
  397. file << "lcomp = node:getSceneNodeBase():getLightComponent()\n";
  398. // Colors
  399. // aiColor3D linear = computeLightColor(light.mColorDiffuse);
  400. aiVector3D linear(light.mColorDiffuse[0], light.mColorDiffuse[1], light.mColorDiffuse[2]);
  401. file << "lcomp:setDiffuseColor(Vec4.new(" << linear[0] << ", " << linear[1] << ", " << linear[2] << ", 1))\n";
  402. // Geometry
  403. switch(light.mType)
  404. {
  405. case aiLightSource_POINT:
  406. {
  407. // At this point I want the radius and have the attenuation factors
  408. // att = Ac + Al*d + Aq*d^2. When d = r then att = 0.0. Also if we assume that Al is 0 then:
  409. // 0 = Ac + Aq*r^2. Solving by r is easy
  410. float r = sqrt(light.mAttenuationConstant / light.mAttenuationQuadratic);
  411. file << "lcomp:setRadius(" << r << ")\n";
  412. }
  413. break;
  414. case aiLightSource_SPOT:
  415. {
  416. float dist = sqrt(light.mAttenuationConstant / light.mAttenuationQuadratic);
  417. float outer = light.mAngleOuterCone;
  418. float inner = light.mAngleInnerCone;
  419. if(outer == inner)
  420. {
  421. inner = outer / 2.0;
  422. }
  423. file << "lcomp:setInnerAngle(" << inner << ")\n"
  424. << "lcomp:setOuterAngle(" << outer << ")\n"
  425. << "lcomp:setDistance(" << dist << ")\n";
  426. break;
  427. }
  428. case aiLightSource_DIRECTIONAL:
  429. {
  430. break;
  431. }
  432. default:
  433. assert(0);
  434. break;
  435. }
  436. // Transform
  437. const aiNode* node = findNodeWithName(light.mName.C_Str(), m_scene->mRootNode);
  438. if(node == nullptr)
  439. {
  440. ERROR("Couldn't find node for light %s", light.mName.C_Str());
  441. }
  442. aiMatrix4x4 rot;
  443. aiMatrix4x4::RotationX(-3.1415 / 2.0, rot);
  444. writeNodeTransform("node", toAnkiMatrix(node->mTransformation * rot));
  445. // Extra
  446. if(light.mProperties.find("shadow") != light.mProperties.end())
  447. {
  448. if(light.mProperties.at("shadow") == "true")
  449. {
  450. file << "lcomp:setShadowEnabled(1)\n";
  451. }
  452. else
  453. {
  454. file << "lcomp:setShadowEnabled(0)\n";
  455. }
  456. }
  457. if(light.mProperties.find("lens_flare") != light.mProperties.end())
  458. {
  459. file << "node:loadLensFlare(\"" << light.mProperties.at("lens_flare") << "\")\n";
  460. }
  461. bool lfCompRetrieved = false;
  462. if(light.mProperties.find("lens_flare_first_sprite_size") != light.mProperties.end())
  463. {
  464. if(!lfCompRetrieved)
  465. {
  466. file << "lfcomp = node:getSceneNodeBase():getLensFlareComponent()\n";
  467. lfCompRetrieved = true;
  468. }
  469. aiVector3D vec;
  470. stringToFloatArray<2>(light.mProperties.at("lens_flare_first_sprite_size"), vec);
  471. file << "lfcomp:setFirstFlareSize(Vec2.new(" << vec[0] << ", " << vec[1] << "))\n";
  472. }
  473. if(light.mProperties.find("lens_flare_color") != light.mProperties.end())
  474. {
  475. if(!lfCompRetrieved)
  476. {
  477. file << "lfcomp = node:getSceneNodeBase():getLensFlareComponent()\n";
  478. lfCompRetrieved = true;
  479. }
  480. aiVector3D vec;
  481. stringToFloatArray<4>(light.mProperties.at("lens_flare_color"), vec);
  482. file << "lfcomp:setColorMultiplier(Vec4.new(" << vec[0] << ", " << vec[1] << ", " << vec[2] << ", " << vec[3]
  483. << "))\n";
  484. }
  485. bool eventCreated = false;
  486. if(light.mProperties.find("light_event_intensity") != light.mProperties.end())
  487. {
  488. if(!eventCreated)
  489. {
  490. file << "event = events:newLightEvent(0.0, -1.0, node:getSceneNodeBase())\n";
  491. eventCreated = true;
  492. }
  493. aiVector3D vec;
  494. stringToFloatArray<4>(light.mProperties.at("light_event_intensity"), vec);
  495. file << "event:setIntensityMultiplier(Vec4.new(" << vec[0] << ", " << vec[1] << ", " << vec[2] << ", " << vec[3]
  496. << "))\n";
  497. }
  498. if(light.mProperties.find("light_event_frequency") != light.mProperties.end())
  499. {
  500. if(!eventCreated)
  501. {
  502. file << "event = events:newLightEvent(0.0, -1.0, node:getSceneNodeBase())\n";
  503. eventCreated = true;
  504. }
  505. float vec[2];
  506. stringToFloatArray<2>(light.mProperties.at("light_event_frequency"), vec);
  507. file << "event:setFrequency(" << vec[0] << ", " << vec[1] << ")\n";
  508. }
  509. }
  510. void Exporter::exportAnimation(const aiAnimation& anim, unsigned index)
  511. {
  512. // Get name
  513. std::string name = anim.mName.C_Str();
  514. if(name.size() == 0)
  515. {
  516. name = std::string("unnamed_") + std::to_string(index);
  517. }
  518. // Find if it's skeleton animation
  519. /*bool isSkeletalAnimation = false;
  520. for(uint32_t i = 0; i < scene.mNumMeshes; i++)
  521. {
  522. const aiMesh& mesh = *scene.mMeshes[i];
  523. if(mesh.HasBones())
  524. {
  525. }
  526. }*/
  527. std::fstream file;
  528. LOGI("Exporting animation %s", name.c_str());
  529. file.open(m_outputDirectory + name + ".ankianim", std::ios::out);
  530. file << XML_HEADER << "\n";
  531. file << "<animation>\n";
  532. file << "\t<channels>\n";
  533. for(uint32_t i = 0; i < anim.mNumChannels; i++)
  534. {
  535. const aiNodeAnim& nAnim = *anim.mChannels[i];
  536. file << "\t\t<channel>\n";
  537. // Name
  538. file << "\t\t\t<name>" << nAnim.mNodeName.C_Str() << "</name>\n";
  539. // Positions
  540. file << "\t\t\t<positionKeys>\n";
  541. for(uint32_t j = 0; j < nAnim.mNumPositionKeys; j++)
  542. {
  543. const aiVectorKey& key = nAnim.mPositionKeys[j];
  544. if(m_flipyz)
  545. {
  546. file << "\t\t\t\t<key><time>" << key.mTime << "</time><value>" << key.mValue[0] << " " << key.mValue[2]
  547. << " " << -key.mValue[1] << "</value></key>\n";
  548. }
  549. else
  550. {
  551. file << "\t\t\t\t<key><time>" << key.mTime << "</time><value>" << key.mValue[0] << " " << key.mValue[1]
  552. << " " << key.mValue[2] << "</value></key>\n";
  553. }
  554. }
  555. file << "\t\t\t</positionKeys>\n";
  556. // Rotations
  557. file << "\t\t\t<rotationKeys>\n";
  558. for(uint32_t j = 0; j < nAnim.mNumRotationKeys; j++)
  559. {
  560. const aiQuatKey& key = nAnim.mRotationKeys[j];
  561. aiMatrix3x3 mat = toAnkiMatrix(key.mValue.GetMatrix());
  562. aiQuaternion quat(mat);
  563. // aiQuaternion quat(key.mValue);
  564. file << "\t\t\t\t<key><time>" << key.mTime << "</time>"
  565. << "<value>" << quat.x << " " << quat.y << " " << quat.z << " " << quat.w << "</value></key>\n";
  566. }
  567. file << "\t\t\t</rotationKeys>\n";
  568. // Scale
  569. file << "\t\t\t<scalingKeys>\n";
  570. for(uint32_t j = 0; j < nAnim.mNumScalingKeys; j++)
  571. {
  572. const aiVectorKey& key = nAnim.mScalingKeys[j];
  573. // Note: only uniform scale
  574. file << "\t\t\t\t<key><time>" << key.mTime << "</time>"
  575. << "<value>" << ((key.mValue[0] + key.mValue[1] + key.mValue[2]) / 3.0) << "</value></key>\n";
  576. }
  577. file << "\t\t\t</scalingKeys>\n";
  578. file << "\t\t</channel>\n";
  579. }
  580. file << "\t</channels>\n";
  581. file << "</animation>\n";
  582. }
  583. void Exporter::exportCamera(const aiCamera& cam)
  584. {
  585. std::ofstream& file = m_sceneFile;
  586. LOGI("Exporting camera %s", cam.mName.C_Str());
  587. // Write the main node
  588. file << "\nnode = scene:newPerspectiveCameraNode(\"" << cam.mName.C_Str() << "\")\n";
  589. file << "scene:setActiveCameraNode(node:getSceneNodeBase())\n";
  590. file << "frustumc = node:getSceneNodeBase():getFrustumComponent()\n";
  591. file << "frustumc:setPerspective(" << cam.mClipPlaneNear << ", " << cam.mClipPlaneFar << ", " << cam.mHorizontalFOV
  592. << ", "
  593. << "1.0 / getMainRenderer():getAspectRatio() * " << cam.mHorizontalFOV << ")\n";
  594. // Find the node
  595. const aiNode* node = findNodeWithName(cam.mName.C_Str(), m_scene->mRootNode);
  596. if(node == nullptr)
  597. {
  598. ERROR("Couldn't find node for camera %s", cam.mName.C_Str());
  599. }
  600. aiMatrix4x4 rot;
  601. aiMatrix4x4::RotationX(-3.1415 / 2.0, rot);
  602. writeNodeTransform("node", toAnkiMatrix(node->mTransformation * rot));
  603. }
  604. void Exporter::load()
  605. {
  606. LOGI("Loading file %s", &m_inputFilename[0]);
  607. const int smoothAngle = 170;
  608. m_importer.SetPropertyFloat(AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE, smoothAngle);
  609. unsigned flags = 0
  610. //| aiProcess_FindInstances
  611. | aiProcess_JoinIdenticalVertices
  612. //| aiProcess_SortByPType
  613. | aiProcess_ImproveCacheLocality | aiProcess_OptimizeMeshes | aiProcess_RemoveRedundantMaterials
  614. | aiProcess_CalcTangentSpace | aiProcess_GenSmoothNormals;
  615. const aiScene* scene = m_importer.ReadFile(m_inputFilename, flags | aiProcess_Triangulate);
  616. if(!scene)
  617. {
  618. ERROR("%s", m_importer.GetErrorString());
  619. }
  620. m_scene = scene;
  621. // Load without triangulation
  622. m_importerNoTriangles.SetPropertyFloat(AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE, smoothAngle);
  623. scene = m_importerNoTriangles.ReadFile(m_inputFilename, flags);
  624. if(!scene)
  625. {
  626. ERROR("%s", m_importerNoTriangles.GetErrorString());
  627. }
  628. m_sceneNoTriangles = scene;
  629. }
  630. void Exporter::visitNode(const aiNode* ainode)
  631. {
  632. if(ainode == nullptr)
  633. {
  634. return;
  635. }
  636. // For every mesh of this node
  637. for(unsigned i = 0; i < ainode->mNumMeshes; i++)
  638. {
  639. unsigned meshIndex = ainode->mMeshes[i];
  640. unsigned mtlIndex = m_scene->mMeshes[meshIndex]->mMaterialIndex;
  641. // Check properties
  642. std::string lod1MeshName;
  643. std::string collisionMesh;
  644. bool special = false;
  645. for(const auto& prop : m_scene->mMeshes[meshIndex]->mProperties)
  646. {
  647. if(prop.first == "particles")
  648. {
  649. ParticleEmitter p;
  650. p.m_filename = prop.second;
  651. p.m_transform = toAnkiMatrix(ainode->mTransformation);
  652. m_particleEmitters.push_back(p);
  653. special = true;
  654. }
  655. else if(prop.first == "collision" && prop.second == "true")
  656. {
  657. StaticCollisionNode n;
  658. n.m_meshIndex = meshIndex;
  659. n.m_transform = toAnkiMatrix(ainode->mTransformation);
  660. m_staticCollisionNodes.push_back(n);
  661. special = true;
  662. }
  663. else if(prop.first == "lod1")
  664. {
  665. lod1MeshName = prop.second;
  666. special = false;
  667. }
  668. else if(prop.first == "reflection_probe" && prop.second == "true")
  669. {
  670. ReflectionProbe probe;
  671. aiMatrix4x4 trf = toAnkiMatrix(ainode->mTransformation);
  672. probe.m_position = aiVector3D(trf.a4, trf.b4, trf.c4);
  673. aiVector3D scale(trf.a1, trf.b2, trf.c3);
  674. assert(scale.x > 0.0f && scale.y > 0.0f && scale.z > 0.0f);
  675. aiVector3D half = scale;
  676. probe.m_aabbMin = probe.m_position - half - probe.m_position;
  677. probe.m_aabbMax = probe.m_position + half - probe.m_position;
  678. m_reflectionProbes.push_back(probe);
  679. special = true;
  680. }
  681. else if(prop.first == "reflection_proxy" && prop.second == "true")
  682. {
  683. ReflectionProxy proxy;
  684. // Find proxy in the other scene
  685. proxy.m_meshIndex = 0xFFFFFFFF;
  686. for(unsigned i = 0; i < m_sceneNoTriangles->mNumMeshes; ++i)
  687. {
  688. if(m_sceneNoTriangles->mMeshes[i]->mName == m_scene->mMeshes[meshIndex]->mName)
  689. {
  690. // Found
  691. proxy.m_meshIndex = i;
  692. break;
  693. }
  694. }
  695. if(proxy.m_meshIndex == 0xFFFFFFFF)
  696. {
  697. ERROR("Reflection proxy mesh not found");
  698. }
  699. proxy.m_transform = toAnkiMatrix(ainode->mTransformation);
  700. m_reflectionProxies.push_back(proxy);
  701. special = true;
  702. }
  703. else if(prop.first == "occluder" && prop.second == "true")
  704. {
  705. OccluderNode occluder;
  706. occluder.m_meshIndex = meshIndex;
  707. occluder.m_transform = toAnkiMatrix(ainode->mTransformation);
  708. m_occluders.push_back(occluder);
  709. special = true;
  710. }
  711. else if(prop.first == "collision_mesh")
  712. {
  713. collisionMesh = prop.second;
  714. special = false;
  715. }
  716. else if(prop.first.find("decal_") == 0)
  717. {
  718. DecalNode decal;
  719. for(const auto& pr : m_scene->mMeshes[meshIndex]->mProperties)
  720. {
  721. if(pr.first == "decal_diffuse_atlas")
  722. {
  723. decal.m_diffuseTextureAtlasFilename = pr.second;
  724. }
  725. else if(pr.first == "decal_diffuse_sub_texture")
  726. {
  727. decal.m_diffuseSubTextureName = pr.second;
  728. }
  729. else if(pr.first == "decal_diffuse_factor")
  730. {
  731. decal.m_factors[0] = std::stof(pr.second);
  732. }
  733. else if(pr.first == "decal_normal_roughness_atlas")
  734. {
  735. decal.m_specularRoughnessAtlasFilename = pr.second;
  736. }
  737. else if(pr.first == "decal_normal_roughness_sub_texture")
  738. {
  739. decal.m_specularRoughnessSubTextureName = pr.second;
  740. }
  741. else if(pr.first == "decal_normal_roughness_factor")
  742. {
  743. decal.m_factors[1] = std::stof(pr.second);
  744. }
  745. }
  746. if(decal.m_diffuseTextureAtlasFilename.empty() || decal.m_diffuseSubTextureName.empty())
  747. {
  748. ERROR("Missing decal information");
  749. }
  750. aiMatrix4x4 trf = toAnkiMatrix(ainode->mTransformation);
  751. decal.m_size = getNonUniformScale(trf);
  752. removeScale(trf);
  753. decal.m_transform = trf;
  754. m_decals.push_back(decal);
  755. special = true;
  756. break;
  757. }
  758. }
  759. if(special)
  760. {
  761. continue;
  762. }
  763. // Create new model
  764. Model mdl;
  765. mdl.m_meshIndex = meshIndex;
  766. mdl.m_materialIndex = mtlIndex;
  767. mdl.m_lod1MeshName = lod1MeshName;
  768. m_models.push_back(mdl);
  769. // Create new node
  770. Node node;
  771. node.m_modelIndex = m_models.size() - 1;
  772. node.m_transform = toAnkiMatrix(ainode->mTransformation);
  773. node.m_group = ainode->mGroup.C_Str();
  774. node.m_collisionMesh = collisionMesh;
  775. m_nodes.push_back(node);
  776. }
  777. // Go to children
  778. for(uint32_t i = 0; i < ainode->mNumChildren; i++)
  779. {
  780. visitNode(ainode->mChildren[i]);
  781. }
  782. }
  783. void Exporter::exportCollisionMesh(uint32_t meshIdx)
  784. {
  785. std::string name = getMeshName(getMeshAt(meshIdx));
  786. std::fstream file;
  787. file.open(m_outputDirectory + name + ".ankicl", std::ios::out);
  788. file << XML_HEADER << '\n';
  789. // Write collision mesh
  790. file << "<collisionShape>\n\t<type>staticMesh</type>\n\t<value>" << m_rpath << name
  791. << ".ankimesh</value>\n</collisionShape>\n";
  792. }
  793. void Exporter::exportAll()
  794. {
  795. LOGI("Exporting scene to %s", &m_outputDirectory[0]);
  796. //
  797. // Open scene file
  798. //
  799. m_sceneFile.open(m_outputDirectory + "scene.lua");
  800. std::ofstream& file = m_sceneFile;
  801. file << "local scene = getSceneGraph()\n"
  802. << "local events = getEventManager()\n"
  803. << "local rot\n"
  804. << "local node\n"
  805. << "local inst\n"
  806. << "local lcomp\n";
  807. //
  808. // Get all node/model data
  809. //
  810. visitNode(m_scene->mRootNode);
  811. //
  812. // Export collision meshes
  813. //
  814. for(auto n : m_staticCollisionNodes)
  815. {
  816. exportMesh(*m_scene->mMeshes[n.m_meshIndex], nullptr, 3);
  817. exportCollisionMesh(n.m_meshIndex);
  818. file << "\n";
  819. writeTransform(n.m_transform);
  820. std::string name = getMeshName(getMeshAt(n.m_meshIndex));
  821. std::string fname = m_rpath + name + ".ankicl";
  822. file << "node = scene:newStaticCollisionNode(\"" << name << "\", \"" << fname << "\", trf)\n";
  823. }
  824. //
  825. // Export particle emitters
  826. //
  827. int i = 0;
  828. for(const ParticleEmitter& p : m_particleEmitters)
  829. {
  830. std::string name = "particles" + std::to_string(i);
  831. file << "\nnode = scene:newParticleEmitterNode(\"" << name << "\", \"" << p.m_filename << "\")\n";
  832. writeNodeTransform("node", p.m_transform);
  833. ++i;
  834. }
  835. //
  836. // Export probes
  837. //
  838. i = 0;
  839. for(const ReflectionProbe& probe : m_reflectionProbes)
  840. {
  841. std::string name = "reflprobe" + std::to_string(i);
  842. file << "\nnode = scene:newReflectionProbeNode(\"" << name << "\", Vec4.new(" << probe.m_aabbMin.x << ", "
  843. << probe.m_aabbMin.y << ", " << probe.m_aabbMin.z << ", 0), Vec4.new(" << probe.m_aabbMax.x << ", "
  844. << probe.m_aabbMax.y << ", " << probe.m_aabbMax.z << ", 0))\n";
  845. aiMatrix4x4 trf;
  846. aiMatrix4x4::Translation(probe.m_position, trf);
  847. writeNodeTransform("node", trf);
  848. ++i;
  849. }
  850. //
  851. // Export proxies
  852. //
  853. i = 0;
  854. for(const ReflectionProxy& proxy : m_reflectionProxies)
  855. {
  856. const aiMesh& mesh = *m_sceneNoTriangles->mMeshes[proxy.m_meshIndex];
  857. exportMesh(mesh, nullptr, 4);
  858. std::string name = "reflproxy" + std::to_string(i);
  859. file << "\nnode = scene:newReflectionProxyNode(\"" << name << "\", \"" << m_rpath << mesh.mName.C_Str()
  860. << ".ankimesh\")\n";
  861. writeNodeTransform("node", proxy.m_transform);
  862. ++i;
  863. }
  864. //
  865. // Export occluders
  866. //
  867. i = 0;
  868. for(const OccluderNode& occluder : m_occluders)
  869. {
  870. const aiMesh& mesh = *m_scene->mMeshes[occluder.m_meshIndex];
  871. exportMesh(mesh, nullptr, 3);
  872. std::string name = "occluder" + std::to_string(i);
  873. file << "\nnode = scene:newOccluderNode(\"" << name << "\", \"" << m_rpath << mesh.mName.C_Str()
  874. << ".ankimesh\")\n";
  875. writeNodeTransform("node", occluder.m_transform);
  876. ++i;
  877. }
  878. //
  879. // Export decals
  880. //
  881. i = 0;
  882. for(const DecalNode& decal : m_decals)
  883. {
  884. std::string name = "decal" + std::to_string(i);
  885. file << "\nnode = scene:newDecalNode(\"" << name << "\")\n";
  886. writeNodeTransform("node", decal.m_transform);
  887. file << "decalc = node:getSceneNodeBase():getDecalComponent()\n";
  888. file << "decalc:setDiffuseDecal(\"" << decal.m_diffuseTextureAtlasFilename << "\", \""
  889. << decal.m_diffuseSubTextureName << "\", " << decal.m_factors[0] << ")\n";
  890. file << "decalc:updateShape(" << decal.m_size.x << ", " << decal.m_size.y << ", " << decal.m_size.z << ")\n";
  891. if(!decal.m_specularRoughnessAtlasFilename.empty())
  892. {
  893. file << "decalc:setSpecularRoughnessDecal(\"" << decal.m_specularRoughnessAtlasFilename << "\", \""
  894. << decal.m_specularRoughnessSubTextureName << "\", " << decal.m_factors[1] << ")\n";
  895. }
  896. ++i;
  897. }
  898. //
  899. // Export nodes and models.
  900. //
  901. for(uint32_t i = 0; i < m_nodes.size(); i++)
  902. {
  903. Node& node = m_nodes[i];
  904. Model& model = m_models[node.m_modelIndex];
  905. // TODO If static bake transform
  906. exportMesh(*m_scene->mMeshes[model.m_meshIndex], nullptr, 3);
  907. exportMaterial(*m_scene->mMaterials[model.m_materialIndex]);
  908. exportModel(model);
  909. std::string modelName = getModelName(model);
  910. std::string nodeName = modelName + node.m_group + std::to_string(i);
  911. // Write the main node
  912. file << "\nnode = scene:newModelNode(\"" << nodeName << "\", \"" << m_rpath << modelName << ".ankimdl\")\n";
  913. writeNodeTransform("node", node.m_transform);
  914. // Write the collision node
  915. if(!node.m_collisionMesh.empty())
  916. {
  917. unsigned i = 0;
  918. if(node.m_collisionMesh == "self")
  919. {
  920. i = model.m_meshIndex;
  921. }
  922. else
  923. {
  924. for(; i < m_scene->mNumMeshes; i++)
  925. {
  926. if(m_scene->mMeshes[i]->mName.C_Str() == node.m_collisionMesh)
  927. {
  928. break;
  929. }
  930. }
  931. }
  932. const bool found = i < m_scene->mNumMeshes;
  933. if(found)
  934. {
  935. exportCollisionMesh(i);
  936. std::string fname = m_rpath + getMeshName(getMeshAt(i)) + ".ankicl";
  937. file << "node = scene:newStaticCollisionNode(\"" << nodeName << "_cl\", \"" << fname << "\", trf)\n";
  938. }
  939. else
  940. {
  941. ERROR("Couldn't find the collision_mesh %s", node.m_collisionMesh.c_str());
  942. }
  943. }
  944. }
  945. //
  946. // Lights
  947. //
  948. for(unsigned i = 0; i < m_scene->mNumLights; i++)
  949. {
  950. exportLight(*m_scene->mLights[i]);
  951. }
  952. //
  953. // Animations
  954. //
  955. for(unsigned i = 0; i < m_scene->mNumAnimations; i++)
  956. {
  957. exportAnimation(*m_scene->mAnimations[i], i);
  958. }
  959. //
  960. // Cameras
  961. //
  962. for(unsigned i = 0; i < m_scene->mNumCameras; i++)
  963. {
  964. exportCamera(*m_scene->mCameras[i]);
  965. }
  966. LOGI("Done exporting scene!");
  967. }