BsSLFXCompiler.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  1. #include "BsSLFXCompiler.h"
  2. #include "BsGpuProgram.h"
  3. #include <regex>
  4. #include "BsShader.h"
  5. #include "BsTechnique.h"
  6. #include "BsPass.h"
  7. #include "BsSamplerState.h"
  8. #include "BsRenderAPI.h"
  9. #include "BsDebug.h"
  10. #include "BsShaderManager.h"
  11. #include "BsShaderInclude.h"
  12. #include "BsMatrix4.h"
  13. #include "BsBuiltinResources.h"
  14. extern "C" {
  15. #include "BsMMAlloc.h"
  16. #include "BsParserFX.h"
  17. #include "BsLexerFX.h"
  18. }
  19. using namespace std;
  20. namespace BansheeEngine
  21. {
  22. // Print out the FX AST, only for debug purposes
  23. void SLFXDebugPrint(ASTFXNode* node, String indent)
  24. {
  25. LOGDBG(indent + "NODE " + toString(node->type));
  26. for (int i = 0; i < node->options->count; i++)
  27. {
  28. OptionDataType odt = OPTION_LOOKUP[(int)node->options->entries[i].type].dataType;
  29. if (odt == ODT_Complex)
  30. {
  31. LOGDBG(indent + toString(i) + ". " + toString(node->options->entries[i].type));
  32. SLFXDebugPrint(node->options->entries[i].value.nodePtr, indent + "\t");
  33. continue;
  34. }
  35. String value;
  36. switch (odt)
  37. {
  38. case ODT_Bool:
  39. value = toString(node->options->entries[i].value.intValue != 0);
  40. break;
  41. case ODT_Int:
  42. value = toString(node->options->entries[i].value.intValue);
  43. break;
  44. case ODT_Float:
  45. value = toString(node->options->entries[i].value.floatValue);
  46. break;
  47. case ODT_String:
  48. value = node->options->entries[i].value.strValue;
  49. break;
  50. case ODT_Matrix:
  51. {
  52. Matrix4 mat4 = *(Matrix4*)(node->options->entries[i].value.matrixValue);
  53. value = toString(mat4);
  54. }
  55. break;
  56. }
  57. LOGDBG(indent + toString(i) + ". " + toString(node->options->entries[i].type) + " = " + value);
  58. }
  59. }
  60. BSLFXCompileResult BSLFXCompiler::compile(const String& source)
  61. {
  62. BSLFXCompileResult output;
  63. String parsedSource = source;
  64. ParseState* parseState = parseStateCreate();
  65. Vector<CodeBlock> codeBlocks = parseCodeBlocks(parsedSource);
  66. parseFX(parseState, parsedSource.c_str());
  67. if (parseState->hasError > 0)
  68. {
  69. output.errorMessage = parseState->errorMessage;
  70. output.errorLine = parseState->errorLine;
  71. output.errorColumn = parseState->errorColumn;
  72. parseStateDelete(parseState);
  73. }
  74. else
  75. {
  76. // Only enable for debug purposes
  77. //SLFXDebugPrint(parseState->rootNode, "");
  78. output = parseShader("Shader", parseState, codeBlocks);
  79. StringStream gpuProgError;
  80. bool hasError = false;
  81. if (output.shader != nullptr)
  82. {
  83. TechniquePtr bestTechnique = output.shader->getBestTechnique();
  84. if (bestTechnique != nullptr)
  85. {
  86. UINT32 numPasses = bestTechnique->getNumPasses();
  87. for (UINT32 i = 0; i < numPasses; i++)
  88. {
  89. PassPtr pass = bestTechnique->getPass(i);
  90. auto checkCompileStatus = [&](const String& prefix, const GpuProgramPtr& prog)
  91. {
  92. if (prog != nullptr)
  93. {
  94. prog->blockUntilCoreInitialized();
  95. if (!prog->isCompiled())
  96. {
  97. hasError = true;
  98. gpuProgError << prefix <<": " << prog->getCompileErrorMessage() << std::endl;
  99. }
  100. }
  101. };
  102. checkCompileStatus("Vertex program", pass->getVertexProgram());
  103. checkCompileStatus("Fragment program", pass->getFragmentProgram());
  104. checkCompileStatus("Geometry program", pass->getGeometryProgram());
  105. checkCompileStatus("Hull program", pass->getHullProgram());
  106. checkCompileStatus("Domain program", pass->getDomainProgram());
  107. checkCompileStatus("Compute program", pass->getComputeProgram());
  108. }
  109. }
  110. }
  111. if (hasError)
  112. {
  113. output.shader = nullptr;
  114. output.errorMessage = "Failed compiling GPU program(s): " + gpuProgError.str();
  115. output.errorLine = 0;
  116. output.errorColumn = 0;
  117. }
  118. }
  119. return output;
  120. }
  121. void BSLFXCompiler::parseFX(ParseState* parseState, const char* source)
  122. {
  123. yyscan_t scanner;
  124. YY_BUFFER_STATE state;
  125. if (yylex_init_extra(parseState, &scanner))
  126. return;
  127. state = yy_scan_string(source, scanner);
  128. if (yyparse(parseState, scanner))
  129. return;
  130. yy_delete_buffer(state, scanner);
  131. yylex_destroy(scanner);
  132. }
  133. Vector<BSLFXCompiler::CodeBlock> BSLFXCompiler::parseCodeBlocks(String& source)
  134. {
  135. std::regex pattern = std::regex(R"((Vertex|Fragment|Geometry|Hull|Domain|Compute|Common)\s*=\s*\{)");
  136. std::smatch matches;
  137. Vector<CodeBlock> codeBlocks;
  138. UINT32 offset = 0;
  139. while (std::regex_search(source.cbegin() + offset, source.cend(), matches, pattern))
  140. {
  141. UINT32 idx = (UINT32)codeBlocks.size();
  142. codeBlocks.push_back(CodeBlock());
  143. CodeBlock& newBlock = codeBlocks.back();
  144. std::string type = matches[1].str();
  145. if (type == "Vertex")
  146. newBlock.type = CodeBlockType::Vertex;
  147. else if (type == "Fragment")
  148. newBlock.type = CodeBlockType::Fragment;
  149. else if (type == "Geometry")
  150. newBlock.type = CodeBlockType::Geometry;
  151. else if (type == "Hull")
  152. newBlock.type = CodeBlockType::Hull;
  153. else if (type == "Domain")
  154. newBlock.type = CodeBlockType::Domain;
  155. else if (type == "Compute")
  156. newBlock.type = CodeBlockType::Compute;
  157. else if (type == "Common")
  158. newBlock.type = CodeBlockType::Common;
  159. offset += (UINT32)matches.position() + (UINT32)matches.length();
  160. StringStream newDataStream;
  161. newDataStream << "Index = " + toString(idx) + ";";
  162. StringStream codeStream;
  163. UINT32 ummatchedBrackets = 1;
  164. for (UINT32 i = offset; i < (UINT32)source.length(); i++)
  165. {
  166. if (source[i] == '{')
  167. ummatchedBrackets++;
  168. if (source[i] == '}')
  169. ummatchedBrackets--;
  170. if (ummatchedBrackets == 0)
  171. break;
  172. if (source[i] == '\r' || source[i] == '\n')
  173. newDataStream << source[i];
  174. codeStream << source[i];
  175. }
  176. newBlock.code = codeStream.str();
  177. source.erase(source.cbegin() + offset, source.cbegin() + offset + (UINT32)newBlock.code.size());
  178. String newData = newDataStream.str();
  179. source.insert(offset, newData);
  180. offset += (UINT32)newData.size();
  181. }
  182. return codeBlocks;
  183. }
  184. void BSLFXCompiler::mergeBlocks(ParseState* mergeInto, ASTFXNode* blocksNode)
  185. {
  186. if (blocksNode == nullptr || blocksNode->type != NT_Blocks)
  187. return;
  188. ASTFXNode* destBlocksNode = nullptr;
  189. for (int i = 0; i < mergeInto->rootNode->options->count; i++)
  190. {
  191. NodeOption* option = &mergeInto->rootNode->options->entries[i];
  192. if (option->type == OT_Blocks)
  193. {
  194. destBlocksNode = option->value.nodePtr;
  195. break;
  196. }
  197. }
  198. if (destBlocksNode == nullptr)
  199. {
  200. destBlocksNode = nodeCreate(mergeInto->memContext, NT_Blocks);
  201. NodeOption blocksOption; blocksOption.type = OT_Blocks; blocksOption.value.nodePtr = destBlocksNode;
  202. nodeOptionsAdd(mergeInto->memContext, mergeInto->rootNode->options, &blocksOption);
  203. }
  204. for (int i = 0; i < blocksNode->options->count; i++)
  205. {
  206. NodeOption* option = &blocksNode->options->entries[i];
  207. if (option->type == OT_Block)
  208. {
  209. ASTFXNode* dstBlock = nodeCreate(mergeInto->memContext, NT_Block);
  210. NodeOption blockOption; blockOption.type = OT_Block; blockOption.value.nodePtr = dstBlock;
  211. nodeOptionsAdd(mergeInto->memContext, destBlocksNode->options, &blockOption);
  212. ASTFXNode* srcBlock = option->value.nodePtr;
  213. for (int j = 0; j < srcBlock->options->count; j++)
  214. copyNodeOption(mergeInto, dstBlock->options, &srcBlock->options->entries[j]);
  215. }
  216. }
  217. }
  218. void BSLFXCompiler::mergeParameters(ParseState* mergeInto, ASTFXNode* paramsNode)
  219. {
  220. if (paramsNode == nullptr || paramsNode->type != NT_Parameters)
  221. return;
  222. ASTFXNode* destParamsNode = nullptr;
  223. for (int i = 0; i < mergeInto->rootNode->options->count; i++)
  224. {
  225. NodeOption* option = &mergeInto->rootNode->options->entries[i];
  226. if (option->type == OT_Parameters)
  227. {
  228. destParamsNode = option->value.nodePtr;
  229. break;
  230. }
  231. }
  232. if (destParamsNode == nullptr)
  233. {
  234. destParamsNode = nodeCreate(mergeInto->memContext, NT_Parameters);
  235. NodeOption paramsOption; paramsOption.type = OT_Parameters; paramsOption.value.nodePtr = destParamsNode;
  236. nodeOptionsAdd(mergeInto->memContext, mergeInto->rootNode->options, &paramsOption);
  237. }
  238. for (int i = 0; i < paramsNode->options->count; i++)
  239. {
  240. NodeOption* option = &paramsNode->options->entries[i];
  241. if (option->type == OT_Parameter)
  242. {
  243. ASTFXNode* dstParam = nodeCreate(mergeInto->memContext, NT_Parameter);
  244. NodeOption paramOption; paramOption.type = OT_Parameter; paramOption.value.nodePtr = dstParam;
  245. nodeOptionsAdd(mergeInto->memContext, destParamsNode->options, &paramOption);
  246. ASTFXNode* srcParam = option->value.nodePtr;
  247. for (int j = 0; j < srcParam->options->count; j++)
  248. copyNodeOption(mergeInto, dstParam->options, &srcParam->options->entries[j]);
  249. }
  250. }
  251. }
  252. void BSLFXCompiler::getTechniqueIdentifier(ASTFXNode* technique, StringID& renderer, String& language)
  253. {
  254. renderer = RendererAny;
  255. language = "Any";
  256. for (int i = 0; i < technique->options->count; i++)
  257. {
  258. NodeOption* option = &technique->options->entries[i];
  259. switch (option->type)
  260. {
  261. case OT_Renderer:
  262. renderer = parseRenderer(removeQuotes(option->value.strValue));
  263. break;
  264. case OT_Language:
  265. language = removeQuotes(option->value.strValue);
  266. break;
  267. }
  268. }
  269. }
  270. bool BSLFXCompiler::isTechniqueMergeValid(ASTFXNode* into, ASTFXNode* from)
  271. {
  272. StringID intoRenderer = RendererAny;
  273. String intoLanguage = "Any";
  274. StringID fromRenderer = RendererAny;
  275. String fromLanguage = "Any";
  276. getTechniqueIdentifier(into, intoRenderer, intoLanguage);
  277. getTechniqueIdentifier(from, fromRenderer, fromLanguage);
  278. return (intoRenderer == fromRenderer || fromRenderer == RendererAny) && (intoLanguage == fromLanguage || fromLanguage == "Any");
  279. }
  280. bool BSLFXCompiler::copyNodeOption(ParseState* into, NodeOptions* parent, NodeOption* option)
  281. {
  282. OptionDataType dataType = OPTION_LOOKUP[(int)option->type].dataType;
  283. if (dataType == ODT_Complex)
  284. {
  285. ASTFXNode* newNode = nullptr;
  286. if (option->value.nodePtr != nullptr)
  287. newNode = nodeCreate(into->memContext, option->value.nodePtr->type);
  288. NodeOption newOption;
  289. newOption.type = option->type;
  290. newOption.value.nodePtr = newNode;
  291. nodeOptionsAdd(into->memContext, parent, &newOption);
  292. return true;
  293. }
  294. else if (dataType == ODT_String)
  295. {
  296. NodeOption newOption;
  297. newOption.type = option->type;
  298. newOption.value.strValue = mmalloc_strdup(into->memContext, option->value.strValue);
  299. nodeOptionsAdd(into->memContext, parent, &newOption);
  300. return false;
  301. }
  302. else
  303. {
  304. nodeOptionsAdd(into->memContext, parent, option);
  305. return false;
  306. }
  307. }
  308. void BSLFXCompiler::mergePass(ParseState* mergeInto, ASTFXNode* mergeIntoNode, ASTFXNode* mergeFromNode, UINT32 codeBlockOffset)
  309. {
  310. if (mergeIntoNode == nullptr || mergeIntoNode->type != NT_Pass || mergeFromNode == nullptr || mergeFromNode->type != NT_Pass)
  311. return;
  312. mergeCode(mergeInto, mergeIntoNode, mergeFromNode, codeBlockOffset);
  313. mergePassStates(mergeInto, mergeIntoNode, mergeFromNode);
  314. }
  315. void BSLFXCompiler::mergeCode(ParseState* mergeInto, ASTFXNode* mergeIntoNode, ASTFXNode* mergeFromNode, UINT32 codeBlockOffset)
  316. {
  317. for (int i = 0; i < mergeFromNode->options->count; i++)
  318. {
  319. NodeOption* option = &mergeFromNode->options->entries[i];
  320. if (option->type == OT_Code)
  321. {
  322. ASTFXNode* srcCodeNode = option->value.nodePtr;
  323. UINT32 origIndex = 0;
  324. for (int j = 0; j < srcCodeNode->options->count; j++)
  325. {
  326. NodeOption* codeOption = &srcCodeNode->options->entries[j];
  327. if (codeOption->type == OT_Index)
  328. origIndex = codeOption->value.intValue;
  329. }
  330. ASTFXNode* destCodeNode = nodeCreate(mergeInto->memContext, NT_Code);
  331. NodeOption index; index.type = OT_Index; index.value.intValue = codeBlockOffset + origIndex;
  332. nodeOptionsAdd(mergeInto->memContext, destCodeNode->options, &index);
  333. NodeOption code; code.type = OT_Code; code.value.nodePtr = destCodeNode;
  334. nodeOptionsAdd(mergeInto->memContext, mergeIntoNode->options, &code);
  335. }
  336. }
  337. }
  338. void BSLFXCompiler::mergePassStates(ParseState* mergeInto, ASTFXNode* mergeIntoNode, ASTFXNode* mergeFromNode)
  339. {
  340. for (int i = 0; i < mergeFromNode->options->count; i++)
  341. {
  342. NodeOption* option = &mergeFromNode->options->entries[i];
  343. // Skip these as we handle them specially elsewhere
  344. if (option->type == OT_Code || option->type == OT_Pass || option->type == OT_Renderer || option->type == OT_Language)
  345. continue;
  346. if (copyNodeOption(mergeInto, mergeIntoNode->options, option))
  347. {
  348. ASTFXNode* newNode = mergeIntoNode->options->entries[mergeIntoNode->options->count - 1].value.nodePtr;
  349. mergePassStates(mergeInto, newNode, option->value.nodePtr);
  350. }
  351. }
  352. }
  353. void BSLFXCompiler::mergeTechnique(ParseState* mergeInto, ASTFXNode* mergeIntoNode, ASTFXNode* mergeFromNode, UINT32 codeBlockOffset)
  354. {
  355. if (mergeIntoNode == nullptr || mergeIntoNode->type != NT_Technique || mergeFromNode == nullptr || mergeFromNode->type != NT_Technique)
  356. return;
  357. mergeCode(mergeInto, mergeIntoNode, mergeFromNode, codeBlockOffset);
  358. mergePassStates(mergeInto, mergeIntoNode, mergeFromNode);
  359. Map<UINT32, ASTFXNode*, std::greater<UINT32>> fromPasses;
  360. UINT32 nextPassIdx = 0;
  361. for (int i = 0; i < mergeFromNode->options->count; i++)
  362. {
  363. NodeOption* option = &mergeFromNode->options->entries[i];
  364. if (option->type == OT_Pass)
  365. {
  366. ASTFXNode* passNode = option->value.nodePtr;
  367. UINT32 passIdx = nextPassIdx;
  368. for (int j = 0; j < passNode->options->count; j++)
  369. {
  370. NodeOption* passOption = &passNode->options->entries[i];
  371. if (passOption->type == OT_Index)
  372. passIdx = (UINT32)passOption->value.intValue;
  373. }
  374. fromPasses[passIdx] = passNode;
  375. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  376. }
  377. }
  378. Map<UINT32, ASTFXNode*, std::greater<UINT32>> intoPasses;
  379. nextPassIdx = 0;
  380. for (int i = 0; i < mergeIntoNode->options->count; i++)
  381. {
  382. NodeOption* option = &mergeIntoNode->options->entries[i];
  383. if (option->type == OT_Pass)
  384. {
  385. ASTFXNode* passNode = option->value.nodePtr;
  386. UINT32 passIdx = nextPassIdx;
  387. for (int j = 0; j < passNode->options->count; j++)
  388. {
  389. NodeOption* passOption = &passNode->options->entries[i];
  390. if (passOption->type == OT_Index)
  391. passIdx = (UINT32)passOption->value.intValue;
  392. }
  393. intoPasses[passIdx] = passNode;
  394. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  395. }
  396. }
  397. for (auto& fromPair : fromPasses)
  398. {
  399. auto iterFind = intoPasses.find(fromPair.first);
  400. if (iterFind != intoPasses.end())
  401. {
  402. mergePass(mergeInto, iterFind->second, fromPair.second, codeBlockOffset);
  403. }
  404. else
  405. {
  406. ASTFXNode* passNode = nodeCreate(mergeInto->memContext, NT_Pass);
  407. NodeOption passOption; passOption.type = OT_Pass; passOption.value.nodePtr = passNode;
  408. nodeOptionsAdd(mergeInto->memContext, mergeIntoNode->options, &passOption);
  409. mergePass(mergeInto, passNode, fromPair.second, codeBlockOffset);
  410. }
  411. }
  412. }
  413. void BSLFXCompiler::mergeTechniques(ParseState* mergeInto, ASTFXNode* techniqueNode, UINT32 codeBlockOffset)
  414. {
  415. if (techniqueNode == nullptr || techniqueNode->type != NT_Technique)
  416. return;
  417. bool anyMerged = false;
  418. for (int i = 0; i < mergeInto->rootNode->options->count; i++)
  419. {
  420. NodeOption* option = &mergeInto->rootNode->options->entries[i];
  421. if (option->type == OT_Technique)
  422. {
  423. if (isTechniqueMergeValid(option->value.nodePtr, techniqueNode))
  424. {
  425. mergeTechnique(mergeInto, option->value.nodePtr, techniqueNode, codeBlockOffset);
  426. anyMerged = true;
  427. break;
  428. }
  429. }
  430. }
  431. // If this is a language specific technique and it wasn't merged with anything, create a new technique node
  432. if (!anyMerged)
  433. {
  434. ASTFXNode* techniqueNode = nodeCreate(mergeInto->memContext, NT_Technique);
  435. NodeOption techniqueOption; techniqueOption.type = OT_Technique; techniqueOption.value.nodePtr = techniqueNode;
  436. nodeOptionsAdd(mergeInto->memContext, mergeInto->rootNode->options, &techniqueOption);
  437. mergeTechnique(mergeInto, techniqueNode, techniqueNode, codeBlockOffset);
  438. }
  439. }
  440. void BSLFXCompiler::mergeAST(ParseState* mergeInto, ASTFXNode* mergeFrom, UINT32 codeBlockOffset)
  441. {
  442. if (mergeInto->rootNode->type != NT_Shader || mergeFrom == nullptr || mergeFrom->type != NT_Shader)
  443. return;
  444. for (int i = 0; i < mergeFrom->options->count; i++)
  445. {
  446. NodeOption* option = &mergeFrom->options->entries[i];
  447. switch (option->type)
  448. {
  449. case OT_Separable:
  450. case OT_Queue:
  451. case OT_Priority:
  452. case OT_Transparent:
  453. nodeOptionsAdd(mergeInto->memContext, mergeInto->rootNode->options, option);
  454. break;
  455. case OT_Technique:
  456. mergeTechniques(mergeInto, option->value.nodePtr, codeBlockOffset);
  457. break;
  458. case OT_Parameters:
  459. mergeParameters(mergeInto, option->value.nodePtr);
  460. break;
  461. case OT_Blocks:
  462. mergeBlocks(mergeInto, option->value.nodePtr);
  463. break;
  464. }
  465. }
  466. }
  467. StringID BSLFXCompiler::parseRenderer(const String& name)
  468. {
  469. if (name == "Any")
  470. return RendererAny;
  471. else if (name == "Default")
  472. return RendererDefault;
  473. return RendererAny;
  474. }
  475. void BSLFXCompiler::parseLanguage(const String& name, StringID& renderAPI, String& language)
  476. {
  477. if (name == "HLSL" || name == "HLSL11")
  478. {
  479. renderAPI = RenderAPIDX11;
  480. language = "hlsl";
  481. }
  482. else if (name == "HLSL9")
  483. {
  484. renderAPI = RenderAPIDX9;
  485. language = "hlsl9";
  486. }
  487. else if (name == "GLSL")
  488. {
  489. renderAPI = RenderAPIOpenGL;
  490. language = "glsl";
  491. }
  492. else // "Any"
  493. {
  494. renderAPI = RenderAPIAny;
  495. language = "";
  496. }
  497. }
  498. GpuParamBlockUsage BSLFXCompiler::parseBlockUsage(BufferUsageValue usage)
  499. {
  500. if (usage == BUV_Dynamic)
  501. return GPBU_DYNAMIC;
  502. return GPBU_STATIC;
  503. }
  504. UINT32 BSLFXCompiler::parseFilterMode(FilterValue filter)
  505. {
  506. switch (filter)
  507. {
  508. case FV_Point:
  509. return FO_POINT;
  510. case FV_Linear:
  511. return FO_LINEAR;
  512. case FV_Anisotropic:
  513. return FO_ANISOTROPIC;
  514. case FV_PointCmp:
  515. return FO_POINT | FO_USE_COMPARISON;
  516. case FV_LinearCmp:
  517. return FO_LINEAR | FO_USE_COMPARISON;
  518. case FV_AnisotropicCmp:
  519. return FO_ANISOTROPIC | FO_USE_COMPARISON;
  520. }
  521. return FO_NONE;
  522. }
  523. CompareFunction BSLFXCompiler::parseCompFunc(CompFuncValue compFunc)
  524. {
  525. switch (compFunc)
  526. {
  527. case CFV_Pass:
  528. return CMPF_ALWAYS_PASS;
  529. case CFV_Fail:
  530. return CMPF_ALWAYS_FAIL;
  531. case CFV_LT:
  532. return CMPF_LESS;
  533. case CFV_LTE:
  534. return CMPF_LESS_EQUAL;
  535. case CFV_EQ:
  536. return CMPF_EQUAL;
  537. case CFV_NEQ:
  538. return CMPF_NOT_EQUAL;
  539. case CFV_GT:
  540. return CMPF_GREATER;
  541. case CFV_GTE:
  542. return CMPF_GREATER_EQUAL;
  543. }
  544. return CMPF_ALWAYS_PASS;
  545. }
  546. TextureAddressingMode BSLFXCompiler::parseAddrMode(AddrModeValue addrMode)
  547. {
  548. switch (addrMode)
  549. {
  550. case AMV_Wrap:
  551. return TAM_WRAP;
  552. case AMV_Mirror:
  553. return TAM_MIRROR;
  554. case AMV_Clamp:
  555. return TAM_CLAMP;
  556. case AMV_Border:
  557. return TAM_BORDER;
  558. }
  559. return TAM_WRAP;
  560. }
  561. BlendFactor BSLFXCompiler::parseBlendFactor(OpValue factor)
  562. {
  563. switch (factor)
  564. {
  565. case OV_One:
  566. return BF_ONE;
  567. case OV_Zero:
  568. return BF_ZERO;
  569. case OV_DestColor:
  570. return BF_DEST_COLOR;
  571. case OV_SrcColor:
  572. return BF_SOURCE_COLOR;
  573. case OV_InvDestColor:
  574. return BF_INV_DEST_COLOR;
  575. case OV_InvSrcColor:
  576. return BF_INV_SOURCE_COLOR;
  577. case OV_DestAlpha:
  578. return BF_DEST_ALPHA;
  579. case OV_SrcAlpha:
  580. return BF_SOURCE_ALPHA;
  581. case OV_InvDestAlpha:
  582. return BF_INV_DEST_ALPHA;
  583. case OV_InvSrcAlpha:
  584. return BF_INV_SOURCE_ALPHA;
  585. }
  586. return BF_ONE;
  587. }
  588. BlendOperation BSLFXCompiler::parseBlendOp(BlendOpValue op)
  589. {
  590. switch (op)
  591. {
  592. case BOV_Add:
  593. return BO_ADD;
  594. case BOV_Max:
  595. return BO_MAX;
  596. case BOV_Min:
  597. return BO_MIN;
  598. case BOV_Subtract:
  599. return BO_SUBTRACT;
  600. case BOV_RevSubtract:
  601. return BO_REVERSE_SUBTRACT;
  602. }
  603. return BO_ADD;
  604. }
  605. void BSLFXCompiler::parseParamType(ParamType type, bool& isObjType, UINT32& typeId)
  606. {
  607. struct ParamData
  608. {
  609. UINT32 type;
  610. bool isObjType;
  611. };
  612. static bool initialized = false;
  613. static ParamData lookup[PT_Count];
  614. if (!initialized)
  615. {
  616. lookup[PT_Float] = { { GPDT_FLOAT1 }, false };
  617. lookup[PT_Float2] = { { GPDT_FLOAT2 }, false };
  618. lookup[PT_Float3] = { { GPDT_FLOAT3 }, false };
  619. lookup[PT_Float4] = { { GPDT_FLOAT4 }, false };
  620. lookup[PT_Int] = { { GPDT_INT1 }, false };
  621. lookup[PT_Int2] = { { GPDT_INT2 }, false };
  622. lookup[PT_Int3] = { { GPDT_INT3 }, false };
  623. lookup[PT_Int4] = { { GPDT_INT4 }, false };
  624. lookup[PT_Mat2x2] = { { GPDT_MATRIX_2X2 }, false };
  625. lookup[PT_Mat2x3] = { { GPDT_MATRIX_2X3 }, false };
  626. lookup[PT_Mat2x4] = { { GPDT_MATRIX_2X4 }, false };
  627. lookup[PT_Mat3x2] = { { GPDT_MATRIX_3X2 }, false };
  628. lookup[PT_Mat3x3] = { { GPDT_MATRIX_3X3 }, false };
  629. lookup[PT_Mat3x4] = { { GPDT_MATRIX_3X4 }, false };
  630. lookup[PT_Mat4x2] = { { GPDT_MATRIX_4X2 }, false };
  631. lookup[PT_Mat4x3] = { { GPDT_MATRIX_4X3 }, false };
  632. lookup[PT_Mat4x4] = { { GPDT_MATRIX_4X4 }, false };
  633. lookup[PT_Sampler1D] = { { GPOT_SAMPLER1D }, true };
  634. lookup[PT_Sampler2D] = { { GPOT_SAMPLER2D }, true };
  635. lookup[PT_Sampler3D] = { { GPOT_SAMPLER3D }, true };
  636. lookup[PT_SamplerCUBE] = { { GPOT_SAMPLERCUBE }, true };
  637. lookup[PT_Sampler2DMS] = { { GPOT_SAMPLER2DMS }, true };
  638. lookup[PT_Texture1D] = { { GPOT_TEXTURE1D }, true };
  639. lookup[PT_Texture2D] = { { GPOT_TEXTURE2D }, true };
  640. lookup[PT_Texture3D] = { { GPOT_TEXTURE3D }, true };
  641. lookup[PT_TextureCUBE] = { { GPOT_TEXTURECUBE }, true };
  642. lookup[PT_Texture2DMS] = { { GPOT_TEXTURE2DMS }, true };
  643. lookup[PT_ByteBuffer] = { { GPOT_BYTE_BUFFER }, true };
  644. lookup[PT_StructBuffer] = { { GPOT_STRUCTURED_BUFFER }, true };
  645. lookup[PT_TypedBufferRW] = { { GPOT_RWTYPED_BUFFER }, true };
  646. lookup[PT_ByteBufferRW] = { { GPOT_RWBYTE_BUFFER }, true };
  647. lookup[PT_StructBufferRW] = { { GPOT_RWSTRUCTURED_BUFFER }, true };
  648. lookup[PT_AppendBuffer] = { { GPOT_RWAPPEND_BUFFER }, true };
  649. lookup[PT_ConsumeBuffer] = { { GPOT_RWCONSUME_BUFFER }, true };
  650. initialized = true;
  651. }
  652. isObjType = lookup[type].isObjType;
  653. typeId = lookup[type].type;
  654. }
  655. StencilOperation BSLFXCompiler::parseStencilOp(OpValue op)
  656. {
  657. switch (op)
  658. {
  659. case OV_Keep:
  660. return SOP_KEEP;
  661. case OV_Zero:
  662. return SOP_ZERO;
  663. case OV_Replace:
  664. return SOP_REPLACE;
  665. case OV_Incr:
  666. return SOP_INCREMENT;
  667. case OV_Decr:
  668. return SOP_DECREMENT;
  669. case OV_IncrWrap:
  670. return SOP_INCREMENT_WRAP;
  671. case OV_DecrWrap:
  672. return SOP_DECREMENT_WRAP;
  673. case OV_Invert:
  674. return SOP_INVERT;
  675. }
  676. return SOP_KEEP;
  677. }
  678. CullingMode BSLFXCompiler::parseCullMode(CullModeValue cm)
  679. {
  680. switch (cm)
  681. {
  682. case CMV_None:
  683. return CULL_NONE;
  684. case CMV_CW:
  685. return CULL_CLOCKWISE;
  686. case CMV_CCW:
  687. return CULL_COUNTERCLOCKWISE;
  688. }
  689. return CULL_COUNTERCLOCKWISE;
  690. }
  691. PolygonMode BSLFXCompiler::parseFillMode(FillModeValue fm)
  692. {
  693. if (fm == FMV_Wire)
  694. return PM_WIREFRAME;
  695. return PM_SOLID;
  696. }
  697. void BSLFXCompiler::parseStencilFront(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  698. {
  699. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  700. return;
  701. for (int i = 0; i < stencilOpNode->options->count; i++)
  702. {
  703. NodeOption* option = &stencilOpNode->options->entries[i];
  704. switch (option->type)
  705. {
  706. case OT_Fail:
  707. desc.frontStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  708. break;
  709. case OT_ZFail:
  710. desc.frontStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  711. break;
  712. case OT_PassOp:
  713. desc.frontStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  714. break;
  715. case OT_CompareFunc:
  716. desc.frontStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  717. break;
  718. }
  719. }
  720. }
  721. void BSLFXCompiler::parseStencilBack(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* stencilOpNode)
  722. {
  723. if (stencilOpNode == nullptr || stencilOpNode->type != NT_StencilOp)
  724. return;
  725. for (int i = 0; i < stencilOpNode->options->count; i++)
  726. {
  727. NodeOption* option = &stencilOpNode->options->entries[i];
  728. switch (option->type)
  729. {
  730. case OT_Fail:
  731. desc.backStencilFailOp = parseStencilOp((OpValue)option->value.intValue);
  732. break;
  733. case OT_ZFail:
  734. desc.backStencilZFailOp = parseStencilOp((OpValue)option->value.intValue);
  735. break;
  736. case OT_PassOp:
  737. desc.backStencilPassOp = parseStencilOp((OpValue)option->value.intValue);
  738. break;
  739. case OT_CompareFunc:
  740. desc.backStencilComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  741. break;
  742. }
  743. }
  744. }
  745. void BSLFXCompiler::parseAddrMode(SAMPLER_STATE_DESC& desc, ASTFXNode* addrModeNode)
  746. {
  747. if (addrModeNode == nullptr || addrModeNode->type != NT_AddrMode)
  748. return;
  749. for (int i = 0; i < addrModeNode->options->count; i++)
  750. {
  751. NodeOption* option = &addrModeNode->options->entries[i];
  752. switch (option->type)
  753. {
  754. case OT_U:
  755. desc.addressMode.u = parseAddrMode((AddrModeValue)option->value.intValue);
  756. break;
  757. case OT_V:
  758. desc.addressMode.v = parseAddrMode((AddrModeValue)option->value.intValue);
  759. break;
  760. case OT_W:
  761. desc.addressMode.w = parseAddrMode((AddrModeValue)option->value.intValue);
  762. break;
  763. }
  764. }
  765. }
  766. void BSLFXCompiler::parseColorBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  767. {
  768. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  769. return;
  770. for (int i = 0; i < blendDefNode->options->count; i++)
  771. {
  772. NodeOption* option = &blendDefNode->options->entries[i];
  773. switch (option->type)
  774. {
  775. case OT_Source:
  776. desc.srcBlend = parseBlendFactor((OpValue)option->value.intValue);
  777. break;
  778. case OT_Dest:
  779. desc.dstBlend = parseBlendFactor((OpValue)option->value.intValue);
  780. break;
  781. case OT_Op:
  782. desc.blendOp = parseBlendOp((BlendOpValue)option->value.intValue);
  783. break;
  784. }
  785. }
  786. }
  787. void BSLFXCompiler::parseAlphaBlendDef(RENDER_TARGET_BLEND_STATE_DESC& desc, ASTFXNode* blendDefNode)
  788. {
  789. if (blendDefNode == nullptr || blendDefNode->type != NT_BlendDef)
  790. return;
  791. for (int i = 0; i < blendDefNode->options->count; i++)
  792. {
  793. NodeOption* option = &blendDefNode->options->entries[i];
  794. switch (option->type)
  795. {
  796. case OT_Source:
  797. desc.srcBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  798. break;
  799. case OT_Dest:
  800. desc.dstBlendAlpha = parseBlendFactor((OpValue)option->value.intValue);
  801. break;
  802. case OT_Op:
  803. desc.blendOpAlpha = parseBlendOp((BlendOpValue)option->value.intValue);
  804. break;
  805. }
  806. }
  807. }
  808. void BSLFXCompiler::parseRenderTargetBlendState(BLEND_STATE_DESC& desc, ASTFXNode* targetNode)
  809. {
  810. if (targetNode == nullptr || targetNode->type != NT_Target)
  811. return;
  812. UINT32 index = 0;
  813. for (int i = 0; i < targetNode->options->count; i++)
  814. {
  815. NodeOption* option = &targetNode->options->entries[i];
  816. switch (option->type)
  817. {
  818. case OT_Index:
  819. index = option->value.intValue;
  820. break;
  821. }
  822. }
  823. if (index >= BS_MAX_MULTIPLE_RENDER_TARGETS)
  824. return;
  825. RENDER_TARGET_BLEND_STATE_DESC& rtDesc = desc.renderTargetDesc[index];
  826. for (int i = 0; i < targetNode->options->count; i++)
  827. {
  828. NodeOption* option = &targetNode->options->entries[i];
  829. switch (option->type)
  830. {
  831. case OT_Blend:
  832. rtDesc.blendEnable = option->value.intValue > 0;
  833. break;
  834. case OT_Color:
  835. parseColorBlendDef(rtDesc, option->value.nodePtr);
  836. break;
  837. case OT_Alpha:
  838. parseAlphaBlendDef(rtDesc, option->value.nodePtr);
  839. break;
  840. case OT_WriteMask:
  841. rtDesc.renderTargetWriteMask = option->value.intValue;
  842. break;
  843. }
  844. }
  845. }
  846. bool BSLFXCompiler::parseBlendState(BLEND_STATE_DESC& desc, ASTFXNode* passNode)
  847. {
  848. if (passNode == nullptr || (passNode->type != NT_Pass && passNode->type != NT_Technique))
  849. return false;
  850. bool default = true;
  851. for (int i = 0; i < passNode->options->count; i++)
  852. {
  853. NodeOption* option = &passNode->options->entries[i];
  854. switch (option->type)
  855. {
  856. case OT_AlphaToCoverage:
  857. desc.alphaToCoverageEnable = option->value.intValue > 0;
  858. default = false;
  859. break;
  860. case OT_IndependantBlend:
  861. desc.independantBlendEnable = option->value.intValue > 0;
  862. default = false;
  863. break;
  864. case OT_Target:
  865. parseRenderTargetBlendState(desc, option->value.nodePtr);
  866. default = false;
  867. break;
  868. }
  869. }
  870. return !default;
  871. }
  872. bool BSLFXCompiler::parseRasterizerState(RASTERIZER_STATE_DESC& desc, ASTFXNode* passNode)
  873. {
  874. if (passNode == nullptr || (passNode->type != NT_Pass && passNode->type != NT_Technique))
  875. return false;
  876. bool default = true;
  877. for (int i = 0; i < passNode->options->count; i++)
  878. {
  879. NodeOption* option = &passNode->options->entries[i];
  880. switch (option->type)
  881. {
  882. case OT_FillMode:
  883. desc.polygonMode = parseFillMode((FillModeValue)option->value.intValue);
  884. default = false;
  885. break;
  886. case OT_CullMode:
  887. desc.cullMode = parseCullMode((CullModeValue)option->value.intValue);
  888. default = false;
  889. break;
  890. case OT_DepthBias:
  891. desc.depthBias = option->value.floatValue;
  892. default = false;
  893. break;
  894. case OT_SDepthBias:
  895. desc.slopeScaledDepthBias = option->value.floatValue;
  896. default = false;
  897. break;
  898. case OT_DepthClip:
  899. desc.depthClipEnable = option->value.intValue > 0;
  900. default = false;
  901. break;
  902. case OT_Scissor:
  903. desc.scissorEnable = option->value.intValue > 0;
  904. default = false;
  905. break;
  906. case OT_Multisample:
  907. desc.multisampleEnable = option->value.intValue > 0;
  908. default = false;
  909. break;
  910. case OT_AALine:
  911. desc.antialiasedLineEnable = option->value.intValue > 0;
  912. default = false;
  913. break;
  914. }
  915. }
  916. return !default;
  917. }
  918. bool BSLFXCompiler::parseDepthStencilState(DEPTH_STENCIL_STATE_DESC& desc, ASTFXNode* passNode)
  919. {
  920. if (passNode == nullptr || (passNode->type != NT_Pass && passNode->type != NT_Technique))
  921. return false;
  922. bool default = true;
  923. for (int i = 0; i < passNode->options->count; i++)
  924. {
  925. NodeOption* option = &passNode->options->entries[i];
  926. switch (option->type)
  927. {
  928. case OT_DepthRead:
  929. desc.depthReadEnable = option->value.intValue > 0;
  930. default = false;
  931. break;
  932. case OT_DepthWrite:
  933. desc.depthWriteEnable = option->value.intValue > 0;
  934. default = false;
  935. break;
  936. case OT_CompareFunc:
  937. desc.depthComparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  938. default = false;
  939. break;
  940. case OT_Stencil:
  941. desc.stencilEnable = option->value.intValue > 0;
  942. default = false;
  943. break;
  944. case OT_StencilReadMask:
  945. desc.stencilReadMask = (UINT8)option->value.intValue;
  946. default = false;
  947. break;
  948. case OT_StencilWriteMask:
  949. desc.stencilWriteMask = (UINT8)option->value.intValue;
  950. default = false;
  951. break;
  952. case OT_StencilOpFront:
  953. parseStencilFront(desc, option->value.nodePtr);
  954. default = false;
  955. break;
  956. case OT_StencilOpBack:
  957. parseStencilBack(desc, option->value.nodePtr);
  958. default = false;
  959. break;
  960. }
  961. }
  962. return !default;
  963. }
  964. SamplerStatePtr BSLFXCompiler::parseSamplerState(ASTFXNode* samplerStateNode)
  965. {
  966. if (samplerStateNode == nullptr || samplerStateNode->type != NT_SamplerState)
  967. return nullptr;
  968. SAMPLER_STATE_DESC desc;
  969. bool default = true;
  970. for (int i = 0; i < samplerStateNode->options->count; i++)
  971. {
  972. NodeOption* option = &samplerStateNode->options->entries[i];
  973. switch (option->type)
  974. {
  975. case OT_AddrMode:
  976. parseAddrMode(desc, option->value.nodePtr);
  977. default = false;
  978. break;
  979. case OT_MinFilter:
  980. desc.minFilter = (FilterOptions)parseFilterMode((FilterValue)option->value.intValue);
  981. default = false;
  982. break;
  983. case OT_MagFilter:
  984. desc.magFilter = (FilterOptions)parseFilterMode((FilterValue)option->value.intValue);
  985. default = false;
  986. break;
  987. case OT_MipFilter:
  988. desc.mipFilter = (FilterOptions)parseFilterMode((FilterValue)option->value.intValue);
  989. default = false;
  990. break;
  991. case OT_MaxAniso:
  992. desc.maxAniso = option->value.intValue;
  993. default = false;
  994. break;
  995. case OT_MipBias:
  996. desc.mipmapBias = option->value.floatValue;
  997. default = false;
  998. break;
  999. case OT_MipMin:
  1000. desc.mipMin = option->value.floatValue;
  1001. default = false;
  1002. break;
  1003. case OT_MipMax:
  1004. desc.mipMax = option->value.floatValue;
  1005. default = false;
  1006. break;
  1007. case OT_BorderColor:
  1008. desc.borderColor = Color(option->value.matrixValue[0], option->value.matrixValue[1],
  1009. option->value.matrixValue[2], option->value.matrixValue[3]);
  1010. default = false;
  1011. break;
  1012. case OT_CompareFunc:
  1013. desc.comparisonFunc = parseCompFunc((CompFuncValue)option->value.intValue);
  1014. default = false;
  1015. break;
  1016. }
  1017. }
  1018. if (default)
  1019. return nullptr;
  1020. return SamplerState::create(desc);
  1021. }
  1022. void BSLFXCompiler::parseCodeBlock(ASTFXNode* codeNode, const Vector<CodeBlock>& codeBlocks, PassData& passData)
  1023. {
  1024. if (codeNode == nullptr || codeNode->type != NT_Code)
  1025. return;
  1026. UINT32 index = (UINT32)-1;
  1027. for (int j = 0; j < codeNode->options->count; j++)
  1028. {
  1029. if (codeNode->options->entries[j].type == OT_Index)
  1030. index = codeNode->options->entries[j].value.intValue;
  1031. }
  1032. if (index != (UINT32)-1 && index < (UINT32)codeBlocks.size())
  1033. {
  1034. const CodeBlock& codeBlock = codeBlocks[index];
  1035. switch (codeBlock.type)
  1036. {
  1037. case CodeBlockType::Vertex:
  1038. passData.vertexCode += codeBlock.code;
  1039. break;
  1040. case CodeBlockType::Fragment:
  1041. passData.fragmentCode += codeBlock.code;
  1042. break;
  1043. case CodeBlockType::Geometry:
  1044. passData.geometryCode += codeBlock.code;
  1045. break;
  1046. case CodeBlockType::Hull:
  1047. passData.hullCode += codeBlock.code;
  1048. break;
  1049. case CodeBlockType::Domain:
  1050. passData.domainCode += codeBlock.code;
  1051. break;
  1052. case CodeBlockType::Compute:
  1053. passData.computeCode += codeBlock.code;
  1054. break;
  1055. case CodeBlockType::Common:
  1056. passData.commonCode += codeBlock.code;
  1057. break;
  1058. }
  1059. }
  1060. }
  1061. PassPtr BSLFXCompiler::parsePass(ASTFXNode* passNode, const Vector<CodeBlock>& codeBlocks, PassData& passData,
  1062. const StringID& renderAPI, const String& language, UINT32& seqIdx)
  1063. {
  1064. if (passNode == nullptr || passNode->type != NT_Pass)
  1065. return nullptr;
  1066. PASS_DESC passDesc;
  1067. passData.blendIsDefault &= !parseBlendState(passData.blendDesc, passNode);
  1068. passData.rasterizerIsDefault &= !parseRasterizerState(passData.rasterizerDesc, passNode);
  1069. passData.depthStencilIsDefault &= !parseDepthStencilState(passData.depthStencilDesc, passNode);
  1070. if (!passData.blendIsDefault)
  1071. passDesc.blendState = BlendState::create(passData.blendDesc);
  1072. if (!passData.rasterizerIsDefault)
  1073. passDesc.rasterizerState = RasterizerState::create(passData.rasterizerDesc);
  1074. if (!passData.depthStencilIsDefault)
  1075. passDesc.depthStencilState = DepthStencilState::create(passData.depthStencilDesc);
  1076. for (int i = 0; i < passNode->options->count; i++)
  1077. {
  1078. NodeOption* option = &passNode->options->entries[i];
  1079. switch (option->type)
  1080. {
  1081. case OT_Index:
  1082. seqIdx = option->value.intValue;
  1083. break;
  1084. case OT_StencilRef:
  1085. passDesc.stencilRefValue = option->value.intValue;
  1086. break;
  1087. case OT_Code:
  1088. parseCodeBlock(option->value.nodePtr, codeBlocks, passData);
  1089. break;
  1090. }
  1091. }
  1092. if (!passData.vertexCode.empty())
  1093. {
  1094. passDesc.vertexProgram = GpuProgram::create(passData.commonCode + passData.vertexCode, "main", language,
  1095. GPT_VERTEX_PROGRAM, getProfile(renderAPI, GPT_VERTEX_PROGRAM));
  1096. }
  1097. if (!passData.fragmentCode.empty())
  1098. {
  1099. passDesc.fragmentProgram = GpuProgram::create(passData.commonCode + passData.fragmentCode, "main", language,
  1100. GPT_FRAGMENT_PROGRAM, getProfile(renderAPI, GPT_FRAGMENT_PROGRAM));
  1101. }
  1102. if (!passData.geometryCode.empty())
  1103. {
  1104. passDesc.geometryProgram = GpuProgram::create(passData.commonCode + passData.geometryCode, "main", language,
  1105. GPT_GEOMETRY_PROGRAM, getProfile(renderAPI, GPT_GEOMETRY_PROGRAM));
  1106. }
  1107. if (!passData.hullCode.empty())
  1108. {
  1109. passDesc.hullProgram = GpuProgram::create(passData.commonCode + passData.hullCode, "main", language,
  1110. GPT_HULL_PROGRAM, getProfile(renderAPI, GPT_HULL_PROGRAM));
  1111. }
  1112. if (!passData.domainCode.empty())
  1113. {
  1114. passDesc.domainProgram = GpuProgram::create(passData.commonCode + passData.domainCode, "main", language,
  1115. GPT_DOMAIN_PROGRAM, getProfile(renderAPI, GPT_DOMAIN_PROGRAM));
  1116. }
  1117. if (!passData.computeCode.empty())
  1118. {
  1119. passDesc.computeProgram = GpuProgram::create(passData.commonCode + passData.computeCode, "main", language,
  1120. GPT_COMPUTE_PROGRAM, getProfile(renderAPI, GPT_COMPUTE_PROGRAM));
  1121. }
  1122. return Pass::create(passDesc);
  1123. }
  1124. TechniquePtr BSLFXCompiler::parseTechnique(ASTFXNode* techniqueNode, const Vector<CodeBlock>& codeBlocks)
  1125. {
  1126. if (techniqueNode == nullptr || techniqueNode->type != NT_Technique)
  1127. return nullptr;
  1128. Vector<ASTFXNode*> passNodes;
  1129. StringID renderer = RendererAny;
  1130. StringID renderAPI = RenderAPIAny;
  1131. String language;
  1132. PassData commonPassData;
  1133. for (int i = 0; i < techniqueNode->options->count; i++)
  1134. {
  1135. NodeOption* option = &techniqueNode->options->entries[i];
  1136. switch (option->type)
  1137. {
  1138. case OT_Pass:
  1139. passNodes.push_back(option->value.nodePtr);
  1140. break;
  1141. case OT_Renderer:
  1142. renderer = parseRenderer(removeQuotes(option->value.strValue));
  1143. break;
  1144. case OT_Language:
  1145. parseLanguage(removeQuotes(option->value.strValue), renderAPI, language);
  1146. break;
  1147. case OT_Code:
  1148. parseCodeBlock(option->value.nodePtr, codeBlocks, commonPassData);
  1149. break;
  1150. }
  1151. }
  1152. commonPassData.blendIsDefault = !parseBlendState(commonPassData.blendDesc, techniqueNode);
  1153. commonPassData.rasterizerIsDefault = !parseRasterizerState(commonPassData.rasterizerDesc, techniqueNode);
  1154. commonPassData.depthStencilIsDefault = !parseDepthStencilState(commonPassData.depthStencilDesc, techniqueNode);
  1155. UINT32 nextPassIdx = 0;
  1156. Map<UINT32, PassPtr, std::greater<UINT32>> passes;
  1157. for (auto& passNode : passNodes)
  1158. {
  1159. PassData passDataCopy = commonPassData;
  1160. UINT32 passIdx = nextPassIdx;
  1161. PassPtr pass = parsePass(passNode, codeBlocks, passDataCopy, renderAPI, language, passIdx);
  1162. if (pass != nullptr)
  1163. passes[passIdx] = pass;
  1164. nextPassIdx = std::max(nextPassIdx, passIdx) + 1;
  1165. }
  1166. Vector<PassPtr> orderedPasses;
  1167. for (auto& KVP : passes)
  1168. orderedPasses.push_back(KVP.second);
  1169. if (orderedPasses.size() > 0)
  1170. return Technique::create(renderAPI, renderer, orderedPasses);
  1171. return nullptr;
  1172. }
  1173. void BSLFXCompiler::parseParameters(SHADER_DESC& desc, ASTFXNode* parametersNode)
  1174. {
  1175. if (parametersNode == nullptr || parametersNode->type != NT_Parameters)
  1176. return;
  1177. for (int i = 0; i < parametersNode->options->count; i++)
  1178. {
  1179. NodeOption* option = &parametersNode->options->entries[i];
  1180. if (option->type != OT_Parameter)
  1181. continue;
  1182. ASTFXNode* parameter = option->value.nodePtr;
  1183. String name;
  1184. String alias;
  1185. UINT32 typeId = 0;
  1186. bool isObjType = false;
  1187. StringID semantic;
  1188. SamplerStatePtr samplerState = nullptr;
  1189. float defaultValue[16];
  1190. HTexture defaultTexture;
  1191. bool hasDefaultValue = false;
  1192. for (int j = 0; j < parameter->options->count; j++)
  1193. {
  1194. NodeOption* paramOption = &parameter->options->entries[j];
  1195. switch (paramOption->type)
  1196. {
  1197. case OT_Identifier:
  1198. name = paramOption->value.strValue;
  1199. break;
  1200. case OT_Alias:
  1201. alias = removeQuotes(paramOption->value.strValue);
  1202. break;
  1203. case OT_ParamType:
  1204. parseParamType((ParamType)paramOption->value.intValue, isObjType, typeId);
  1205. break;
  1206. case OT_ParamValue:
  1207. memcpy(defaultValue, paramOption->value.matrixValue, sizeof(defaultValue));
  1208. hasDefaultValue = true;
  1209. break;
  1210. case OT_ParamStrValue:
  1211. {
  1212. String defaultTextureName = removeQuotes(paramOption->value.strValue);
  1213. defaultTexture = getBuiltinTexture(defaultTextureName);
  1214. hasDefaultValue = true;
  1215. }
  1216. break;
  1217. case OT_Auto:
  1218. semantic = removeQuotes(paramOption->value.strValue);
  1219. break;
  1220. case OT_SamplerState:
  1221. samplerState = parseSamplerState(paramOption->value.nodePtr);
  1222. break;
  1223. }
  1224. }
  1225. if (name.empty())
  1226. continue;
  1227. auto addParameter = [&](const String& paramName, const String& gpuVarName)
  1228. {
  1229. if (isObjType)
  1230. {
  1231. GpuParamObjectType objType = (GpuParamObjectType)typeId;
  1232. if (Shader::isSampler(objType))
  1233. {
  1234. if(hasDefaultValue)
  1235. desc.addParameter(paramName, gpuVarName, objType, samplerState, semantic);
  1236. else
  1237. desc.addParameter(paramName, gpuVarName, objType, semantic);
  1238. }
  1239. else if(Shader::isTexture(objType))
  1240. {
  1241. if(hasDefaultValue)
  1242. desc.addParameter(paramName, gpuVarName, objType, defaultTexture, semantic);
  1243. else
  1244. desc.addParameter(paramName, gpuVarName, objType, semantic);
  1245. }
  1246. else
  1247. desc.addParameter(paramName, gpuVarName, objType, semantic);
  1248. }
  1249. else
  1250. {
  1251. if (hasDefaultValue)
  1252. desc.addParameter(paramName, gpuVarName, (GpuParamDataType)typeId, semantic, 1, 0, (UINT8*)defaultValue);
  1253. else
  1254. desc.addParameter(paramName, gpuVarName, (GpuParamDataType)typeId, semantic);
  1255. }
  1256. };
  1257. addParameter(name, name);
  1258. if (!alias.empty())
  1259. addParameter(name, alias);
  1260. }
  1261. }
  1262. void BSLFXCompiler::parseBlocks(SHADER_DESC& desc, ASTFXNode* blocksNode)
  1263. {
  1264. if (blocksNode == nullptr || blocksNode->type != NT_Blocks)
  1265. return;
  1266. for (int i = 0; i < blocksNode->options->count; i++)
  1267. {
  1268. NodeOption* option = &blocksNode->options->entries[i];
  1269. if (option->type != OT_Block)
  1270. continue;
  1271. ASTFXNode* parameter = option->value.nodePtr;
  1272. String name;
  1273. bool shared = false;
  1274. GpuParamBlockUsage usage = GPBU_STATIC;
  1275. StringID semantic;
  1276. for (int j = 0; j < parameter->options->count; j++)
  1277. {
  1278. NodeOption* paramOption = &parameter->options->entries[j];
  1279. switch (paramOption->type)
  1280. {
  1281. case OT_Identifier:
  1282. name = paramOption->value.strValue;
  1283. break;
  1284. case OT_Shared:
  1285. shared = paramOption->value.intValue > 0;
  1286. break;
  1287. case OT_Usage:
  1288. usage = parseBlockUsage((BufferUsageValue)paramOption->value.intValue);
  1289. break;
  1290. case OT_Auto:
  1291. semantic = removeQuotes(paramOption->value.strValue);
  1292. break;
  1293. }
  1294. }
  1295. if (name.empty())
  1296. continue;
  1297. desc.setParamBlockAttribs(name, shared, usage, semantic);
  1298. }
  1299. }
  1300. BSLFXCompileResult BSLFXCompiler::parseShader(const String& name, ParseState* parseState, Vector<CodeBlock>& codeBlocks)
  1301. {
  1302. BSLFXCompileResult output;
  1303. if (parseState->rootNode == nullptr || parseState->rootNode->type != NT_Shader)
  1304. {
  1305. output.errorMessage = "Root not is null or not a shader.";
  1306. return output;
  1307. }
  1308. // Merge all include ASTs
  1309. std::function<ParseState*(ParseState*, Vector<CodeBlock>&)> parseIncludes =
  1310. [&](ParseState* parentParseState, Vector<CodeBlock>& parentCodeBlocks) -> ParseState*
  1311. {
  1312. ASTFXNode* node = parentParseState->rootNode;
  1313. Vector<tuple<ParseState*, Vector<CodeBlock>>> toMerge;
  1314. for (int i = 0; i < node->options->count; i++)
  1315. {
  1316. NodeOption* option = &node->options->entries[i];
  1317. if (option->type == OT_Include)
  1318. {
  1319. String includePath = removeQuotes(option->value.strValue);
  1320. HShaderInclude include = ShaderManager::instance().findInclude(includePath);
  1321. if (include != nullptr)
  1322. {
  1323. include.blockUntilLoaded();
  1324. String includeSource = include->getString();
  1325. ParseState* includeParseState = parseStateCreate();
  1326. Vector<CodeBlock> includeCodeBlocks = parseCodeBlocks(includeSource);
  1327. parseFX(includeParseState, includeSource.c_str());
  1328. if (includeParseState->hasError > 0)
  1329. {
  1330. output.errorMessage = includeParseState->errorMessage;
  1331. output.errorLine = includeParseState->errorLine;
  1332. output.errorColumn = includeParseState->errorColumn;
  1333. parseStateDelete(includeParseState);
  1334. return nullptr;
  1335. }
  1336. else
  1337. {
  1338. ParseState* combinedIncludeParseState = parseIncludes(includeParseState, includeCodeBlocks);
  1339. toMerge.push_back(make_tuple(combinedIncludeParseState, includeCodeBlocks));
  1340. }
  1341. }
  1342. else
  1343. {
  1344. output.errorMessage = "Cannot find shader include file: " + includePath;
  1345. return nullptr;
  1346. }
  1347. }
  1348. }
  1349. UINT32 size = (UINT32)toMerge.size();
  1350. if (size > 0)
  1351. {
  1352. Vector<CodeBlock>& outputCodeBlocks = get<1>(toMerge[0]);
  1353. for (UINT32 i = 1; i < size; i++)
  1354. {
  1355. mergeAST(get<0>(toMerge[0]), get<0>(toMerge[i])->rootNode, (UINT32)outputCodeBlocks.size());
  1356. const Vector<CodeBlock>& curCodeBlocks = get<1>(toMerge[i]);
  1357. for (auto& codeBlock : curCodeBlocks)
  1358. outputCodeBlocks.push_back(codeBlock);
  1359. parseStateDelete(get<0>(toMerge[i]));
  1360. }
  1361. mergeAST(get<0>(toMerge[0]), node, (UINT32)outputCodeBlocks.size());
  1362. for (auto& codeBlock : parentCodeBlocks)
  1363. outputCodeBlocks.push_back(codeBlock);
  1364. parseStateDelete(parentParseState);
  1365. parentCodeBlocks = outputCodeBlocks;
  1366. return get<0>(toMerge[0]);
  1367. }
  1368. else
  1369. return parentParseState;
  1370. };
  1371. parseState = parseIncludes(parseState, codeBlocks);
  1372. if (parseState == nullptr) // Error
  1373. return output;
  1374. Vector<String> topLevelIncludes;
  1375. SHADER_DESC shaderDesc;
  1376. Vector<TechniquePtr> techniques;
  1377. for (int i = 0; i < parseState->rootNode->options->count; i++)
  1378. {
  1379. NodeOption* option = &parseState->rootNode->options->entries[i];
  1380. switch (option->type)
  1381. {
  1382. case OT_Include:
  1383. {
  1384. String includePath = removeQuotes(option->value.strValue);
  1385. topLevelIncludes.push_back(includePath);
  1386. }
  1387. break;
  1388. case OT_Separable:
  1389. shaderDesc.separablePasses = option->value.intValue > 1;
  1390. break;
  1391. case OT_Queue:
  1392. shaderDesc.queuePriority = option->value.intValue;
  1393. break;
  1394. case OT_Priority:
  1395. shaderDesc.queuePriority = option->value.intValue;
  1396. break;
  1397. case OT_Transparent:
  1398. shaderDesc.flags |= (UINT32)ShaderFlags::Transparent;
  1399. break;
  1400. case OT_Technique:
  1401. {
  1402. TechniquePtr technique = parseTechnique(option->value.nodePtr, codeBlocks);
  1403. if (technique != nullptr)
  1404. techniques.push_back(technique);
  1405. break;
  1406. }
  1407. case OT_Parameters:
  1408. parseParameters(shaderDesc, option->value.nodePtr);
  1409. break;
  1410. case OT_Blocks:
  1411. parseBlocks(shaderDesc, option->value.nodePtr);
  1412. break;
  1413. }
  1414. }
  1415. parseStateDelete(parseState);
  1416. output.shader = Shader::_createPtr(name, shaderDesc, techniques);
  1417. output.shader->setIncludeFiles(topLevelIncludes);
  1418. return output;
  1419. }
  1420. String BSLFXCompiler::removeQuotes(const char* input)
  1421. {
  1422. UINT32 len = (UINT32)strlen(input);
  1423. String output(len - 2, ' ');
  1424. for (UINT32 i = 0; i < (len - 2); i++)
  1425. output[i] = input[i + 1];
  1426. return output;
  1427. }
  1428. GpuProgramProfile BSLFXCompiler::getProfile(const StringID& renderAPI, GpuProgramType type)
  1429. {
  1430. StringID target = renderAPI;
  1431. if (target == RenderAPIAny)
  1432. target = RenderAPICore::instance().getName();
  1433. if (target == RenderAPIDX11 || target == RenderAPIOpenGL)
  1434. {
  1435. switch (type)
  1436. {
  1437. case GPT_VERTEX_PROGRAM:
  1438. return GPP_VS_5_0;
  1439. case GPT_FRAGMENT_PROGRAM:
  1440. return GPP_FS_5_0;
  1441. case GPT_GEOMETRY_PROGRAM:
  1442. return GPP_GS_5_0;
  1443. case GPT_HULL_PROGRAM:
  1444. return GPP_HS_5_0;
  1445. case GPT_DOMAIN_PROGRAM:
  1446. return GPP_DS_5_0;
  1447. case GPT_COMPUTE_PROGRAM:
  1448. return GPP_CS_5_0;
  1449. }
  1450. }
  1451. else if (target == RenderAPIDX9)
  1452. {
  1453. switch (type)
  1454. {
  1455. case GPT_VERTEX_PROGRAM:
  1456. return GPP_VS_3_0;
  1457. case GPT_FRAGMENT_PROGRAM:
  1458. return GPP_FS_3_0;
  1459. }
  1460. }
  1461. return GPP_NONE;
  1462. }
  1463. HTexture BSLFXCompiler::getBuiltinTexture(const String& name)
  1464. {
  1465. if (StringUtil::compare(name, String("white"), false) == 0)
  1466. return BuiltinResources::getTexture(BuiltinTexture::White);
  1467. else if (StringUtil::compare(name, String("black"), false) == 0)
  1468. return BuiltinResources::getTexture(BuiltinTexture::Black);
  1469. else if (StringUtil::compare(name, String("normal"), false) == 0)
  1470. return BuiltinResources::getTexture(BuiltinTexture::Normal);
  1471. return HTexture();
  1472. }
  1473. }