BsSLFXCompiler.cpp 50 KB

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