BsSLFXCompiler.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsSLFXCompiler.h"
  4. #include "RenderAPI/BsGpuProgram.h"
  5. #include <regex>
  6. #include "Material/BsShader.h"
  7. #include "Material/BsTechnique.h"
  8. #include "Material/BsPass.h"
  9. #include "RenderAPI/BsSamplerState.h"
  10. #include "RenderAPI/BsRenderAPI.h"
  11. #include "Debug/BsDebug.h"
  12. #include "Material/BsShaderManager.h"
  13. #include "Material/BsShaderInclude.h"
  14. #include "Math/BsMatrix4.h"
  15. #include "Resources/BsBuiltinResources.h"
  16. #define XSC_ENABLE_LANGUAGE_EXT 1
  17. #include "Xsc/Xsc.h"
  18. #include "Material/BsShaderVariation.h"
  19. extern "C" {
  20. #include "BsMMAlloc.h"
  21. #include "BsParserFX.h"
  22. #include "BsLexerFX.h"
  23. }
  24. using namespace std;
  25. namespace bs
  26. {
  27. // Print out the FX AST, only for debug purposes
  28. void SLFXDebugPrint(ASTFXNode* node, String indent)
  29. {
  30. LOGDBG(indent + "NODE " + toString(node->type));
  31. for (int i = 0; i < node->options->count; i++)
  32. {
  33. OptionDataType odt = OPTION_LOOKUP[(int)node->options->entries[i].type].dataType;
  34. if (odt == ODT_Complex)
  35. {
  36. LOGDBG(indent + toString(i) + ". " + toString(node->options->entries[i].type));
  37. SLFXDebugPrint(node->options->entries[i].value.nodePtr, indent + "\t");
  38. continue;
  39. }
  40. String value;
  41. switch (odt)
  42. {
  43. case ODT_Bool:
  44. value = toString(node->options->entries[i].value.intValue != 0);
  45. break;
  46. case ODT_Int:
  47. value = toString(node->options->entries[i].value.intValue);
  48. break;
  49. case ODT_Float:
  50. value = toString(node->options->entries[i].value.floatValue);
  51. break;
  52. case ODT_String:
  53. value = node->options->entries[i].value.strValue;
  54. break;
  55. case ODT_Matrix:
  56. {
  57. Matrix4 mat4 = *(Matrix4*)(node->options->entries[i].value.matrixValue);
  58. value = toString(mat4);
  59. }
  60. break;
  61. default:
  62. break;
  63. }
  64. LOGDBG(indent + toString(i) + ". " + toString(node->options->entries[i].type) + " = " + value);
  65. }
  66. }
  67. class XscLog : public Xsc::Log
  68. {
  69. public:
  70. void SubmitReport(const Xsc::Report& report) override
  71. {
  72. switch (report.Type())
  73. {
  74. case Xsc::ReportTypes::Info:
  75. mInfos.push_back({ FullIndent(), report });
  76. break;
  77. case Xsc::ReportTypes::Warning:
  78. mWarnings.push_back({ FullIndent(), report });
  79. break;
  80. case Xsc::ReportTypes::Error:
  81. mErrors.push_back({ FullIndent(), report });
  82. break;
  83. }
  84. }
  85. void getMessages(StringStream& output)
  86. {
  87. printAndClearReports(output, mInfos);
  88. printAndClearReports(output, mWarnings, (mWarnings.size() == 1 ? "WARNING" : "WARNINGS"));
  89. printAndClearReports(output, mErrors, (mErrors.size() == 1 ? "ERROR" : "ERRORS"));
  90. }
  91. private:
  92. struct IndentReport
  93. {
  94. std::string indent;
  95. Xsc::Report report;
  96. };
  97. static void printMultiLineString(StringStream& output, const std::string& str, const std::string& indent)
  98. {
  99. // Determine at which position the actual text begins (excluding the "error (X:Y) : " or the like)
  100. auto textStartPos = str.find(" : ");
  101. if (textStartPos != std::string::npos)
  102. textStartPos += 3;
  103. else
  104. textStartPos = 0;
  105. std::string newLineIndent(textStartPos, ' ');
  106. size_t start = 0;
  107. bool useNewLineIndent = false;
  108. while (start < str.size())
  109. {
  110. output << indent;
  111. if (useNewLineIndent)
  112. output << newLineIndent;
  113. // Print next line
  114. auto end = str.find('\n', start);
  115. if (end != std::string::npos)
  116. {
  117. output << str.substr(start, end - start);
  118. start = end + 1;
  119. }
  120. else
  121. {
  122. output << str.substr(start);
  123. start = end;
  124. }
  125. output << std::endl;
  126. useNewLineIndent = true;
  127. }
  128. }
  129. void printReport(StringStream& output, const IndentReport& r)
  130. {
  131. // Print optional context description
  132. if (!r.report.Context().empty())
  133. printMultiLineString(output, r.report.Context(), r.indent);
  134. // Print report message
  135. const auto& msg = r.report.Message();
  136. printMultiLineString(output, msg, r.indent);
  137. // Print optional line and line-marker
  138. if (r.report.HasLine())
  139. {
  140. const auto& line = r.report.Line();
  141. const auto& marker = r.report.Marker();
  142. // Print line
  143. output << r.indent << line << std::endl;
  144. // Print line marker
  145. output << r.indent << marker << std::endl;
  146. }
  147. // Print optional hints
  148. for (const auto& hint : r.report.GetHints())
  149. output << r.indent << hint << std::endl;
  150. }
  151. void printAndClearReports(StringStream& output, Vector<IndentReport>& reports, const String& headline = "")
  152. {
  153. if (!reports.empty())
  154. {
  155. if (!headline.empty())
  156. {
  157. String s = toString((UINT32)reports.size()) + " " + headline;
  158. output << s << std::endl;
  159. output << String(s.size(), '-') << std::endl;
  160. }
  161. for (const auto& r : reports)
  162. printReport(output, r);
  163. reports.clear();
  164. }
  165. }
  166. Vector<IndentReport> mInfos;
  167. Vector<IndentReport> mWarnings;
  168. Vector<IndentReport> mErrors;
  169. };
  170. GpuParamObjectType ReflTypeToTextureType(Xsc::Reflection::BufferType type)
  171. {
  172. switch(type)
  173. {
  174. case Xsc::Reflection::BufferType::RWTexture1D: return GPOT_RWTEXTURE1D;
  175. case Xsc::Reflection::BufferType::RWTexture1DArray: return GPOT_RWTEXTURE1DARRAY;
  176. case Xsc::Reflection::BufferType::RWTexture2D: return GPOT_RWTEXTURE2D;
  177. case Xsc::Reflection::BufferType::RWTexture2DArray: return GPOT_RWTEXTURE2DARRAY;
  178. case Xsc::Reflection::BufferType::RWTexture3D: return GPOT_RWTEXTURE3D;
  179. case Xsc::Reflection::BufferType::Texture1D: return GPOT_TEXTURE1D;
  180. case Xsc::Reflection::BufferType::Texture1DArray: return GPOT_TEXTURE1DARRAY;
  181. case Xsc::Reflection::BufferType::Texture2D: return GPOT_TEXTURE2D;
  182. case Xsc::Reflection::BufferType::Texture2DArray: return GPOT_TEXTURE2DARRAY;
  183. case Xsc::Reflection::BufferType::Texture3D: return GPOT_TEXTURE3D;
  184. case Xsc::Reflection::BufferType::TextureCube: return GPOT_TEXTURECUBE;
  185. case Xsc::Reflection::BufferType::TextureCubeArray: return GPOT_TEXTURECUBEARRAY;
  186. case Xsc::Reflection::BufferType::Texture2DMS: return GPOT_TEXTURE2DMS;
  187. case Xsc::Reflection::BufferType::Texture2DMSArray: return GPOT_TEXTURE2DMSARRAY;
  188. default: return GPOT_UNKNOWN;
  189. }
  190. }
  191. GpuParamObjectType ReflTypeToBufferType(Xsc::Reflection::BufferType type)
  192. {
  193. switch(type)
  194. {
  195. case Xsc::Reflection::BufferType::Buffer: return GPOT_RWTYPED_BUFFER;
  196. case Xsc::Reflection::BufferType::StructuredBuffer: return GPOT_STRUCTURED_BUFFER;
  197. case Xsc::Reflection::BufferType::ByteAddressBuffer: return GPOT_BYTE_BUFFER;
  198. case Xsc::Reflection::BufferType::RWBuffer: return GPOT_RWTYPED_BUFFER;
  199. case Xsc::Reflection::BufferType::RWStructuredBuffer: return GPOT_RWSTRUCTURED_BUFFER;
  200. case Xsc::Reflection::BufferType::RWByteAddressBuffer: return GPOT_RWBYTE_BUFFER;
  201. case Xsc::Reflection::BufferType::AppendStructuredBuffer: return GPOT_RWAPPEND_BUFFER;
  202. case Xsc::Reflection::BufferType::ConsumeStructuredBuffer: return GPOT_RWCONSUME_BUFFER;
  203. default: return GPOT_UNKNOWN;
  204. }
  205. }
  206. GpuParamDataType ReflTypeToDataType(Xsc::Reflection::DataType type)
  207. {
  208. switch (type)
  209. {
  210. case Xsc::Reflection::DataType::Bool: return GPDT_BOOL;
  211. case Xsc::Reflection::DataType::Float: return GPDT_FLOAT1;
  212. case Xsc::Reflection::DataType::Float2: return GPDT_FLOAT2;
  213. case Xsc::Reflection::DataType::Float3: return GPDT_FLOAT3;
  214. case Xsc::Reflection::DataType::Float4: return GPDT_FLOAT4;
  215. case Xsc::Reflection::DataType::UInt:
  216. case Xsc::Reflection::DataType::Int:
  217. return GPDT_INT1;
  218. case Xsc::Reflection::DataType::UInt2:
  219. case Xsc::Reflection::DataType::Int2:
  220. return GPDT_INT2;
  221. case Xsc::Reflection::DataType::UInt3:
  222. case Xsc::Reflection::DataType::Int3:
  223. return GPDT_INT3;
  224. case Xsc::Reflection::DataType::UInt4:
  225. case Xsc::Reflection::DataType::Int4:
  226. return GPDT_INT4;
  227. case Xsc::Reflection::DataType::Float2x2: return GPDT_MATRIX_2X2;
  228. case Xsc::Reflection::DataType::Float2x3: return GPDT_MATRIX_2X3;
  229. case Xsc::Reflection::DataType::Float2x4: return GPDT_MATRIX_2X4;
  230. case Xsc::Reflection::DataType::Float3x2: return GPDT_MATRIX_3X4;
  231. case Xsc::Reflection::DataType::Float3x3: return GPDT_MATRIX_3X3;
  232. case Xsc::Reflection::DataType::Float3x4: return GPDT_MATRIX_3X4;
  233. case Xsc::Reflection::DataType::Float4x2: return GPDT_MATRIX_4X2;
  234. case Xsc::Reflection::DataType::Float4x3: return GPDT_MATRIX_4X3;
  235. case Xsc::Reflection::DataType::Float4x4: return GPDT_MATRIX_4X4;
  236. default: return GPDT_UNKNOWN;
  237. }
  238. }
  239. HTexture getBuiltinTexture(UINT32 idx)
  240. {
  241. if (idx == 1)
  242. return BuiltinResources::getTexture(BuiltinTexture::White);
  243. else if (idx == 2)
  244. return BuiltinResources::getTexture(BuiltinTexture::Black);
  245. else if (idx == 3)
  246. return BuiltinResources::getTexture(BuiltinTexture::Normal);
  247. return HTexture();
  248. }
  249. TextureAddressingMode parseTexAddrMode(Xsc::Reflection::TextureAddressMode addrMode)
  250. {
  251. switch (addrMode)
  252. {
  253. case Xsc::Reflection::TextureAddressMode::Border:
  254. return TAM_BORDER;
  255. case Xsc::Reflection::TextureAddressMode::Clamp:
  256. return TAM_CLAMP;
  257. case Xsc::Reflection::TextureAddressMode::Mirror:
  258. case Xsc::Reflection::TextureAddressMode::MirrorOnce:
  259. return TAM_MIRROR;
  260. case Xsc::Reflection::TextureAddressMode::Wrap:
  261. default:
  262. return TAM_WRAP;
  263. }
  264. }
  265. CompareFunction parseCompFunction(Xsc::Reflection::ComparisonFunc compFunc)
  266. {
  267. switch(compFunc)
  268. {
  269. case Xsc::Reflection::ComparisonFunc::Always:
  270. default:
  271. return CMPF_ALWAYS_PASS;
  272. case Xsc::Reflection::ComparisonFunc::Never:
  273. return CMPF_ALWAYS_FAIL;
  274. case Xsc::Reflection::ComparisonFunc::Equal:
  275. return CMPF_EQUAL;
  276. case Xsc::Reflection::ComparisonFunc::Greater:
  277. return CMPF_GREATER;
  278. case Xsc::Reflection::ComparisonFunc::GreaterEqual:
  279. return CMPF_GREATER_EQUAL;
  280. case Xsc::Reflection::ComparisonFunc::Less:
  281. return CMPF_LESS;
  282. case Xsc::Reflection::ComparisonFunc::LessEqual:
  283. return CMPF_LESS_EQUAL;
  284. case Xsc::Reflection::ComparisonFunc::NotEqual:
  285. return CMPF_NOT_EQUAL;
  286. }
  287. }
  288. SPtr<SamplerState> parseSamplerState(const Xsc::Reflection::SamplerState& sampState)
  289. {
  290. SAMPLER_STATE_DESC desc;
  291. desc.addressMode.u = parseTexAddrMode(sampState.addressU);
  292. desc.addressMode.v = parseTexAddrMode(sampState.addressV);
  293. desc.addressMode.w = parseTexAddrMode(sampState.addressW);
  294. desc.borderColor[0] = sampState.borderColor[0];
  295. desc.borderColor[1] = sampState.borderColor[1];
  296. desc.borderColor[2] = sampState.borderColor[2];
  297. desc.borderColor[3] = sampState.borderColor[3];
  298. desc.comparisonFunc = parseCompFunction(sampState.comparisonFunc);
  299. desc.maxAniso = sampState.maxAnisotropy;
  300. desc.mipMax = sampState.maxLOD;
  301. desc.mipMin = sampState.minLOD;
  302. desc.mipmapBias = sampState.mipLODBias;
  303. switch (sampState.filter)
  304. {
  305. case Xsc::Reflection::Filter::MinMagMipPoint:
  306. case Xsc::Reflection::Filter::ComparisonMinMagMipPoint:
  307. desc.minFilter = FO_POINT;
  308. desc.magFilter = FO_POINT;
  309. desc.mipFilter = FO_POINT;
  310. break;
  311. case Xsc::Reflection::Filter::MinMagPointMipLinear:
  312. case Xsc::Reflection::Filter::ComparisonMinMagPointMipLinear:
  313. desc.minFilter = FO_POINT;
  314. desc.magFilter = FO_POINT;
  315. desc.mipFilter = FO_LINEAR;
  316. break;
  317. case Xsc::Reflection::Filter::MinPointMagLinearMipPoint:
  318. case Xsc::Reflection::Filter::ComparisonMinPointMagLinearMipPoint:
  319. desc.minFilter = FO_POINT;
  320. desc.magFilter = FO_LINEAR;
  321. desc.mipFilter = FO_POINT;
  322. break;
  323. case Xsc::Reflection::Filter::MinPointMagMipLinear:
  324. case Xsc::Reflection::Filter::ComparisonMinPointMagMipLinear:
  325. desc.minFilter = FO_POINT;
  326. desc.magFilter = FO_LINEAR;
  327. desc.mipFilter = FO_LINEAR;
  328. break;
  329. case Xsc::Reflection::Filter::MinLinearMagMipPoint:
  330. case Xsc::Reflection::Filter::ComparisonMinLinearMagMipPoint:
  331. desc.minFilter = FO_LINEAR;
  332. desc.magFilter = FO_POINT;
  333. desc.mipFilter = FO_POINT;
  334. break;
  335. case Xsc::Reflection::Filter::MinLinearMagPointMipLinear:
  336. case Xsc::Reflection::Filter::ComparisonMinLinearMagPointMipLinear:
  337. desc.minFilter = FO_LINEAR;
  338. desc.magFilter = FO_POINT;
  339. desc.mipFilter = FO_LINEAR;
  340. break;
  341. case Xsc::Reflection::Filter::MinMagLinearMipPoint:
  342. case Xsc::Reflection::Filter::ComparisonMinMagLinearMipPoint:
  343. desc.minFilter = FO_LINEAR;
  344. desc.magFilter = FO_LINEAR;
  345. desc.mipFilter = FO_POINT;
  346. break;
  347. case Xsc::Reflection::Filter::MinMagMipLinear:
  348. case Xsc::Reflection::Filter::ComparisonMinMagMipLinear:
  349. desc.minFilter = FO_LINEAR;
  350. desc.magFilter = FO_LINEAR;
  351. desc.mipFilter = FO_LINEAR;
  352. break;
  353. case Xsc::Reflection::Filter::Anisotropic:
  354. case Xsc::Reflection::Filter::ComparisonAnisotropic:
  355. desc.minFilter = FO_ANISOTROPIC;
  356. desc.magFilter = FO_ANISOTROPIC;
  357. desc.minFilter = FO_ANISOTROPIC;
  358. break;
  359. default:
  360. break;
  361. }
  362. return SamplerState::create(desc);
  363. }
  364. void parseParameters(const Xsc::Reflection::ReflectionData& reflData, SHADER_DESC& desc)
  365. {
  366. for(auto& entry : reflData.uniforms)
  367. {
  368. if ((entry.flags & Xsc::Reflection::Uniform::Flags::Internal) != 0)
  369. continue;
  370. String ident = entry.ident.c_str();
  371. switch(entry.type)
  372. {
  373. case Xsc::Reflection::UniformType::UniformBuffer:
  374. desc.setParamBlockAttribs(entry.ident.c_str(), false, GPBU_STATIC);
  375. break;
  376. case Xsc::Reflection::UniformType::Buffer:
  377. {
  378. GpuParamObjectType objType = ReflTypeToTextureType((Xsc::Reflection::BufferType)entry.baseType);
  379. if(objType != GPOT_UNKNOWN)
  380. {
  381. // Ignore parameters that were already registered in some previous variation. Note that this implies
  382. // you cannot have same names for different parameters in different variations.
  383. if (desc.textureParams.find(ident) != desc.textureParams.end())
  384. continue;
  385. if (entry.defaultValue == -1)
  386. desc.addParameter(ident, ident, objType);
  387. else
  388. desc.addParameter(ident, ident, objType, getBuiltinTexture(entry.defaultValue));
  389. }
  390. else
  391. {
  392. // Ignore parameters that were already registered in some previous variation. Note that this implies
  393. // you cannot have same names for different parameters in different variations.
  394. if (desc.bufferParams.find(ident) != desc.bufferParams.end())
  395. continue;
  396. objType = ReflTypeToBufferType((Xsc::Reflection::BufferType)entry.baseType);
  397. desc.addParameter(ident, ident, objType);
  398. }
  399. }
  400. break;
  401. case Xsc::Reflection::UniformType::Sampler:
  402. {
  403. auto findIter = reflData.samplerStates.find(entry.ident);
  404. if (findIter != reflData.samplerStates.end())
  405. {
  406. // Ignore parameters that were already registered in some previous variation. Note that this implies
  407. // you cannot have same names for different parameters in different variations.
  408. if(desc.samplerParams.find(ident) != desc.samplerParams.end())
  409. continue;
  410. String alias = findIter->second.alias.c_str();
  411. if(findIter->second.isNonDefault)
  412. {
  413. SPtr<SamplerState> defaultVal = parseSamplerState(findIter->second);
  414. desc.addParameter(ident, ident, GPOT_SAMPLER2D, defaultVal);
  415. if (!alias.empty())
  416. desc.addParameter(ident, alias, GPOT_SAMPLER2D, defaultVal);
  417. }
  418. else
  419. {
  420. desc.addParameter(ident, ident, GPOT_SAMPLER2D);
  421. if (!alias.empty())
  422. desc.addParameter(ident, alias, GPOT_SAMPLER2D);
  423. }
  424. }
  425. else
  426. {
  427. desc.addParameter(ident, ident, GPOT_SAMPLER2D);
  428. }
  429. break;
  430. }
  431. case Xsc::Reflection::UniformType::Variable:
  432. {
  433. bool isBlockInternal = false;
  434. if(entry.uniformBlock != -1)
  435. {
  436. std::string blockName = reflData.constantBuffers[entry.uniformBlock].ident;
  437. for (auto& uniform : reflData.uniforms)
  438. {
  439. if (uniform.type == Xsc::Reflection::UniformType::UniformBuffer && uniform.ident == blockName)
  440. {
  441. isBlockInternal = (uniform.flags & Xsc::Reflection::Uniform::Flags::Internal) != 0;
  442. break;
  443. }
  444. }
  445. }
  446. if (!isBlockInternal)
  447. {
  448. GpuParamDataType type = ReflTypeToDataType((Xsc::Reflection::DataType)entry.baseType);
  449. if ((entry.flags & Xsc::Reflection::Uniform::Flags::Color) != 0 &&
  450. (type == GPDT_FLOAT3 || type == GPDT_FLOAT4))
  451. {
  452. type = GPDT_COLOR;
  453. }
  454. if (entry.defaultValue == -1)
  455. desc.addParameter(ident, ident, type);
  456. else
  457. {
  458. const Xsc::Reflection::DefaultValue& defVal = reflData.defaultValues[entry.defaultValue];
  459. desc.addParameter(ident, ident, type, StringID::NONE, 1, 0, (UINT8*)defVal.matrix);
  460. }
  461. }
  462. }
  463. break;
  464. case Xsc::Reflection::UniformType::Struct:
  465. break;
  466. default: ;
  467. }
  468. }
  469. }
  470. /** Types of supported code output when cross compiling HLSL to GLSL. */
  471. enum class CrossCompileOutput
  472. {
  473. GLSL45,
  474. GLSL41,
  475. VKSL45
  476. };
  477. String crossCompile(const String& hlsl, GpuProgramType type, CrossCompileOutput outputType, bool optionalEntry,
  478. UINT32& startBindingSlot, SHADER_DESC* shaderDesc = nullptr, Vector<GpuProgramType>* detectedTypes = nullptr)
  479. {
  480. SPtr<StringStream> input = bs_shared_ptr_new<StringStream>();
  481. bool isVulkan = outputType == CrossCompileOutput::VKSL45;
  482. if (isVulkan)
  483. *input << "#define VULKAN 1" << std::endl;
  484. else
  485. *input << "#define OPENGL 1" << std::endl;
  486. *input << hlsl;
  487. Xsc::ShaderInput inputDesc;
  488. inputDesc.shaderVersion = Xsc::InputShaderVersion::HLSL5;
  489. inputDesc.sourceCode = input;
  490. inputDesc.extensions = Xsc::Extensions::LayoutAttribute;
  491. switch (type)
  492. {
  493. case GPT_VERTEX_PROGRAM:
  494. inputDesc.shaderTarget = Xsc::ShaderTarget::VertexShader;
  495. inputDesc.entryPoint = "vsmain";
  496. break;
  497. case GPT_GEOMETRY_PROGRAM:
  498. inputDesc.shaderTarget = Xsc::ShaderTarget::GeometryShader;
  499. inputDesc.entryPoint = "gsmain";
  500. break;
  501. case GPT_HULL_PROGRAM:
  502. inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationControlShader;
  503. inputDesc.entryPoint = "hsmain";
  504. break;
  505. case GPT_DOMAIN_PROGRAM:
  506. inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationEvaluationShader;
  507. inputDesc.entryPoint = "dsmain";
  508. break;
  509. case GPT_FRAGMENT_PROGRAM:
  510. inputDesc.shaderTarget = Xsc::ShaderTarget::FragmentShader;
  511. inputDesc.entryPoint = "fsmain";
  512. break;
  513. case GPT_COMPUTE_PROGRAM:
  514. inputDesc.shaderTarget = Xsc::ShaderTarget::ComputeShader;
  515. inputDesc.entryPoint = "csmain";
  516. break;
  517. default:
  518. break;
  519. }
  520. StringStream output;
  521. Xsc::ShaderOutput outputDesc;
  522. outputDesc.sourceCode = &output;
  523. outputDesc.options.autoBinding = isVulkan;
  524. outputDesc.options.autoBindingStartSlot = startBindingSlot;
  525. outputDesc.options.separateShaders = true;
  526. outputDesc.options.separateSamplers = false;
  527. outputDesc.nameMangling.inputPrefix = "bs_";
  528. outputDesc.nameMangling.outputPrefix = "bs_";
  529. outputDesc.nameMangling.useAlwaysSemantics = true;
  530. outputDesc.nameMangling.renameBufferFields = true;
  531. switch(outputType)
  532. {
  533. case CrossCompileOutput::GLSL45:
  534. outputDesc.shaderVersion = Xsc::OutputShaderVersion::GLSL450;
  535. break;
  536. case CrossCompileOutput::GLSL41:
  537. outputDesc.shaderVersion = Xsc::OutputShaderVersion::GLSL410;
  538. break;
  539. case CrossCompileOutput::VKSL45:
  540. outputDesc.shaderVersion = Xsc::OutputShaderVersion::VKSL450;
  541. break;
  542. default: ;
  543. }
  544. XscLog log;
  545. Xsc::Reflection::ReflectionData reflectionData;
  546. bool compileSuccess = Xsc::CompileShader(inputDesc, outputDesc, &log, &reflectionData);
  547. if (!compileSuccess)
  548. {
  549. // If enabled, don't fail if entry point isn't found
  550. bool done = true;
  551. if(optionalEntry)
  552. {
  553. bool entryFound = false;
  554. for (auto& entry : reflectionData.functions)
  555. {
  556. if(entry.ident == inputDesc.entryPoint)
  557. {
  558. entryFound = true;
  559. break;
  560. }
  561. }
  562. if (!entryFound)
  563. done = false;
  564. }
  565. if (done)
  566. {
  567. StringStream logOutput;
  568. log.getMessages(logOutput);
  569. LOGERR("Shader cross compilation failed. Log: \n\n" + logOutput.str());
  570. return "";
  571. }
  572. }
  573. for (auto& entry : reflectionData.constantBuffers)
  574. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  575. for (auto& entry : reflectionData.textures)
  576. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  577. for (auto& entry : reflectionData.storageBuffers)
  578. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  579. if(detectedTypes != nullptr)
  580. {
  581. for(auto& entry : reflectionData.functions)
  582. {
  583. if (entry.ident == "vsmain")
  584. detectedTypes->push_back(GPT_VERTEX_PROGRAM);
  585. else if (entry.ident == "fsmain")
  586. detectedTypes->push_back(GPT_FRAGMENT_PROGRAM);
  587. else if (entry.ident == "gsmain")
  588. detectedTypes->push_back(GPT_GEOMETRY_PROGRAM);
  589. else if (entry.ident == "dsmain")
  590. detectedTypes->push_back(GPT_DOMAIN_PROGRAM);
  591. else if (entry.ident == "hsmain")
  592. detectedTypes->push_back(GPT_HULL_PROGRAM);
  593. else if (entry.ident == "csmain")
  594. detectedTypes->push_back(GPT_COMPUTE_PROGRAM);
  595. }
  596. // If no entry points found, and error occurred, report error
  597. if(!compileSuccess && detectedTypes->size() == 0)
  598. {
  599. StringStream logOutput;
  600. log.getMessages(logOutput);
  601. LOGERR("Shader cross compilation failed. Log: \n\n" + logOutput.str());
  602. return "";
  603. }
  604. }
  605. if (shaderDesc != nullptr)
  606. parseParameters(reflectionData, *shaderDesc);
  607. return output.str();
  608. }
  609. // Convert HLSL code to GLSL
  610. String HLSLtoGLSL(const String& hlsl, GpuProgramType type, CrossCompileOutput outputType, UINT32& startBindingSlot)
  611. {
  612. return crossCompile(hlsl, type, outputType, false, startBindingSlot);
  613. }
  614. void reflectHLSL(const String& hlsl, SHADER_DESC& shaderDesc, Vector<GpuProgramType>& entryPoints)
  615. {
  616. UINT32 dummy = 0;
  617. crossCompile(hlsl, GPT_VERTEX_PROGRAM, CrossCompileOutput::GLSL45, true, dummy, &shaderDesc, &entryPoints);
  618. }
  619. BSLFXCompileResult BSLFXCompiler::compile(const String& name, const String& source,
  620. const UnorderedMap<String, String>& defines)
  621. {
  622. String parsedSource = source;
  623. // Run the lexer/parser and generate the AST
  624. ParseState* parseState = parseStateCreate();
  625. BSLFXCompileResult output = parseFX(parseState, parsedSource.c_str(), defines);
  626. if(!output.errorMessage.empty())
  627. parseStateDelete(parseState);
  628. else
  629. {
  630. // Only enable for debug purposes
  631. //SLFXDebugPrint(parseState->rootNode, "");
  632. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  633. {
  634. parseStateDelete(parseState);
  635. output.errorMessage = "Root not is null or not a shader.";
  636. return output;
  637. }
  638. // Parse global shader options & technique meta-data
  639. SHADER_DESC shaderDesc;
  640. Vector<pair<ASTFXNode*, TechniqueMetaData>> techniqueMetaData;
  641. //// Go in reverse because options are added in reverse order during parsing
  642. for (int i = parseState->rootNode->options->count - 1; i >= 0; i--)
  643. {
  644. NodeOption* option = &parseState->rootNode->options->entries[i];
  645. switch (option->type)
  646. {
  647. case OT_Options:
  648. parseOptions(option->value.nodePtr, shaderDesc);
  649. break;
  650. case OT_Technique:
  651. {
  652. // We initially parse only meta-data, so we can handle out-of-order technique definitions
  653. TechniqueMetaData metaData = parseTechniqueMetaData(option->value.nodePtr);
  654. techniqueMetaData.push_back(std::make_pair(option->value.nodePtr, metaData));
  655. break;
  656. }
  657. default:
  658. break;
  659. }
  660. }
  661. // Inherit variations from mixins
  662. bool* techniqueWasParsed = bs_stack_alloc<bool>((UINT32)techniqueMetaData.size());
  663. std::function<bool(const TechniqueMetaData&, TechniqueMetaData&)> parseInherited =
  664. [&](const TechniqueMetaData& metaData, TechniqueMetaData& combinedMetaData)
  665. {
  666. for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter)
  667. {
  668. const String& includes = *riter;
  669. UINT32 baseIdx = -1;
  670. for (UINT32 i = 0; i < (UINT32)techniqueMetaData.size(); i++)
  671. {
  672. auto& entry = techniqueMetaData[i];
  673. if (!entry.second.isMixin)
  674. continue;
  675. if (entry.second.name == includes)
  676. {
  677. bool matches = entry.second.language == metaData.language || entry.second.language == "Any";
  678. // We want the last matching technique, in order to allow techniques to override each other
  679. if (matches)
  680. baseIdx = i;
  681. }
  682. }
  683. if (baseIdx != (UINT32)-1)
  684. {
  685. auto& entry = techniqueMetaData[baseIdx];
  686. // Was already parsed previously, don't parse it multiple times (happens when multiple techniques
  687. // include the same mixin)
  688. if (techniqueWasParsed[baseIdx])
  689. continue;
  690. if (!parseInherited(entry.second, combinedMetaData))
  691. return false;
  692. for(auto& variation : entry.second.variations)
  693. combinedMetaData.variations.push_back(variation);
  694. techniqueWasParsed[baseIdx] = true;
  695. }
  696. else
  697. {
  698. output.errorMessage = "Mixin \"" + includes + "\" cannot be found.";
  699. return false;
  700. }
  701. }
  702. return true;
  703. };
  704. for (auto& entry : techniqueMetaData)
  705. {
  706. TechniqueMetaData& metaData = entry.second;
  707. if (metaData.isMixin)
  708. continue;
  709. bs_zero_out(techniqueWasParsed, techniqueMetaData.size());
  710. TechniqueMetaData combinedMetaData = metaData;
  711. if (!parseInherited(metaData, combinedMetaData))
  712. {
  713. parseStateDelete(parseState);
  714. bs_stack_free(techniqueWasParsed);
  715. return output;
  716. }
  717. entry.second = combinedMetaData;
  718. }
  719. bs_stack_free(techniqueWasParsed);
  720. parseStateDelete(parseState);
  721. // Build a list of different variations and re-parse the source using the relevant defines
  722. Vector<SPtr<Technique>> techniques;
  723. UnorderedSet<String> includes;
  724. for (auto& entry : techniqueMetaData)
  725. {
  726. TechniqueMetaData& metaData = entry.second;
  727. if (metaData.isMixin)
  728. continue;
  729. // Generate a list of variations
  730. Vector<ShaderVariation> variations;
  731. if (metaData.variations.empty())
  732. variations.push_back(ShaderVariation());
  733. else
  734. {
  735. Vector<const VariationData*> todo;
  736. for (UINT32 i = 0; i < (UINT32)metaData.variations.size(); i++)
  737. todo.push_back(&metaData.variations[i]);
  738. while (!todo.empty())
  739. {
  740. const VariationData* current = todo.back();
  741. todo.erase(todo.end() - 1);
  742. // Variation parameter that's either defined or isn't
  743. if (current->values.empty())
  744. {
  745. // This is the first variation parameter, register new variations
  746. if (variations.empty())
  747. {
  748. ShaderVariation a;
  749. ShaderVariation b;
  750. b.addParam(ShaderVariation::Param(current->identifier, 1));
  751. variations.push_back(a);
  752. variations.push_back(b);
  753. }
  754. else // Duplicate existing variations, and add the parameter
  755. {
  756. UINT32 numVariations = (UINT32)variations.size();
  757. for (UINT32 i = 0; i < numVariations; i++)
  758. {
  759. // Make a copy
  760. variations.push_back(variations[i]);
  761. // Add the parameter to existing variation
  762. variations[i].addParam(ShaderVariation::Param(current->identifier, 1));
  763. }
  764. }
  765. }
  766. else // Variation parameter with multiple values
  767. {
  768. // This is the first variation parameter, register new variations
  769. if (variations.empty())
  770. {
  771. for (UINT32 i = 0; i < (UINT32)current->values.size(); i++)
  772. {
  773. ShaderVariation variation;
  774. variation.addParam(ShaderVariation::Param(current->identifier, current->values[i]));
  775. variations.push_back(variation);
  776. }
  777. }
  778. else // Duplicate existing variations, and add the parameter
  779. {
  780. UINT32 numVariations = (UINT32)variations.size();
  781. for (UINT32 i = 0; i < numVariations; i++)
  782. {
  783. for (UINT32 j = 1; j < (UINT32)current->values.size(); j++)
  784. {
  785. ShaderVariation copy = variations[i];
  786. copy.addParam(ShaderVariation::Param(current->identifier, current->values[j]));
  787. variations.push_back(copy);
  788. }
  789. variations[i].addParam(ShaderVariation::Param(current->identifier, current->values[0]));
  790. }
  791. }
  792. }
  793. }
  794. }
  795. // For every variation, re-parse the file with relevant defines
  796. for(auto& variation : variations)
  797. {
  798. UnorderedMap<String, String> globalDefines = defines;
  799. UnorderedMap<String, String> variationDefines = variation.getDefines().getAll();
  800. for(auto& define : variationDefines)
  801. globalDefines[define.first] = define.second;
  802. ParseState* variationParseState = parseStateCreate();
  803. output = parseFX(variationParseState, parsedSource.c_str(), globalDefines);
  804. if (!output.errorMessage.empty())
  805. parseStateDelete(variationParseState);
  806. else
  807. {
  808. Vector<String> codeBlocks;
  809. CodeString* codeString = variationParseState->codeStrings;
  810. while (codeString != nullptr)
  811. {
  812. while ((INT32)codeBlocks.size() <= codeString->index)
  813. codeBlocks.push_back(String());
  814. codeBlocks[codeString->index] = String(codeString->code, codeString->size);
  815. codeString = codeString->next;
  816. }
  817. output = parseTechnique(variationParseState, entry.second.name, codeBlocks, variation, techniques,
  818. includes, shaderDesc);
  819. if(!output.errorMessage.empty())
  820. return output;
  821. }
  822. }
  823. }
  824. // Generate a shader from the parsed techniques
  825. Vector<String> includeArray;
  826. for (auto& entry : includes)
  827. includeArray.push_back(entry);
  828. output.shader = Shader::_createPtr(name, shaderDesc, techniques);
  829. output.shader->setIncludeFiles(includeArray);
  830. // Verify GPU programs compile correctly
  831. StringStream gpuProgError;
  832. bool hasError = false;
  833. if (output.shader != nullptr)
  834. {
  835. Vector<SPtr<Technique>> techniques = output.shader->getCompatibleTechniques();
  836. for (auto& technique : techniques)
  837. {
  838. UINT32 numPasses = technique->getNumPasses();
  839. for (UINT32 i = 0; i < numPasses; i++)
  840. {
  841. SPtr<Pass> pass = technique->getPass(i);
  842. auto checkCompileStatus = [&](const String& prefix, const SPtr<GpuProgram>& prog)
  843. {
  844. if (prog != nullptr)
  845. {
  846. prog->blockUntilCoreInitialized();
  847. if (!prog->isCompiled())
  848. {
  849. hasError = true;
  850. gpuProgError << prefix << ": " << prog->getCompileErrorMessage() << std::endl;
  851. }
  852. }
  853. };
  854. checkCompileStatus("Vertex program", pass->getVertexProgram());
  855. checkCompileStatus("Fragment program", pass->getFragmentProgram());
  856. checkCompileStatus("Geometry program", pass->getGeometryProgram());
  857. checkCompileStatus("Hull program", pass->getHullProgram());
  858. checkCompileStatus("Domain program", pass->getDomainProgram());
  859. checkCompileStatus("Compute program", pass->getComputeProgram());
  860. }
  861. }
  862. }
  863. if (hasError)
  864. {
  865. output.errorMessage = "Failed compiling GPU program(s): " + gpuProgError.str();
  866. output.errorLine = 0;
  867. output.errorColumn = 0;
  868. }
  869. }
  870. return output;
  871. }
  872. BSLFXCompileResult BSLFXCompiler::parseFX(ParseState* parseState, const char* source, const UnorderedMap<String, String>& defines)
  873. {
  874. for(auto& define : defines)
  875. {
  876. if (define.first.size() == 0)
  877. continue;
  878. addDefine(parseState, define.first.c_str());
  879. if(define.second.size() > 0)
  880. addDefineExpr(parseState, define.second.c_str());
  881. }
  882. yyscan_t scanner;
  883. YY_BUFFER_STATE state;
  884. BSLFXCompileResult output;
  885. if (yylex_init_extra(parseState, &scanner))
  886. {
  887. output.errorMessage = "Internal error: Lexer failed to initialize.";
  888. return output;
  889. }
  890. // If debug output from lexer is needed uncomment this and add %debug option to lexer file
  891. //yyset_debug(true, scanner);
  892. // If debug output from parser is needed uncomment this and add %debug option to parser file
  893. //yydebug = true;
  894. state = yy_scan_string(source, scanner);
  895. if (yyparse(parseState, scanner))
  896. {
  897. if (parseState->hasError > 0)
  898. {
  899. output.errorMessage = parseState->errorMessage;
  900. output.errorLine = parseState->errorLine;
  901. output.errorColumn = parseState->errorColumn;
  902. if (parseState->errorFile != nullptr)
  903. output.errorFile = parseState->errorFile;
  904. }
  905. else
  906. output.errorMessage = "Internal error: Parsing failed.";
  907. return output;
  908. }
  909. yy_delete_buffer(state, scanner);
  910. yylex_destroy(scanner);
  911. return output;
  912. }
  913. BSLFXCompiler::TechniqueMetaData BSLFXCompiler::parseTechniqueMetaData(ASTFXNode* technique)
  914. {
  915. TechniqueMetaData metaData;
  916. metaData.language = "hlsl";
  917. metaData.isMixin = technique->type == NT_Mixin;
  918. for (int i = 0; i < technique->options->count; i++)
  919. {
  920. NodeOption* option = &technique->options->entries[i];
  921. switch (option->type)
  922. {
  923. case OT_Tags:
  924. {
  925. ASTFXNode* tagsNode = option->value.nodePtr;
  926. for (int j = 0; j < tagsNode->options->count; j++)
  927. {
  928. NodeOption* tagOption = &tagsNode->options->entries[j];
  929. if (tagOption->type == OT_TagValue)
  930. metaData.tags.push_back(removeQuotes(tagOption->value.strValue));
  931. }
  932. }
  933. break;
  934. case OT_Variations:
  935. {
  936. ASTFXNode* variationsNode = option->value.nodePtr;
  937. for (int j = 0; j < variationsNode->options->count; j++)
  938. {
  939. NodeOption* variationOption = &variationsNode->options->entries[j];
  940. if(variationOption->type == OT_Variation)
  941. parseVariations(metaData, variationOption->value.nodePtr);
  942. }
  943. }
  944. break;
  945. case OT_Identifier:
  946. metaData.name = option->value.strValue;
  947. break;
  948. case OT_Mixin:
  949. metaData.includes.push_back(option->value.strValue);
  950. break;
  951. default:
  952. break;
  953. }
  954. }
  955. return metaData;
  956. }
  957. void BSLFXCompiler::parseVariations(TechniqueMetaData& metaData, ASTFXNode* variations)
  958. {
  959. assert(variations->type == NT_Variation);
  960. VariationData variationData;
  961. for (int i = 0; i < variations->options->count; i++)
  962. {
  963. NodeOption* option = &variations->options->entries[i];
  964. switch (option->type)
  965. {
  966. case OT_Identifier:
  967. variationData.identifier = option->value.strValue;
  968. break;
  969. case OT_VariationValue:
  970. variationData.values.push_back(option->value.intValue);
  971. break;
  972. default:
  973. break;
  974. }
  975. }
  976. if (!variationData.identifier.empty())
  977. metaData.variations.push_back(variationData);
  978. }
  979. QueueSortType BSLFXCompiler::parseSortType(CullAndSortModeValue sortType)
  980. {
  981. switch (sortType)
  982. {
  983. case CASV_BackToFront:
  984. return QueueSortType::BackToFront;
  985. case CASV_FrontToBack:
  986. return QueueSortType::FrontToBack;
  987. case CASV_None:
  988. return QueueSortType::None;
  989. default:
  990. break;
  991. }
  992. return QueueSortType::None;
  993. }
  994. CompareFunction BSLFXCompiler::parseCompFunc(CompFuncValue compFunc)
  995. {
  996. switch (compFunc)
  997. {
  998. case CFV_Pass:
  999. return CMPF_ALWAYS_PASS;
  1000. case CFV_Fail:
  1001. return CMPF_ALWAYS_FAIL;
  1002. case CFV_LT:
  1003. return CMPF_LESS;
  1004. case CFV_LTE:
  1005. return CMPF_LESS_EQUAL;
  1006. case CFV_EQ:
  1007. return CMPF_EQUAL;
  1008. case CFV_NEQ:
  1009. return CMPF_NOT_EQUAL;
  1010. case CFV_GT:
  1011. return CMPF_GREATER;
  1012. case CFV_GTE:
  1013. return CMPF_GREATER_EQUAL;
  1014. }
  1015. return CMPF_ALWAYS_PASS;
  1016. }
  1017. BlendFactor BSLFXCompiler::parseBlendFactor(OpValue factor)
  1018. {
  1019. switch (factor)
  1020. {
  1021. case OV_One:
  1022. return BF_ONE;
  1023. case OV_Zero:
  1024. return BF_ZERO;
  1025. case OV_DestColor:
  1026. return BF_DEST_COLOR;
  1027. case OV_SrcColor:
  1028. return BF_SOURCE_COLOR;
  1029. case OV_InvDestColor:
  1030. return BF_INV_DEST_COLOR;
  1031. case OV_InvSrcColor:
  1032. return BF_INV_SOURCE_COLOR;
  1033. case OV_DestAlpha:
  1034. return BF_DEST_ALPHA;
  1035. case OV_SrcAlpha:
  1036. return BF_SOURCE_ALPHA;
  1037. case OV_InvDestAlpha:
  1038. return BF_INV_DEST_ALPHA;
  1039. case OV_InvSrcAlpha:
  1040. return BF_INV_SOURCE_ALPHA;
  1041. default:
  1042. break;
  1043. }
  1044. return BF_ONE;
  1045. }
  1046. BlendOperation BSLFXCompiler::parseBlendOp(BlendOpValue op)
  1047. {
  1048. switch (op)
  1049. {
  1050. case BOV_Add:
  1051. return BO_ADD;
  1052. case BOV_Max:
  1053. return BO_MAX;
  1054. case BOV_Min:
  1055. return BO_MIN;
  1056. case BOV_Subtract:
  1057. return BO_SUBTRACT;
  1058. case BOV_RevSubtract:
  1059. return BO_REVERSE_SUBTRACT;
  1060. }
  1061. return BO_ADD;
  1062. }
  1063. StencilOperation BSLFXCompiler::parseStencilOp(OpValue op)
  1064. {
  1065. switch (op)
  1066. {
  1067. case OV_Keep:
  1068. return SOP_KEEP;
  1069. case OV_Zero:
  1070. return SOP_ZERO;
  1071. case OV_Replace:
  1072. return SOP_REPLACE;
  1073. case OV_Incr:
  1074. return SOP_INCREMENT;
  1075. case OV_Decr:
  1076. return SOP_DECREMENT;
  1077. case OV_IncrWrap:
  1078. return SOP_INCREMENT_WRAP;
  1079. case OV_DecrWrap:
  1080. return SOP_DECREMENT_WRAP;
  1081. case OV_Invert:
  1082. return SOP_INVERT;
  1083. default:
  1084. break;
  1085. }
  1086. return SOP_KEEP;
  1087. }
  1088. CullingMode BSLFXCompiler::parseCullMode(CullAndSortModeValue cm)
  1089. {
  1090. switch (cm)
  1091. {
  1092. case CASV_None:
  1093. return CULL_NONE;
  1094. case CASV_CW:
  1095. return CULL_CLOCKWISE;
  1096. case CASV_CCW:
  1097. return CULL_COUNTERCLOCKWISE;
  1098. default:
  1099. break;
  1100. }
  1101. return CULL_COUNTERCLOCKWISE;
  1102. }
  1103. PolygonMode BSLFXCompiler::parseFillMode(FillModeValue fm)
  1104. {
  1105. if (fm == FMV_Wire)
  1106. return PM_WIREFRAME;
  1107. return PM_SOLID;
  1108. }
  1109. void BSLFXCompiler::parseStencilFront(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  1110. {
  1111. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  1112. return;
  1113. for (int i = 0; i < stencilOpNode->options->count; i++)
  1114. {
  1115. NodeOption* option = &stencilOpNode->options->entries[i];
  1116. switch (option->type)
  1117. {
  1118. case OT_Fail:
  1119. desc.frontStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  1120. break;
  1121. case OT_ZFail:
  1122. desc.frontStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  1123. break;
  1124. case OT_PassOp:
  1125. desc.frontStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  1126. break;
  1127. case OT_CompareFunc:
  1128. desc.frontStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1129. break;
  1130. default:
  1131. break;
  1132. }
  1133. }
  1134. }
  1135. void BSLFXCompiler::parseStencilBack(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  1136. {
  1137. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  1138. return;
  1139. for (int i = 0; i < stencilOpNode->options->count; i++)
  1140. {
  1141. NodeOption* option = &stencilOpNode->options->entries[i];
  1142. switch (option->type)
  1143. {
  1144. case OT_Fail:
  1145. desc.backStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  1146. break;
  1147. case OT_ZFail:
  1148. desc.backStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  1149. break;
  1150. case OT_PassOp:
  1151. desc.backStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  1152. break;
  1153. case OT_CompareFunc:
  1154. desc.backStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1155. break;
  1156. default:
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. void BSLFXCompiler::parseColorBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  1162. {
  1163. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  1164. return;
  1165. for (int i = 0; i < blendDefNode->options->count; i++)
  1166. {
  1167. NodeOption* option = &blendDefNode->options->entries[i];
  1168. switch (option->type)
  1169. {
  1170. case OT_Source:
  1171. desc.srcBlend = parseBlendFactor((OpValue)option->value.intValue);
  1172. break;
  1173. case OT_Dest:
  1174. desc.dstBlend = parseBlendFactor((OpValue)option->value.intValue);
  1175. break;
  1176. case OT_Op:
  1177. desc.blendOp = parseBlendOp((BlendOpValue)option->value.intValue);
  1178. break;
  1179. default:
  1180. break;
  1181. }
  1182. }
  1183. }
  1184. void BSLFXCompiler::parseAlphaBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  1185. {
  1186. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  1187. return;
  1188. for (int i = 0; i < blendDefNode->options->count; i++)
  1189. {
  1190. NodeOption* option = &blendDefNode->options->entries[i];
  1191. switch (option->type)
  1192. {
  1193. case OT_Source:
  1194. desc.srcBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  1195. break;
  1196. case OT_Dest:
  1197. desc.dstBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  1198. break;
  1199. case OT_Op:
  1200. desc.blendOpAlpha = parseBlendOp((BlendOpValue)option->value.intValue);
  1201. break;
  1202. default:
  1203. break;
  1204. }
  1205. }
  1206. }
  1207. void BSLFXCompiler::parseRenderTargetBlendState(BLEND_STATE_DESC& desc, ASTFXNode* targetNode)
  1208. {
  1209. if (targetNode == nullptr || targetNode->type != NT_Target)
  1210. return;
  1211. UINT32 index = 0;
  1212. for (int i = 0; i < targetNode->options->count; i++)
  1213. {
  1214. NodeOption* option = &targetNode->options->entries[i];
  1215. switch (option->type)
  1216. {
  1217. case OT_Index:
  1218. index = option->value.intValue;
  1219. break;
  1220. default:
  1221. break;
  1222. }
  1223. }
  1224. if (index >= BS_MAX_MULTIPLE_RENDER_TARGETS)
  1225. return;
  1226. RENDER_TARGET_BLEND_STATE_DESC& rtDesc = desc.renderTargetDesc[index];
  1227. for (int i = 0; i < targetNode->options->count; i++)
  1228. {
  1229. NodeOption* option = &targetNode->options->entries[i];
  1230. switch (option->type)
  1231. {
  1232. case OT_Enabled:
  1233. rtDesc.blendEnable = option->value.intValue > 0;
  1234. break;
  1235. case OT_Color:
  1236. parseColorBlendDef(rtDesc, option->value.nodePtr);
  1237. break;
  1238. case OT_Alpha:
  1239. parseAlphaBlendDef(rtDesc, option->value.nodePtr);
  1240. break;
  1241. case OT_WriteMask:
  1242. rtDesc.renderTargetWriteMask = option->value.intValue;
  1243. break;
  1244. default:
  1245. break;
  1246. }
  1247. }
  1248. }
  1249. bool BSLFXCompiler::parseBlendState(PassData& desc, ASTFXNode* blendNode)
  1250. {
  1251. if (blendNode == nullptr || blendNode->type != NT_Blend)
  1252. return false;
  1253. bool isDefault = true;
  1254. for (int i = 0; i < blendNode->options->count; i++)
  1255. {
  1256. NodeOption* option = &blendNode->options->entries[i];
  1257. switch (option->type)
  1258. {
  1259. case OT_AlphaToCoverage:
  1260. desc.blendDesc.alphaToCoverageEnable = option->value.intValue > 0;
  1261. isDefault = false;
  1262. break;
  1263. case OT_IndependantBlend:
  1264. desc.blendDesc.independantBlendEnable = option->value.intValue > 0;
  1265. isDefault = false;
  1266. break;
  1267. case OT_Target:
  1268. parseRenderTargetBlendState(desc.blendDesc, option->value.nodePtr);
  1269. isDefault = false;
  1270. break;
  1271. default:
  1272. break;
  1273. }
  1274. }
  1275. return !isDefault;
  1276. }
  1277. bool BSLFXCompiler::parseRasterizerState(PassData& desc, ASTFXNode* rasterNode)
  1278. {
  1279. if (rasterNode == nullptr || rasterNode->type != NT_Raster)
  1280. return false;
  1281. bool isDefault = true;
  1282. for (int i = 0; i < rasterNode->options->count; i++)
  1283. {
  1284. NodeOption* option = &rasterNode->options->entries[i];
  1285. switch (option->type)
  1286. {
  1287. case OT_FillMode:
  1288. desc.rasterizerDesc.polygonMode = parseFillMode((FillModeValue)option->value.intValue);
  1289. isDefault = false;
  1290. break;
  1291. case OT_CullMode:
  1292. desc.rasterizerDesc.cullMode = parseCullMode((CullAndSortModeValue)option->value.intValue);
  1293. isDefault = false;
  1294. break;
  1295. case OT_DepthBias:
  1296. desc.rasterizerDesc.depthBias = option->value.floatValue;
  1297. isDefault = false;
  1298. break;
  1299. case OT_SDepthBias:
  1300. desc.rasterizerDesc.slopeScaledDepthBias = option->value.floatValue;
  1301. isDefault = false;
  1302. break;
  1303. case OT_DepthClip:
  1304. desc.rasterizerDesc.depthClipEnable = option->value.intValue > 0;
  1305. isDefault = false;
  1306. break;
  1307. case OT_Scissor:
  1308. desc.rasterizerDesc.scissorEnable = option->value.intValue > 0;
  1309. isDefault = false;
  1310. break;
  1311. case OT_Multisample:
  1312. desc.rasterizerDesc.multisampleEnable = option->value.intValue > 0;
  1313. isDefault = false;
  1314. break;
  1315. case OT_AALine:
  1316. desc.rasterizerDesc.antialiasedLineEnable = option->value.intValue > 0;
  1317. isDefault = false;
  1318. break;
  1319. default:
  1320. break;
  1321. }
  1322. }
  1323. return !isDefault;
  1324. }
  1325. bool BSLFXCompiler::parseDepthState(PassData& passData, ASTFXNode* depthNode)
  1326. {
  1327. if (depthNode == nullptr || depthNode->type != NT_Depth)
  1328. return false;
  1329. bool isDefault = true;
  1330. for (int i = 0; i < depthNode->options->count; i++)
  1331. {
  1332. NodeOption* option = &depthNode->options->entries[i];
  1333. switch (option->type)
  1334. {
  1335. case OT_DepthRead:
  1336. passData.depthStencilDesc.depthReadEnable = option->value.intValue > 0;
  1337. isDefault = false;
  1338. break;
  1339. case OT_DepthWrite:
  1340. passData.depthStencilDesc.depthWriteEnable = option->value.intValue > 0;
  1341. isDefault = false;
  1342. break;
  1343. case OT_CompareFunc:
  1344. passData.depthStencilDesc.depthComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1345. isDefault = false;
  1346. break;
  1347. default:
  1348. break;
  1349. }
  1350. }
  1351. return !isDefault;
  1352. }
  1353. bool BSLFXCompiler::parseStencilState(PassData& passData, ASTFXNode* stencilNode)
  1354. {
  1355. if (stencilNode == nullptr || stencilNode->type != NT_Stencil)
  1356. return false;
  1357. bool isDefault = true;
  1358. for (int i = 0; i < stencilNode->options->count; i++)
  1359. {
  1360. NodeOption* option = &stencilNode->options->entries[i];
  1361. switch (option->type)
  1362. {
  1363. case OT_Enabled:
  1364. passData.depthStencilDesc.stencilEnable = option->value.intValue > 0;
  1365. isDefault = false;
  1366. break;
  1367. case OT_StencilReadMask:
  1368. passData.depthStencilDesc.stencilReadMask = (UINT8)option->value.intValue;
  1369. isDefault = false;
  1370. break;
  1371. case OT_StencilWriteMask:
  1372. passData.depthStencilDesc.stencilWriteMask = (UINT8)option->value.intValue;
  1373. isDefault = false;
  1374. break;
  1375. case OT_StencilOpFront:
  1376. parseStencilFront(passData.depthStencilDesc, option->value.nodePtr);
  1377. isDefault = false;
  1378. break;
  1379. case OT_StencilOpBack:
  1380. parseStencilBack(passData.depthStencilDesc, option->value.nodePtr);
  1381. isDefault = false;
  1382. break;
  1383. case OT_StencilRef:
  1384. passData.stencilRefValue = option->value.intValue;
  1385. break;
  1386. default:
  1387. break;
  1388. }
  1389. }
  1390. return !isDefault;
  1391. }
  1392. void BSLFXCompiler::parseCodeBlock(ASTFXNode* codeNode, const Vector<String>& codeBlocks, PassData& passData)
  1393. {
  1394. if (codeNode == nullptr || (codeNode->type != NT_Code))
  1395. {
  1396. return;
  1397. }
  1398. UINT32 index = (UINT32)-1;
  1399. for (int j = 0; j < codeNode->options->count; j++)
  1400. {
  1401. if (codeNode->options->entries[j].type == OT_Index)
  1402. index = codeNode->options->entries[j].value.intValue;
  1403. }
  1404. if (index != (UINT32)-1 && index < (UINT32)codeBlocks.size())
  1405. {
  1406. switch (codeNode->type)
  1407. {
  1408. case NT_Code:
  1409. passData.code += codeBlocks[index];
  1410. break;
  1411. default:
  1412. break;
  1413. }
  1414. }
  1415. }
  1416. void BSLFXCompiler::parsePass(ASTFXNode* passNode, const Vector<String>& codeBlocks, PassData& passData)
  1417. {
  1418. if (passNode == nullptr || passNode->type != NT_Pass)
  1419. return;
  1420. for (int i = 0; i < passNode->options->count; i++)
  1421. {
  1422. NodeOption* option = &passNode->options->entries[i];
  1423. switch (option->type)
  1424. {
  1425. case OT_Blend:
  1426. passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr);
  1427. break;
  1428. case OT_Raster:
  1429. passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr);
  1430. break;
  1431. case OT_Depth:
  1432. passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr);
  1433. break;
  1434. case OT_Stencil:
  1435. passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr);
  1436. break;
  1437. case OT_Code:
  1438. parseCodeBlock(option->value.nodePtr, codeBlocks, passData);
  1439. break;
  1440. default:
  1441. break;
  1442. }
  1443. }
  1444. }
  1445. void BSLFXCompiler::parseTechnique(ASTFXNode* techniqueNode, const Vector<String>& codeBlocks, TechniqueData& techniqueData)
  1446. {
  1447. if (techniqueNode == nullptr || (techniqueNode->type != NT_Technique && techniqueNode->type != NT_Mixin))
  1448. return;
  1449. // There must always be at least one pass
  1450. if(techniqueData.passes.empty())
  1451. {
  1452. techniqueData.passes.push_back(PassData());
  1453. techniqueData.passes.back().seqIdx = 0;
  1454. }
  1455. PassData combinedCommonPassData;
  1456. UINT32 nextPassIdx = 0;
  1457. // Go in reverse because options are added in reverse order during parsing
  1458. for (int i = techniqueNode->options->count - 1; i >= 0; i--)
  1459. {
  1460. NodeOption* option = &techniqueNode->options->entries[i];
  1461. switch (option->type)
  1462. {
  1463. case OT_Pass:
  1464. {
  1465. UINT32 passIdx = nextPassIdx;
  1466. PassData* passData = nullptr;
  1467. for (auto& entry : techniqueData.passes)
  1468. {
  1469. if (entry.seqIdx == passIdx)
  1470. passData = &entry;
  1471. }
  1472. if (passData == nullptr)
  1473. {
  1474. techniqueData.passes.push_back(PassData());
  1475. passData = &techniqueData.passes.back();
  1476. passData->seqIdx = passIdx;
  1477. }
  1478. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  1479. passData->code = combinedCommonPassData.code + passData->code;
  1480. ASTFXNode* passNode = option->value.nodePtr;
  1481. parsePass(passNode, codeBlocks, *passData);
  1482. }
  1483. break;
  1484. case OT_Code:
  1485. {
  1486. PassData commonPassData;
  1487. parseCodeBlock(option->value.nodePtr, codeBlocks, commonPassData);
  1488. for (auto& passData : techniqueData.passes)
  1489. passData.code += commonPassData.code;
  1490. combinedCommonPassData.code += commonPassData.code;
  1491. }
  1492. break;
  1493. case OT_FeatureSet:
  1494. techniqueData.metaData.featureSet = option->value.strValue;
  1495. break;
  1496. default:
  1497. break;
  1498. }
  1499. }
  1500. // Parse common pass states
  1501. for (int i = 0; i < techniqueNode->options->count; i++)
  1502. {
  1503. NodeOption* option = &techniqueNode->options->entries[i];
  1504. switch (option->type)
  1505. {
  1506. case OT_Blend:
  1507. for (auto& passData : techniqueData.passes)
  1508. passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr);
  1509. break;
  1510. case OT_Raster:
  1511. for (auto& passData : techniqueData.passes)
  1512. passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr);
  1513. break;
  1514. case OT_Depth:
  1515. for (auto& passData : techniqueData.passes)
  1516. passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr);
  1517. break;
  1518. case OT_Stencil:
  1519. for (auto& passData : techniqueData.passes)
  1520. passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr);
  1521. break;
  1522. default:
  1523. break;
  1524. }
  1525. }
  1526. }
  1527. void BSLFXCompiler::parseOptions(ASTFXNode* optionsNode, SHADER_DESC& shaderDesc)
  1528. {
  1529. if (optionsNode == nullptr || optionsNode->type != NT_Options)
  1530. return;
  1531. for (int i = optionsNode->options->count - 1; i >= 0; i--)
  1532. {
  1533. NodeOption* option = &optionsNode->options->entries[i];
  1534. switch (option->type)
  1535. {
  1536. case OT_Separable:
  1537. shaderDesc.separablePasses = option->value.intValue > 1;
  1538. break;
  1539. case OT_Sort:
  1540. shaderDesc.queueSortType = parseSortType((CullAndSortModeValue)option->value.intValue);
  1541. break;
  1542. case OT_Priority:
  1543. shaderDesc.queuePriority = option->value.intValue;
  1544. break;
  1545. case OT_Transparent:
  1546. shaderDesc.flags |= (UINT32)ShaderFlags::Transparent;
  1547. break;
  1548. default:
  1549. break;
  1550. }
  1551. }
  1552. }
  1553. BSLFXCompileResult BSLFXCompiler::parseTechnique(ParseState* parseState, const String& name,
  1554. const Vector<String>& codeBlocks, const ShaderVariation& variation, Vector<SPtr<Technique>>& techniques,
  1555. UnorderedSet<String>& includes, SHADER_DESC& shaderDesc)
  1556. {
  1557. BSLFXCompileResult output;
  1558. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  1559. {
  1560. parseStateDelete(parseState);
  1561. output.errorMessage = "Root not is null or not a shader.";
  1562. return output;
  1563. }
  1564. Vector<pair<ASTFXNode*, TechniqueData>> techniqueData;
  1565. // Go in reverse because options are added in reverse order during parsing
  1566. for (int i = parseState->rootNode->options->count - 1; i >= 0; i--)
  1567. {
  1568. NodeOption* option = &parseState->rootNode->options->entries[i];
  1569. switch (option->type)
  1570. {
  1571. case OT_Technique:
  1572. {
  1573. // We initially parse only meta-data, so we can handle out-of-order technique definitions
  1574. TechniqueMetaData metaData = parseTechniqueMetaData(option->value.nodePtr);
  1575. // Skip all techniques except the one we're parsing
  1576. if(metaData.name != name && !metaData.isMixin)
  1577. continue;
  1578. techniqueData.push_back(std::make_pair(option->value.nodePtr, TechniqueData()));
  1579. TechniqueData& data = techniqueData.back().second;
  1580. data.metaData = metaData;
  1581. break;
  1582. }
  1583. default:
  1584. break;
  1585. }
  1586. }
  1587. bool* techniqueWasParsed = bs_stack_alloc<bool>((UINT32)techniqueData.size());
  1588. std::function<bool(const TechniqueMetaData&, TechniqueData&)> parseInherited =
  1589. [&](const TechniqueMetaData& metaData, TechniqueData& outTechnique)
  1590. {
  1591. for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter)
  1592. {
  1593. const String& includes = *riter;
  1594. UINT32 baseIdx = -1;
  1595. for(UINT32 i = 0; i < (UINT32)techniqueData.size(); i++)
  1596. {
  1597. auto& entry = techniqueData[i];
  1598. if (!entry.second.metaData.isMixin)
  1599. continue;
  1600. if (entry.second.metaData.name == includes)
  1601. {
  1602. bool matches =
  1603. (entry.second.metaData.language == metaData.language ||
  1604. entry.second.metaData.language == "Any");
  1605. // We want the last matching technique, in order to allow techniques to override each other
  1606. if (matches)
  1607. baseIdx = i;
  1608. }
  1609. }
  1610. if (baseIdx != (UINT32)-1)
  1611. {
  1612. auto& entry = techniqueData[baseIdx];
  1613. // Was already parsed previously, don't parse it multiple times (happens when multiple techniques
  1614. // include the same mixin)
  1615. if (techniqueWasParsed[baseIdx])
  1616. continue;
  1617. if (!parseInherited(entry.second.metaData, outTechnique))
  1618. return false;
  1619. parseTechnique(entry.first, codeBlocks, outTechnique);
  1620. techniqueWasParsed[baseIdx] = true;
  1621. }
  1622. else
  1623. {
  1624. output.errorMessage = "Mixin \"" + includes + "\" cannot be found.";
  1625. return false;
  1626. }
  1627. }
  1628. return true;
  1629. };
  1630. // Actually parse techniques
  1631. for (auto& entry : techniqueData)
  1632. {
  1633. const TechniqueMetaData& metaData = entry.second.metaData;
  1634. if (metaData.isMixin)
  1635. continue;
  1636. bs_zero_out(techniqueWasParsed, techniqueData.size());
  1637. if (!parseInherited(metaData, entry.second))
  1638. {
  1639. parseStateDelete(parseState);
  1640. bs_stack_free(techniqueWasParsed);
  1641. return output;
  1642. }
  1643. parseTechnique(entry.first, codeBlocks, entry.second);
  1644. }
  1645. bs_stack_free(techniqueWasParsed);
  1646. IncludeLink* includeLink = parseState->includes;
  1647. while(includeLink != nullptr)
  1648. {
  1649. String includeFilename = includeLink->data->filename;
  1650. auto iterFind = std::find(includes.begin(), includes.end(), includeFilename);
  1651. if (iterFind == includes.end())
  1652. includes.insert(includeFilename);
  1653. includeLink = includeLink->next;
  1654. }
  1655. parseStateDelete(parseState);
  1656. // Parse extended HLSL code and generate per-program code, also convert to GLSL/VKSL
  1657. UINT32 end = (UINT32)techniqueData.size();
  1658. for(UINT32 i = 0; i < end; i++)
  1659. {
  1660. const TechniqueMetaData& metaData = techniqueData[i].second.metaData;
  1661. if (metaData.isMixin)
  1662. continue;
  1663. TechniqueData& hlslTechnique = techniqueData[i].second;
  1664. TechniqueData glslTechnique = techniqueData[i].second;
  1665. // When working with OpenGL, lower-end feature sets are supported. For other backends, high-end is always assumed.
  1666. CrossCompileOutput glslVersion = CrossCompileOutput::GLSL41;
  1667. if(glslTechnique.metaData.featureSet == "HighEnd")
  1668. {
  1669. glslTechnique.metaData.language = "glsl";
  1670. glslVersion = CrossCompileOutput::GLSL45;
  1671. }
  1672. else
  1673. glslTechnique.metaData.language = "glsl4_1";
  1674. TechniqueData vkslTechnique = techniqueData[i].second;
  1675. vkslTechnique.metaData.language = "vksl";
  1676. UINT32 numPasses = (UINT32)hlslTechnique.passes.size();
  1677. for(UINT32 j = 0; j < numPasses; j++)
  1678. {
  1679. PassData& hlslPassData = hlslTechnique.passes[j];
  1680. PassData& glslPassData = glslTechnique.passes[j];
  1681. PassData& vkslPassData = vkslTechnique.passes[j];
  1682. // Clean non-standard HLSL
  1683. static const std::regex regex("\\[\\s*layout\\s*\\(.*\\)\\s*\\]|\\[\\s*internal\\s*\\]|\\[\\s*color\\s*\\]|\\[\\s*alias\\s*\\(.*\\)\\s*\\]");
  1684. hlslPassData.code = regex_replace(hlslPassData.code, regex, "");
  1685. // Find valid entry points and parameters
  1686. // Note: XShaderCompiler needs to do a full pass when doing reflection, and for each individual program
  1687. // type. If performance is ever important here it could be good to update XShaderCompiler so it can
  1688. // somehow save the AST and then re-use it for multiple actions.
  1689. Vector<GpuProgramType> types;
  1690. reflectHLSL(glslPassData.code, shaderDesc, types);
  1691. UINT32 glslBinding = 0;
  1692. UINT32 vkslBinding = 0;
  1693. // Cross-compile for all detected shader types
  1694. // Note: I'm just copying HLSL code as-is. This code will contain all entry points which could have
  1695. // an effect on compile time. It would be ideal to remove dead code depending on program type. This would
  1696. // involve adding a HLSL code generator to XShaderCompiler.
  1697. for(auto& type : types)
  1698. {
  1699. switch(type)
  1700. {
  1701. case GPT_VERTEX_PROGRAM:
  1702. hlslPassData.vertexCode = hlslPassData.code;
  1703. glslPassData.vertexCode = HLSLtoGLSL(glslPassData.code, GPT_VERTEX_PROGRAM,
  1704. glslVersion, glslBinding);
  1705. vkslPassData.vertexCode = HLSLtoGLSL(glslPassData.code, GPT_VERTEX_PROGRAM,
  1706. CrossCompileOutput::VKSL45, vkslBinding);
  1707. break;
  1708. case GPT_FRAGMENT_PROGRAM:
  1709. hlslPassData.fragmentCode = hlslPassData.code;
  1710. glslPassData.fragmentCode = HLSLtoGLSL(glslPassData.code, GPT_FRAGMENT_PROGRAM,
  1711. glslVersion, glslBinding);
  1712. vkslPassData.fragmentCode = HLSLtoGLSL(glslPassData.code, GPT_FRAGMENT_PROGRAM,
  1713. CrossCompileOutput::VKSL45, vkslBinding);
  1714. break;
  1715. case GPT_GEOMETRY_PROGRAM:
  1716. hlslPassData.geometryCode = hlslPassData.code;
  1717. glslPassData.geometryCode = HLSLtoGLSL(glslPassData.code, GPT_GEOMETRY_PROGRAM,
  1718. glslVersion, glslBinding);
  1719. vkslPassData.geometryCode = HLSLtoGLSL(glslPassData.code, GPT_GEOMETRY_PROGRAM,
  1720. CrossCompileOutput::VKSL45, vkslBinding);
  1721. break;
  1722. case GPT_HULL_PROGRAM:
  1723. hlslPassData.hullCode = hlslPassData.code;
  1724. glslPassData.hullCode = HLSLtoGLSL(glslPassData.code, GPT_HULL_PROGRAM,
  1725. glslVersion, glslBinding);
  1726. vkslPassData.hullCode = HLSLtoGLSL(glslPassData.code, GPT_HULL_PROGRAM,
  1727. CrossCompileOutput::VKSL45, vkslBinding);
  1728. break;
  1729. case GPT_DOMAIN_PROGRAM:
  1730. hlslPassData.domainCode = hlslPassData.code;
  1731. glslPassData.domainCode = HLSLtoGLSL(glslPassData.code, GPT_DOMAIN_PROGRAM,
  1732. glslVersion, glslBinding);
  1733. vkslPassData.domainCode = HLSLtoGLSL(glslPassData.code, GPT_DOMAIN_PROGRAM,
  1734. CrossCompileOutput::VKSL45, vkslBinding);
  1735. break;
  1736. case GPT_COMPUTE_PROGRAM:
  1737. hlslPassData.computeCode = hlslPassData.code;
  1738. glslPassData.computeCode = HLSLtoGLSL(glslPassData.code, GPT_COMPUTE_PROGRAM,
  1739. glslVersion, glslBinding);
  1740. vkslPassData.computeCode = HLSLtoGLSL(glslPassData.code, GPT_COMPUTE_PROGRAM,
  1741. CrossCompileOutput::VKSL45, vkslBinding);
  1742. break;
  1743. default:
  1744. break;
  1745. }
  1746. }
  1747. }
  1748. techniqueData.push_back(std::make_pair(nullptr, glslTechnique));
  1749. techniqueData.push_back(std::make_pair(nullptr, vkslTechnique));
  1750. }
  1751. for(auto& entry : techniqueData)
  1752. {
  1753. const TechniqueMetaData& metaData = entry.second.metaData;
  1754. if (metaData.isMixin)
  1755. continue;
  1756. Map<UINT32, SPtr<Pass>, std::greater<UINT32>> passes;
  1757. for (auto& passData : entry.second.passes)
  1758. {
  1759. PASS_DESC passDesc;
  1760. if (!passData.blendIsDefault)
  1761. passDesc.blendState = BlendState::create(passData.blendDesc);
  1762. if (!passData.rasterizerIsDefault)
  1763. passDesc.rasterizerState = RasterizerState::create(passData.rasterizerDesc);
  1764. if (!passData.depthStencilIsDefault)
  1765. passDesc.depthStencilState = DepthStencilState::create(passData.depthStencilDesc);
  1766. auto createProgram =
  1767. [](const String& language, const String& entry, const String& code, GpuProgramType type) -> SPtr<GpuProgram>
  1768. {
  1769. if (code.empty())
  1770. return nullptr;
  1771. GPU_PROGRAM_DESC desc;
  1772. desc.language = language;
  1773. desc.entryPoint = entry;
  1774. desc.source = code;
  1775. desc.type = type;
  1776. return GpuProgram::create(desc);
  1777. };
  1778. bool isHLSL = metaData.language == "hlsl";
  1779. passDesc.vertexProgram = createProgram(
  1780. metaData.language,
  1781. isHLSL ? "vsmain" : "main",
  1782. passData.vertexCode,
  1783. GPT_VERTEX_PROGRAM);
  1784. passDesc.fragmentProgram = createProgram(
  1785. metaData.language,
  1786. isHLSL ? "fsmain" : "main",
  1787. passData.fragmentCode,
  1788. GPT_FRAGMENT_PROGRAM);
  1789. passDesc.geometryProgram = createProgram(
  1790. metaData.language,
  1791. isHLSL ? "gsmain" : "main",
  1792. passData.geometryCode,
  1793. GPT_GEOMETRY_PROGRAM);
  1794. passDesc.hullProgram = createProgram(
  1795. metaData.language,
  1796. isHLSL ? "hsmain" : "main",
  1797. passData.hullCode,
  1798. GPT_HULL_PROGRAM);
  1799. passDesc.domainProgram = createProgram(
  1800. metaData.language,
  1801. isHLSL ? "dsmain" : "main",
  1802. passData.domainCode,
  1803. GPT_DOMAIN_PROGRAM);
  1804. passDesc.computeProgram = createProgram(
  1805. metaData.language,
  1806. isHLSL ? "csmain" : "main",
  1807. passData.computeCode,
  1808. GPT_COMPUTE_PROGRAM);
  1809. passDesc.stencilRefValue = passData.stencilRefValue;
  1810. SPtr<Pass> pass = Pass::create(passDesc);
  1811. if (pass != nullptr)
  1812. passes[passData.seqIdx] = pass;
  1813. }
  1814. Vector<SPtr<Pass>> orderedPasses;
  1815. for (auto& KVP : passes)
  1816. orderedPasses.push_back(KVP.second);
  1817. if (orderedPasses.size() > 0)
  1818. {
  1819. SPtr<Technique> technique = Technique::create(metaData.language, metaData.tags, variation, orderedPasses);
  1820. techniques.push_back(technique);
  1821. }
  1822. }
  1823. return output;
  1824. }
  1825. String BSLFXCompiler::removeQuotes(const char* input)
  1826. {
  1827. UINT32 len = (UINT32)strlen(input);
  1828. String output(len - 2, ' ');
  1829. for (UINT32 i = 0; i < (len - 2); i++)
  1830. output[i] = input[i + 1];
  1831. return output;
  1832. }
  1833. }