Model.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. // Copyright (C) 2014, Panagiotis Christopoulos Charitos.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include "Common.h"
  6. #include <cassert>
  7. #include <algorithm>
  8. //==============================================================================
  9. static const aiMesh& getMesh(const Exporter& exporter, unsigned index)
  10. {
  11. assert(index < exporter.scene->mNumMeshes);
  12. return *exporter.scene->mMeshes[index];
  13. }
  14. //==============================================================================
  15. static const aiMaterial& getMaterial(const Exporter& exporter, unsigned index)
  16. {
  17. assert(index < exporter.scene->mNumMaterials);
  18. return *exporter.scene->mMaterials[index];
  19. }
  20. //==============================================================================
  21. static std::string getMeshName(const aiMesh& mesh)
  22. {
  23. return std::string(mesh.mName.C_Str());
  24. }
  25. //==============================================================================
  26. static std::string getMaterialName(const aiMaterial& mtl, bool instanced)
  27. {
  28. aiString ainame;
  29. std::string name;
  30. if(mtl.Get(AI_MATKEY_NAME, ainame) == AI_SUCCESS)
  31. {
  32. name = ainame.C_Str();
  33. if(instanced)
  34. {
  35. name += "_inst";
  36. }
  37. }
  38. else
  39. {
  40. ERROR("Material's name is missing\n");
  41. }
  42. return name;
  43. }
  44. //==============================================================================
  45. std::string getModelName(const Exporter& exporter, const Model& model)
  46. {
  47. std::string name =
  48. getMeshName(getMesh(exporter, model.meshIndex)) + "_"
  49. + getMaterialName(getMaterial(exporter, model.mtlIndex),
  50. model.instanced);
  51. return name;
  52. }
  53. //==============================================================================
  54. void exportMesh(
  55. const Exporter& exporter,
  56. const aiMesh& mesh,
  57. const aiMatrix4x4* transform)
  58. {
  59. std::string name = getMeshName(mesh);
  60. std::fstream file;
  61. LOGI("Exporting mesh %s\n", name.c_str());
  62. uint32_t vertsCount = mesh.mNumVertices;
  63. // Open file
  64. file.open(exporter.outDir + name + ".ankimesh",
  65. std::ios::out | std::ios::binary);
  66. // Write magic word
  67. file.write("ANKIMESH", 8);
  68. // Write the name
  69. uint32_t size = name.size();
  70. file.write((char*)&size, sizeof(uint32_t));
  71. file.write(&name[0], size);
  72. // Write positions
  73. file.write((char*)&vertsCount, sizeof(uint32_t));
  74. for(uint32_t i = 0; i < mesh.mNumVertices; i++)
  75. {
  76. aiVector3D pos = mesh.mVertices[i];
  77. // Transform
  78. if(transform)
  79. {
  80. pos = (*transform) * pos;
  81. }
  82. // flip
  83. if(exporter.flipyz)
  84. {
  85. static const aiMatrix4x4 toLefthanded(
  86. 1, 0, 0, 0,
  87. 0, 0, 1, 0,
  88. 0, -1, 0, 0,
  89. 0, 0, 0, 1);
  90. pos = toLefthanded * pos;
  91. }
  92. for(uint32_t j = 0; j < 3; j++)
  93. {
  94. file.write((char*)&pos[j], sizeof(float));
  95. }
  96. }
  97. // Write the indices
  98. file.write((char*)&mesh.mNumFaces, sizeof(uint32_t));
  99. for(uint32_t i = 0; i < mesh.mNumFaces; i++)
  100. {
  101. const aiFace& face = mesh.mFaces[i];
  102. if(face.mNumIndices != 3)
  103. {
  104. ERROR("For some reason the assimp didn't triangulate\n");
  105. }
  106. for(uint32_t j = 0; j < 3; j++)
  107. {
  108. uint32_t index = face.mIndices[j];
  109. file.write((char*)&index, sizeof(uint32_t));
  110. }
  111. }
  112. // Write the tex coords
  113. file.write((char*)&vertsCount, sizeof(uint32_t));
  114. // For all channels
  115. for(uint32_t ch = 0; ch < mesh.GetNumUVChannels(); ch++)
  116. {
  117. if(mesh.mNumUVComponents[ch] != 2)
  118. {
  119. ERROR("Incorrect number of UV components\n");
  120. }
  121. // For all tex coords of this channel
  122. for(uint32_t i = 0; i < vertsCount; i++)
  123. {
  124. aiVector3D texCoord = mesh.mTextureCoords[ch][i];
  125. for(uint32_t j = 0; j < 2; j++)
  126. {
  127. file.write((char*)&texCoord[j], sizeof(float));
  128. }
  129. }
  130. }
  131. // Write bone weigths count
  132. if(mesh.HasBones())
  133. {
  134. #if 0
  135. // Write file
  136. file.write((char*)&vertsCount, sizeof(uint32_t));
  137. // Gather info for each vertex
  138. std::vector<Vw> vw;
  139. vw.resize(vertsCount);
  140. memset(&vw[0], 0, sizeof(Vw) * vertsCount);
  141. // For all bones
  142. for(uint32_t i = 0; i < mesh.mNumBones; i++)
  143. {
  144. const aiBone& bone = *mesh.mBones[i];
  145. // for every weights of the bone
  146. for(uint32_t j = 0; j < bone.mWeightsCount; j++)
  147. {
  148. const aiVertexWeight& weigth = bone.mWeights[j];
  149. // Sanity check
  150. if(weight.mVertexId >= vertCount)
  151. {
  152. ERROR("Out of bounds vert ID");
  153. }
  154. Vm& a = vm[weight.mVertexId];
  155. // Check out of bounds
  156. if(a.bonesCount >= MAX_BONES_PER_VERTEX)
  157. {
  158. LOGW("Too many bones for vertex %d\n", weigth.mVertexId);
  159. continue;
  160. }
  161. // Write to vertex
  162. a.boneIds[a.bonesCount] = i;
  163. a.weigths[a.bonesCount] = weigth.mWeigth;
  164. ++a.bonesCount;
  165. }
  166. // Now write the file
  167. }
  168. #endif
  169. }
  170. else
  171. {
  172. uint32_t num = 0;
  173. file.write((char*)&num, sizeof(uint32_t));
  174. }
  175. }
  176. //==============================================================================
  177. void exportSkeleton(const Exporter& exporter, const aiMesh& mesh)
  178. {
  179. assert(mesh.HasBones());
  180. std::string name = mesh.mName.C_Str();
  181. std::fstream file;
  182. LOGI("Exporting skeleton %s\n", name.c_str());
  183. // Open file
  184. file.open(exporter.outDir + name + ".skel", std::ios::out);
  185. file << XML_HEADER << "\n";
  186. file << "<skeleton>\n";
  187. file << "\t<bones>\n";
  188. bool rootBoneFound = false;
  189. for(uint32_t i = 0; i < mesh.mNumBones; i++)
  190. {
  191. const aiBone& bone = *mesh.mBones[i];
  192. file << "\t\t<bone>\n";
  193. // <name>
  194. file << "\t\t\t<name>" << bone.mName.C_Str() << "</name>\n";
  195. if(strcmp(bone.mName.C_Str(), "root") == 0)
  196. {
  197. rootBoneFound = true;
  198. }
  199. // <transform>
  200. file << "\t\t\t<transform>";
  201. for(uint32_t j = 0; j < 16; j++)
  202. {
  203. file << bone.mOffsetMatrix[j] << " ";
  204. }
  205. file << "</transform>\n";
  206. file << "\t\t</bone>\n";
  207. }
  208. if(!rootBoneFound)
  209. {
  210. ERROR("There should be one bone named \"root\"\n");
  211. }
  212. file << "\t</bones>\n";
  213. file << "</skeleton>\n";
  214. }
  215. //==============================================================================
  216. void exportMaterial(
  217. const Exporter& exporter,
  218. const aiMaterial& mtl,
  219. bool instanced)
  220. {
  221. std::string diffTex;
  222. std::string normTex;
  223. std::string specColTex;
  224. std::string shininessTex;
  225. std::string dispTex;
  226. aiString path;
  227. std::string name = getMaterialName(mtl, instanced);
  228. LOGI("Exporting material %s\n", name.c_str());
  229. // Diffuse texture
  230. if(mtl.GetTextureCount(aiTextureType_DIFFUSE) > 0)
  231. {
  232. if(mtl.GetTexture(aiTextureType_DIFFUSE, 0, &path) == AI_SUCCESS)
  233. {
  234. diffTex = getFilename(path.C_Str());
  235. }
  236. else
  237. {
  238. ERROR("Failed to retrieve texture\n");
  239. }
  240. }
  241. // Normal texture
  242. if(mtl.GetTextureCount(aiTextureType_NORMALS) > 0)
  243. {
  244. if(mtl.GetTexture(aiTextureType_NORMALS, 0, &path) == AI_SUCCESS)
  245. {
  246. normTex = getFilename(path.C_Str());
  247. }
  248. else
  249. {
  250. ERROR("Failed to retrieve texture\n");
  251. }
  252. }
  253. // Specular color
  254. if(mtl.GetTextureCount(aiTextureType_SPECULAR) > 0)
  255. {
  256. if(mtl.GetTexture(aiTextureType_SPECULAR, 0, &path) == AI_SUCCESS)
  257. {
  258. specColTex = getFilename(path.C_Str());
  259. }
  260. else
  261. {
  262. ERROR("Failed to retrieve texture\n");
  263. }
  264. }
  265. // Shininess color
  266. if(mtl.GetTextureCount(aiTextureType_SHININESS) > 0)
  267. {
  268. if(mtl.GetTexture(aiTextureType_SHININESS, 0, &path) == AI_SUCCESS)
  269. {
  270. shininessTex = getFilename(path.C_Str());
  271. }
  272. else
  273. {
  274. ERROR("Failed to retrieve texture\n");
  275. }
  276. }
  277. // Height texture
  278. if(mtl.GetTextureCount(aiTextureType_DISPLACEMENT) > 0)
  279. {
  280. if(mtl.GetTexture(aiTextureType_DISPLACEMENT, 0, &path) == AI_SUCCESS)
  281. {
  282. dispTex = getFilename(path.C_Str());
  283. }
  284. else
  285. {
  286. ERROR("Failed to retrieve texture\n");
  287. }
  288. }
  289. // Write file
  290. static const char* diffNormSpecFragTemplate =
  291. #include "templates/diffNormSpecFrag.h"
  292. ;
  293. static const char* simpleVertTemplate =
  294. #include "templates/simpleVert.h"
  295. ;
  296. static const char* tessVertTemplate =
  297. #include "templates/tessVert.h"
  298. ;
  299. static const char* readRgbFromTextureTemplate = R"(
  300. <operation>
  301. <id>%id%</id>
  302. <returnType>vec3</returnType>
  303. <function>readRgbFromTexture</function>
  304. <arguments>
  305. <argument>%map%</argument>
  306. <argument>out2</argument>
  307. </arguments>
  308. </operation>)";
  309. static const char* readRFromTextureTemplate = R"(
  310. <operation>
  311. <id>%id%</id>
  312. <returnType>float</returnType>
  313. <function>readRFromTexture</function>
  314. <arguments>
  315. <argument>%map%</argument>
  316. <argument>out2</argument>
  317. </arguments>
  318. </operation>)";
  319. // Compose full template
  320. // First geometry part
  321. std::string materialStr;
  322. materialStr = R"(<?xml version="1.0" encoding="UTF-8" ?>)";
  323. materialStr += "\n<material>\n\t<programs>\n";
  324. if(dispTex.empty())
  325. {
  326. materialStr += simpleVertTemplate;
  327. }
  328. else
  329. {
  330. materialStr += tessVertTemplate;
  331. }
  332. materialStr += "\n";
  333. // Then fragment part
  334. materialStr += diffNormSpecFragTemplate;
  335. materialStr += "\n\t</programs>\t</material>";
  336. // Replace strings
  337. if(!dispTex.empty())
  338. {
  339. materialStr = replaceAllString(materialStr, "%dispMap%",
  340. exporter.texrpath + dispTex);
  341. }
  342. // Diffuse
  343. if(!diffTex.empty())
  344. {
  345. materialStr = replaceAllString(materialStr, "%diffuseColorInput%",
  346. R"(<input><type>sampler2D</type><name>uDiffuseColor</name><value>)"
  347. + exporter.texrpath + diffTex
  348. + R"(</value></input>)");
  349. materialStr = replaceAllString(materialStr, "%diffuseColorFunc%",
  350. readRgbFromTextureTemplate);
  351. materialStr = replaceAllString(materialStr, "%id%",
  352. "10");
  353. materialStr = replaceAllString(materialStr, "%map%",
  354. "uDiffuseColor");
  355. materialStr = replaceAllString(materialStr, "%diffuseColorArg%",
  356. "out10");
  357. }
  358. else
  359. {
  360. aiColor3D diffCol = {0.0, 0.0, 0.0};
  361. mtl.Get(AI_MATKEY_COLOR_DIFFUSE, diffCol);
  362. materialStr = replaceAllString(materialStr, "%diffuseColorInput%",
  363. R"(<input><type>vec3</type><name>uDiffuseColor</name><value>)"
  364. + std::to_string(diffCol[0]) + " "
  365. + std::to_string(diffCol[1]) + " "
  366. + std::to_string(diffCol[2])
  367. + R"(</value></input>)");
  368. materialStr = replaceAllString(materialStr, "%diffuseColorFunc%",
  369. "");
  370. materialStr = replaceAllString(materialStr, "%diffuseColorArg%",
  371. "uDiffuseColor");
  372. }
  373. // Normal
  374. if(!normTex.empty())
  375. {
  376. materialStr = replaceAllString(materialStr, "%normalInput%",
  377. R"(<input><type>sampler2D</type><name>uNormal</name><value>)"
  378. + exporter.texrpath + normTex
  379. + R"(</value></input>)");
  380. materialStr = replaceAllString(materialStr, "%normalFunc%",
  381. R"(
  382. <operation>
  383. <id>20</id>
  384. <returnType>vec3</returnType>
  385. <function>readNormalFromTexture</function>
  386. <arguments>
  387. <argument>out0</argument>
  388. <argument>out1</argument>
  389. <argument>uNormal</argument>
  390. <argument>out2</argument>
  391. </arguments>
  392. </operation>)");
  393. materialStr = replaceAllString(materialStr, "%normalArg%",
  394. "out20");
  395. }
  396. else
  397. {
  398. materialStr = replaceAllString(materialStr, "%normalInput%", " ");
  399. materialStr = replaceAllString(materialStr, "%normalFunc%", " ");
  400. materialStr = replaceAllString(materialStr, "%normalArg%", "out0");
  401. }
  402. // Specular
  403. if(!specColTex.empty())
  404. {
  405. materialStr = replaceAllString(materialStr, "%specularColorInput%",
  406. R"(<input><type>sampler2D</type><name>uSpecularColor</name><value>)"
  407. + exporter.texrpath + specColTex
  408. + R"(</value></input>)");
  409. materialStr = replaceAllString(materialStr, "%specularColorFunc%",
  410. readRFromTextureTemplate);
  411. materialStr = replaceAllString(materialStr, "%id%",
  412. "50");
  413. materialStr = replaceAllString(materialStr, "%map%",
  414. "uSpecularColor");
  415. materialStr = replaceAllString(materialStr, "%specularColorArg%",
  416. "out50");
  417. }
  418. else
  419. {
  420. aiColor3D specCol = {0.0, 0.0, 0.0};
  421. mtl.Get(AI_MATKEY_COLOR_SPECULAR, specCol);
  422. materialStr = replaceAllString(materialStr, "%specularColorInput%",
  423. R"(<input><type>float</type><name>uSpecularColor</name><value>)"
  424. + std::to_string((specCol[0] + specCol[1] + specCol[2]) / 3.0)
  425. + R"(</value></input>)");
  426. materialStr = replaceAllString(materialStr, "%specularColorFunc%",
  427. "");
  428. materialStr = replaceAllString(materialStr, "%specularColorArg%",
  429. "uSpecularColor");
  430. }
  431. if(!shininessTex.empty())
  432. {
  433. materialStr = replaceAllString(materialStr, "%specularPowerInput%",
  434. R"(<input><type>sampler2D</type><name>uSpecularPower</name><value>)"
  435. + exporter.texrpath + shininessTex
  436. + R"(</value></input>)");
  437. materialStr = replaceAllString(materialStr, "%specularPowerValue%",
  438. exporter.texrpath + shininessTex);
  439. materialStr = replaceAllString(materialStr, "%specularPowerFunc%",
  440. readRFromTextureTemplate);
  441. materialStr = replaceAllString(materialStr, "%id%",
  442. "60");
  443. materialStr = replaceAllString(materialStr, "%map%",
  444. "uSpecularPower");
  445. materialStr = replaceAllString(materialStr, "%specularPowerArg%",
  446. "out60");
  447. }
  448. else
  449. {
  450. float shininess = 0.0;
  451. mtl.Get(AI_MATKEY_SHININESS, shininess);
  452. //shininess = std::min(128.0f, shininess) 128.0;
  453. const int MAX_SHININESS = 511.0;
  454. if(shininess > MAX_SHININESS)
  455. {
  456. LOGW("Shininness exceeds %d\n", MAX_SHININESS);
  457. }
  458. shininess = shininess / MAX_SHININESS;
  459. materialStr = replaceAllString(materialStr, "%specularPowerInput%",
  460. R"(<input><type>float</type><name>uSpecularPower</name><value>)"
  461. + std::to_string(shininess)
  462. + R"(</value></input>)");
  463. materialStr = replaceAllString(materialStr, "%specularPowerFunc%",
  464. "");
  465. materialStr = replaceAllString(materialStr, "%specularPowerArg%",
  466. "uSpecularPower");
  467. }
  468. materialStr = replaceAllString(materialStr, "%maxSpecularPower%", " ");
  469. materialStr = replaceAllString(materialStr, "%instanced%",
  470. (instanced) ? "1" : "0");
  471. materialStr = replaceAllString(materialStr, "%diffuseMap%",
  472. exporter.texrpath + diffTex);
  473. // Replace texture extensions with .anki
  474. materialStr = replaceAllString(materialStr, ".tga", ".ankitex");
  475. materialStr = replaceAllString(materialStr, ".png", ".ankitex");
  476. materialStr = replaceAllString(materialStr, ".jpg", ".ankitex");
  477. materialStr = replaceAllString(materialStr, ".jpeg", ".ankitex");
  478. // Open and write file
  479. std::fstream file;
  480. file.open(exporter.outDir + name + ".ankimtl", std::ios::out);
  481. file << materialStr;
  482. }
  483. //==============================================================================
  484. void exportModel(const Exporter& exporter, const Model& model)
  485. {
  486. std::string name = getModelName(exporter, model);
  487. LOGI("Exporting model %s\n", name.c_str());
  488. std::fstream file;
  489. file.open(exporter.outDir + name + ".ankimdl", std::ios::out);
  490. file << XML_HEADER << '\n';
  491. file << "<model>\n";
  492. file << "\t<modelPatches>\n";
  493. // start
  494. file << "\t\t<modelPatch>\n";
  495. // Write mesh
  496. file << "\t\t\t<mesh>" << exporter.rpath
  497. << getMeshName(getMesh(exporter, model.meshIndex))
  498. << ".ankimesh</mesh>\n";
  499. // Write material
  500. file << "\t\t\t<material>" << exporter.rpath
  501. << getMaterialName(getMaterial(exporter, model.mtlIndex),
  502. model.instanced)
  503. << ".ankimtl</material>\n";
  504. // end
  505. file << "\t\t</modelPatch>\n";
  506. file << "\t</modelPatches>\n";
  507. file << "</model>\n";
  508. }