BsSLFXCompiler.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099
  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: break;
  465. default: ;
  466. }
  467. }
  468. }
  469. String crossCompile(const String& hlsl, GpuProgramType type, bool vulkan, bool optionalEntry, UINT32& startBindingSlot,
  470. SHADER_DESC* shaderDesc = nullptr, Vector<GpuProgramType>* detectedTypes = nullptr)
  471. {
  472. SPtr<StringStream> input = bs_shared_ptr_new<StringStream>();
  473. if (vulkan)
  474. *input << "#define VULKAN 1" << std::endl;
  475. else
  476. *input << "#define OPENGL 1" << std::endl;
  477. *input << hlsl;
  478. Xsc::ShaderInput inputDesc;
  479. inputDesc.shaderVersion = Xsc::InputShaderVersion::HLSL5;
  480. inputDesc.sourceCode = input;
  481. inputDesc.extensions = Xsc::Extensions::LayoutAttribute;
  482. switch (type)
  483. {
  484. case GPT_VERTEX_PROGRAM:
  485. inputDesc.shaderTarget = Xsc::ShaderTarget::VertexShader;
  486. inputDesc.entryPoint = "vsmain";
  487. break;
  488. case GPT_GEOMETRY_PROGRAM:
  489. inputDesc.shaderTarget = Xsc::ShaderTarget::GeometryShader;
  490. inputDesc.entryPoint = "gsmain";
  491. break;
  492. case GPT_HULL_PROGRAM:
  493. inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationControlShader;
  494. inputDesc.entryPoint = "hsmain";
  495. break;
  496. case GPT_DOMAIN_PROGRAM:
  497. inputDesc.shaderTarget = Xsc::ShaderTarget::TessellationEvaluationShader;
  498. inputDesc.entryPoint = "dsmain";
  499. break;
  500. case GPT_FRAGMENT_PROGRAM:
  501. inputDesc.shaderTarget = Xsc::ShaderTarget::FragmentShader;
  502. inputDesc.entryPoint = "fsmain";
  503. break;
  504. case GPT_COMPUTE_PROGRAM:
  505. inputDesc.shaderTarget = Xsc::ShaderTarget::ComputeShader;
  506. inputDesc.entryPoint = "csmain";
  507. break;
  508. default:
  509. break;
  510. }
  511. StringStream output;
  512. Xsc::ShaderOutput outputDesc;
  513. outputDesc.sourceCode = &output;
  514. outputDesc.options.autoBinding = vulkan;
  515. outputDesc.options.autoBindingStartSlot = startBindingSlot;
  516. outputDesc.options.separateShaders = true;
  517. outputDesc.options.separateSamplers = false;
  518. outputDesc.nameMangling.inputPrefix = "bs_";
  519. outputDesc.nameMangling.outputPrefix = "bs_";
  520. outputDesc.nameMangling.useAlwaysSemantics = true;
  521. outputDesc.nameMangling.renameBufferFields = true;
  522. if (vulkan)
  523. outputDesc.shaderVersion = Xsc::OutputShaderVersion::VKSL450;
  524. else
  525. outputDesc.shaderVersion = Xsc::OutputShaderVersion::GLSL450;
  526. XscLog log;
  527. Xsc::Reflection::ReflectionData reflectionData;
  528. bool compileSuccess = Xsc::CompileShader(inputDesc, outputDesc, &log, &reflectionData);
  529. if (!compileSuccess)
  530. {
  531. // If enabled, don't fail if entry point isn't found
  532. bool done = true;
  533. if(optionalEntry)
  534. {
  535. bool entryFound = false;
  536. for (auto& entry : reflectionData.functions)
  537. {
  538. if(entry.ident == inputDesc.entryPoint)
  539. {
  540. entryFound = true;
  541. break;
  542. }
  543. }
  544. if (!entryFound)
  545. done = false;
  546. }
  547. if (done)
  548. {
  549. StringStream logOutput;
  550. log.getMessages(logOutput);
  551. LOGERR("Shader cross compilation failed. Log: \n\n" + logOutput.str());
  552. return "";
  553. }
  554. }
  555. for (auto& entry : reflectionData.constantBuffers)
  556. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  557. for (auto& entry : reflectionData.textures)
  558. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  559. for (auto& entry : reflectionData.storageBuffers)
  560. startBindingSlot = std::max(startBindingSlot, entry.location + 1u);
  561. if(detectedTypes != nullptr)
  562. {
  563. for(auto& entry : reflectionData.functions)
  564. {
  565. if (entry.ident == "vsmain")
  566. detectedTypes->push_back(GPT_VERTEX_PROGRAM);
  567. else if (entry.ident == "fsmain")
  568. detectedTypes->push_back(GPT_FRAGMENT_PROGRAM);
  569. else if (entry.ident == "gsmain")
  570. detectedTypes->push_back(GPT_GEOMETRY_PROGRAM);
  571. else if (entry.ident == "dsmain")
  572. detectedTypes->push_back(GPT_DOMAIN_PROGRAM);
  573. else if (entry.ident == "hsmain")
  574. detectedTypes->push_back(GPT_HULL_PROGRAM);
  575. else if (entry.ident == "csmain")
  576. detectedTypes->push_back(GPT_COMPUTE_PROGRAM);
  577. }
  578. // If no entry points found, and error occurred, report error
  579. if(!compileSuccess && detectedTypes->size() == 0)
  580. {
  581. StringStream logOutput;
  582. log.getMessages(logOutput);
  583. LOGERR("Shader cross compilation failed. Log: \n\n" + logOutput.str());
  584. return "";
  585. }
  586. }
  587. if (shaderDesc != nullptr)
  588. parseParameters(reflectionData, *shaderDesc);
  589. return output.str();
  590. }
  591. // Convert HLSL code to GLSL
  592. String HLSLtoGLSL(const String& hlsl, GpuProgramType type, bool vulkan, UINT32& startBindingSlot)
  593. {
  594. return crossCompile(hlsl, type, vulkan, false, startBindingSlot);
  595. }
  596. void reflectHLSL(const String& hlsl, SHADER_DESC& shaderDesc, Vector<GpuProgramType>& entryPoints)
  597. {
  598. UINT32 dummy = 0;
  599. crossCompile(hlsl, GPT_VERTEX_PROGRAM, false, true, dummy, &shaderDesc, &entryPoints);
  600. }
  601. BSLFXCompileResult BSLFXCompiler::compile(const String& name, const String& source,
  602. const UnorderedMap<String, String>& defines)
  603. {
  604. String parsedSource = source;
  605. // Run the lexer/parser and generate the AST
  606. ParseState* parseState = parseStateCreate();
  607. BSLFXCompileResult output = parseFX(parseState, parsedSource.c_str(), defines);
  608. if(!output.errorMessage.empty())
  609. parseStateDelete(parseState);
  610. else
  611. {
  612. // Only enable for debug purposes
  613. //SLFXDebugPrint(parseState->rootNode, "");
  614. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  615. {
  616. parseStateDelete(parseState);
  617. output.errorMessage = "Root not is null or not a shader.";
  618. return output;
  619. }
  620. // Parse global shader options & technique meta-data
  621. SHADER_DESC shaderDesc;
  622. Vector<pair<ASTFXNode*, TechniqueMetaData>> techniqueMetaData;
  623. //// Go in reverse because options are added in reverse order during parsing
  624. for (int i = parseState->rootNode->options->count - 1; i >= 0; i--)
  625. {
  626. NodeOption* option = &parseState->rootNode->options->entries[i];
  627. switch (option->type)
  628. {
  629. case OT_Options:
  630. parseOptions(option->value.nodePtr, shaderDesc);
  631. break;
  632. case OT_Technique:
  633. {
  634. // We initially parse only meta-data, so we can handle out-of-order technique definitions
  635. TechniqueMetaData metaData = parseTechniqueMetaData(option->value.nodePtr);
  636. techniqueMetaData.push_back(std::make_pair(option->value.nodePtr, metaData));
  637. break;
  638. }
  639. default:
  640. break;
  641. }
  642. }
  643. // Inherit variations from mixins
  644. bool* techniqueWasParsed = bs_stack_alloc<bool>((UINT32)techniqueMetaData.size());
  645. std::function<bool(const TechniqueMetaData&, TechniqueMetaData&)> parseInherited =
  646. [&](const TechniqueMetaData& metaData, TechniqueMetaData& combinedMetaData)
  647. {
  648. for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter)
  649. {
  650. const String& includes = *riter;
  651. UINT32 baseIdx = -1;
  652. for (UINT32 i = 0; i < (UINT32)techniqueMetaData.size(); i++)
  653. {
  654. auto& entry = techniqueMetaData[i];
  655. if (!entry.second.isMixin)
  656. continue;
  657. if (entry.second.name == includes)
  658. {
  659. bool matches =
  660. (entry.second.language == metaData.language ||
  661. entry.second.language == "Any") &&
  662. (entry.second.renderer == metaData.renderer ||
  663. entry.second.renderer == RendererAny);
  664. // We want the last matching technique, in order to allow techniques to override each other
  665. if (matches)
  666. baseIdx = i;
  667. }
  668. }
  669. if (baseIdx != (UINT32)-1)
  670. {
  671. auto& entry = techniqueMetaData[baseIdx];
  672. // Was already parsed previously, don't parse it multiple times (happens when multiple techniques
  673. // include the same mixin)
  674. if (techniqueWasParsed[baseIdx])
  675. continue;
  676. if (!parseInherited(entry.second, combinedMetaData))
  677. return false;
  678. for(auto& variation : entry.second.variations)
  679. combinedMetaData.variations.push_back(variation);
  680. techniqueWasParsed[baseIdx] = true;
  681. }
  682. else
  683. {
  684. output.errorMessage = "Mixin \"" + includes + "\" cannot be found.";
  685. return false;
  686. }
  687. }
  688. return true;
  689. };
  690. for (auto& entry : techniqueMetaData)
  691. {
  692. TechniqueMetaData& metaData = entry.second;
  693. if (metaData.isMixin)
  694. continue;
  695. bs_zero_out(techniqueWasParsed, techniqueMetaData.size());
  696. TechniqueMetaData combinedMetaData = metaData;
  697. if (!parseInherited(metaData, combinedMetaData))
  698. {
  699. parseStateDelete(parseState);
  700. bs_stack_free(techniqueWasParsed);
  701. return output;
  702. }
  703. entry.second = combinedMetaData;
  704. }
  705. bs_stack_free(techniqueWasParsed);
  706. parseStateDelete(parseState);
  707. // Build a list of different variations and re-parse the source using the relevant defines
  708. Vector<SPtr<Technique>> techniques;
  709. UnorderedSet<String> includes;
  710. for (auto& entry : techniqueMetaData)
  711. {
  712. TechniqueMetaData& metaData = entry.second;
  713. if (metaData.isMixin)
  714. continue;
  715. // Generate a list of variations
  716. Vector<ShaderVariation> variations;
  717. if (metaData.variations.empty())
  718. variations.push_back(ShaderVariation());
  719. else
  720. {
  721. Vector<const VariationData*> todo;
  722. for (UINT32 i = 0; i < (UINT32)metaData.variations.size(); i++)
  723. todo.push_back(&metaData.variations[i]);
  724. while (!todo.empty())
  725. {
  726. const VariationData* current = todo.back();
  727. todo.erase(todo.end() - 1);
  728. // Variation parameter that's either defined or isn't
  729. if (current->values.empty())
  730. {
  731. // This is the first variation parameter, register new variations
  732. if (variations.empty())
  733. {
  734. ShaderVariation a;
  735. ShaderVariation b;
  736. b.addParam(ShaderVariation::Param(current->identifier, 1));
  737. variations.push_back(a);
  738. variations.push_back(b);
  739. }
  740. else // Duplicate existing variations, and add the parameter
  741. {
  742. UINT32 numVariations = (UINT32)variations.size();
  743. for (UINT32 i = 0; i < numVariations; i++)
  744. {
  745. // Make a copy
  746. variations.push_back(variations[i]);
  747. // Add the parameter to existing variation
  748. variations[i].addParam(ShaderVariation::Param(current->identifier, 1));
  749. }
  750. }
  751. }
  752. else // Variation parameter with multiple values
  753. {
  754. // This is the first variation parameter, register new variations
  755. if (variations.empty())
  756. {
  757. for (UINT32 i = 0; i < (UINT32)current->values.size(); i++)
  758. {
  759. ShaderVariation variation;
  760. variation.addParam(ShaderVariation::Param(current->identifier, current->values[i]));
  761. variations.push_back(variation);
  762. }
  763. }
  764. else // Duplicate existing variations, and add the parameter
  765. {
  766. UINT32 numVariations = (UINT32)variations.size();
  767. for (UINT32 i = 0; i < numVariations; i++)
  768. {
  769. for (UINT32 j = 1; j < (UINT32)current->values.size(); j++)
  770. {
  771. ShaderVariation copy = variations[i];
  772. copy.addParam(ShaderVariation::Param(current->identifier, current->values[j]));
  773. variations.push_back(copy);
  774. }
  775. variations[i].addParam(ShaderVariation::Param(current->identifier, current->values[0]));
  776. }
  777. }
  778. }
  779. }
  780. }
  781. // For every variation, re-parse the file with relevant defines
  782. for(auto& variation : variations)
  783. {
  784. UnorderedMap<String, String> globalDefines = defines;
  785. UnorderedMap<String, String> variationDefines = variation.getDefines().getAll();
  786. for(auto& define : variationDefines)
  787. globalDefines[define.first] = define.second;
  788. ParseState* variationParseState = parseStateCreate();
  789. output = parseFX(variationParseState, parsedSource.c_str(), globalDefines);
  790. if (!output.errorMessage.empty())
  791. parseStateDelete(variationParseState);
  792. else
  793. {
  794. Vector<String> codeBlocks;
  795. CodeString* codeString = variationParseState->codeStrings;
  796. while (codeString != nullptr)
  797. {
  798. while ((INT32)codeBlocks.size() <= codeString->index)
  799. codeBlocks.push_back(String());
  800. codeBlocks[codeString->index] = String(codeString->code, codeString->size);
  801. codeString = codeString->next;
  802. }
  803. output = parseTechnique(variationParseState, entry.second.name, codeBlocks, variation, techniques,
  804. includes, shaderDesc);
  805. if(!output.errorMessage.empty())
  806. return output;
  807. }
  808. }
  809. }
  810. // Generate a shader from the parsed techniques
  811. Vector<String> includeArray;
  812. for (auto& entry : includes)
  813. includeArray.push_back(entry);
  814. output.shader = Shader::_createPtr(name, shaderDesc, techniques);
  815. output.shader->setIncludeFiles(includeArray);
  816. // Verify GPU programs compile correctly
  817. StringStream gpuProgError;
  818. bool hasError = false;
  819. if (output.shader != nullptr)
  820. {
  821. Vector<SPtr<Technique>> techniques = output.shader->getCompatibleTechniques();
  822. for (auto& technique : techniques)
  823. {
  824. UINT32 numPasses = technique->getNumPasses();
  825. for (UINT32 i = 0; i < numPasses; i++)
  826. {
  827. SPtr<Pass> pass = technique->getPass(i);
  828. auto checkCompileStatus = [&](const String& prefix, const SPtr<GpuProgram>& prog)
  829. {
  830. if (prog != nullptr)
  831. {
  832. prog->blockUntilCoreInitialized();
  833. if (!prog->isCompiled())
  834. {
  835. hasError = true;
  836. gpuProgError << prefix << ": " << prog->getCompileErrorMessage() << std::endl;
  837. }
  838. }
  839. };
  840. checkCompileStatus("Vertex program", pass->getVertexProgram());
  841. checkCompileStatus("Fragment program", pass->getFragmentProgram());
  842. checkCompileStatus("Geometry program", pass->getGeometryProgram());
  843. checkCompileStatus("Hull program", pass->getHullProgram());
  844. checkCompileStatus("Domain program", pass->getDomainProgram());
  845. checkCompileStatus("Compute program", pass->getComputeProgram());
  846. }
  847. }
  848. }
  849. if (hasError)
  850. {
  851. output.errorMessage = "Failed compiling GPU program(s): " + gpuProgError.str();
  852. output.errorLine = 0;
  853. output.errorColumn = 0;
  854. }
  855. }
  856. return output;
  857. }
  858. BSLFXCompileResult BSLFXCompiler::parseFX(ParseState* parseState, const char* source, const UnorderedMap<String, String>& defines)
  859. {
  860. for(auto& define : defines)
  861. {
  862. if (define.first.size() == 0)
  863. continue;
  864. addDefine(parseState, define.first.c_str());
  865. if(define.second.size() > 0)
  866. addDefineExpr(parseState, define.second.c_str());
  867. }
  868. yyscan_t scanner;
  869. YY_BUFFER_STATE state;
  870. BSLFXCompileResult output;
  871. if (yylex_init_extra(parseState, &scanner))
  872. {
  873. output.errorMessage = "Internal error: Lexer failed to initialize.";
  874. return output;
  875. }
  876. // If debug output from lexer is needed uncomment this and add %debug option to lexer file
  877. //yyset_debug(true, scanner);
  878. // If debug output from parser is needed uncomment this and add %debug option to parser file
  879. //yydebug = true;
  880. state = yy_scan_string(source, scanner);
  881. if (yyparse(parseState, scanner))
  882. {
  883. if (parseState->hasError > 0)
  884. {
  885. output.errorMessage = parseState->errorMessage;
  886. output.errorLine = parseState->errorLine;
  887. output.errorColumn = parseState->errorColumn;
  888. if (parseState->errorFile != nullptr)
  889. output.errorFile = parseState->errorFile;
  890. }
  891. else
  892. output.errorMessage = "Internal error: Parsing failed.";
  893. return output;
  894. }
  895. yy_delete_buffer(state, scanner);
  896. yylex_destroy(scanner);
  897. return output;
  898. }
  899. BSLFXCompiler::TechniqueMetaData BSLFXCompiler::parseTechniqueMetaData(ASTFXNode* technique)
  900. {
  901. TechniqueMetaData metaData;
  902. metaData.renderer = RendererAny;
  903. metaData.language = "hlsl";
  904. metaData.isMixin = technique->type == NT_Mixin;
  905. for (int i = 0; i < technique->options->count; i++)
  906. {
  907. NodeOption* option = &technique->options->entries[i];
  908. switch (option->type)
  909. {
  910. case OT_Renderer:
  911. metaData.renderer = parseRenderer(removeQuotes(option->value.strValue));
  912. break;
  913. case OT_Tags:
  914. {
  915. ASTFXNode* tagsNode = option->value.nodePtr;
  916. for (int j = 0; j < tagsNode->options->count; j++)
  917. {
  918. NodeOption* tagOption = &tagsNode->options->entries[j];
  919. if (tagOption->type == OT_TagValue)
  920. metaData.tags.push_back(removeQuotes(tagOption->value.strValue));
  921. }
  922. }
  923. break;
  924. case OT_Variations:
  925. {
  926. ASTFXNode* variationsNode = option->value.nodePtr;
  927. for (int j = 0; j < variationsNode->options->count; j++)
  928. {
  929. NodeOption* variationOption = &variationsNode->options->entries[j];
  930. if(variationOption->type == OT_Variation)
  931. parseVariations(metaData, variationOption->value.nodePtr);
  932. }
  933. }
  934. break;
  935. case OT_Identifier:
  936. metaData.name = option->value.strValue;
  937. break;
  938. case OT_Mixin:
  939. metaData.includes.push_back(option->value.strValue);
  940. break;
  941. default:
  942. break;
  943. }
  944. }
  945. return metaData;
  946. }
  947. void BSLFXCompiler::parseVariations(TechniqueMetaData& metaData, ASTFXNode* variations)
  948. {
  949. assert(variations->type == NT_Variation);
  950. VariationData variationData;
  951. for (int i = 0; i < variations->options->count; i++)
  952. {
  953. NodeOption* option = &variations->options->entries[i];
  954. switch (option->type)
  955. {
  956. case OT_Identifier:
  957. variationData.identifier = option->value.strValue;
  958. break;
  959. case OT_VariationValue:
  960. variationData.values.push_back(option->value.intValue);
  961. break;
  962. default:
  963. break;
  964. }
  965. }
  966. if (!variationData.identifier.empty())
  967. metaData.variations.push_back(variationData);
  968. }
  969. StringID BSLFXCompiler::parseRenderer(const String& name)
  970. {
  971. if (name == "Any")
  972. return RendererAny;
  973. else if (name == "Default")
  974. return RendererDefault;
  975. return RendererAny;
  976. }
  977. QueueSortType BSLFXCompiler::parseSortType(CullAndSortModeValue sortType)
  978. {
  979. switch (sortType)
  980. {
  981. case CASV_BackToFront:
  982. return QueueSortType::BackToFront;
  983. case CASV_FrontToBack:
  984. return QueueSortType::FrontToBack;
  985. case CASV_None:
  986. return QueueSortType::None;
  987. default:
  988. break;
  989. }
  990. return QueueSortType::None;
  991. }
  992. CompareFunction BSLFXCompiler::parseCompFunc(CompFuncValue compFunc)
  993. {
  994. switch (compFunc)
  995. {
  996. case CFV_Pass:
  997. return CMPF_ALWAYS_PASS;
  998. case CFV_Fail:
  999. return CMPF_ALWAYS_FAIL;
  1000. case CFV_LT:
  1001. return CMPF_LESS;
  1002. case CFV_LTE:
  1003. return CMPF_LESS_EQUAL;
  1004. case CFV_EQ:
  1005. return CMPF_EQUAL;
  1006. case CFV_NEQ:
  1007. return CMPF_NOT_EQUAL;
  1008. case CFV_GT:
  1009. return CMPF_GREATER;
  1010. case CFV_GTE:
  1011. return CMPF_GREATER_EQUAL;
  1012. }
  1013. return CMPF_ALWAYS_PASS;
  1014. }
  1015. BlendFactor BSLFXCompiler::parseBlendFactor(OpValue factor)
  1016. {
  1017. switch (factor)
  1018. {
  1019. case OV_One:
  1020. return BF_ONE;
  1021. case OV_Zero:
  1022. return BF_ZERO;
  1023. case OV_DestColor:
  1024. return BF_DEST_COLOR;
  1025. case OV_SrcColor:
  1026. return BF_SOURCE_COLOR;
  1027. case OV_InvDestColor:
  1028. return BF_INV_DEST_COLOR;
  1029. case OV_InvSrcColor:
  1030. return BF_INV_SOURCE_COLOR;
  1031. case OV_DestAlpha:
  1032. return BF_DEST_ALPHA;
  1033. case OV_SrcAlpha:
  1034. return BF_SOURCE_ALPHA;
  1035. case OV_InvDestAlpha:
  1036. return BF_INV_DEST_ALPHA;
  1037. case OV_InvSrcAlpha:
  1038. return BF_INV_SOURCE_ALPHA;
  1039. default:
  1040. break;
  1041. }
  1042. return BF_ONE;
  1043. }
  1044. BlendOperation BSLFXCompiler::parseBlendOp(BlendOpValue op)
  1045. {
  1046. switch (op)
  1047. {
  1048. case BOV_Add:
  1049. return BO_ADD;
  1050. case BOV_Max:
  1051. return BO_MAX;
  1052. case BOV_Min:
  1053. return BO_MIN;
  1054. case BOV_Subtract:
  1055. return BO_SUBTRACT;
  1056. case BOV_RevSubtract:
  1057. return BO_REVERSE_SUBTRACT;
  1058. }
  1059. return BO_ADD;
  1060. }
  1061. StencilOperation BSLFXCompiler::parseStencilOp(OpValue op)
  1062. {
  1063. switch (op)
  1064. {
  1065. case OV_Keep:
  1066. return SOP_KEEP;
  1067. case OV_Zero:
  1068. return SOP_ZERO;
  1069. case OV_Replace:
  1070. return SOP_REPLACE;
  1071. case OV_Incr:
  1072. return SOP_INCREMENT;
  1073. case OV_Decr:
  1074. return SOP_DECREMENT;
  1075. case OV_IncrWrap:
  1076. return SOP_INCREMENT_WRAP;
  1077. case OV_DecrWrap:
  1078. return SOP_DECREMENT_WRAP;
  1079. case OV_Invert:
  1080. return SOP_INVERT;
  1081. default:
  1082. break;
  1083. }
  1084. return SOP_KEEP;
  1085. }
  1086. CullingMode BSLFXCompiler::parseCullMode(CullAndSortModeValue cm)
  1087. {
  1088. switch (cm)
  1089. {
  1090. case CASV_None:
  1091. return CULL_NONE;
  1092. case CASV_CW:
  1093. return CULL_CLOCKWISE;
  1094. case CASV_CCW:
  1095. return CULL_COUNTERCLOCKWISE;
  1096. default:
  1097. break;
  1098. }
  1099. return CULL_COUNTERCLOCKWISE;
  1100. }
  1101. PolygonMode BSLFXCompiler::parseFillMode(FillModeValue fm)
  1102. {
  1103. if (fm == FMV_Wire)
  1104. return PM_WIREFRAME;
  1105. return PM_SOLID;
  1106. }
  1107. void BSLFXCompiler::parseStencilFront(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  1108. {
  1109. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  1110. return;
  1111. for (int i = 0; i < stencilOpNode->options->count; i++)
  1112. {
  1113. NodeOption* option = &stencilOpNode->options->entries[i];
  1114. switch (option->type)
  1115. {
  1116. case OT_Fail:
  1117. desc.frontStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  1118. break;
  1119. case OT_ZFail:
  1120. desc.frontStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  1121. break;
  1122. case OT_PassOp:
  1123. desc.frontStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  1124. break;
  1125. case OT_CompareFunc:
  1126. desc.frontStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1127. break;
  1128. default:
  1129. break;
  1130. }
  1131. }
  1132. }
  1133. void BSLFXCompiler::parseStencilBack(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  1134. {
  1135. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  1136. return;
  1137. for (int i = 0; i < stencilOpNode->options->count; i++)
  1138. {
  1139. NodeOption* option = &stencilOpNode->options->entries[i];
  1140. switch (option->type)
  1141. {
  1142. case OT_Fail:
  1143. desc.backStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  1144. break;
  1145. case OT_ZFail:
  1146. desc.backStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  1147. break;
  1148. case OT_PassOp:
  1149. desc.backStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  1150. break;
  1151. case OT_CompareFunc:
  1152. desc.backStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1153. break;
  1154. default:
  1155. break;
  1156. }
  1157. }
  1158. }
  1159. void BSLFXCompiler::parseColorBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  1160. {
  1161. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  1162. return;
  1163. for (int i = 0; i < blendDefNode->options->count; i++)
  1164. {
  1165. NodeOption* option = &blendDefNode->options->entries[i];
  1166. switch (option->type)
  1167. {
  1168. case OT_Source:
  1169. desc.srcBlend = parseBlendFactor((OpValue)option->value.intValue);
  1170. break;
  1171. case OT_Dest:
  1172. desc.dstBlend = parseBlendFactor((OpValue)option->value.intValue);
  1173. break;
  1174. case OT_Op:
  1175. desc.blendOp = parseBlendOp((BlendOpValue)option->value.intValue);
  1176. break;
  1177. default:
  1178. break;
  1179. }
  1180. }
  1181. }
  1182. void BSLFXCompiler::parseAlphaBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  1183. {
  1184. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  1185. return;
  1186. for (int i = 0; i < blendDefNode->options->count; i++)
  1187. {
  1188. NodeOption* option = &blendDefNode->options->entries[i];
  1189. switch (option->type)
  1190. {
  1191. case OT_Source:
  1192. desc.srcBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  1193. break;
  1194. case OT_Dest:
  1195. desc.dstBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  1196. break;
  1197. case OT_Op:
  1198. desc.blendOpAlpha = parseBlendOp((BlendOpValue)option->value.intValue);
  1199. break;
  1200. default:
  1201. break;
  1202. }
  1203. }
  1204. }
  1205. void BSLFXCompiler::parseRenderTargetBlendState(BLEND_STATE_DESC& desc, ASTFXNode* targetNode)
  1206. {
  1207. if (targetNode == nullptr || targetNode->type != NT_Target)
  1208. return;
  1209. UINT32 index = 0;
  1210. for (int i = 0; i < targetNode->options->count; i++)
  1211. {
  1212. NodeOption* option = &targetNode->options->entries[i];
  1213. switch (option->type)
  1214. {
  1215. case OT_Index:
  1216. index = option->value.intValue;
  1217. break;
  1218. default:
  1219. break;
  1220. }
  1221. }
  1222. if (index >= BS_MAX_MULTIPLE_RENDER_TARGETS)
  1223. return;
  1224. RENDER_TARGET_BLEND_STATE_DESC& rtDesc = desc.renderTargetDesc[index];
  1225. for (int i = 0; i < targetNode->options->count; i++)
  1226. {
  1227. NodeOption* option = &targetNode->options->entries[i];
  1228. switch (option->type)
  1229. {
  1230. case OT_Enabled:
  1231. rtDesc.blendEnable = option->value.intValue > 0;
  1232. break;
  1233. case OT_Color:
  1234. parseColorBlendDef(rtDesc, option->value.nodePtr);
  1235. break;
  1236. case OT_Alpha:
  1237. parseAlphaBlendDef(rtDesc, option->value.nodePtr);
  1238. break;
  1239. case OT_WriteMask:
  1240. rtDesc.renderTargetWriteMask = option->value.intValue;
  1241. break;
  1242. default:
  1243. break;
  1244. }
  1245. }
  1246. }
  1247. bool BSLFXCompiler::parseBlendState(PassData& desc, ASTFXNode* blendNode)
  1248. {
  1249. if (blendNode == nullptr || blendNode->type != NT_Blend)
  1250. return false;
  1251. bool isDefault = true;
  1252. for (int i = 0; i < blendNode->options->count; i++)
  1253. {
  1254. NodeOption* option = &blendNode->options->entries[i];
  1255. switch (option->type)
  1256. {
  1257. case OT_AlphaToCoverage:
  1258. desc.blendDesc.alphaToCoverageEnable = option->value.intValue > 0;
  1259. isDefault = false;
  1260. break;
  1261. case OT_IndependantBlend:
  1262. desc.blendDesc.independantBlendEnable = option->value.intValue > 0;
  1263. isDefault = false;
  1264. break;
  1265. case OT_Target:
  1266. parseRenderTargetBlendState(desc.blendDesc, option->value.nodePtr);
  1267. isDefault = false;
  1268. break;
  1269. default:
  1270. break;
  1271. }
  1272. }
  1273. return !isDefault;
  1274. }
  1275. bool BSLFXCompiler::parseRasterizerState(PassData& desc, ASTFXNode* rasterNode)
  1276. {
  1277. if (rasterNode == nullptr || rasterNode->type != NT_Raster)
  1278. return false;
  1279. bool isDefault = true;
  1280. for (int i = 0; i < rasterNode->options->count; i++)
  1281. {
  1282. NodeOption* option = &rasterNode->options->entries[i];
  1283. switch (option->type)
  1284. {
  1285. case OT_FillMode:
  1286. desc.rasterizerDesc.polygonMode = parseFillMode((FillModeValue)option->value.intValue);
  1287. isDefault = false;
  1288. break;
  1289. case OT_CullMode:
  1290. desc.rasterizerDesc.cullMode = parseCullMode((CullAndSortModeValue)option->value.intValue);
  1291. isDefault = false;
  1292. break;
  1293. case OT_DepthBias:
  1294. desc.rasterizerDesc.depthBias = option->value.floatValue;
  1295. isDefault = false;
  1296. break;
  1297. case OT_SDepthBias:
  1298. desc.rasterizerDesc.slopeScaledDepthBias = option->value.floatValue;
  1299. isDefault = false;
  1300. break;
  1301. case OT_DepthClip:
  1302. desc.rasterizerDesc.depthClipEnable = option->value.intValue > 0;
  1303. isDefault = false;
  1304. break;
  1305. case OT_Scissor:
  1306. desc.rasterizerDesc.scissorEnable = option->value.intValue > 0;
  1307. isDefault = false;
  1308. break;
  1309. case OT_Multisample:
  1310. desc.rasterizerDesc.multisampleEnable = option->value.intValue > 0;
  1311. isDefault = false;
  1312. break;
  1313. case OT_AALine:
  1314. desc.rasterizerDesc.antialiasedLineEnable = option->value.intValue > 0;
  1315. isDefault = false;
  1316. break;
  1317. default:
  1318. break;
  1319. }
  1320. }
  1321. return !isDefault;
  1322. }
  1323. bool BSLFXCompiler::parseDepthState(PassData& passData, ASTFXNode* depthNode)
  1324. {
  1325. if (depthNode == nullptr || depthNode->type != NT_Depth)
  1326. return false;
  1327. bool isDefault = true;
  1328. for (int i = 0; i < depthNode->options->count; i++)
  1329. {
  1330. NodeOption* option = &depthNode->options->entries[i];
  1331. switch (option->type)
  1332. {
  1333. case OT_DepthRead:
  1334. passData.depthStencilDesc.depthReadEnable = option->value.intValue > 0;
  1335. isDefault = false;
  1336. break;
  1337. case OT_DepthWrite:
  1338. passData.depthStencilDesc.depthWriteEnable = option->value.intValue > 0;
  1339. isDefault = false;
  1340. break;
  1341. case OT_CompareFunc:
  1342. passData.depthStencilDesc.depthComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1343. isDefault = false;
  1344. break;
  1345. default:
  1346. break;
  1347. }
  1348. }
  1349. return !isDefault;
  1350. }
  1351. bool BSLFXCompiler::parseStencilState(PassData& passData, ASTFXNode* stencilNode)
  1352. {
  1353. if (stencilNode == nullptr || stencilNode->type != NT_Stencil)
  1354. return false;
  1355. bool isDefault = true;
  1356. for (int i = 0; i < stencilNode->options->count; i++)
  1357. {
  1358. NodeOption* option = &stencilNode->options->entries[i];
  1359. switch (option->type)
  1360. {
  1361. case OT_Enabled:
  1362. passData.depthStencilDesc.stencilEnable = option->value.intValue > 0;
  1363. isDefault = false;
  1364. break;
  1365. case OT_StencilReadMask:
  1366. passData.depthStencilDesc.stencilReadMask = (UINT8)option->value.intValue;
  1367. isDefault = false;
  1368. break;
  1369. case OT_StencilWriteMask:
  1370. passData.depthStencilDesc.stencilWriteMask = (UINT8)option->value.intValue;
  1371. isDefault = false;
  1372. break;
  1373. case OT_StencilOpFront:
  1374. parseStencilFront(passData.depthStencilDesc, option->value.nodePtr);
  1375. isDefault = false;
  1376. break;
  1377. case OT_StencilOpBack:
  1378. parseStencilBack(passData.depthStencilDesc, option->value.nodePtr);
  1379. isDefault = false;
  1380. break;
  1381. case OT_StencilRef:
  1382. passData.stencilRefValue = option->value.intValue;
  1383. break;
  1384. default:
  1385. break;
  1386. }
  1387. }
  1388. return !isDefault;
  1389. }
  1390. void BSLFXCompiler::parseCodeBlock(ASTFXNode* codeNode, const Vector<String>& codeBlocks, PassData& passData)
  1391. {
  1392. if (codeNode == nullptr || (codeNode->type != NT_Code))
  1393. {
  1394. return;
  1395. }
  1396. UINT32 index = (UINT32)-1;
  1397. for (int j = 0; j < codeNode->options->count; j++)
  1398. {
  1399. if (codeNode->options->entries[j].type == OT_Index)
  1400. index = codeNode->options->entries[j].value.intValue;
  1401. }
  1402. if (index != (UINT32)-1 && index < (UINT32)codeBlocks.size())
  1403. {
  1404. switch (codeNode->type)
  1405. {
  1406. case NT_Code:
  1407. passData.code += codeBlocks[index];
  1408. break;
  1409. default:
  1410. break;
  1411. }
  1412. }
  1413. }
  1414. void BSLFXCompiler::parsePass(ASTFXNode* passNode, const Vector<String>& codeBlocks, PassData& passData)
  1415. {
  1416. if (passNode == nullptr || passNode->type != NT_Pass)
  1417. return;
  1418. for (int i = 0; i < passNode->options->count; i++)
  1419. {
  1420. NodeOption* option = &passNode->options->entries[i];
  1421. switch (option->type)
  1422. {
  1423. case OT_Blend:
  1424. passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr);
  1425. break;
  1426. case OT_Raster:
  1427. passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr);
  1428. break;
  1429. case OT_Depth:
  1430. passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr);
  1431. break;
  1432. case OT_Stencil:
  1433. passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr);
  1434. break;
  1435. case OT_Code:
  1436. parseCodeBlock(option->value.nodePtr, codeBlocks, passData);
  1437. break;
  1438. default:
  1439. break;
  1440. }
  1441. }
  1442. }
  1443. void BSLFXCompiler::parseTechnique(ASTFXNode* techniqueNode, const Vector<String>& codeBlocks, TechniqueData& techniqueData)
  1444. {
  1445. if (techniqueNode == nullptr || (techniqueNode->type != NT_Technique && techniqueNode->type != NT_Mixin))
  1446. return;
  1447. // There must always be at least one pass
  1448. if(techniqueData.passes.empty())
  1449. {
  1450. techniqueData.passes.push_back(PassData());
  1451. techniqueData.passes.back().seqIdx = 0;
  1452. }
  1453. PassData combinedCommonPassData;
  1454. UINT32 nextPassIdx = 0;
  1455. // Go in reverse because options are added in reverse order during parsing
  1456. for (int i = techniqueNode->options->count - 1; i >= 0; i--)
  1457. {
  1458. NodeOption* option = &techniqueNode->options->entries[i];
  1459. switch (option->type)
  1460. {
  1461. case OT_Pass:
  1462. {
  1463. UINT32 passIdx = nextPassIdx;
  1464. PassData* passData = nullptr;
  1465. for (auto& entry : techniqueData.passes)
  1466. {
  1467. if (entry.seqIdx == passIdx)
  1468. passData = &entry;
  1469. }
  1470. if (passData == nullptr)
  1471. {
  1472. techniqueData.passes.push_back(PassData());
  1473. passData = &techniqueData.passes.back();
  1474. passData->seqIdx = passIdx;
  1475. }
  1476. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  1477. passData->code = combinedCommonPassData.code + passData->code;
  1478. ASTFXNode* passNode = option->value.nodePtr;
  1479. parsePass(passNode, codeBlocks, *passData);
  1480. }
  1481. break;
  1482. case OT_Code:
  1483. {
  1484. PassData commonPassData;
  1485. parseCodeBlock(option->value.nodePtr, codeBlocks, commonPassData);
  1486. for (auto& passData : techniqueData.passes)
  1487. passData.code += commonPassData.code;
  1488. combinedCommonPassData.code += commonPassData.code;
  1489. }
  1490. break;
  1491. default:
  1492. break;
  1493. }
  1494. }
  1495. // Parse common pass states
  1496. for (int i = 0; i < techniqueNode->options->count; i++)
  1497. {
  1498. NodeOption* option = &techniqueNode->options->entries[i];
  1499. switch (option->type)
  1500. {
  1501. case OT_Blend:
  1502. for (auto& passData : techniqueData.passes)
  1503. passData.blendIsDefault &= !parseBlendState(passData, option->value.nodePtr);
  1504. break;
  1505. case OT_Raster:
  1506. for (auto& passData : techniqueData.passes)
  1507. passData.rasterizerIsDefault &= !parseRasterizerState(passData, option->value.nodePtr);
  1508. break;
  1509. case OT_Depth:
  1510. for (auto& passData : techniqueData.passes)
  1511. passData.depthStencilIsDefault &= !parseDepthState(passData, option->value.nodePtr);
  1512. break;
  1513. case OT_Stencil:
  1514. for (auto& passData : techniqueData.passes)
  1515. passData.depthStencilIsDefault &= !parseStencilState(passData, option->value.nodePtr);
  1516. break;
  1517. default:
  1518. break;
  1519. }
  1520. }
  1521. }
  1522. void BSLFXCompiler::parseOptions(ASTFXNode* optionsNode, SHADER_DESC& shaderDesc)
  1523. {
  1524. if (optionsNode == nullptr || optionsNode->type != NT_Options)
  1525. return;
  1526. for (int i = optionsNode->options->count - 1; i >= 0; i--)
  1527. {
  1528. NodeOption* option = &optionsNode->options->entries[i];
  1529. switch (option->type)
  1530. {
  1531. case OT_Separable:
  1532. shaderDesc.separablePasses = option->value.intValue > 1;
  1533. break;
  1534. case OT_Sort:
  1535. shaderDesc.queueSortType = parseSortType((CullAndSortModeValue)option->value.intValue);
  1536. break;
  1537. case OT_Priority:
  1538. shaderDesc.queuePriority = option->value.intValue;
  1539. break;
  1540. case OT_Transparent:
  1541. shaderDesc.flags |= (UINT32)ShaderFlags::Transparent;
  1542. break;
  1543. default:
  1544. break;
  1545. }
  1546. }
  1547. }
  1548. BSLFXCompileResult BSLFXCompiler::parseTechnique(ParseState* parseState, const String& name,
  1549. const Vector<String>& codeBlocks, const ShaderVariation& variation, Vector<SPtr<Technique>>& techniques,
  1550. UnorderedSet<String>& includes, SHADER_DESC& shaderDesc)
  1551. {
  1552. BSLFXCompileResult output;
  1553. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  1554. {
  1555. parseStateDelete(parseState);
  1556. output.errorMessage = "Root not is null or not a shader.";
  1557. return output;
  1558. }
  1559. Vector<pair<ASTFXNode*, TechniqueData>> techniqueData;
  1560. // Go in reverse because options are added in reverse order during parsing
  1561. for (int i = parseState->rootNode->options->count - 1; i >= 0; i--)
  1562. {
  1563. NodeOption* option = &parseState->rootNode->options->entries[i];
  1564. switch (option->type)
  1565. {
  1566. case OT_Technique:
  1567. {
  1568. // We initially parse only meta-data, so we can handle out-of-order technique definitions
  1569. TechniqueMetaData metaData = parseTechniqueMetaData(option->value.nodePtr);
  1570. // Skip all techniques except the one we're parsing
  1571. if(metaData.name != name && !metaData.isMixin)
  1572. continue;
  1573. techniqueData.push_back(std::make_pair(option->value.nodePtr, TechniqueData()));
  1574. TechniqueData& data = techniqueData.back().second;
  1575. data.metaData = metaData;
  1576. break;
  1577. }
  1578. default:
  1579. break;
  1580. }
  1581. }
  1582. bool* techniqueWasParsed = bs_stack_alloc<bool>((UINT32)techniqueData.size());
  1583. std::function<bool(const TechniqueMetaData&, TechniqueData&)> parseInherited =
  1584. [&](const TechniqueMetaData& metaData, TechniqueData& outTechnique)
  1585. {
  1586. for (auto riter = metaData.includes.rbegin(); riter != metaData.includes.rend(); ++riter)
  1587. {
  1588. const String& includes = *riter;
  1589. UINT32 baseIdx = -1;
  1590. for(UINT32 i = 0; i < (UINT32)techniqueData.size(); i++)
  1591. {
  1592. auto& entry = techniqueData[i];
  1593. if (!entry.second.metaData.isMixin)
  1594. continue;
  1595. if (entry.second.metaData.name == includes)
  1596. {
  1597. bool matches =
  1598. (entry.second.metaData.language == metaData.language ||
  1599. entry.second.metaData.language == "Any") &&
  1600. (entry.second.metaData.renderer == metaData.renderer ||
  1601. entry.second.metaData.renderer == RendererAny);
  1602. // We want the last matching technique, in order to allow techniques to override each other
  1603. if (matches)
  1604. baseIdx = i;
  1605. }
  1606. }
  1607. if (baseIdx != (UINT32)-1)
  1608. {
  1609. auto& entry = techniqueData[baseIdx];
  1610. // Was already parsed previously, don't parse it multiple times (happens when multiple techniques
  1611. // include the same mixin)
  1612. if (techniqueWasParsed[baseIdx])
  1613. continue;
  1614. if (!parseInherited(entry.second.metaData, outTechnique))
  1615. return false;
  1616. parseTechnique(entry.first, codeBlocks, outTechnique);
  1617. techniqueWasParsed[baseIdx] = true;
  1618. }
  1619. else
  1620. {
  1621. output.errorMessage = "Mixin \"" + includes + "\" cannot be found.";
  1622. return false;
  1623. }
  1624. }
  1625. return true;
  1626. };
  1627. // Actually parse techniques
  1628. for (auto& entry : techniqueData)
  1629. {
  1630. const TechniqueMetaData& metaData = entry.second.metaData;
  1631. if (metaData.isMixin)
  1632. continue;
  1633. bs_zero_out(techniqueWasParsed, techniqueData.size());
  1634. if (!parseInherited(metaData, entry.second))
  1635. {
  1636. parseStateDelete(parseState);
  1637. bs_stack_free(techniqueWasParsed);
  1638. return output;
  1639. }
  1640. parseTechnique(entry.first, codeBlocks, entry.second);
  1641. }
  1642. bs_stack_free(techniqueWasParsed);
  1643. IncludeLink* includeLink = parseState->includes;
  1644. while(includeLink != nullptr)
  1645. {
  1646. String includeFilename = includeLink->data->filename;
  1647. auto iterFind = std::find(includes.begin(), includes.end(), includeFilename);
  1648. if (iterFind == includes.end())
  1649. includes.insert(includeFilename);
  1650. includeLink = includeLink->next;
  1651. }
  1652. parseStateDelete(parseState);
  1653. // Parse extended HLSL code and generate per-program code, also convert to GLSL/VKSL
  1654. UINT32 end = (UINT32)techniqueData.size();
  1655. for(UINT32 i = 0; i < end; i++)
  1656. {
  1657. const TechniqueMetaData& metaData = techniqueData[i].second.metaData;
  1658. if (metaData.isMixin)
  1659. continue;
  1660. TechniqueData& hlslTechnique = techniqueData[i].second;
  1661. TechniqueData glslTechnique = techniqueData[i].second;
  1662. glslTechnique.metaData.language = "glsl";
  1663. TechniqueData vkslTechnique = techniqueData[i].second;
  1664. vkslTechnique.metaData.language = "vksl";
  1665. UINT32 numPasses = (UINT32)hlslTechnique.passes.size();
  1666. for(UINT32 j = 0; j < numPasses; j++)
  1667. {
  1668. PassData& hlslPassData = hlslTechnique.passes[j];
  1669. PassData& glslPassData = glslTechnique.passes[j];
  1670. PassData& vkslPassData = vkslTechnique.passes[j];
  1671. // Clean non-standard HLSL
  1672. static const std::regex regex("\\[\\s*layout\\s*\\(.*\\)\\s*\\]|\\[\\s*internal\\s*\\]|\\[\\s*color\\s*\\]|\\[\\s*alias\\s*\\(.*\\)\\s*\\]");
  1673. hlslPassData.code = regex_replace(hlslPassData.code, regex, "");
  1674. // Find valid entry points and parameters
  1675. // Note: XShaderCompiler needs to do a full pass when doing reflection, and for each individual program
  1676. // type. If performance is ever important here it could be good to update XShaderCompiler so it can
  1677. // somehow save the AST and then re-use it for multiple actions.
  1678. Vector<GpuProgramType> types;
  1679. reflectHLSL(glslPassData.code, shaderDesc, types);
  1680. UINT32 glslBinding = 0;
  1681. UINT32 vkslBinding = 0;
  1682. // Cross-compile for all detected shader types
  1683. // Note: I'm just copying HLSL code as-is. This code will contain all entry points which could have
  1684. // an effect on compile time. It would be ideal to remove dead code depending on program type. This would
  1685. // involve adding a HLSL code generator to XShaderCompiler.
  1686. for(auto& type : types)
  1687. {
  1688. switch(type)
  1689. {
  1690. case GPT_VERTEX_PROGRAM:
  1691. hlslPassData.vertexCode = hlslPassData.code;
  1692. glslPassData.vertexCode = HLSLtoGLSL(glslPassData.code, GPT_VERTEX_PROGRAM, false, glslBinding);
  1693. vkslPassData.vertexCode = HLSLtoGLSL(glslPassData.code, GPT_VERTEX_PROGRAM, true, vkslBinding);
  1694. break;
  1695. case GPT_FRAGMENT_PROGRAM:
  1696. hlslPassData.fragmentCode = hlslPassData.code;
  1697. glslPassData.fragmentCode = HLSLtoGLSL(glslPassData.code, GPT_FRAGMENT_PROGRAM, false, glslBinding);
  1698. vkslPassData.fragmentCode = HLSLtoGLSL(glslPassData.code, GPT_FRAGMENT_PROGRAM, true, vkslBinding);
  1699. break;
  1700. case GPT_GEOMETRY_PROGRAM:
  1701. hlslPassData.geometryCode = hlslPassData.code;
  1702. glslPassData.geometryCode = HLSLtoGLSL(glslPassData.code, GPT_GEOMETRY_PROGRAM, false, glslBinding);
  1703. vkslPassData.geometryCode = HLSLtoGLSL(glslPassData.code, GPT_GEOMETRY_PROGRAM, true, vkslBinding);
  1704. break;
  1705. case GPT_HULL_PROGRAM:
  1706. hlslPassData.hullCode = hlslPassData.code;
  1707. glslPassData.hullCode = HLSLtoGLSL(glslPassData.code, GPT_HULL_PROGRAM, false, glslBinding);
  1708. vkslPassData.hullCode = HLSLtoGLSL(glslPassData.code, GPT_HULL_PROGRAM, true, vkslBinding);
  1709. break;
  1710. case GPT_DOMAIN_PROGRAM:
  1711. hlslPassData.domainCode = hlslPassData.code;
  1712. glslPassData.domainCode = HLSLtoGLSL(glslPassData.code, GPT_DOMAIN_PROGRAM, false, glslBinding);
  1713. vkslPassData.domainCode = HLSLtoGLSL(glslPassData.code, GPT_DOMAIN_PROGRAM, true, vkslBinding);
  1714. break;
  1715. case GPT_COMPUTE_PROGRAM:
  1716. hlslPassData.computeCode = hlslPassData.code;
  1717. glslPassData.computeCode = HLSLtoGLSL(glslPassData.code, GPT_COMPUTE_PROGRAM, false, glslBinding);
  1718. vkslPassData.computeCode = HLSLtoGLSL(glslPassData.code, GPT_COMPUTE_PROGRAM, true, vkslBinding);
  1719. break;
  1720. default:
  1721. break;
  1722. }
  1723. }
  1724. }
  1725. techniqueData.push_back(std::make_pair(nullptr, glslTechnique));
  1726. techniqueData.push_back(std::make_pair(nullptr, vkslTechnique));
  1727. }
  1728. for(auto& entry : techniqueData)
  1729. {
  1730. const TechniqueMetaData& metaData = entry.second.metaData;
  1731. if (metaData.isMixin)
  1732. continue;
  1733. Map<UINT32, SPtr<Pass>, std::greater<UINT32>> passes;
  1734. for (auto& passData : entry.second.passes)
  1735. {
  1736. PASS_DESC passDesc;
  1737. if (!passData.blendIsDefault)
  1738. passDesc.blendState = BlendState::create(passData.blendDesc);
  1739. if (!passData.rasterizerIsDefault)
  1740. passDesc.rasterizerState = RasterizerState::create(passData.rasterizerDesc);
  1741. if (!passData.depthStencilIsDefault)
  1742. passDesc.depthStencilState = DepthStencilState::create(passData.depthStencilDesc);
  1743. auto createProgram =
  1744. [](const String& language, const String& entry, const String& code, GpuProgramType type) -> SPtr<GpuProgram>
  1745. {
  1746. if (code.empty())
  1747. return nullptr;
  1748. GPU_PROGRAM_DESC desc;
  1749. desc.language = language;
  1750. desc.entryPoint = entry;
  1751. desc.source = code;
  1752. desc.type = type;
  1753. return GpuProgram::create(desc);
  1754. };
  1755. bool isHLSL = metaData.language == "hlsl";
  1756. passDesc.vertexProgram = createProgram(
  1757. metaData.language,
  1758. isHLSL ? "vsmain" : "main",
  1759. passData.vertexCode,
  1760. GPT_VERTEX_PROGRAM);
  1761. passDesc.fragmentProgram = createProgram(
  1762. metaData.language,
  1763. isHLSL ? "fsmain" : "main",
  1764. passData.fragmentCode,
  1765. GPT_FRAGMENT_PROGRAM);
  1766. passDesc.geometryProgram = createProgram(
  1767. metaData.language,
  1768. isHLSL ? "gsmain" : "main",
  1769. passData.geometryCode,
  1770. GPT_GEOMETRY_PROGRAM);
  1771. passDesc.hullProgram = createProgram(
  1772. metaData.language,
  1773. isHLSL ? "hsmain" : "main",
  1774. passData.hullCode,
  1775. GPT_HULL_PROGRAM);
  1776. passDesc.domainProgram = createProgram(
  1777. metaData.language,
  1778. isHLSL ? "dsmain" : "main",
  1779. passData.domainCode,
  1780. GPT_DOMAIN_PROGRAM);
  1781. passDesc.computeProgram = createProgram(
  1782. metaData.language,
  1783. isHLSL ? "csmain" : "main",
  1784. passData.computeCode,
  1785. GPT_COMPUTE_PROGRAM);
  1786. passDesc.stencilRefValue = passData.stencilRefValue;
  1787. SPtr<Pass> pass = Pass::create(passDesc);
  1788. if (pass != nullptr)
  1789. passes[passData.seqIdx] = pass;
  1790. }
  1791. Vector<SPtr<Pass>> orderedPasses;
  1792. for (auto& KVP : passes)
  1793. orderedPasses.push_back(KVP.second);
  1794. if (orderedPasses.size() > 0)
  1795. {
  1796. SPtr<Technique> technique = Technique::create(metaData.language, metaData.renderer, metaData.tags,
  1797. variation, orderedPasses);
  1798. techniques.push_back(technique);
  1799. }
  1800. }
  1801. return output;
  1802. }
  1803. String BSLFXCompiler::removeQuotes(const char* input)
  1804. {
  1805. UINT32 len = (UINT32)strlen(input);
  1806. String output(len - 2, ' ');
  1807. for (UINT32 i = 0; i < (len - 2); i++)
  1808. output[i] = input[i + 1];
  1809. return output;
  1810. }
  1811. }