Compiler.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. #include <irrlicht/irrlicht.h>
  2. #include <iostream>
  3. #include <fstream>
  4. #include <string>
  5. // filesystem
  6. #include <WallpaperEngine/FileSystem/utils.h>
  7. // video engine
  8. #include <WallpaperEngine/Irrlicht/Irrlicht.h>
  9. // shader compiler
  10. #include <WallpaperEngine/Render/Shaders/Compiler.h>
  11. #include <WallpaperEngine/Core/Core.h>
  12. namespace WallpaperEngine::Render::Shaders
  13. {
  14. Compiler::Compiler (irr::io::path& file, Type type, std::map<std::string, int>* combos, bool recursive)
  15. {
  16. this->m_recursive = recursive;
  17. this->m_combos = combos;
  18. // begin with an space so it gets ignored properly on parse
  19. if (recursive == false)
  20. {
  21. // compatibility layer for OpenGL shaders
  22. this->m_content = "#version 120\n"
  23. "#define highp\n"
  24. "#define mediump\n"
  25. "#define lowp\n"
  26. "#define mul(x, y) (y * x)\n"
  27. "#define frac fract\n"
  28. "#define CAST2(x) (vec2(x))\n"
  29. "#define CAST3(x) (vec3(x))\n"
  30. "#define CAST4(x) (vec4(x))\n"
  31. "#define CAST3X3(x) (mat3(x))\n"
  32. "#define saturate(x) (clamp(x, 0.0, 1.0))\n"
  33. "#define texSample2D texture2D\n"
  34. "#define texSample2DLod texture2DLod\n"
  35. "#define texture2DLod texture2D\n"
  36. "#define atan2 atan\n"
  37. "#define ddx dFdx\n"
  38. "#define ddy(x) dFdy(-(x))\n"
  39. "#define GLSL 1\n\n";
  40. std::map<std::string, int>::const_iterator cur = this->m_combos->begin ();
  41. std::map<std::string, int>::const_iterator end = this->m_combos->end ();
  42. for (; cur != end; cur ++)
  43. {
  44. this->m_content += "#define " + (*cur).first + " " + std::to_string ((*cur).second) + "\n";
  45. }
  46. }
  47. else
  48. {
  49. this->m_content = "";
  50. }
  51. this->m_content.append (WallpaperEngine::FileSystem::loadFullFile (file));
  52. // append file content
  53. this->m_type = type;
  54. this->m_file = file;
  55. }
  56. bool Compiler::peekString(std::string str, std::string::const_iterator& it)
  57. {
  58. std::string::const_iterator check = str.begin();
  59. std::string::const_iterator cur = it;
  60. while (cur != this->m_content.end () && check != str.end ())
  61. {
  62. if (*cur != *check) return false;
  63. cur ++; check ++;
  64. }
  65. if (cur == this->m_content.end ())
  66. {
  67. return false;
  68. }
  69. if (check != str.end ())
  70. {
  71. return false;
  72. }
  73. it = cur;
  74. return true;
  75. }
  76. bool Compiler::expectSemicolon (std::string::const_iterator& it)
  77. {
  78. if (*it != ';')
  79. {
  80. this->m_error = true;
  81. this->m_errorInfo = "Expected semicolon but got " + *it;
  82. return false;
  83. }
  84. it ++;
  85. return true;
  86. }
  87. void Compiler::ignoreSpaces(std::string::const_iterator &it)
  88. {
  89. while (it != this->m_content.end() && (*it == ' ' || *it == '\t')) it ++;
  90. }
  91. void Compiler::ignoreUpToNextLineFeed (std::string::const_iterator& it)
  92. {
  93. while (it != this->m_content.end() && *it != '\n') it ++;
  94. }
  95. void Compiler::ignoreUpToBlockCommentEnd (std::string::const_iterator& it)
  96. {
  97. while (it != this->m_content.end() && this->peekString ("*/", it) == false) it ++;
  98. }
  99. std::string Compiler::extractType (std::string::const_iterator& it)
  100. {
  101. std::vector<std::string>::const_iterator cur = sTypes.begin ();
  102. std::vector<std::string>::const_iterator end = sTypes.end ();
  103. while (cur != end)
  104. {
  105. if (this->peekString (*cur, it) == true)
  106. {
  107. return *cur;
  108. }
  109. cur ++;
  110. }
  111. this->m_error = true;
  112. this->m_errorInfo = "Expected type";
  113. return "";
  114. }
  115. std::string Compiler::extractName (std::string::const_iterator& it)
  116. {
  117. std::string::const_iterator cur = it;
  118. std::string::const_iterator begin = cur;
  119. // first character has to be a valid alphabetic characer
  120. if (this->isChar (cur) == false && *cur != '_')
  121. {
  122. this->m_error = true;
  123. this->m_errorInfo = "Expected name doesn't start with a valid character";
  124. return "";
  125. }
  126. cur ++;
  127. while (cur != this->m_content.end () && (this->isChar (cur) == true || *cur == '_' || this->isNumeric (cur) == true)) cur ++;
  128. it = cur;
  129. return std::string (begin, cur);
  130. }
  131. bool Compiler::isChar (std::string::const_iterator& it)
  132. {
  133. return ((*it) >= 'A' && (*it) <= 'Z') || ((*it) >= 'a' && (*it) <= 'z');
  134. }
  135. bool Compiler::isNumeric (std::string::const_iterator& it)
  136. {
  137. return (*it) >= '0' && (*it) <= '9';
  138. }
  139. std::string Compiler::extractQuotedValue(std::string::const_iterator& it)
  140. {
  141. std::string::const_iterator cur = it;
  142. if (*cur != '"')
  143. {
  144. m_error = true;
  145. m_errorInfo = "Expected opening \" but got " + (*cur);
  146. return "";
  147. }
  148. cur ++;
  149. while (cur != this->m_content.end () && *cur != '\n' && *cur != '"') cur ++;
  150. if (cur == this->m_content.end ())
  151. {
  152. m_error = true;
  153. m_errorInfo = "Expected closing \" not found";
  154. it = cur;
  155. return "";
  156. }
  157. std::string filename = std::string (++it, cur);
  158. it = ++cur;
  159. return filename;
  160. }
  161. std::string Compiler::lookupShaderFile (std::string filename)
  162. {
  163. // get file information
  164. irr::io::path shader = ("shaders/" + filename).c_str ();
  165. if (shader == "")
  166. {
  167. this->m_error = true;
  168. this->m_errorInfo = "Cannot find file " + filename + " to include";
  169. return "";
  170. }
  171. // now compile the new shader
  172. // do not include the default header (as it's already included in the parent)
  173. Compiler loader (shader, this->m_type, this->m_combos, true);
  174. return loader.precompile ();
  175. }
  176. std::string Compiler::lookupReplaceSymbol (std::string symbol)
  177. {
  178. std::map<std::string, std::string>::const_iterator cur = sVariableReplacement.begin ();
  179. std::map<std::string, std::string>::const_iterator end = sVariableReplacement.end ();
  180. while (cur != end)
  181. {
  182. if (cur->first == symbol)
  183. {
  184. return cur->second;
  185. }
  186. cur ++;
  187. }
  188. // if there is no replacement, return the original
  189. return symbol;
  190. }
  191. std::string Compiler::precompile()
  192. {
  193. #define BREAK_IF_ERROR if (this->m_error == true) { WallpaperEngine::Irrlicht::device->getLogger ()->log ("ERROR PRE-COMPILING SHADER", irr::ELL_ERROR); WallpaperEngine::Irrlicht::device->getLogger ()->log (this->m_errorInfo.c_str (), irr::ELL_ERROR); return ""; }
  194. // parse the shader and find #includes and such things and translate them to the correct name
  195. // also remove any #version definition to prevent errors
  196. std::string::const_iterator it = this->m_content.begin ();
  197. // reset error indicator
  198. this->m_error = false;
  199. this->m_errorInfo = "";
  200. // search preprocessor macros and parse them
  201. while (it != this->m_content.end () && this->m_error == false)
  202. {
  203. if (*it == ' ' || *it == '\t' || *it == '\n' || *it == '\r' || *it == '\0' || *it == '{' || *it == '}' || *it == '[' || *it == ']' || *it == '.')
  204. {
  205. this->m_compiledContent += *it;
  206. it ++;
  207. }
  208. else if (*it == '#')
  209. {
  210. if (this->peekString ("#include", it) == true)
  211. {
  212. std::string filename = "";
  213. // ignore whitespaces
  214. this->ignoreSpaces (it); BREAK_IF_ERROR
  215. // extract value between quotes
  216. filename = this->extractQuotedValue (it); BREAK_IF_ERROR
  217. // try to find the file first
  218. this->m_compiledContent += "// begin of included from file " + filename + "\r\n";
  219. this->m_compiledContent += this->lookupShaderFile (filename);
  220. this->m_compiledContent += "\r\n// end of included from file " + filename + "\r\n";
  221. }
  222. else
  223. {
  224. this->m_compiledContent += '#';
  225. it ++;
  226. }
  227. }
  228. else if (*it == 'u')
  229. {
  230. // uniforms might have extra information for their values
  231. if (this->peekString ("uniform", it) == true)
  232. {
  233. this->ignoreSpaces (it);
  234. std::string type = this->extractType (it); BREAK_IF_ERROR
  235. this->ignoreSpaces (it);
  236. std::string name = this->extractName (it); BREAK_IF_ERROR
  237. this->ignoreSpaces (it);
  238. this->expectSemicolon (it); BREAK_IF_ERROR
  239. this->ignoreSpaces (it);
  240. // check if there is any actual extra information and parse it
  241. if (this->peekString ("//", it) == true)
  242. {
  243. this->ignoreSpaces (it);
  244. std::string::const_iterator begin = it;
  245. this->ignoreUpToNextLineFeed (it);
  246. std::string configuration; configuration.append (begin, it);
  247. // parse the parameter information
  248. this->parseParameterConfiguration (type, name, configuration); BREAK_IF_ERROR
  249. this->m_compiledContent += "uniform " + type + " " + name + "; // " + configuration;
  250. }
  251. else
  252. {
  253. this->m_compiledContent += "uniform " + type + " " + name + ";";
  254. }
  255. }
  256. }
  257. else if (*it == 'a')
  258. {
  259. // find attribute definitions
  260. if (this->peekString ("attribute", it) == true)
  261. {
  262. this->ignoreSpaces (it);
  263. std::string type = this->extractType (it); BREAK_IF_ERROR
  264. this->ignoreSpaces (it);
  265. std::string name = this->extractName (it); BREAK_IF_ERROR
  266. this->ignoreSpaces (it);
  267. this->expectSemicolon (it); BREAK_IF_ERROR
  268. this->m_compiledContent += "// attribute";
  269. this->m_compiledContent += " " + type + " ";
  270. this->m_compiledContent += name;
  271. this->m_compiledContent += "; /* replaced by " + this->lookupReplaceSymbol (name) + " */";
  272. }
  273. else
  274. {
  275. // check for types first
  276. std::string type = this->extractType (it);
  277. // types not found, try names
  278. if (this->m_error == false)
  279. {
  280. this->m_compiledContent += type;
  281. }
  282. else
  283. {
  284. this->m_error = false;
  285. std::string name = this->extractName (it);
  286. if (this->m_error == false)
  287. {
  288. // check if the name is a translated one or not
  289. this->m_compiledContent += this->lookupReplaceSymbol (name);
  290. }
  291. else
  292. {
  293. this->m_error = false;
  294. this->m_compiledContent += *it;
  295. it ++;
  296. }
  297. }
  298. }
  299. }
  300. else if (*it == '/')
  301. {
  302. if (this->peekString ("//", it) == true)
  303. {
  304. std::string::const_iterator begin = it - 2;
  305. // is there a COMBO mark to take care of?
  306. this->ignoreSpaces (it);
  307. if (this->peekString ("[COMBO]", it) == true)
  308. {
  309. // parse combo json data to define the proper variables
  310. this->ignoreSpaces (it);
  311. begin = it;
  312. this->ignoreUpToNextLineFeed (it);
  313. std::string configuration; configuration.append (begin, it);
  314. this->m_compiledContent += "// [COMBO] " + configuration;
  315. this->parseComboConfiguration (configuration); BREAK_IF_ERROR;
  316. }
  317. else if (this->peekString ("[COMBO_OFF]", it) == true)
  318. {
  319. // parse combo json data to define the proper variables
  320. this->ignoreSpaces (it);
  321. begin = it;
  322. this->ignoreUpToNextLineFeed (it);
  323. std::string configuration; configuration.append (begin, it);
  324. this->m_compiledContent += "// [COMBO_OFF] " + configuration;
  325. this->parseComboConfiguration (configuration); BREAK_IF_ERROR;
  326. }
  327. else
  328. {
  329. this->ignoreUpToNextLineFeed (it);
  330. this->m_compiledContent.append (begin, it);
  331. }
  332. }
  333. else if (this->peekString ("/*", it) == true)
  334. {
  335. std::string::const_iterator begin = it - 2;
  336. this->ignoreUpToBlockCommentEnd (it);
  337. this->m_compiledContent.append (begin, it);
  338. }
  339. else
  340. {
  341. this->m_compiledContent += *it;
  342. it ++;
  343. }
  344. }
  345. else
  346. {
  347. // check for types first
  348. std::string type = this->extractType (it);
  349. // types not found, try names
  350. if (this->m_error == false)
  351. {
  352. this->m_compiledContent += type;
  353. }
  354. else
  355. {
  356. this->m_error = false;
  357. std::string name = this->extractName (it);
  358. if (this->m_error == false)
  359. {
  360. // check if the name is a translated one or not
  361. this->m_compiledContent += this->lookupReplaceSymbol (name);
  362. }
  363. else
  364. {
  365. this->m_error = false;
  366. this->m_compiledContent += *it;
  367. it ++;
  368. }
  369. }
  370. }
  371. }
  372. if (this->m_recursive == false)
  373. {
  374. WallpaperEngine::Irrlicht::device->getLogger ()->log ("Compiled shader output for", this->m_file.c_str ());
  375. WallpaperEngine::Irrlicht::device->getLogger ()->log (this->m_compiledContent.c_str ());
  376. }
  377. return this->m_compiledContent;
  378. #undef BREAK_IF_ERROR
  379. }
  380. void Compiler::parseComboConfiguration (const std::string& content)
  381. {
  382. json data = json::parse (content);
  383. json::const_iterator combo = data.find ("combo");
  384. json::const_iterator defvalue = data.find ("default");
  385. // add line feed just in case
  386. this->m_compiledContent += "\n";
  387. if (combo == data.end () || defvalue == data.end ())
  388. {
  389. WallpaperEngine::Irrlicht::device->getLogger ()->log ("Cannot parse combo information", irr::ELL_ERROR);
  390. return;
  391. }
  392. // check the combos
  393. std::map<std::string, int>::const_iterator entry = this->m_combos->find ((*combo).get <std::string> ());
  394. // if the combo was not found in the predefined values this means that the default value in the JSON data can be used
  395. // so only define the ones that are not already defined
  396. if (entry == this->m_combos->end ())
  397. {
  398. // if no combo is defined just load the default settings
  399. if ((*defvalue).is_number_float ())
  400. {
  401. this->m_compiledContent += "#define " + (*combo).get <std::string> () + " " + std::to_string ((*defvalue).get <irr::f32> ()) + "\n";
  402. }
  403. else if ((*defvalue).is_number_integer ())
  404. {
  405. this->m_compiledContent += "#define " + (*combo).get <std::string> () + " " + std::to_string ((*defvalue).get <irr::s32> ()) + "\n";
  406. }
  407. else if ((*defvalue).is_string ())
  408. {
  409. this->m_compiledContent += "#define " + (*combo).get <std::string> () + " " + (*defvalue).get <std::string> () + "\n";
  410. }
  411. else
  412. {
  413. WallpaperEngine::Irrlicht::device->getLogger ()->log ("Cannot parse combo information, unknown type", irr::ELL_ERROR);
  414. }
  415. }
  416. }
  417. void Compiler::parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content)
  418. {
  419. json data = json::parse (content);
  420. json::const_iterator material = data.find ("material");
  421. json::const_iterator defvalue = data.find ("default");
  422. json::const_iterator range = data.find ("range");
  423. // this is not a real parameter
  424. if (material == data.end () || defvalue == data.end ())
  425. {
  426. if (type != "sampler2D")
  427. WallpaperEngine::Irrlicht::device->getLogger ()->log ("Cannot parse parameter info for ", name.c_str (), irr::ELL_ERROR);
  428. return;
  429. }
  430. ShaderParameter* param = new ShaderParameter;
  431. param->identifierName = (*material).get <std::string> ();
  432. param->variableName = name;
  433. param->type = type;
  434. if (type == "vec4" || type == "vec3")
  435. {
  436. if ((*defvalue).is_string () == false)
  437. {
  438. irr::core::vector3df* vector = new irr::core::vector3df;
  439. vector->X = 0.0f;
  440. vector->Y = 0.0f;
  441. vector->Z = 0.0f;
  442. param->defaultValue = vector;
  443. }
  444. else
  445. {
  446. irr::core::vector3df tmp = WallpaperEngine::Core::ato3vf ((*defvalue).get <std::string> ().c_str ());
  447. irr::core::vector3df* vector = new irr::core::vector3df;
  448. vector->X = tmp.X;
  449. vector->Y = tmp.Y;
  450. vector->Z = tmp.Z;
  451. param->defaultValue = vector;
  452. }
  453. }
  454. else if (type == "vec2")
  455. {
  456. if ((*defvalue).is_string () == false)
  457. {
  458. irr::core::vector2df* vector = new irr::core::vector2df;
  459. vector->X = 0.0f;
  460. vector->Y = 0.0f;
  461. param->defaultValue = vector;
  462. }
  463. else
  464. {
  465. irr::core::vector2df* vector = new irr::core::vector2df;
  466. irr::core::vector2df tmp = WallpaperEngine::Core::ato2vf ((*defvalue).get <std::string> ().c_str ());
  467. vector->X = tmp.X;
  468. vector->Y = tmp.Y;
  469. param->defaultValue = vector;
  470. }
  471. }
  472. else if (type == "float")
  473. {
  474. if ((*defvalue).is_number () == false)
  475. {
  476. irr::f32* val = new irr::f32;
  477. *val = 0.0f;
  478. param->defaultValue = val;
  479. }
  480. else
  481. {
  482. irr::f32* val = new irr::f32;
  483. *val = (*defvalue).get <irr::f32> ();
  484. param->defaultValue = val;
  485. }
  486. }
  487. else if (type == "sampler2D")
  488. {
  489. // samplers are not saved, we can ignore them for now
  490. delete param;
  491. return;
  492. }
  493. else
  494. {
  495. this->m_error = true;
  496. this->m_errorInfo = "Unknown parameter type: " + type + " for " + param->identifierName + " (" + param->variableName + ")";
  497. return;
  498. }
  499. this->m_parameters.push_back (param);
  500. }
  501. Compiler::ShaderParameter* Compiler::findParameter (std::string identifier)
  502. {
  503. std::vector<ShaderParameter*>::const_iterator cur = this->m_parameters.begin ();
  504. std::vector<ShaderParameter*>::const_iterator end = this->m_parameters.end ();
  505. for (; cur != end; cur ++)
  506. {
  507. if ((*cur)->identifierName == identifier)
  508. {
  509. return (*cur);
  510. }
  511. }
  512. return nullptr;
  513. }
  514. std::vector <Compiler::ShaderParameter*>& Compiler::getParameters ()
  515. {
  516. return this->m_parameters;
  517. }
  518. std::map<std::string, std::string> Compiler::sVariableReplacement =
  519. {
  520. // attribute vec3 a_position
  521. {"a_Position", "gl_Vertex.xyz"},
  522. // attribute vec2 a_TexCoord
  523. {"a_TexCoord", "gl_MultiTexCoord0.xy"},
  524. // attribute vec3 a_Normal
  525. {"a_Normal", "gl_Normal.xyz"}
  526. };
  527. std::vector<std::string> Compiler::sTypes =
  528. {
  529. "vec4", "vec3", "vec2", "float", "sampler2D", "mat4"
  530. };
  531. }