Compiler.cpp 21 KB

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