ShaderUnit.cpp 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025
  1. #include "ShaderUnit.h"
  2. #include "WallpaperEngine/Logging/Log.h"
  3. #include <array>
  4. #include <cctype>
  5. #include <charconv>
  6. #include <cmath>
  7. #include <exception>
  8. #include <functional>
  9. #include <mutex>
  10. #include <optional>
  11. #include <regex>
  12. #include <set>
  13. #include <stack>
  14. #include <string>
  15. #include <unordered_map>
  16. #include <utility>
  17. #include "GLSLContext.h"
  18. #include "WallpaperEngine/Assets/AssetLoadException.h"
  19. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariable.h"
  20. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableFloat.h"
  21. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableInteger.h"
  22. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector2.h"
  23. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector3.h"
  24. #include "WallpaperEngine/Render/Shaders/Variables/ShaderVariableVector4.h"
  25. #include "WallpaperEngine/Data/Builders/VectorBuilder.h"
  26. #include "WallpaperEngine/FileSystem/Container.h"
  27. namespace {
  28. // libstdc++ looks the "w" class up by name for every \b and refetches the ctype facet per test (most of a model scene's
  29. // load time), done once here
  30. struct ShaderRegexTraits : std::regex_traits<char> {
  31. struct ClassTable {
  32. char_class_type mask;
  33. std::array<bool, 256> members;
  34. explicit ClassTable (char name) {
  35. const std::regex_traits<char> traits;
  36. this->mask = traits.lookup_classname (&name, &name + 1);
  37. for (int c = 0; c < 256; c++) {
  38. this->members[c] = traits.isctype (static_cast<char> (c), this->mask);
  39. }
  40. }
  41. };
  42. static const ClassTable& word () {
  43. static const ClassTable table ('w');
  44. return table;
  45. }
  46. static const ClassTable& space () {
  47. static const ClassTable table ('s');
  48. return table;
  49. }
  50. template <typename Iterator>
  51. char_class_type lookup_classname (Iterator first, Iterator last, bool icase = false) const {
  52. if (!icase && std::distance (first, last) == 1 && *first == 'w') {
  53. return word ().mask;
  54. }
  55. return std::regex_traits<char>::lookup_classname (first, last, icase);
  56. }
  57. bool isctype (char c, char_class_type mask) const {
  58. for (const ClassTable* table : { &word (), &space () }) {
  59. if (mask == table->mask) {
  60. return table->members[static_cast<unsigned char> (c)];
  61. }
  62. }
  63. return std::regex_traits<char>::isctype (c, mask);
  64. }
  65. };
  66. using Regex = std::basic_regex<char, ShaderRegexTraits>;
  67. constexpr size_t MEMO_LIMIT = 512;
  68. using RegexIterator = std::regex_iterator<std::string::const_iterator, char, ShaderRegexTraits>;
  69. } // namespace
  70. // the wpe_ defines rename words GLSL reserves that are plain identifiers in HLSL (3681571511's fxaa has a
  71. // "float common")
  72. #define SHADER_HEADER(filename) \
  73. "#version 330\n" \
  74. "// ======================================================\n" \
  75. "// Processed shader " \
  76. + filename \
  77. + "\n" \
  78. "// ======================================================\n" \
  79. "precision highp float;\n" \
  80. "#define mul(x, y) ((y) * (x))\n" \
  81. "#define max(x, y) max (y, x)\n" \
  82. "#define lerp mix\n" \
  83. "#define frac fract\n" \
  84. "#define CASTI(x) (int(x))\n" \
  85. "#define CASTU(x) (uint(x))\n" \
  86. "#define CASTF(x) (float(x))\n" \
  87. "#define CAST4U(x) (uvec4(x))\n" \
  88. "#define CAST2(x) (vec2(x))\n" \
  89. "#define CAST3(x) (vec3(x))\n" \
  90. "#define CAST4(x) (vec4(x))\n" \
  91. "#define CAST3X3(x) (mat3(x))\n" \
  92. "#define float2 vec2\n" \
  93. "#define float3 vec3\n" \
  94. "#define float4 vec4\n" \
  95. "#define int2 ivec2\n" \
  96. "#define int3 ivec3\n" \
  97. "#define int4 ivec4\n" \
  98. "#define saturate(x) (clamp(x, 0.0, 1.0))\n" \
  99. "#define texSample2D texture\n" \
  100. "#define texSample2DLod textureLod\n" \
  101. "#define texSample3D texture\n" \
  102. "#define sampler2DComparison sampler2DShadow\n" \
  103. "#define texSample2DCompare(s, u, d) vec4 (texture (s, vec3 (u, d)))\n" \
  104. "#define atan2 atan\n" \
  105. "#define fmod(x, y) ((x)-(y)*trunc((x)/(y)))\n" \
  106. "#define ddx dFdx\n" \
  107. "#define ddy(x) dFdy(-(x))\n" \
  108. "#define active wpe_active\n" \
  109. "#define asm wpe_asm\n" \
  110. "#define cast wpe_cast\n" \
  111. "#define common wpe_common\n" \
  112. "#define enum wpe_enum\n" \
  113. "#define external wpe_external\n" \
  114. "#define filter wpe_filter\n" \
  115. "#define fixed wpe_fixed\n" \
  116. "#define goto wpe_goto\n" \
  117. "#define input wpe_input\n" \
  118. "#define long wpe_long\n" \
  119. "#define noinline wpe_noinline\n" \
  120. "#define output wpe_output\n" \
  121. "#define partition wpe_partition\n" \
  122. "#define public wpe_public\n" \
  123. "#define resource wpe_resource\n" \
  124. "#define short wpe_short\n" \
  125. "#define sizeof wpe_sizeof\n" \
  126. "#define superp wpe_superp\n" \
  127. "#define this wpe_this\n" \
  128. "#define union wpe_union\n" \
  129. "#define using wpe_using\n" \
  130. "#define GLSL 1\n\n";
  131. #define FRAGMENT_SHADER_DEFINES \
  132. "out vec4 out_FragColor;\n" \
  133. "#define varying in\n"
  134. #define GEOMETRY_SHADER_DEFINES "#define GEOMETRY 1\n"
  135. #define GEOMETRY_INPUT_PREFIX "wpeGs_"
  136. #define VERTEX_SHADER_DEFINES \
  137. "#define attribute in\n" \
  138. "#define varying out\n"
  139. #define DEFINE_COMBO(name, value) "#define " + name + " " + std::to_string (value) + "\n";
  140. using namespace WallpaperEngine::Render;
  141. using namespace WallpaperEngine::Data::Builders;
  142. using namespace WallpaperEngine::Render::Shaders;
  143. namespace {
  144. // "name|name|..." of every uniform, varying and attribute the source declares, for regex alternations
  145. std::string declaredInputNames (const std::string& source) {
  146. static const Regex inputDecl (R"(\b(?:uniform|varying|attribute)\s+\w+\s+([A-Za-z_]\w*))");
  147. std::string names;
  148. for (auto it = RegexIterator (source.cbegin (), source.cend (), inputDecl); it != RegexIterator (); ++it) {
  149. names += (names.empty () ? "" : "|") + (*it)[1].str ();
  150. }
  151. return names;
  152. }
  153. // the #if/#elif/#else lines leading to the branch that contains pos, one list per open level, so code
  154. // moved somewhere else can be put back under the same condition
  155. std::vector<std::vector<std::string>> conditionalBranch (const std::string& source, const size_t pos) {
  156. static const Regex directive (R"(^[ \t]*#[ \t]*(if|ifdef|ifndef|elif|else|endif)\b)");
  157. std::vector<std::vector<std::string>> levels;
  158. size_t start = 0;
  159. while (start < pos) {
  160. const size_t end = std::min (source.find ('\n', start), source.size ());
  161. const std::string line = source.substr (start, end - start);
  162. if (std::smatch match; std::regex_search (line, match, directive)) {
  163. const std::string kind = match[1].str ();
  164. if (kind == "endif") {
  165. if (!levels.empty ()) {
  166. levels.pop_back ();
  167. }
  168. } else if (kind == "elif" || kind == "else") {
  169. if (!levels.empty ()) {
  170. levels.back ().push_back (line);
  171. }
  172. } else {
  173. levels.push_back ({ line });
  174. }
  175. }
  176. start = end + 1;
  177. }
  178. return levels;
  179. }
  180. // the quoted filename of the #include at start, or nothing if the quotes aren't on the same line
  181. std::optional<std::string> includeFilename (const std::string& source, const size_t start) {
  182. const size_t lineEnd = std::min (source.find ('\n', start), source.size ());
  183. const size_t quoteStart = source.find ('"', start);
  184. if (quoteStart >= lineEnd) {
  185. return std::nullopt;
  186. }
  187. const size_t quoteEnd = source.find ('"', quoteStart + 1);
  188. if (quoteEnd >= lineEnd) {
  189. return std::nullopt;
  190. }
  191. return source.substr (quoteStart + 1, quoteEnd - quoteStart - 1);
  192. }
  193. } // namespace
  194. ShaderUnit::ShaderUnit (
  195. const GLSLContext::UnitType type, std::string file, std::string content, const AssetLocator& assetLocator,
  196. const ShaderConstantMap& constants, const TextureMap& passTextures, const TextureMap& overrideTextures,
  197. const ComboMap& combos, const ComboMap& overrideCombos
  198. ) :
  199. m_type (type), m_file (std::move (file)), m_content (std::move (content)), m_combos (combos),
  200. m_overrideCombos (overrideCombos), m_constants (constants), m_passTextures (passTextures),
  201. m_overrideTextures (overrideTextures), m_link (nullptr), m_assetLocator (assetLocator) {
  202. this->preprocess ();
  203. }
  204. void ShaderUnit::preprocess () {
  205. this->m_preprocessed = this->m_content;
  206. this->preprocessIncludes ();
  207. this->preprocessRequires ();
  208. this->preprocessVariables ();
  209. // every combo permutation brings the same source again
  210. static std::mutex cacheMutex;
  211. static std::unordered_map<std::string, std::string> rewritten;
  212. std::string input = this->m_preprocessed;
  213. bool cached = false;
  214. {
  215. std::lock_guard lock (cacheMutex);
  216. if (const auto found = rewritten.find (input); found != rewritten.end ()) {
  217. this->m_preprocessed = found->second;
  218. cached = true;
  219. }
  220. }
  221. if (!cached) {
  222. this->preprocessBalanceConditionals ();
  223. this->preprocessSwizzledDeclarations ();
  224. this->preprocessScalarSwizzles ();
  225. std::lock_guard lock (cacheMutex);
  226. if (rewritten.size () >= MEMO_LIMIT) {
  227. rewritten.clear ();
  228. }
  229. rewritten.emplace (std::move (input), this->m_preprocessed);
  230. }
  231. const std::string from = "gl_FragColor";
  232. const std::string to = "out_FragColor";
  233. size_t start_pos = 0;
  234. while ((start_pos = this->m_preprocessed.find (from, start_pos)) != std::string::npos) {
  235. this->m_preprocessed.replace (start_pos, from.length (), to);
  236. start_pos += to.length (); // avoids re-matching if 'to' is a substring of 'from'
  237. }
  238. }
  239. void ShaderUnit::preprocessVariables () {
  240. size_t start = 0, end = 0;
  241. while ((end = this->m_preprocessed.find ('\n', start)) != std::string::npos) {
  242. std::string line = this->m_preprocessed.substr (start, end - start);
  243. const size_t combo = line.find ("// [COMBO] ");
  244. const size_t uniform = line.find ("uniform ");
  245. const size_t comment = line.find ("// ");
  246. const size_t semicolon = line.find (';');
  247. if (combo != std::string::npos) {
  248. this->parseComboConfiguration (line.substr (combo + strlen ("// [COMBO] ")), 0);
  249. } else if (
  250. uniform != std::string::npos && comment != std::string::npos && semicolon != std::string::npos &&
  251. // semicolon before comment means it's a trailing comment, not a commented-out line
  252. // (doesn't account for block comments)
  253. semicolon < comment
  254. ) {
  255. // uniforms with trailing comments never have a value assigned, which is what lets this find type/name
  256. const size_t last_space = line.find_last_of (' ', semicolon);
  257. if (last_space != std::string::npos) {
  258. const size_t previous_space = line.find_last_of (' ', last_space - 1);
  259. if (previous_space != std::string::npos) {
  260. std::string type = line.substr (previous_space + 1, last_space - previous_space - 1);
  261. std::string name = line.substr (last_space + 1, semicolon - last_space - 1);
  262. std::string json = line.substr (comment + 2);
  263. this->parseParameterConfiguration (type, name, json);
  264. }
  265. }
  266. }
  267. start = end + 1;
  268. }
  269. }
  270. void ShaderUnit::preprocessIncludes () {
  271. // wallpaper64.exe sub_140162100: line by line, a line starting with #include is replaced by the file between its
  272. // quotes (shaders/<name>, expanded the same way) where it stands, every file only once per unit. A file that was
  273. // already included, or a line without the quotes, leaves an empty line. WE's translator (sub_1400F5CB0) then
  274. // takes every attribute/varying/uniform line out of the code and declares it up front, so included functions see
  275. // uniforms the file only declares after the #include. Here the file's own declarations outside any #if move up to
  276. // where its first include starts, conditional ones stay where they are
  277. std::set<std::string> included;
  278. std::string out;
  279. std::string hoisted;
  280. size_t firstInclude = std::string::npos;
  281. int depth = 0;
  282. const std::string& source = this->m_preprocessed;
  283. size_t start = 0;
  284. while (start < source.size ()) {
  285. size_t end = source.find ('\n', start);
  286. if (end == std::string::npos) {
  287. end = source.size ();
  288. }
  289. const std::string line = source.substr (start, end - start);
  290. const size_t first = line.find_first_not_of (" \t");
  291. const std::string trimmed = first == std::string::npos ? "" : line.substr (first);
  292. if (trimmed.starts_with ("#if")) {
  293. depth++;
  294. } else if (trimmed.starts_with ("#endif")) {
  295. depth = std::max (depth - 1, 0);
  296. }
  297. if (line.starts_with ("#include")) {
  298. if (firstInclude == std::string::npos) {
  299. firstInclude = out.size ();
  300. }
  301. out += this->expandIncludes (line, included);
  302. } else if (
  303. firstInclude != std::string::npos && depth == 0
  304. && (trimmed.starts_with ("uniform ") || trimmed.starts_with ("varying ")
  305. || trimmed.starts_with ("attribute "))
  306. ) {
  307. hoisted += line + '\n';
  308. out += '\n';
  309. } else {
  310. out += line + '\n';
  311. }
  312. start = end + 1;
  313. }
  314. if (!hoisted.empty ()) {
  315. out.insert (firstInclude, hoisted);
  316. }
  317. this->m_preprocessed = out;
  318. }
  319. std::string ShaderUnit::expandIncludes (const std::string& source, std::set<std::string>& included) const {
  320. std::string out;
  321. size_t start = 0;
  322. while (start < source.size ()) {
  323. size_t end = source.find ('\n', start);
  324. if (end == std::string::npos) {
  325. end = source.size ();
  326. }
  327. if (source.compare (start, 8, "#include") != 0) {
  328. out.append (source, start, end - start + (end < source.size () ? 1 : 0));
  329. start = end + 1;
  330. continue;
  331. }
  332. const auto filename = includeFilename (source, start);
  333. if (!filename.has_value ()) {
  334. sLog.error ("Malformed #include directive in shader ", this->m_file);
  335. } else if (included.insert (*filename).second) {
  336. try {
  337. out += this->expandIncludes (this->m_assetLocator.includeShader (*filename), included);
  338. } catch (AssetLoadException&) {
  339. sLog.error ("Shader include ", *filename, " of ", this->m_file, " was not found");
  340. }
  341. }
  342. out += '\n';
  343. start = end + 1;
  344. }
  345. return out;
  346. }
  347. void ShaderUnit::preprocessRequires () {
  348. size_t start = 0, end = 0;
  349. while ((start = this->m_preprocessed.find ("#require", end)) != std::string::npos) {
  350. const size_t lineEnd = this->m_preprocessed.find_first_of ('\n', start);
  351. const size_t nameStart = start + std::string ("#require ").length ();
  352. if (nameStart >= lineEnd) {
  353. sLog.error ("Malformed #require directive (no module name) in shader ", this->m_file);
  354. end = lineEnd;
  355. continue;
  356. }
  357. std::string moduleName = this->m_preprocessed.substr (nameStart, lineEnd - nameStart);
  358. while (!moduleName.empty () && (moduleName.back () == ' ' || moduleName.back () == '\r')) {
  359. moduleName.pop_back ();
  360. }
  361. if (moduleName.empty ()) {
  362. sLog.error ("Malformed #require directive (empty module name) in shader ", this->m_file);
  363. end = lineEnd;
  364. continue;
  365. }
  366. sLog.debug ("Resolving require module: ", moduleName, " in shader ", this->m_file);
  367. std::string moduleCode = this->resolveRequireModule (moduleName);
  368. this->m_preprocessed = this->m_preprocessed.replace (start, 2, "//");
  369. if (!moduleCode.empty ()) {
  370. this->m_preprocessed.insert (start, moduleCode);
  371. end = start + moduleCode.length ();
  372. } else {
  373. end = lineEnd;
  374. }
  375. }
  376. }
  377. std::string ShaderUnit::resolveRequireModule (const std::string& moduleName) const {
  378. if (moduleName == "LightingV1") {
  379. return this->generateLightingV1 ();
  380. }
  381. sLog.error ("Unknown #require module: ", moduleName, " in shader ", this->m_file);
  382. return "";
  383. }
  384. std::string ShaderUnit::generateLightingV1 () const {
  385. // wallpaper64.exe 2.8.42 sub_140169140, from the pass's LIGHTS_* defines (sub_1401A5C40). WE emits nothing when the
  386. // pass's LIGHTING combo is 0; its default is only parsed after the requires, so the preprocessor decides that here
  387. const auto count = [this] (const std::string& name) {
  388. for (const ComboMap* combos : { &this->m_overrideCombos, &this->m_combos }) {
  389. if (const auto it = combos->find (name); it != combos->end ()) {
  390. return std::max (it->second, 0);
  391. }
  392. }
  393. return 0;
  394. };
  395. const int points = count ("LIGHTS_POINT");
  396. const int spots = count ("LIGHTS_SPOT");
  397. const int tubes = count ("LIGHTS_TUBE");
  398. const int directionals = count ("LIGHTS_DIRECTIONAL");
  399. const int spotShadowCookies = count ("LIGHTS_SPOT_SHADOW_COOKIE");
  400. const int spotShadows = count ("LIGHTS_SPOT_SHADOW");
  401. const int spotCookies = count ("LIGHTS_SPOT_COOKIE");
  402. const int directionalShadows = count ("LIGHTS_DIRECTIONAL_SHADOW");
  403. const int pointShadows = count ("LIGHTS_POINT_SHADOW");
  404. const int features = spotShadowCookies + spotShadows + spotCookies + 3 * directionalShadows;
  405. std::string out = "// begin of generated module LightingV1\n#if LIGHTING\n";
  406. const auto declare = [&out] (const char* type, const char* name, const int size) {
  407. out += std::string ("uniform ") + type + " " + name + "[" + std::to_string (size) + "];\n";
  408. };
  409. const auto index = [] (const char* name, const int value) {
  410. return std::string ("\tconst uint ") + name + " = " + std::to_string (value) + "u;\n";
  411. };
  412. if (points) {
  413. declare ("vec4", "g_LPoint_Color", points);
  414. declare ("vec4", "g_LPoint_Origin", points);
  415. }
  416. if (spots) {
  417. declare ("vec4", "g_LSpot_Color", spots);
  418. declare ("vec4", "g_LSpot_Origin", spots);
  419. declare ("vec4", "g_LSpot_Direction", spots);
  420. declare ("vec4", "g_LSpot_Exponent", spots);
  421. }
  422. if (tubes) {
  423. declare ("vec4", "g_LTube_Color", tubes);
  424. declare ("vec4", "g_LTube_OriginA", tubes);
  425. declare ("vec4", "g_LTube_OriginB", tubes);
  426. }
  427. if (directionals) {
  428. declare ("vec4", "g_LDirectional_Color", directionals);
  429. declare ("vec4", "g_LDirectional_Direction", directionals);
  430. }
  431. if (features) {
  432. declare ("mat4", "g_LFeature_ShadowProjection", features);
  433. declare ("vec4", "g_LFeature_ShadowProjectionTransform", features);
  434. }
  435. if (pointShadows) {
  436. declare ("vec4", "g_LFeature_ShadowPointProjection", pointShadows);
  437. declare ("vec4", "g_LFeature_ShadowPointProjectionTransform", pointShadows);
  438. }
  439. out += "vec3 PerformLighting_V1(vec3 worldPos, vec3 color, vec3 normal, vec3 viewVector, vec3 specularTint, vec3 "
  440. "ambient, float roughness, float metallic)\n{\n\tvec3 light = CAST3(0.0);\n";
  441. int light = 0;
  442. for (; light < pointShadows; light++) {
  443. out += "{\n" + index ("i", light);
  444. out += "\tvec3 lightDelta = g_LPoint_Origin[i].xyz - worldPos;\n"
  445. "\tvec4 projectedCoords = CalculateProjectedCoordsPoint(worldPos, g_LPoint_Origin[i].xyz, "
  446. "g_LFeature_ShadowPointProjection[i], g_LFeature_ShadowPointProjectionTransform[i]);\n"
  447. "\tfloat shadowFactor = PerformPointShadowMapping(projectedCoords);\n"
  448. "\tlight += ComputePBRLightShadow(normal, lightDelta, viewVector, color, g_LPoint_Color[i].rgb, "
  449. "g_LPoint_Color[i].w, g_LPoint_Origin[i].w, specularTint, ambient, roughness, metallic, shadowFactor);\n"
  450. "}\n";
  451. }
  452. for (; light < points; light++) {
  453. out += "{\n" + index ("i", light);
  454. out += "\tvec3 lightDelta = g_LPoint_Origin[i].xyz - worldPos;\n"
  455. "\tlight += ComputePBRLightShadow(normal, lightDelta, viewVector, color, g_LPoint_Color[i].rgb, "
  456. "g_LPoint_Color[i].w, g_LPoint_Origin[i].w, specularTint, ambient, roughness, metallic, 1.0);\n"
  457. "}\n";
  458. }
  459. // spots: shadow and cookie, cookie, shadow, plain, one running index
  460. const std::string spotCookieSample = "\tvec3 projectedCoords = CalculateProjectedCoords(worldPos, "
  461. "g_LFeature_ShadowProjection[i]);\n";
  462. const std::string spotShadowSample = "\tfloat shadowFactor = PerformShadowMapping(projectedCoords, "
  463. "g_LFeature_ShadowProjectionTransform[i]);\n";
  464. const std::string spotCone
  465. = "\tfloat spotCookie = -dot(normalize(lightDelta), g_LSpot_Direction[i].xyz);\n"
  466. "\tspotCookie = smoothstep(g_LSpot_Direction[i].w, g_LSpot_Origin[i].w, spotCookie);\n";
  467. const auto spotLight = [] (const char* scale, const char* shadow) {
  468. return std::string (
  469. "\tlight += ComputePBRLightShadow(normal, lightDelta, viewVector, color, g_LSpot_Color[i].rgb * "
  470. )
  471. + scale + ", g_LSpot_Color[i].w, g_LSpot_Exponent[i].x, specularTint, ambient, roughness, metallic, "
  472. + shadow + ");\n";
  473. };
  474. const std::string spotDelta = "\tvec3 lightDelta = g_LSpot_Origin[i].xyz - worldPos;\n";
  475. const std::string cookieSample = "\tvec3 colorCookie = texSample2D(COOKIE_SAMPLER, projectedCoords.xy).rgb;\n";
  476. int spot = 0;
  477. for (int n = 0; n < spotShadowCookies; n++, spot++) {
  478. out += "{\n" + index ("i", spot) + spotDelta + spotCookieSample + spotShadowSample + cookieSample
  479. + spotLight ("colorCookie", "shadowFactor") + "}\n";
  480. }
  481. for (int n = 0; n < spotCookies; n++, spot++) {
  482. out += "{\n" + index ("i", spot) + spotDelta + spotCookieSample + cookieSample
  483. + spotLight ("colorCookie", "1.0") + "}\n";
  484. }
  485. for (int n = 0; n < spotShadows; n++, spot++) {
  486. out += "{\n" + index ("i", spot) + spotDelta + spotCone + spotCookieSample + spotShadowSample
  487. + spotLight ("spotCookie", "shadowFactor") + "}\n";
  488. }
  489. for (; spot < spots; spot++) {
  490. out += "{\n" + index ("i", spot) + spotDelta + spotCone + spotLight ("spotCookie", "1.0") + "}\n";
  491. }
  492. for (int tube = 0; tube < tubes; tube++) {
  493. out += "{\n" + index ("i", tube);
  494. out += "\tvec3 lightDelta = PointSegmentDelta(worldPos, g_LTube_OriginA[i].xyz, g_LTube_OriginB[i].xyz);\n"
  495. "\tlight += ComputePBRLightShadow(normal, lightDelta, viewVector, color, g_LTube_Color[i].rgb, "
  496. "g_LTube_Color[i].w, g_LTube_OriginA[i].w, specularTint, ambient, roughness, metallic, 1.0);\n"
  497. "}\n";
  498. }
  499. // shadowed directional lights read three cascades starting after the spots' shadow/cookie matrices; WE moves that
  500. // start by one per light, not three
  501. int cascade = spotShadowCookies + spotCookies + spotShadows;
  502. int directional = 0;
  503. for (; directional < directionalShadows; directional++, cascade++) {
  504. out += "{\n" + index ("i", directional) + index ("p1", cascade) + index ("p2", cascade + 1)
  505. + index ("p3", cascade + 2);
  506. out += "\tvec4 projectedCoords1 = CalculateProjectedCoordsCascades(worldPos, "
  507. "g_LFeature_ShadowProjection[p1]);\n"
  508. "\tvec4 projectedCoords2 = CalculateProjectedCoordsCascades(worldPos, "
  509. "g_LFeature_ShadowProjection[p2]);\n"
  510. "\tvec4 projectedCoords3 = CalculateProjectedCoordsCascades(worldPos, "
  511. "g_LFeature_ShadowProjection[p3]);\n"
  512. "\tprojectedCoords1.xyz = mix(projectedCoords1.xyz, projectedCoords2.xyz, projectedCoords1.w);\n"
  513. "\tprojectedCoords1.xyz = mix(projectedCoords1.xyz, projectedCoords3.xyz, projectedCoords2.w);\n"
  514. "\tvec4 uvTransforms = mix(g_LFeature_ShadowProjectionTransform[p1], "
  515. "g_LFeature_ShadowProjectionTransform[p2], projectedCoords1.w);\n"
  516. "\tuvTransforms = mix(uvTransforms, g_LFeature_ShadowProjectionTransform[p3], projectedCoords2.w);\n"
  517. "\tfloat shadowFactor = max(projectedCoords3.w, PerformShadowMapping(projectedCoords1.xyz, "
  518. "uvTransforms));\n"
  519. "\tlight += ComputePBRLightShadowInfinite(normal, g_LDirectional_Direction[i].xyz, viewVector, color, "
  520. "g_LDirectional_Color[i].rgb, specularTint, ambient, roughness, metallic, shadowFactor);\n"
  521. "}\n";
  522. }
  523. for (; directional < directionals; directional++) {
  524. out += "{\n" + index ("i", directional);
  525. out += "\tlight += ComputePBRLightShadowInfinite(normal, g_LDirectional_Direction[i].xyz, viewVector, color, "
  526. "g_LDirectional_Color[i].rgb, specularTint, ambient, roughness, metallic, 1.0);\n"
  527. "}\n";
  528. }
  529. out += "\treturn light;\n}\n#endif\n// end of generated module LightingV1\n";
  530. return out;
  531. }
  532. void ShaderUnit::preprocessBalanceConditionals () {
  533. static const Regex directive (R"((?:^|\n)[ \t]*#(ifndef|ifdef|if|endif)\b)");
  534. int depth = 0;
  535. std::vector<size_t> extraEndifs;
  536. auto begin = RegexIterator (this->m_preprocessed.cbegin (), this->m_preprocessed.cend (), directive);
  537. auto end = RegexIterator ();
  538. for (auto it = begin; it != end; ++it) {
  539. const std::string& keyword = (*it)[1].str ();
  540. if (keyword == "endif") {
  541. if (depth == 0) {
  542. // position of the '#' character for this directive
  543. extraEndifs.push_back (it->position (1) - 1);
  544. } else {
  545. depth--;
  546. }
  547. } else {
  548. depth++;
  549. }
  550. }
  551. // comment out the extra #endif directives, from the end so earlier offsets stay valid
  552. for (auto it = extraEndifs.rbegin (); it != extraEndifs.rend (); ++it) {
  553. sLog.out ("Found #endif with no matching #if in shader ", this->m_file, ", ignoring it");
  554. this->m_preprocessed.replace (*it, 2, "//");
  555. }
  556. }
  557. void ShaderUnit::preprocessSwizzledDeclarations () {
  558. static const Regex swizzledDecl (
  559. R"(\b(varying|uniform|attribute)(\s+[A-Za-z0-9_]+\s+[A-Za-z_][A-Za-z0-9_]*)\.[xyzwrgba]+(\s*;))"
  560. );
  561. const std::string original = this->m_preprocessed;
  562. this->m_preprocessed = std::regex_replace (this->m_preprocessed, swizzledDecl, "$1$2$3");
  563. if (this->m_preprocessed != original) {
  564. sLog.out ("Dropped swizzle from declaration name in shader ", this->m_file);
  565. }
  566. }
  567. void ShaderUnit::preprocessScalarSwizzles () {
  568. // genericropeparticle's non geometry shader TRAILSCROLLALPHA + TRAILFADESIZE branch writes sizeStart.w on a
  569. // float, WE never compiles that branch (it draws ropes with a geometry shader) and GLSL rejects it. A single
  570. // component swizzle of a variable that is only ever declared as float is the variable itself
  571. static const Regex declaration (
  572. R"(\b(float|int|bool|u?int|[biu]?vec[234]|mat[234](?:x[234])?)\s+([A-Za-z_][A-Za-z0-9_]*)\b)"
  573. );
  574. std::set<std::string> scalars;
  575. std::set<std::string> others;
  576. for (auto it = RegexIterator (this->m_preprocessed.begin (), this->m_preprocessed.end (), declaration);
  577. it != RegexIterator (); ++it) {
  578. ((*it)[1] == "float" ? scalars : others).insert ((*it)[2]);
  579. }
  580. for (const auto& name : scalars) {
  581. // regex is slow, most names never have a dot after them
  582. if (others.contains (name) || this->m_preprocessed.find (name + ".") == std::string::npos) {
  583. continue;
  584. }
  585. const Regex swizzle ("\\b" + name + "\\.[xyzwrgba](?![A-Za-z0-9_])");
  586. this->m_preprocessed = std::regex_replace (this->m_preprocessed, swizzle, name);
  587. // scalar .xx/.xxx/.xxxx (or .rr...) replication, e.g. 3035844290 bokeh_blur
  588. for (const char* width : { "4", "3", "2" }) {
  589. const Regex replicate ("\\b" + name + "\\.(?:[x]{" + width + "}|[r]{" + width + "})(?![A-Za-z0-9_])");
  590. this->m_preprocessed
  591. = std::regex_replace (this->m_preprocessed, replicate, std::string ("vec") + width + " (" + name + ")");
  592. }
  593. }
  594. }
  595. std::string ShaderUnit::applyVectorTruncationCompatibility (std::string source) const {
  596. static const Regex vectorDecl (R"(\b(vec[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
  597. static const Regex narrowAssign (R"(\b(vec[23])\s+[A-Za-z_][A-Za-z0-9_]*\s*=\s*([^;{}]+);)");
  598. // name -> width, 0 when the same name is declared with different widths in different scopes
  599. std::unordered_map<std::string, int> widths;
  600. for (auto it = RegexIterator (source.cbegin (), source.cend (), vectorDecl); it != RegexIterator (); ++it) {
  601. const int width = (*it)[1].str ().back () - '0';
  602. const std::string name = (*it)[2].str ();
  603. const auto found = widths.find (name);
  604. if (found == widths.end ()) {
  605. widths.emplace (name, width);
  606. } else if (found->second != width) {
  607. found->second = 0;
  608. }
  609. }
  610. static const char* swizzles[] = { "", "", ".xy", ".xyz" };
  611. bool changed = false;
  612. const auto truncate = [&] (const std::string& expr, const int targetWidth) {
  613. // HLSL truncates a wider operand anywhere the result narrows, so plain grouping parens are
  614. // looked through too: "vec2 uv = (v4 * res.xy) / 4" -> "(v4.xy * res.xy) / 4". call arguments,
  615. // indices and groups that get swizzled or indexed afterwards keep their operands as they are
  616. std::vector<bool> groups;
  617. int blocked = 0;
  618. std::string fixed;
  619. for (size_t i = 0; i < expr.size ();) {
  620. const char c = expr[i];
  621. if (c == '(' || c == '[') {
  622. bool grouping = c == '(';
  623. if (grouping) {
  624. size_t prev = i;
  625. while (prev > 0 && std::isspace (static_cast<unsigned char> (expr[prev - 1]))) {
  626. prev--;
  627. }
  628. if (prev > 0
  629. && (std::isalnum (static_cast<unsigned char> (expr[prev - 1])) || expr[prev - 1] == '_')) {
  630. grouping = false;
  631. }
  632. }
  633. if (grouping) {
  634. int nested = 0;
  635. size_t close = i;
  636. for (; close < expr.size (); close++) {
  637. if (expr[close] == '(' || expr[close] == '[') {
  638. nested++;
  639. } else if ((expr[close] == ')' || expr[close] == ']') && --nested == 0) {
  640. break;
  641. }
  642. }
  643. size_t next = close + 1;
  644. while (next < expr.size () && std::isspace (static_cast<unsigned char> (expr[next]))) {
  645. next++;
  646. }
  647. if (close >= expr.size () || (next < expr.size () && (expr[next] == '.' || expr[next] == '['))) {
  648. grouping = false;
  649. }
  650. }
  651. groups.push_back (grouping);
  652. blocked += grouping ? 0 : 1;
  653. } else if ((c == ')' || c == ']') && !groups.empty ()) {
  654. blocked -= groups.back () ? 0 : 1;
  655. groups.pop_back ();
  656. }
  657. if (!(std::isalpha (static_cast<unsigned char> (c)) || c == '_')) {
  658. fixed += c;
  659. i++;
  660. continue;
  661. }
  662. size_t end = i;
  663. while (end < expr.size () && (std::isalnum (static_cast<unsigned char> (expr[end])) || expr[end] == '_')) {
  664. end++;
  665. }
  666. const std::string ident = expr.substr (i, end - i);
  667. fixed += ident;
  668. size_t before = i;
  669. while (before > 0 && std::isspace (static_cast<unsigned char> (expr[before - 1]))) {
  670. before--;
  671. }
  672. size_t after = end;
  673. while (after < expr.size () && std::isspace (static_cast<unsigned char> (expr[after]))) {
  674. after++;
  675. }
  676. const bool member = before > 0 && expr[before - 1] == '.';
  677. const bool accessed
  678. = after < expr.size () && (expr[after] == '.' || expr[after] == '(' || expr[after] == '[');
  679. const auto found = widths.find (ident);
  680. if (blocked == 0 && !member && !accessed && found != widths.end () && found->second > targetWidth) {
  681. fixed += swizzles[targetWidth];
  682. changed = true;
  683. }
  684. i = end;
  685. }
  686. return fixed;
  687. };
  688. std::string result;
  689. size_t last = 0;
  690. for (auto it = RegexIterator (source.cbegin (), source.cend (), narrowAssign); it != RegexIterator (); ++it) {
  691. const size_t exprStart = it->position (2);
  692. result.append (source, last, exprStart - last);
  693. result += truncate ((*it)[2].str (), (*it)[1].str ().back () - '0');
  694. last = exprStart + it->length (2);
  695. }
  696. result.append (source, last, std::string::npos);
  697. // the coordinates of a 2D sample are a float2 in HLSL, "texSample2D(s, uv.xy - (k * v4))" truncates v4
  698. static const Regex sampleCall (R"(\btexSample2D(?:Lod)?\s*\()");
  699. std::string sampled;
  700. last = 0;
  701. for (auto it = RegexIterator (result.cbegin (), result.cend (), sampleCall); it != RegexIterator (); ++it) {
  702. const size_t open = it->position () + it->length () - 1;
  703. size_t argStart = std::string::npos;
  704. size_t argEnd = std::string::npos;
  705. int nested = 0;
  706. for (size_t i = open; i < result.size (); i++) {
  707. const char c = result[i];
  708. if (c == '(' || c == '[') {
  709. nested++;
  710. } else if (c == ')' || c == ']') {
  711. if (--nested == 0) {
  712. if (argStart != std::string::npos && argEnd == std::string::npos) {
  713. argEnd = i;
  714. }
  715. break;
  716. }
  717. } else if (c == ',' && nested == 1) {
  718. if (argStart == std::string::npos) {
  719. argStart = i + 1;
  720. } else if (argEnd == std::string::npos) {
  721. argEnd = i;
  722. }
  723. } else if (c == ';' || c == '{' || c == '}') {
  724. break;
  725. }
  726. }
  727. if (argStart == std::string::npos || argEnd == std::string::npos || argStart < last) {
  728. continue;
  729. }
  730. sampled.append (result, last, argStart - last);
  731. sampled += truncate (result.substr (argStart, argEnd - argStart), 2);
  732. last = argEnd;
  733. }
  734. if (!changed) {
  735. return source;
  736. }
  737. sampled.append (result, last, std::string::npos);
  738. sLog.out ("Applied vector truncation compatibility in shader ", this->m_file);
  739. return sampled;
  740. }
  741. std::string ShaderUnit::applyFloatConditionCompatibility (std::string source) const {
  742. static const Regex floatDecl (R"(\b(float|vec[234]|int|bool|mat[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
  743. static const Regex ternaryCond (R"(\b([A-Za-z_][A-Za-z0-9_]*)\s*\?)");
  744. static const Regex ifCond (R"(\bif\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\))");
  745. // names that are only ever declared as float
  746. std::unordered_map<std::string, bool> onlyFloat;
  747. for (auto it = RegexIterator (source.cbegin (), source.cend (), floatDecl); it != RegexIterator (); ++it) {
  748. const bool isFloat = (*it)[1].str () == "float";
  749. const std::string name = (*it)[2].str ();
  750. const auto found = onlyFloat.find (name);
  751. if (found == onlyFloat.end ()) {
  752. onlyFloat.emplace (name, isFloat);
  753. } else if (!isFloat) {
  754. found->second = false;
  755. }
  756. }
  757. std::string result;
  758. size_t last = 0;
  759. bool changed = false;
  760. auto rewrite = [&] (const Regex& pattern, bool ternary) {
  761. result.clear ();
  762. last = 0;
  763. for (auto it = RegexIterator (source.cbegin (), source.cend (), pattern); it != RegexIterator (); ++it) {
  764. const std::string name = (*it)[1].str ();
  765. const auto found = onlyFloat.find (name);
  766. if (found == onlyFloat.end () || !found->second) {
  767. continue;
  768. }
  769. const size_t nameStart = it->position (1);
  770. const size_t nameEnd = nameStart + name.size ();
  771. if (ternary) {
  772. size_t before = nameStart;
  773. while (before > 0 && std::isspace (static_cast<unsigned char> (source[before - 1]))) {
  774. before--;
  775. }
  776. if (before == 0) {
  777. continue;
  778. }
  779. // only where the float is the whole condition (or a whole && / || operand), not e.g. `x == f ? ..`
  780. const char prev = source[before - 1];
  781. const char beforePrev = before > 1 ? source[before - 2] : ' ';
  782. const bool assignment = prev == '=' && std::string ("=!<>").find (beforePrev) == std::string::npos;
  783. if (!assignment && prev != '(' && prev != ',' && prev != '&' && prev != '|') {
  784. continue;
  785. }
  786. }
  787. result.append (source, last, nameStart - last);
  788. result += "(" + name + " != 0.0)";
  789. last = nameEnd;
  790. changed = true;
  791. }
  792. result.append (source, last, std::string::npos);
  793. source = result;
  794. };
  795. rewrite (ternaryCond, true);
  796. rewrite (ifCond, false);
  797. if (changed) {
  798. sLog.out ("Applied float condition compatibility in shader ", this->m_file);
  799. }
  800. return source;
  801. }
  802. std::string ShaderUnit::applyBoolArithmeticCompatibility (std::string source) const {
  803. static const Regex decl (R"(\b(float|int|uint|bool|[biu]?vec[234]|mat[234])\s+([A-Za-z_][A-Za-z0-9_]*)\b)");
  804. static const Regex assign (R"(\b([A-Za-z_][A-Za-z0-9_]*)\s*([-+*/]?=)\s*([A-Za-z_][A-Za-z0-9_]*)\s*;)");
  805. // every type each name is declared with (#if branches may declare it differently)
  806. std::unordered_map<std::string, std::set<std::string>> types;
  807. for (auto it = RegexIterator (source.cbegin (), source.cend (), decl); it != RegexIterator (); ++it) {
  808. types[(*it)[2].str ()].insert ((*it)[1].str ());
  809. }
  810. const auto only = [] (const std::set<std::string>& set, std::initializer_list<const char*> allowed) {
  811. return std::ranges::all_of (set, [&allowed] (const std::string& type) {
  812. return std::ranges::any_of (allowed, [&type] (const char* a) { return type == a; });
  813. });
  814. };
  815. std::string result;
  816. size_t last = 0;
  817. for (auto it = RegexIterator (source.cbegin (), source.cend (), assign); it != RegexIterator (); ++it) {
  818. const auto target = types.find ((*it)[1].str ());
  819. const auto value = types.find ((*it)[3].str ());
  820. if (target == types.end () || value == types.end () || value->second != std::set<std::string> { "bool" }
  821. || !only (target->second, { "int", "uint", "float" })) {
  822. continue;
  823. }
  824. // int converts to float implicitly, so int () fits either way
  825. const std::string cast = target->second == std::set<std::string> { "uint" } ? "uint" : "int";
  826. result.append (source, last, it->position (3) - last);
  827. result += cast + "(" + (*it)[3].str () + ")";
  828. last = it->position (3) + it->length (3);
  829. }
  830. if (last == 0) {
  831. return source;
  832. }
  833. result.append (source, last, std::string::npos);
  834. sLog.out ("Applied bool arithmetic compatibility in shader ", this->m_file);
  835. return result;
  836. }
  837. std::string ShaderUnit::applyLinkedVaryingCompatibility (std::string source) const {
  838. if (this->m_type != GLSLContext::UnitType_Vertex || this->m_link == nullptr) {
  839. return source;
  840. }
  841. Regex fragmentVec4Varying (R"(\bvarying\s+vec4\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
  842. std::smatch varyingMatch;
  843. std::string linked = this->m_link->m_preprocessed;
  844. size_t linkedOffset = 0;
  845. while (std::regex_search (linked.cbegin () + linkedOffset, linked.cend (), varyingMatch, fragmentVec4Varying)) {
  846. const std::string name = varyingMatch[1].str ();
  847. linkedOffset += varyingMatch.position () + varyingMatch.length ();
  848. const Regex vertexVec2Decl ("\\bvarying\\s+vec2\\s+" + name + "\\s*;");
  849. if (!std::regex_search (source, vertexVec2Decl)) {
  850. continue;
  851. }
  852. // m_preprocessed still has the #if branches: a varying declared once per branch (generic's v_TexCoord, vec4
  853. // with LIGHTMAP, vec2 without) already matches the fragment side in every combination
  854. const Regex anyVertexDecl ("\\bvarying\\s+\\w+\\s+" + name + "\\s*;");
  855. if (std::distance (RegexIterator (source.cbegin (), source.cend (), anyVertexDecl), RegexIterator ()) != 1) {
  856. continue;
  857. }
  858. source = std::regex_replace (source, vertexVec2Decl, "varying vec4 " + name + ";");
  859. const Regex assignment ("(^|\\n)([ \\t]*)" + name + "\\s*=\\s*([^;\\n]+);");
  860. std::smatch assignmentMatch;
  861. size_t offset = 0;
  862. while (std::regex_search (source.cbegin () + offset, source.cend (), assignmentMatch, assignment)) {
  863. const std::string prefix = assignmentMatch[1].str ();
  864. const std::string indent = assignmentMatch[2].str ();
  865. const std::string expression = assignmentMatch[3].str ();
  866. const std::string replacement = prefix + indent + name + " = vec4(" + expression + ", 0.0, 1.0);";
  867. const size_t position = offset + assignmentMatch.position ();
  868. source.replace (position, assignmentMatch.length (), replacement);
  869. offset = position + replacement.length ();
  870. }
  871. }
  872. return source;
  873. }
  874. std::string ShaderUnit::applyNarrowFragmentVaryingCompatibility (std::string source) const {
  875. if (this->m_type != GLSLContext::UnitType_Fragment || this->m_link == nullptr) {
  876. return source;
  877. }
  878. static const Regex vertexVarying (R"(\bvarying\s+vec([34])\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
  879. static const Regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
  880. static const char* swizzles[] = { "", "", ".xy", ".xyz" };
  881. if (!std::regex_search (source, mainOpen)) {
  882. return source;
  883. }
  884. const std::string& linked = this->m_link->m_preprocessed;
  885. std::string copyCode;
  886. std::string names;
  887. for (auto it = RegexIterator (linked.cbegin (), linked.cend (), vertexVarying); it != RegexIterator (); ++it) {
  888. const int vertexWidth = (*it)[1].str ()[0] - '0';
  889. const std::string name = (*it)[2].str ();
  890. const Regex anyDecl ("\\bvarying\\s+\\w+\\s+" + name + "\\s*;");
  891. const Regex narrowDecl ("\\bvarying\\s+vec([23])\\s+" + name + "\\s*;");
  892. std::smatch declMatch;
  893. // conditionals are still in the source here, a varying declared once per #if branch
  894. // (the stock generic shaders) can't be told apart from a real mismatch, leave those alone
  895. const auto declarations = [&anyDecl] (const std::string& text) {
  896. return std::distance (RegexIterator (text.cbegin (), text.cend (), anyDecl), RegexIterator ());
  897. };
  898. if (declarations (linked) != 1 || declarations (source) != 1
  899. || !std::regex_search (source, declMatch, narrowDecl) || declMatch[1].str ()[0] - '0' >= vertexWidth) {
  900. continue;
  901. }
  902. const int width = declMatch[1].str ()[0] - '0';
  903. const std::string type = "vec" + std::to_string (width);
  904. const std::string copy = "wpeVar_" + name;
  905. source = std::regex_replace (source, Regex ("(^|[^.\\w])" + name + "\\b"), "$1" + copy);
  906. source = std::regex_replace (
  907. source, Regex ("\\bvarying\\s+" + type + "\\s+" + copy + "\\s*;"),
  908. "varying vec" + std::to_string (vertexWidth) + " " + name + "; " + type + " " + copy + ";"
  909. );
  910. copyCode += " " + copy + " = " + name + swizzles[width] + ";";
  911. names += (names.empty () ? "" : ", ") + name;
  912. }
  913. if (copyCode.empty ()) {
  914. return source;
  915. }
  916. std::smatch mainMatch;
  917. std::regex_search (source, mainMatch, mainOpen);
  918. source.insert (mainMatch.position (0) + mainMatch.length (0), copyCode);
  919. sLog.out ("Applied narrow fragment varying compatibility in ", this->m_file, " for ", names);
  920. return source;
  921. }
  922. std::string ShaderUnit::applyFragmentTexCoordCompatibility (std::string source) const {
  923. if (this->m_type != GLSLContext::UnitType_Fragment) {
  924. return source;
  925. }
  926. const Regex texCoordBeforeCast2 (R"(\bv_TexCoord\b(\s*[-+*/]\s*CAST2\s*\())");
  927. const Regex cast2BeforeTexCoord (R"((CAST2\s*\([^)]+\)\s*[-+*/]\s*)\bv_TexCoord\b)");
  928. const Regex wideTexCoordDecl (R"(\bvarying\s+vec[34]\s+v_TexCoord\s*;)");
  929. if (!std::regex_search (source, wideTexCoordDecl)
  930. || (!std::regex_search (source, texCoordBeforeCast2) && !std::regex_search (source, cast2BeforeTexCoord))) {
  931. return source;
  932. }
  933. const std::string original = source;
  934. source = std::regex_replace (source, texCoordBeforeCast2, "v_TexCoord.xy$1");
  935. source = std::regex_replace (source, cast2BeforeTexCoord, "$1v_TexCoord.xy");
  936. if (source != original) {
  937. sLog.out ("Applied fragment TexCoord vec2 compatibility in ", this->m_file);
  938. }
  939. return source;
  940. }
  941. std::string ShaderUnit::applyFragmentVaryingShadowCompatibility (std::string source) const {
  942. if (this->m_type != GLSLContext::UnitType_Fragment) {
  943. return source;
  944. }
  945. static const Regex varyingDecl (R"(\bvarying\s+(vec[234]|float)\s+([A-Za-z_][A-Za-z0-9_]*)\s*;)");
  946. std::vector<std::pair<std::string, std::string>> shadowed;
  947. for (auto it = RegexIterator (source.cbegin (), source.cend (), varyingDecl); it != RegexIterator (); ++it) {
  948. const std::string type = (*it)[1].str ();
  949. const std::string name = (*it)[2].str ();
  950. // only shadow varyings the shader actually reassigns - a plain read-only "in" is fine as-is,
  951. // and touching the declaration unnecessarily risks breaking a shader that works today.
  952. // writes to a typed local of the same name don't count, that local already shadows the varying
  953. const Regex localDecl ("\\b(?:vec[234]|float|int|bool)\\s+" + name + "\\b");
  954. const std::string withoutLocals = std::regex_replace (source, localDecl, " ");
  955. const Regex assignmentUse (
  956. "(?:\\b" + name + "\\b(?:\\.[xyzwrgba]+)?\\s*(?:=(?!=)|\\+=|-=|\\*=|/=|\\+\\+|--))|(?:(?:\\+\\+|--)\\s*"
  957. + name + "\\b)"
  958. );
  959. if (!std::regex_search (withoutLocals, assignmentUse)) {
  960. continue;
  961. }
  962. shadowed.emplace_back (type, name);
  963. }
  964. if (shadowed.empty ()) {
  965. return source;
  966. }
  967. static const Regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
  968. if (!std::regex_search (source, mainOpen)) {
  969. return source;
  970. }
  971. // every use goes through a writable global copy instead, filled from the real (read-only)
  972. // input at the top of main(). a global rather than a local in main() so helper functions
  973. // writing to it work too, and the input keeps its name so it still links to the vertex output
  974. std::string copyCode;
  975. for (const auto& [type, name] : shadowed) {
  976. const std::string copy = "wpeVar_" + name;
  977. const Regex use ("(^|[^.\\w])" + name + "\\b");
  978. const Regex decl ("\\bvarying\\s+" + type + "\\s+" + copy + "\\s*;");
  979. source = std::regex_replace (source, use, "$1" + copy);
  980. source = std::regex_replace (source, decl, "varying " + type + " " + name + "; " + type + " " + copy + ";");
  981. copyCode += " " + copy + " = " + name + ";";
  982. }
  983. std::smatch mainMatch;
  984. std::regex_search (source, mainMatch, mainOpen);
  985. source.insert (mainMatch.position (0) + mainMatch.length (0), copyCode);
  986. std::string names;
  987. for (const auto& [type, name] : shadowed) {
  988. names += (names.empty () ? "" : ", ") + name;
  989. }
  990. sLog.out ("Applied fragment varying shadow compatibility in ", this->m_file, " for ", names);
  991. return source;
  992. }
  993. std::string ShaderUnit::applyDirectiveSemicolonCompatibility (std::string source) const {
  994. static const Regex directive (R"((^|\n)([ \t]*#[ \t]*(?:if|elif)\b[^\n;]*?)[ \t]*;[ \t]*(?=\r?\n|$))");
  995. std::string result = std::regex_replace (source, directive, "$1$2");
  996. if (result != source) {
  997. sLog.out ("Dropped trailing semicolon from #if/#elif directive(s) in ", this->m_file);
  998. }
  999. return result;
  1000. }
  1001. std::string ShaderUnit::applyHlslAttributeCompatibility (std::string source) const {
  1002. static const Regex attribute (
  1003. R"(([;{}]|^|\n)([ \t]*)\[\s*(?:loop|unroll|branch|flatten|fastopt|allow_uav_condition|forcecase|call)\s*(?:\(\s*\w*\s*\))?\s*\](?=\s*(?:for|while|do|if|switch)\b))"
  1004. );
  1005. std::string result = std::regex_replace (source, attribute, "$1$2");
  1006. if (result != source) {
  1007. sLog.out ("Dropped HLSL flow control attribute(s) in ", this->m_file);
  1008. }
  1009. return result;
  1010. }
  1011. std::string ShaderUnit::applyPackedFloatArrayCompatibility (std::string source) const {
  1012. // WE packs a uniform float array into vec4 registers (every cached g_AudioSpectrum64Left is float4[16] in its
  1013. // compiled shader's RDEF), so "name[a][b]" reads register a, component b (3605510527's video effect). GLSL
  1014. // can't index a float, the same element is name[a * 4 + b]. HLSL's % on floats is fmod
  1015. static const Regex declaration (R"(\buniform\s+float\s+([A-Za-z_]\w*)\s*\[\s*(\d+)\s*\]\s*;)");
  1016. const auto closing = [&source] (size_t open) -> size_t {
  1017. int depth = 0;
  1018. for (size_t i = open; i < source.size (); i++) {
  1019. if (source[i] == '[' || source[i] == '(') {
  1020. depth++;
  1021. } else if (source[i] == ']' || source[i] == ')') {
  1022. if (--depth == 0) {
  1023. return source[i] == ']' ? i : std::string::npos;
  1024. }
  1025. }
  1026. }
  1027. return std::string::npos;
  1028. };
  1029. const auto component = [] (const std::string& expression) {
  1030. int depth = 0;
  1031. for (size_t i = 0; i < expression.size (); i++) {
  1032. if (expression[i] == '(' || expression[i] == '[') {
  1033. depth++;
  1034. } else if (expression[i] == ')' || expression[i] == ']') {
  1035. depth--;
  1036. } else if (expression[i] == '%' && depth == 0) {
  1037. return "int(fmod(float(" + expression.substr (0, i) + "), float(" + expression.substr (i + 1) + ")))";
  1038. }
  1039. }
  1040. return "int(" + expression + ")";
  1041. };
  1042. std::set<std::string> names;
  1043. for (auto it = RegexIterator (source.cbegin (), source.cend (), declaration); it != RegexIterator (); ++it) {
  1044. if (std::stoi ((*it)[2].str ()) % 4 == 0) {
  1045. names.insert ((*it)[1].str ());
  1046. }
  1047. }
  1048. bool changed = false;
  1049. for (const auto& name : names) {
  1050. const Regex use ("\\b" + name + "\\s*\\[");
  1051. size_t offset = 0;
  1052. std::smatch match;
  1053. while (std::regex_search (source.cbegin () + offset, source.cend (), match, use)) {
  1054. const size_t start = offset + match.position ();
  1055. const size_t firstOpen = start + match.length () - 1;
  1056. const size_t firstClose = closing (firstOpen);
  1057. offset = start + match.length ();
  1058. if (firstClose == std::string::npos) {
  1059. continue;
  1060. }
  1061. size_t secondOpen = firstClose + 1;
  1062. while (secondOpen < source.size () && std::isspace (static_cast<unsigned char> (source[secondOpen]))) {
  1063. secondOpen++;
  1064. }
  1065. if (secondOpen >= source.size () || source[secondOpen] != '[') {
  1066. continue;
  1067. }
  1068. const size_t secondClose = closing (secondOpen);
  1069. if (secondClose == std::string::npos) {
  1070. continue;
  1071. }
  1072. const std::string first = source.substr (firstOpen + 1, firstClose - firstOpen - 1);
  1073. const std::string second = source.substr (secondOpen + 1, secondClose - secondOpen - 1);
  1074. const std::string replacement = name + "[int(" + first + ") * 4 + " + component (second) + "]";
  1075. source.replace (start, secondClose + 1 - start, replacement);
  1076. offset = start + replacement.size ();
  1077. changed = true;
  1078. }
  1079. }
  1080. if (changed) {
  1081. sLog.out ("Applied packed float array compatibility in ", this->m_file);
  1082. }
  1083. return source;
  1084. }
  1085. std::string ShaderUnit::applyNonConstantConstCompatibility (std::string source) const {
  1086. // locals only, globals sit at column 0
  1087. static const Regex constLocal (R"((^|\n)([ \t]+)const\s+([^;=]+=([^;]*);))");
  1088. // plain variables and function parameters, anything declared const is skipped below
  1089. static const Regex variableDecl (
  1090. R"((\bconst\s+)?\b(?:float|int|uint|bool|[biu]?vec[234]|mat[234](?:x[234])?)\s+([A-Za-z_]\w*)\s*(?=[=;,)\[]))"
  1091. );
  1092. static const Regex declaredName (R"(^[^=]*?([A-Za-z_]\w*)\s*(?:\[[^\]]*\]\s*)?=)");
  1093. std::string names = R"(texSample2D\w*|texture\w*|g_\w+|v_\w+|wpeVar_\w+)";
  1094. if (const std::string inputs = declaredInputNames (source); !inputs.empty ()) {
  1095. names += "|" + inputs;
  1096. }
  1097. for (auto it = RegexIterator (source.cbegin (), source.cend (), variableDecl); it != RegexIterator (); ++it) {
  1098. if (!(*it)[1].matched) {
  1099. names += "|" + (*it)[2].str ();
  1100. }
  1101. }
  1102. std::string result;
  1103. size_t count = 0;
  1104. auto last = source.cbegin ();
  1105. for (auto it = RegexIterator (source.cbegin (), source.cend (), constLocal); it != RegexIterator (); ++it) {
  1106. const auto& match = *it;
  1107. const Regex nonConstant (R"(\b(?:)" + names + R"()\b)");
  1108. if (!std::regex_search (match[4].first, match[4].second, nonConstant)) {
  1109. continue;
  1110. }
  1111. // later consts reading this one aren't constant either
  1112. if (std::smatch nameMatch; std::regex_search (match[3].first, match[3].second, nameMatch, declaredName)) {
  1113. names += "|" + nameMatch[1].str ();
  1114. }
  1115. result.append (last, match[0].first);
  1116. result += match[1].str () + match[2].str () + match[3].str ();
  1117. last = match[0].second;
  1118. count++;
  1119. }
  1120. if (count == 0) {
  1121. return source;
  1122. }
  1123. result.append (last, source.cend ());
  1124. sLog.out ("Dropped const from ", count, " non-constant local(s) in ", this->m_file);
  1125. return result;
  1126. }
  1127. std::string ShaderUnit::applyNonConstantGlobalConstCompatibility (std::string source) const {
  1128. static const Regex constGlobal (
  1129. R"((^|\n)[ \t]*const\s+((?:float|int|uint|bool|[biu]?vec[234]|mat[234](?:x[234])?)\s+([A-Za-z_]\w*))\s*=([^;]*);)"
  1130. );
  1131. static const Regex mainOpen (R"(\bvoid\s+main\s*\([^)]*\)\s*\{)");
  1132. // only statements outside any function body count as globals
  1133. std::vector<bool> topLevel (source.size () + 1, false);
  1134. int depth = 0;
  1135. bool comment = false;
  1136. for (size_t i = 0; i < source.size (); i++) {
  1137. topLevel[i] = depth == 0;
  1138. if (source[i] == '\n') {
  1139. comment = false;
  1140. } else if (!comment && source.compare (i, 2, "//") == 0) {
  1141. comment = true;
  1142. } else if (!comment && source[i] == '{') {
  1143. depth++;
  1144. } else if (!comment && source[i] == '}' && depth > 0) {
  1145. depth--;
  1146. }
  1147. }
  1148. std::string nonConstant = R"(texSample2D\w*|texture\w*|wpeVar_\w+)";
  1149. if (const std::string inputs = declaredInputNames (source); !inputs.empty ()) {
  1150. nonConstant += "|" + inputs;
  1151. }
  1152. std::string result;
  1153. std::string assignments;
  1154. std::vector<std::string> moved;
  1155. auto last = source.cbegin ();
  1156. for (auto it = RegexIterator (source.cbegin (), source.cend (), constGlobal); it != RegexIterator (); ++it) {
  1157. const auto& match = *it;
  1158. const std::string name = match[3].str ();
  1159. const std::string init = match[4].str ();
  1160. if (!topLevel[match.position (0) + match[1].length ()]) {
  1161. continue;
  1162. }
  1163. // a const that reads an earlier moved one isn't constant anymore either
  1164. const Regex uses (R"(\b(?:)" + nonConstant + R"()\b)");
  1165. if (!std::regex_search (init, uses)) {
  1166. continue;
  1167. }
  1168. result.append (last, match[0].first);
  1169. result += match[1].str () + match[2].str () + ";";
  1170. last = match[0].second;
  1171. // a declaration inside #if PROPERTIES == 6 only exists in that branch, so its assignment must too
  1172. const auto branch = conditionalBranch (source, match.position (0) + match[1].length ());
  1173. if (branch.empty ()) {
  1174. assignments += " " + name + " =" + init + ";";
  1175. } else {
  1176. for (const auto& level : branch) {
  1177. for (const auto& line : level) {
  1178. assignments += "\n" + line;
  1179. }
  1180. }
  1181. assignments += "\n" + name + " =" + init + ";";
  1182. for (size_t i = 0; i < branch.size (); i++) {
  1183. assignments += "\n#endif";
  1184. }
  1185. assignments += "\n";
  1186. }
  1187. nonConstant += "|" + name;
  1188. moved.push_back (name);
  1189. }
  1190. if (moved.empty ()) {
  1191. return source;
  1192. }
  1193. result.append (last, source.cend ());
  1194. const auto mains = std::distance (RegexIterator (result.cbegin (), result.cend (), mainOpen), RegexIterator ());
  1195. if (mains != 1) {
  1196. return source;
  1197. }
  1198. std::smatch mainMatch;
  1199. std::regex_search (result, mainMatch, mainOpen);
  1200. result.insert (mainMatch.position (0) + mainMatch.length (0), assignments);
  1201. std::string names;
  1202. for (const auto& name : moved) {
  1203. names += (names.empty () ? "" : ", ") + name;
  1204. }
  1205. sLog.out ("Moved non-constant global const initializer(s) into main() in ", this->m_file, ": ", names);
  1206. return result;
  1207. }
  1208. int ShaderUnit::defineValue (const std::string& name, const std::string& source) const {
  1209. for (const ComboMap* combos : { &this->m_overrideCombos, &this->m_combos, &this->m_discoveredCombos }) {
  1210. for (const auto& [comboName, value] : *combos) {
  1211. std::string uppercase;
  1212. std::ranges::transform (comboName, std::back_inserter (uppercase), ::toupper);
  1213. if (uppercase == name) {
  1214. return value;
  1215. }
  1216. }
  1217. }
  1218. // the shader's own fallback, like "#ifndef TRAILSUBDIVISION #define TRAILSUBDIVISION 0"
  1219. std::smatch match;
  1220. if (std::regex_search (source, match, Regex ("#define\\s+" + name + "\\s+(-?\\d+)"))) {
  1221. return std::stoi (match[1].str ());
  1222. }
  1223. return 0;
  1224. }
  1225. namespace {
  1226. /** + - * / and parentheses over integers, what WE's [maxvertexcount(...)] expressions use */
  1227. int evaluateCount (const std::string& text, size_t& at) {
  1228. const auto skip = [&] () {
  1229. while (at < text.size () && std::isspace (static_cast<unsigned char> (text[at]))) {
  1230. at++;
  1231. }
  1232. };
  1233. const std::function<int ()> sum = [&] () -> int {
  1234. const std::function<int ()> factor = [&] () -> int {
  1235. skip ();
  1236. if (at < text.size () && text[at] == '(') {
  1237. at++;
  1238. const int value = sum ();
  1239. skip ();
  1240. at++;
  1241. return value;
  1242. }
  1243. if (at < text.size () && text[at] == '-') {
  1244. at++;
  1245. return -factor ();
  1246. }
  1247. int value = 0;
  1248. while (at < text.size () && std::isdigit (static_cast<unsigned char> (text[at]))) {
  1249. value = value * 10 + (text[at++] - '0');
  1250. }
  1251. return value;
  1252. };
  1253. const auto product = [&] () {
  1254. int value = factor ();
  1255. for (skip (); at < text.size () && (text[at] == '*' || text[at] == '/'); skip ()) {
  1256. const char op = text[at++];
  1257. const int right = factor ();
  1258. value = op == '*' ? value * right : (right != 0 ? value / right : 0);
  1259. }
  1260. return value;
  1261. };
  1262. int value = product ();
  1263. for (skip (); at < text.size () && (text[at] == '+' || text[at] == '-'); skip ()) {
  1264. const char op = text[at++];
  1265. const int right = product ();
  1266. value = op == '+' ? value + right : value - right;
  1267. }
  1268. return value;
  1269. };
  1270. return sum ();
  1271. }
  1272. } // namespace
  1273. std::string ShaderUnit::applyGeometryOutputNames (std::string source) const {
  1274. if (this->m_type != GLSLContext::UnitType_Vertex || !this->m_feedsGeometry) {
  1275. return source;
  1276. }
  1277. static const Regex varyingDecl (R"(\bvarying\s+\w+\s+([A-Za-z_]\w*)\s*;)");
  1278. std::set<std::string> names;
  1279. for (auto it = RegexIterator (source.cbegin (), source.cend (), varyingDecl); it != RegexIterator (); ++it) {
  1280. names.insert ((*it)[1].str ());
  1281. }
  1282. for (const auto& name : names) {
  1283. source = std::regex_replace (source, Regex ("\\b" + name + "\\b"), GEOMETRY_INPUT_PREFIX + name);
  1284. }
  1285. return source;
  1286. }
  1287. std::string ShaderUnit::applyGeometryDialect (std::string source) const {
  1288. // [maxvertexcount(N)] -> the input and output layouts, N worked out with the combos this unit gets
  1289. static const Regex maxVertexCount (R"(\[\s*maxvertexcount\s*\(([^\]]*)\)\s*\])");
  1290. std::smatch match;
  1291. if (std::regex_search (source, match, maxVertexCount)) {
  1292. std::string expression = match[1].str ();
  1293. static const Regex identifier (R"([A-Za-z_]\w*)");
  1294. std::string resolved;
  1295. auto last = expression.cbegin ();
  1296. for (auto it = RegexIterator (expression.cbegin (), expression.cend (), identifier); it != RegexIterator ();
  1297. ++it) {
  1298. resolved.append (last, (*it)[0].first);
  1299. resolved += std::to_string (this->defineValue ((*it)[0].str (), source));
  1300. last = (*it)[0].second;
  1301. }
  1302. resolved.append (last, expression.cend ());
  1303. size_t at = 0;
  1304. const int count = std::max (1, evaluateCount (resolved, at));
  1305. source.replace (
  1306. match.position (0), match.length (0),
  1307. "layout(points) in;\nlayout(triangle_strip, max_vertices = " + std::to_string (count) + ") out;\n"
  1308. );
  1309. }
  1310. // the vertex stage's outputs arrive as arrays under the names applyGeometryOutputNames gave them (the same
  1311. // names are often outputs here too, v_Color), gl_Position is a builtin on both sides
  1312. source = std::regex_replace (source, Regex (R"(\b(in|out)\s+vec4\s+gl_Position\s*;)"), "");
  1313. source = std::regex_replace (
  1314. source, Regex (R"((^|\n)(\s*)in\s+(\w+)\s+(\w+)\s*;)"), "$1$2in $3 " GEOMETRY_INPUT_PREFIX "$4[];"
  1315. );
  1316. source
  1317. = std::regex_replace (source, Regex (R"(\bIN\s*\[([^\]]+)\]\s*\.\s*gl_Position\b)"), "gl_in[$1].gl_Position");
  1318. source = std::regex_replace (source, Regex (R"(\bIN\s*\[([^\]]+)\]\s*\.\s*(\w+))"), GEOMETRY_INPUT_PREFIX "$2[$1]");
  1319. // "PS_INPUT v;" is the vertex being written: its fields are the outputs themselves
  1320. static const Regex vertexDecl (R"(\bPS_INPUT\s+(\w+)\s*;)");
  1321. if (std::regex_search (source, match, vertexDecl)) {
  1322. const std::string name = match[1].str ();
  1323. source = std::regex_replace (source, vertexDecl, "");
  1324. source = std::regex_replace (source, Regex ("(^|[^\\w.])" + name + "\\s*\\.\\s*(\\w+)"), "$1$2");
  1325. source = std::regex_replace (
  1326. source, Regex ("\\bOUT\\s*\\.\\s*Append\\s*\\(\\s*" + name + "\\s*\\)\\s*;"), "EmitVertex();"
  1327. );
  1328. }
  1329. source = std::regex_replace (source, Regex (R"(\bOUT\s*\.\s*RestartStrip\s*\(\s*\)\s*;)"), "EndPrimitive();");
  1330. // HLSL lets a loop body redeclare its counter ("for (int s ...) { float s = ...") and use the new one from then
  1331. // on, GLSL doesn't: the counter gets another name in the loop header
  1332. static const Regex loopHeader (R"(for\s*\(\s*int\s+(\w+)\s*=[^;]*;[^;]*;[^)]*\))");
  1333. std::string result;
  1334. auto last = source.cbegin ();
  1335. for (auto it = RegexIterator (source.cbegin (), source.cend (), loopHeader); it != RegexIterator (); ++it) {
  1336. const std::string counter = (*it)[1].str ();
  1337. const size_t bodyStart = static_cast<size_t> ((*it)[0].second - source.cbegin ());
  1338. const size_t bodyEnd = std::min (source.size (), source.find ('}', bodyStart));
  1339. const std::string body = source.substr (bodyStart, bodyEnd - bodyStart);
  1340. std::string header = (*it)[0].str ();
  1341. if (std::regex_search (body, Regex ("\\b(?:float|int|uint|vec[234])\\s+" + counter + "\\s*="))) {
  1342. header = std::regex_replace (header, Regex ("\\b" + counter + "\\b"), "wpeLoop_" + counter);
  1343. }
  1344. result.append (last, (*it)[0].first);
  1345. result += header;
  1346. last = (*it)[0].second;
  1347. }
  1348. result.append (last, source.cend ());
  1349. return result;
  1350. }
  1351. void ShaderUnit::parseComboConfiguration (const std::string& content, const int defaultValue) {
  1352. // "require"/"requireany" on a combo are editor-only, they decide whether the editor shows the
  1353. // option. wallpaper64.exe (sub_140133B60) never reads them, it just takes the default
  1354. JSON data;
  1355. try {
  1356. data = JSON::parseAsset (content);
  1357. } catch (const std::exception& e) {
  1358. sLog.error ("Cannot parse combo metadata in shader ", this->m_file, ": ", e.what ());
  1359. return;
  1360. }
  1361. const auto combo = data.require<std::string> ("combo", "cannot parse combo information");
  1362. // "type" is ignored - appears to be editor-only metadata
  1363. const auto defvalue = data.find ("default");
  1364. const auto entry = this->m_combos.find (combo);
  1365. const auto entryOverride = this->m_overrideCombos.find (combo);
  1366. this->m_usedCombos.emplace (combo, true);
  1367. // not predefined anywhere -> fall back to the JSON's own default value
  1368. if (entry == this->m_combos.end () && entryOverride == this->m_overrideCombos.end ()) {
  1369. // like WE: whole numbers (floats included) are taken as-is, a missing or any other default is 0
  1370. int value = defaultValue;
  1371. if (defvalue != data.end () && defvalue->is_number_integer ()) {
  1372. value = defvalue->get<int> ();
  1373. } else if (defvalue != data.end () && defvalue->is_number_float ()) {
  1374. const double number = defvalue->get<double> ();
  1375. if (std::trunc (number) == number) {
  1376. value = static_cast<int> (number);
  1377. }
  1378. }
  1379. this->m_discoveredCombos.emplace (combo, value);
  1380. }
  1381. }
  1382. void ShaderUnit::parseParameterConfiguration (
  1383. const std::string& type, const std::string& name, const std::string& content
  1384. ) {
  1385. // WE only takes the comment as metadata when it parses to a JSON object and skips the uniform silently
  1386. // otherwise (sub_14016CE60), a plain "// note" behind a uniform is common
  1387. JSON data;
  1388. try {
  1389. data = JSON::parseAsset (content);
  1390. } catch (const std::exception&) {
  1391. return;
  1392. }
  1393. if (!data.is_object ()) {
  1394. return;
  1395. }
  1396. const auto material = data.optional ("material");
  1397. const auto defvalue = data.optional ("default");
  1398. const auto combo = data.find ("combo");
  1399. auto constant = this->m_constants.end ();
  1400. if (material.has_value ()) {
  1401. constant = this->m_constants.find (*material);
  1402. }
  1403. if (constant == this->m_constants.end () && !defvalue.has_value ()) {
  1404. if (type != "sampler2D") {
  1405. sLog.exception ("Cannot parse parameter data for ", name, " in shader ", this->m_file);
  1406. }
  1407. }
  1408. Variables::ShaderVariable* parameter = nullptr;
  1409. if (type == "vec4") {
  1410. parameter
  1411. = new Variables::ShaderVariableVector4 (VectorBuilder::parse<glm::vec4> (defvalue->get<std::string> ()));
  1412. } else if (type == "vec3") {
  1413. parameter = new Variables::ShaderVariableVector3 (VectorBuilder::parse<glm::vec3> (*defvalue));
  1414. } else if (type == "vec2") {
  1415. parameter = new Variables::ShaderVariableVector2 (VectorBuilder::parse<glm::vec2> (*defvalue));
  1416. } else if (type == "float") {
  1417. if (defvalue->is_string ()) {
  1418. parameter = new Variables::ShaderVariableFloat (std::stoi (defvalue->get<std::string> ()));
  1419. } else {
  1420. parameter = new Variables::ShaderVariableFloat (defvalue->get<float> ());
  1421. }
  1422. } else if (type == "int") {
  1423. if (defvalue->is_string ()) {
  1424. parameter = new Variables::ShaderVariableInteger (std::stoi (defvalue->get<std::string> ()));
  1425. } else {
  1426. parameter = new Variables::ShaderVariableInteger (defvalue->get<int> ());
  1427. }
  1428. } else if (type == "sampler2D" || type == "sampler2DComparison") {
  1429. const auto textureName = data.find ("default");
  1430. const auto requireany = data.find ("requireany");
  1431. const auto require = data.find ("require");
  1432. constexpr std::string_view prefix = "g_Texture";
  1433. size_t index = 0;
  1434. const char* digits = name.data () + std::min (name.size (), prefix.size ());
  1435. const char* nameEnd = name.data () + name.size ();
  1436. if (!name.starts_with (prefix) || std::from_chars (digits, nameEnd, index).ptr != nameEnd) {
  1437. sLog.error ("Cannot determine texture slot for ", name, " in shader ", this->m_file);
  1438. return;
  1439. }
  1440. if (combo != data.end ()) {
  1441. // TODO: CLEANUP HOW THIS IS DETERMINED FIRST
  1442. const auto textureSlotUsed
  1443. = this->m_passTextures.contains (index) || this->m_overrideTextures.contains (index);
  1444. bool isRequired = false;
  1445. int comboValue = 1;
  1446. if (textureSlotUsed) {
  1447. // texture already exists, so the combo must be set; these tend to have no default value
  1448. isRequired = true;
  1449. } else if (require != data.end ()) {
  1450. if (requireany != data.end () && requireany->get<bool> ()) {
  1451. // requireany: any one mismatching value makes this required (OR semantics)
  1452. for (const auto& item : require->items ()) {
  1453. const std::string& macro = item.key ();
  1454. const auto it = this->m_combos.find (macro);
  1455. if (it == this->m_combos.end () || this->m_overrideCombos.contains (macro)
  1456. || it->second != item.value ()) {
  1457. isRequired = true;
  1458. break;
  1459. }
  1460. }
  1461. } else {
  1462. isRequired = true;
  1463. // require without requireany: every listed value must match (AND semantics)
  1464. for (const auto& item : require->items ()) {
  1465. const std::string& macro = item.key ();
  1466. const auto it = this->m_combos.find (macro);
  1467. // a missing macro is fine here, only the value comparison matters
  1468. if ((it != this->m_combos.end () || this->m_overrideCombos.contains (macro))
  1469. && it->second == item.value ()) {
  1470. isRequired = false;
  1471. break;
  1472. }
  1473. }
  1474. }
  1475. }
  1476. if (isRequired && !textureSlotUsed) {
  1477. if (!defvalue.has_value ()) {
  1478. isRequired = false;
  1479. } else {
  1480. if (this->m_combos.contains (*combo) || this->m_overrideCombos.contains (*combo)) {
  1481. isRequired = false;
  1482. } else if (defvalue->is_string ()) {
  1483. comboValue = std::stoi (defvalue->get<std::string> ().c_str ());
  1484. } else if (defvalue->is_number ()) {
  1485. comboValue = *defvalue;
  1486. } else {
  1487. sLog.exception (
  1488. "Cannot determine default value for combo ", combo->get<std::string> (),
  1489. " because it's not specified by the shader and is not given a default value: ", this->m_file
  1490. );
  1491. }
  1492. }
  1493. }
  1494. if (isRequired) {
  1495. this->m_discoveredCombos.emplace (*combo, comboValue);
  1496. this->m_usedCombos.emplace (*combo, true);
  1497. }
  1498. }
  1499. // Some shaders (e.g. effects/refract.frag's normal map) declare `"default":""` on purpose -
  1500. // an explicitly empty default means "no texture unless the object's own effect config
  1501. // supplies one", not "a texture literally named the empty string". Registering it anyway
  1502. // sent every such object into a doomed asset lookup for a blank path on every use of that
  1503. // shader, whether or not the combo gating it was even active.
  1504. if (textureName != data.end () && !textureName->get<std::string> ().empty ()) {
  1505. this->m_defaultTextures.emplace (index, *textureName);
  1506. }
  1507. if (const auto formatCombo = data.find ("formatcombo");
  1508. formatCombo != data.end () && formatCombo->is_boolean () && formatCombo->get<bool> ()) {
  1509. this->m_formatComboSlots.insert (static_cast<int> (index));
  1510. }
  1511. if (const auto components = data.find ("components"); components != data.end () && components->is_array ()) {
  1512. auto& combos = this->m_componentCombos[static_cast<int> (index)];
  1513. for (const auto& component : *components) {
  1514. const auto componentCombo = component.is_object () ? component.find ("combo") : component.end ();
  1515. combos.push_back (
  1516. componentCombo != component.end () && componentCombo->is_string ()
  1517. ? componentCombo->get<std::string> ()
  1518. : std::string ()
  1519. );
  1520. }
  1521. }
  1522. return;
  1523. } else {
  1524. sLog.error ("Unknown parameter type: ", type, " for ", name, " in shader ", this->m_file);
  1525. return;
  1526. }
  1527. if (material.has_value () && parameter != nullptr) {
  1528. parameter->setIdentifierName (*material);
  1529. parameter->setName (name);
  1530. parameter->setInDegrees (data.optional ("conversion", std::string ()) == "rad2deg");
  1531. this->m_parameters.push_back (parameter);
  1532. }
  1533. }
  1534. const ComboMap& ShaderUnit::getCombos () const { return this->m_combos; }
  1535. const ComboMap& ShaderUnit::getDiscoveredCombos () const { return this->m_discoveredCombos; }
  1536. bool ShaderUnit::refersTo (const std::string& identifier) const {
  1537. const auto isWordChar = [] (const char c) { return std::isalnum (static_cast<unsigned char> (c)) || c == '_'; };
  1538. for (size_t at = this->m_preprocessed.find (identifier); at != std::string::npos;
  1539. at = this->m_preprocessed.find (identifier, at + 1)) {
  1540. const size_t end = at + identifier.size ();
  1541. if ((at == 0 || !isWordChar (this->m_preprocessed[at - 1]))
  1542. && (end == this->m_preprocessed.size () || !isWordChar (this->m_preprocessed[end]))) {
  1543. return true;
  1544. }
  1545. }
  1546. return false;
  1547. }
  1548. void ShaderUnit::linkToUnit (const ShaderUnit* unit) { this->m_link = unit; }
  1549. void ShaderUnit::feedGeometryStage () { this->m_feedsGeometry = true; }
  1550. const ShaderUnit* ShaderUnit::getLinkedUnit () const { return this->m_link; }
  1551. const std::string& ShaderUnit::compile () {
  1552. if (!this->m_final.empty ()) {
  1553. return this->m_final;
  1554. }
  1555. this->m_final = SHADER_HEADER (this->m_file);
  1556. // GLSL has no builtin log10 (unlike HLSL), so some shaders provide their own under "#if GLSL"
  1557. // (which is always true here). Adding a blanket compatibility macro would get expanded right
  1558. // over such a shader's own function definition and mangle it, so only add it when the shader
  1559. // doesn't already define log10 itself.
  1560. static const Regex log10Definition (
  1561. R"(\b(?:void|float|int|uint|bool|vec[234]|ivec[234]|uvec[234]|bvec[234]|mat[234](?:x[234])?)\s+log10\s*\()"
  1562. );
  1563. // memoized per source, compile() runs again for every pass a text layer rebuilds
  1564. static std::mutex cacheMutex;
  1565. static std::unordered_map<std::string, bool> definesLog10;
  1566. static std::unordered_map<std::string, std::string> compatCache;
  1567. bool hasLog10 = false;
  1568. {
  1569. std::lock_guard lock (cacheMutex);
  1570. auto found = definesLog10.find (this->m_content);
  1571. if (found == definesLog10.end ()) {
  1572. found = definesLog10.emplace (this->m_content, std::regex_search (this->m_content, log10Definition)).first;
  1573. }
  1574. hasLog10 = found->second;
  1575. }
  1576. if (!hasLog10) {
  1577. this->m_final += "#define log10(x) (log2(x) * 0.301029995663981)\n";
  1578. }
  1579. if (this->m_feedsGeometry) {
  1580. this->m_final += "// outputs renamed for the geometry stage\n";
  1581. }
  1582. if (this->m_type == GLSLContext::UnitType_Fragment) {
  1583. this->m_final += FRAGMENT_SHADER_DEFINES;
  1584. } else if (this->m_type == GLSLContext::UnitType_Geometry) {
  1585. this->m_final += GEOMETRY_SHADER_DEFINES;
  1586. } else {
  1587. this->m_final += VERTEX_SHADER_DEFINES;
  1588. }
  1589. std::map<std::string, bool> addedCombos;
  1590. for (const auto& [name, value] : this->m_overrideCombos) {
  1591. std::string uppercase;
  1592. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  1593. if (!addedCombos.contains (uppercase)) {
  1594. this->m_final += DEFINE_COMBO (uppercase, value);
  1595. addedCombos.emplace (uppercase, true);
  1596. }
  1597. }
  1598. for (const auto& [name, value] : this->m_combos) {
  1599. std::string uppercase;
  1600. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  1601. if (!addedCombos.contains (uppercase)) {
  1602. this->m_final += DEFINE_COMBO (uppercase, value);
  1603. addedCombos.emplace (uppercase, true);
  1604. }
  1605. }
  1606. for (const auto& [name, value] : this->m_discoveredCombos) {
  1607. std::string uppercase;
  1608. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  1609. if (!addedCombos.contains (uppercase)) {
  1610. this->m_final += DEFINE_COMBO (uppercase, value);
  1611. addedCombos.emplace (uppercase, true);
  1612. }
  1613. }
  1614. if (this->m_link != nullptr) {
  1615. for (const auto& [name, value] : this->m_link->getCombos ()) {
  1616. std::string uppercase;
  1617. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  1618. if (!addedCombos.contains (uppercase)) {
  1619. this->m_final += DEFINE_COMBO (uppercase, value);
  1620. addedCombos.emplace (uppercase, true);
  1621. }
  1622. }
  1623. for (const auto& [name, value] : this->m_link->getDiscoveredCombos ()) {
  1624. std::string uppercase;
  1625. std::ranges::transform (name, std::back_inserter (uppercase), ::toupper);
  1626. if (!addedCombos.contains (uppercase)) {
  1627. this->m_final += DEFINE_COMBO (uppercase, value);
  1628. addedCombos.emplace (uppercase, true);
  1629. }
  1630. }
  1631. }
  1632. // these passes only read what's in the key (plus defines for geometry), so permutations share results
  1633. std::string cacheKey = std::to_string (this->m_type) + (this->m_feedsGeometry ? "g" : "");
  1634. if (this->m_type == GLSLContext::UnitType_Geometry) {
  1635. cacheKey += '\x1f';
  1636. cacheKey += this->m_final;
  1637. for (const auto& [name, value] : this->m_combos) {
  1638. cacheKey += '\x1f';
  1639. cacheKey += name;
  1640. cacheKey += '=';
  1641. cacheKey += std::to_string (value);
  1642. }
  1643. }
  1644. cacheKey += '\x1f';
  1645. cacheKey += this->m_preprocessed;
  1646. cacheKey += '\x1f';
  1647. if (this->m_link != nullptr) {
  1648. cacheKey += this->m_link->m_preprocessed;
  1649. }
  1650. {
  1651. std::lock_guard lock (cacheMutex);
  1652. if (const auto cached = compatCache.find (cacheKey); cached != compatCache.end ()) {
  1653. this->m_final += cached->second;
  1654. return this->m_final;
  1655. }
  1656. }
  1657. const std::string compat = this->applyNonConstantConstCompatibility (this->applyBoolArithmeticCompatibility (
  1658. this->applyFloatConditionCompatibility (this->applyVectorTruncationCompatibility (
  1659. this->applyFragmentVaryingShadowCompatibility (this->applyFragmentTexCoordCompatibility (
  1660. this->applyNarrowFragmentVaryingCompatibility (this->applyLinkedVaryingCompatibility (
  1661. this->applyNonConstantGlobalConstCompatibility (this->applyDirectiveSemicolonCompatibility (
  1662. this->applyHlslAttributeCompatibility (this->applyPackedFloatArrayCompatibility (
  1663. this->m_type == GLSLContext::UnitType_Geometry
  1664. ? this->applyGeometryDialect (this->m_preprocessed)
  1665. : this->applyGeometryOutputNames (this->m_preprocessed)
  1666. ))
  1667. ))
  1668. ))
  1669. ))
  1670. ))
  1671. ));
  1672. {
  1673. std::lock_guard lock (cacheMutex);
  1674. if (compatCache.size () >= MEMO_LIMIT) {
  1675. compatCache.clear ();
  1676. }
  1677. compatCache.emplace (std::move (cacheKey), compat);
  1678. }
  1679. this->m_final += compat;
  1680. // actual GLSL compilation happens in the pass, which has the context this unit doesn't
  1681. return this->m_final;
  1682. }
  1683. const std::vector<Variables::ShaderVariable*>& ShaderUnit::getParameters () const { return this->m_parameters; }
  1684. const TextureMap& ShaderUnit::getTextures () const { return this->m_defaultTextures; }
  1685. const std::set<int>& ShaderUnit::getFormatComboSlots () const { return this->m_formatComboSlots; }
  1686. const std::map<int, std::vector<std::string>>& ShaderUnit::getComponentCombos () const {
  1687. return this->m_componentCombos;
  1688. }