BsSLFXCompiler.cpp 43 KB

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