BsSLFXCompiler.cpp 45 KB

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