compiler.cpp 23 KB

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