compiler.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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, bool recursive)
  17. {
  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 atan2 atan\n"
  36. "#define ddx dFdx\n"
  37. "#define ddy(x) dFdy(-(x))\n"
  38. "#define GLSL 1\n\n";
  39. }
  40. else
  41. {
  42. this->m_content = "";
  43. }
  44. this->m_content.append (wp::fs::utils::loadFullFile (file));
  45. // append file content
  46. this->m_type = type;
  47. this->m_file = file;
  48. }
  49. bool compiler::peekString(std::string str, std::string::const_iterator& it)
  50. {
  51. std::string::const_iterator check = str.begin();
  52. std::string::const_iterator cur = it;
  53. while (cur != this->m_content.end () && check != str.end ())
  54. {
  55. if (*cur != *check) return false;
  56. cur ++; check ++;
  57. }
  58. if (cur == this->m_content.end ())
  59. {
  60. return false;
  61. }
  62. if (check != str.end ())
  63. {
  64. return false;
  65. }
  66. it = cur;
  67. return true;
  68. }
  69. bool compiler::expectSemicolon (std::string::const_iterator& it)
  70. {
  71. if (*it != ';')
  72. {
  73. this->m_error = true;
  74. this->m_errorInfo = "Expected semicolon but got " + *it;
  75. return false;
  76. }
  77. it ++;
  78. return true;
  79. }
  80. void compiler::ignoreSpaces(std::string::const_iterator &it)
  81. {
  82. while (it != this->m_content.end() && (*it == ' ' || *it == '\t')) it ++;
  83. }
  84. void compiler::ignoreUpToNextLineFeed (std::string::const_iterator& it)
  85. {
  86. while (it != this->m_content.end() && *it != '\n') it ++;
  87. }
  88. void compiler::ignoreUpToBlockCommentEnd (std::string::const_iterator& it)
  89. {
  90. while (it != this->m_content.end() && this->peekString ("*/", it) == false) it ++;
  91. }
  92. std::string compiler::extractType (std::string::const_iterator& it)
  93. {
  94. std::vector<std::string>::const_iterator cur = sTypes.begin ();
  95. std::vector<std::string>::const_iterator end = sTypes.end ();
  96. while (cur != end)
  97. {
  98. if (this->peekString (*cur, it) == true)
  99. {
  100. return *cur;
  101. }
  102. cur ++;
  103. }
  104. this->m_error = true;
  105. this->m_errorInfo = "Expected type";
  106. return "";
  107. }
  108. std::string compiler::extractName (std::string::const_iterator& it)
  109. {
  110. std::string::const_iterator cur = it;
  111. std::string::const_iterator begin = cur;
  112. // first character has to be a valid alphabetic characer
  113. if (this->isChar (cur) == false && *cur != '_')
  114. {
  115. this->m_error = true;
  116. this->m_errorInfo = "Expected name doesn't start with a valid character";
  117. return "";
  118. }
  119. cur ++;
  120. while (cur != this->m_content.end () && (this->isChar (cur) == true || *cur == '_' || this->isNumeric (cur) == true)) cur ++;
  121. it = cur;
  122. return std::string (begin, cur);
  123. }
  124. bool compiler::isChar (std::string::const_iterator& it)
  125. {
  126. return ((*it) >= 'A' && (*it) <= 'Z') || ((*it) >= 'a' && (*it) <= 'z');
  127. }
  128. bool compiler::isNumeric (std::string::const_iterator& it)
  129. {
  130. return (*it) >= '0' && (*it) <= '9';
  131. }
  132. std::string compiler::extractQuotedValue(std::string::const_iterator& it)
  133. {
  134. std::string::const_iterator cur = it;
  135. if (*cur != '"')
  136. {
  137. m_error = true;
  138. m_errorInfo = "Expected opening \" but got " + (*cur);
  139. return "";
  140. }
  141. cur ++;
  142. while (cur != this->m_content.end () && *cur != '\n' && *cur != '"') cur ++;
  143. if (cur == this->m_content.end ())
  144. {
  145. m_error = true;
  146. m_errorInfo = "Expected closing \" not found";
  147. it = cur;
  148. return "";
  149. }
  150. std::string filename = std::string (++it, cur);
  151. it = ++cur;
  152. return filename;
  153. }
  154. std::string compiler::lookupShaderFile (std::string filename)
  155. {
  156. // get file information
  157. irr::io::path shader = ("shaders/" + filename).c_str ();
  158. if (shader == "")
  159. {
  160. this->m_error = true;
  161. this->m_errorInfo = "Cannot find file " + filename + " to include";
  162. return "";
  163. }
  164. // now compile the new shader
  165. // do not include the default header (as it's already included in the parent)
  166. compiler loader (shader, this->m_type, true);
  167. return loader.precompile ();
  168. }
  169. std::string compiler::lookupReplaceSymbol (std::string symbol)
  170. {
  171. std::map<std::string, std::string>::const_iterator cur = sVariableReplacement.begin ();
  172. std::map<std::string, std::string>::const_iterator end = sVariableReplacement.end ();
  173. while (cur != end)
  174. {
  175. if (cur->first == symbol)
  176. {
  177. return cur->second;
  178. }
  179. cur ++;
  180. }
  181. // if there is no replacement, return the original
  182. return symbol;
  183. }
  184. std::string compiler::precompile()
  185. {
  186. #define BREAK_IF_ERROR if (this->m_error == true) { wp::irrlicht::device->getLogger ()->log ("ERROR PRE-COMPILING SHADER"); wp::irrlicht::device->getLogger ()->log (this->m_errorInfo.c_str ()); return ""; }
  187. // parse the shader and find #includes and such things and translate them to the correct name
  188. // also remove any #version definition to prevent errors
  189. std::string::const_iterator it = this->m_content.begin ();
  190. // reset error indicator
  191. this->m_error = false;
  192. this->m_errorInfo = "";
  193. // search preprocessor macros and parse them
  194. while (it != this->m_content.end () && this->m_error == false)
  195. {
  196. if (*it == ' ' || *it == '\t' || *it == '\n' || *it == '\r' || *it == '\0' || *it == '{' || *it == '}' || *it == '[' || *it == ']' || *it == '.')
  197. {
  198. this->m_compiledContent += *it;
  199. it ++;
  200. }
  201. else if (*it == '#')
  202. {
  203. if (this->peekString ("#include", it) == true)
  204. {
  205. std::string filename = "";
  206. // ignore whitespaces
  207. this->ignoreSpaces (it); BREAK_IF_ERROR
  208. // extract value between quotes
  209. filename = this->extractQuotedValue (it); BREAK_IF_ERROR
  210. // try to find the file first
  211. this->m_compiledContent += "// begin of included from file " + filename + "\r\n";
  212. this->m_compiledContent += this->lookupShaderFile (filename);
  213. this->m_compiledContent += "\r\n// end of included from file " + filename + "\r\n";
  214. }
  215. else
  216. {
  217. this->m_compiledContent += '#';
  218. it ++;
  219. }
  220. }
  221. else if (*it == 'u')
  222. {
  223. // uniforms might have extra information for their values
  224. if (this->peekString ("uniform", it) == true)
  225. {
  226. this->ignoreSpaces (it);
  227. std::string type = this->extractType (it); BREAK_IF_ERROR
  228. this->ignoreSpaces (it);
  229. std::string name = this->extractName (it); BREAK_IF_ERROR
  230. this->ignoreSpaces (it);
  231. this->expectSemicolon (it); BREAK_IF_ERROR
  232. this->ignoreSpaces (it);
  233. // check if there is any actual extra information and parse it
  234. if (this->peekString ("//", it) == true)
  235. {
  236. this->ignoreSpaces (it);
  237. std::string::const_iterator begin = it;
  238. this->ignoreUpToNextLineFeed (it);
  239. std::string configuration; configuration.append (begin, it);
  240. // parse the parameter information
  241. this->parseParameterConfiguration (type, name, configuration); BREAK_IF_ERROR
  242. this->m_compiledContent += "uniform " + type + " " + name + "; // " + configuration;
  243. }
  244. else
  245. {
  246. this->m_compiledContent += "uniform " + type + " " + name + ";";
  247. }
  248. }
  249. }
  250. else if (*it == 'a')
  251. {
  252. // find attribute definitions
  253. if (this->peekString ("attribute", it) == true)
  254. {
  255. this->ignoreSpaces (it);
  256. std::string type = this->extractType (it); BREAK_IF_ERROR
  257. this->ignoreSpaces (it);
  258. std::string name = this->extractName (it); BREAK_IF_ERROR
  259. this->ignoreSpaces (it);
  260. this->expectSemicolon (it); BREAK_IF_ERROR
  261. this->m_compiledContent += "// attribute";
  262. this->m_compiledContent += " " + type + " ";
  263. this->m_compiledContent += name;
  264. this->m_compiledContent += "; /* replaced by " + this->lookupReplaceSymbol (name) + " */";
  265. }
  266. else
  267. {
  268. // check for types first
  269. std::string type = this->extractType (it);
  270. // types not found, try names
  271. if (this->m_error == false)
  272. {
  273. this->m_compiledContent += type;
  274. }
  275. else
  276. {
  277. this->m_error = false;
  278. std::string name = this->extractName (it);
  279. if (this->m_error == false)
  280. {
  281. // check if the name is a translated one or not
  282. this->m_compiledContent += this->lookupReplaceSymbol (name);
  283. }
  284. else
  285. {
  286. this->m_error = false;
  287. this->m_compiledContent += *it;
  288. it ++;
  289. }
  290. }
  291. }
  292. }
  293. else if (*it == '/')
  294. {
  295. if (this->peekString ("//", it) == true)
  296. {
  297. std::string::const_iterator begin = it - 2;
  298. this->ignoreUpToNextLineFeed (it);
  299. this->m_compiledContent.append (begin, it);
  300. }
  301. else if (this->peekString ("/*", it) == true)
  302. {
  303. std::string::const_iterator begin = it - 2;
  304. this->ignoreUpToBlockCommentEnd (it);
  305. this->m_compiledContent.append (begin, it);
  306. }
  307. else
  308. {
  309. this->m_compiledContent += *it;
  310. it ++;
  311. }
  312. }
  313. else
  314. {
  315. // check for types first
  316. std::string type = this->extractType (it);
  317. // types not found, try names
  318. if (this->m_error == false)
  319. {
  320. this->m_compiledContent += type;
  321. }
  322. else
  323. {
  324. this->m_error = false;
  325. std::string name = this->extractName (it);
  326. if (this->m_error == false)
  327. {
  328. // check if the name is a translated one or not
  329. this->m_compiledContent += this->lookupReplaceSymbol (name);
  330. }
  331. else
  332. {
  333. this->m_error = false;
  334. this->m_compiledContent += *it;
  335. it ++;
  336. }
  337. }
  338. }
  339. }
  340. wp::irrlicht::device->getLogger ()->log ("Compiled shader output for", this->m_file.c_str ());
  341. wp::irrlicht::device->getLogger ()->log (this->m_compiledContent.c_str ());
  342. return this->m_compiledContent;
  343. #undef BREAK_IF_ERROR
  344. }
  345. void compiler::parseParameterConfiguration (const std::string& type, const std::string& name, const std::string& content)
  346. {
  347. json data = json::parse (content);
  348. json::const_iterator material = data.find ("material");
  349. json::const_iterator defvalue = data.find ("default");
  350. json::const_iterator range = data.find ("range");
  351. // this is not a real parameter
  352. if (material == data.end () || defvalue == data.end ())
  353. {
  354. return;
  355. }
  356. ShaderParameter* param = new ShaderParameter;
  357. param->identifierName = (*material).get <std::string> ();
  358. param->variableName = name;
  359. param->type = type;
  360. if (type == "vec4" || type == "vec3")
  361. {
  362. if ((*defvalue).is_string () == false)
  363. {
  364. irr::core::vector3df* vector = new irr::core::vector3df;
  365. vector->X = 0.0f;
  366. vector->Y = 0.0f;
  367. vector->Z = 0.0f;
  368. param->defaultValue = vector;
  369. }
  370. else
  371. {
  372. irr::core::vector3df tmp = wp::core::ato3vf ((*defvalue).get <std::string> ().c_str ());
  373. irr::core::vector3df* vector = new irr::core::vector3df;
  374. vector->X = tmp.X;
  375. vector->Y = tmp.Y;
  376. vector->Z = tmp.Z;
  377. param->defaultValue = vector;
  378. }
  379. }
  380. else if (type == "vec2")
  381. {
  382. if ((*defvalue).is_string () == false)
  383. {
  384. irr::core::vector2df* vector = new irr::core::vector2df;
  385. vector->X = 0.0f;
  386. vector->Y = 0.0f;
  387. param->defaultValue = vector;
  388. }
  389. else
  390. {
  391. irr::core::vector2df* vector = new irr::core::vector2df;
  392. irr::core::vector2df tmp = wp::core::ato2vf ((*defvalue).get <std::string> ().c_str ());
  393. vector->X = tmp.X;
  394. vector->Y = tmp.Y;
  395. param->defaultValue = vector;
  396. }
  397. }
  398. else if (type == "float")
  399. {
  400. if ((*defvalue).is_number () == false)
  401. {
  402. irr::f32* val = new irr::f32;
  403. *val = 0.0f;
  404. param->defaultValue = val;
  405. }
  406. else
  407. {
  408. irr::f32* val = new irr::f32;
  409. *val = (*defvalue).get <irr::f32> ();
  410. param->defaultValue = val;
  411. }
  412. }
  413. else if (type == "sampler2D")
  414. {
  415. param->defaultValue = nullptr;
  416. }
  417. else
  418. {
  419. this->m_error = true;
  420. this->m_errorInfo = "Unknown parameter type: " + type + " for " + param->identifierName + " (" + param->variableName + ")";
  421. return;
  422. }
  423. this->m_parameters.push_back (param);
  424. }
  425. compiler::ShaderParameter* compiler::findParameter (std::string identifier)
  426. {
  427. std::vector<ShaderParameter*>::const_iterator cur = this->m_parameters.begin ();
  428. std::vector<ShaderParameter*>::const_iterator end = this->m_parameters.end ();
  429. for (; cur != end; cur ++)
  430. {
  431. if ((*cur)->identifierName == identifier)
  432. {
  433. return (*cur);
  434. }
  435. }
  436. return nullptr;
  437. }
  438. std::vector <compiler::ShaderParameter*>& compiler::getParameters ()
  439. {
  440. return this->m_parameters;
  441. }
  442. std::map<std::string, std::string> compiler::sVariableReplacement =
  443. {
  444. // attribute vec3 a_position
  445. {"a_Position", "gl_Vertex.xyz"},
  446. // attribute vec2 a_TexCoord
  447. {"a_TexCoord", "gl_MultiTexCoord0.xy"},
  448. // attribute vec3 a_Normal
  449. {"a_Normal", "gl_Normal.xyz"}
  450. };
  451. std::vector<std::string> compiler::sTypes =
  452. {
  453. "vec4", "vec3", "vec2", "float", "sampler2D", "mat4"
  454. };
  455. }
  456. }