BsSLFXCompiler.cpp 50 KB

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