GlslDecompiler.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679
  1. using OpenTK.Graphics.OpenGL;
  2. using Ryujinx.Graphics.Texture;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Text;
  8. namespace Ryujinx.Graphics.Gal.Shader
  9. {
  10. public class GlslDecompiler
  11. {
  12. private delegate string GetInstExpr(ShaderIrOp op);
  13. private Dictionary<ShaderIrInst, GetInstExpr> _instsExpr;
  14. private enum OperType
  15. {
  16. Bool,
  17. F32,
  18. I32
  19. }
  20. private const string IdentationStr = " ";
  21. private const int MaxVertexInput = 3;
  22. private GlslDecl _decl;
  23. private ShaderHeader _header, _headerB;
  24. private ShaderIrBlock[] _blocks, _blocksB;
  25. private StringBuilder _sb;
  26. public int MaxUboSize { get; }
  27. private bool _isNvidiaDriver;
  28. public GlslDecompiler(int maxUboSize, bool isNvidiaDriver)
  29. {
  30. _instsExpr = new Dictionary<ShaderIrInst, GetInstExpr>()
  31. {
  32. { ShaderIrInst.Abs, GetAbsExpr },
  33. { ShaderIrInst.Add, GetAddExpr },
  34. { ShaderIrInst.And, GetAndExpr },
  35. { ShaderIrInst.Asr, GetAsrExpr },
  36. { ShaderIrInst.Band, GetBandExpr },
  37. { ShaderIrInst.Bnot, GetBnotExpr },
  38. { ShaderIrInst.Bor, GetBorExpr },
  39. { ShaderIrInst.Bxor, GetBxorExpr },
  40. { ShaderIrInst.Ceil, GetCeilExpr },
  41. { ShaderIrInst.Ceq, GetCeqExpr },
  42. { ShaderIrInst.Cge, GetCgeExpr },
  43. { ShaderIrInst.Cgt, GetCgtExpr },
  44. { ShaderIrInst.Clamps, GetClampsExpr },
  45. { ShaderIrInst.Clampu, GetClampuExpr },
  46. { ShaderIrInst.Cle, GetCleExpr },
  47. { ShaderIrInst.Clt, GetCltExpr },
  48. { ShaderIrInst.Cne, GetCneExpr },
  49. { ShaderIrInst.Cut, GetCutExpr },
  50. { ShaderIrInst.Exit, GetExitExpr },
  51. { ShaderIrInst.Fabs, GetAbsExpr },
  52. { ShaderIrInst.Fadd, GetAddExpr },
  53. { ShaderIrInst.Fceq, GetCeqExpr },
  54. { ShaderIrInst.Fcequ, GetCequExpr },
  55. { ShaderIrInst.Fcge, GetCgeExpr },
  56. { ShaderIrInst.Fcgeu, GetCgeuExpr },
  57. { ShaderIrInst.Fcgt, GetCgtExpr },
  58. { ShaderIrInst.Fcgtu, GetCgtuExpr },
  59. { ShaderIrInst.Fclamp, GetFclampExpr },
  60. { ShaderIrInst.Fcle, GetCleExpr },
  61. { ShaderIrInst.Fcleu, GetCleuExpr },
  62. { ShaderIrInst.Fclt, GetCltExpr },
  63. { ShaderIrInst.Fcltu, GetCltuExpr },
  64. { ShaderIrInst.Fcnan, GetCnanExpr },
  65. { ShaderIrInst.Fcne, GetCneExpr },
  66. { ShaderIrInst.Fcneu, GetCneuExpr },
  67. { ShaderIrInst.Fcnum, GetCnumExpr },
  68. { ShaderIrInst.Fcos, GetFcosExpr },
  69. { ShaderIrInst.Fex2, GetFex2Expr },
  70. { ShaderIrInst.Ffma, GetFfmaExpr },
  71. { ShaderIrInst.Flg2, GetFlg2Expr },
  72. { ShaderIrInst.Floor, GetFloorExpr },
  73. { ShaderIrInst.Fmax, GetMaxExpr },
  74. { ShaderIrInst.Fmin, GetMinExpr },
  75. { ShaderIrInst.Fmul, GetMulExpr },
  76. { ShaderIrInst.Fneg, GetNegExpr },
  77. { ShaderIrInst.Frcp, GetFrcpExpr },
  78. { ShaderIrInst.Frsq, GetFrsqExpr },
  79. { ShaderIrInst.Fsin, GetFsinExpr },
  80. { ShaderIrInst.Fsqrt, GetFsqrtExpr },
  81. { ShaderIrInst.Ftos, GetFtosExpr },
  82. { ShaderIrInst.Ftou, GetFtouExpr },
  83. { ShaderIrInst.Ipa, GetIpaExpr },
  84. { ShaderIrInst.Kil, GetKilExpr },
  85. { ShaderIrInst.Lsl, GetLslExpr },
  86. { ShaderIrInst.Lsr, GetLsrExpr },
  87. { ShaderIrInst.Max, GetMaxExpr },
  88. { ShaderIrInst.Min, GetMinExpr },
  89. { ShaderIrInst.Mul, GetMulExpr },
  90. { ShaderIrInst.Neg, GetNegExpr },
  91. { ShaderIrInst.Not, GetNotExpr },
  92. { ShaderIrInst.Or, GetOrExpr },
  93. { ShaderIrInst.Stof, GetStofExpr },
  94. { ShaderIrInst.Sub, GetSubExpr },
  95. { ShaderIrInst.Texb, GetTexbExpr },
  96. { ShaderIrInst.Texq, GetTexqExpr },
  97. { ShaderIrInst.Texs, GetTexsExpr },
  98. { ShaderIrInst.Tld4, GetTld4Expr },
  99. { ShaderIrInst.Trunc, GetTruncExpr },
  100. { ShaderIrInst.Txlf, GetTxlfExpr },
  101. { ShaderIrInst.Utof, GetUtofExpr },
  102. { ShaderIrInst.Xor, GetXorExpr }
  103. };
  104. MaxUboSize = maxUboSize / 16;
  105. _isNvidiaDriver = isNvidiaDriver;
  106. }
  107. public GlslProgram Decompile(
  108. IGalMemory memory,
  109. long vpAPosition,
  110. long vpBPosition,
  111. GalShaderType shaderType)
  112. {
  113. _header = new ShaderHeader(memory, vpAPosition);
  114. _headerB = new ShaderHeader(memory, vpBPosition);
  115. _blocks = ShaderDecoder.Decode(memory, vpAPosition);
  116. _blocksB = ShaderDecoder.Decode(memory, vpBPosition);
  117. GlslDecl declVpA = new GlslDecl(_blocks, shaderType, _header);
  118. GlslDecl declVpB = new GlslDecl(_blocksB, shaderType, _headerB);
  119. _decl = GlslDecl.Merge(declVpA, declVpB);
  120. return Decompile();
  121. }
  122. public GlslProgram Decompile(IGalMemory memory, long position, GalShaderType shaderType)
  123. {
  124. _header = new ShaderHeader(memory, position);
  125. _headerB = null;
  126. _blocks = ShaderDecoder.Decode(memory, position);
  127. _blocksB = null;
  128. _decl = new GlslDecl(_blocks, shaderType, _header);
  129. return Decompile();
  130. }
  131. private GlslProgram Decompile()
  132. {
  133. _sb = new StringBuilder();
  134. _sb.AppendLine("#version 410 core");
  135. PrintDeclHeader();
  136. PrintDeclTextures();
  137. PrintDeclUniforms();
  138. PrintDeclAttributes();
  139. PrintDeclInAttributes();
  140. PrintDeclOutAttributes();
  141. PrintDeclGprs();
  142. PrintDeclPreds();
  143. PrintDeclSsy();
  144. if (_blocksB != null)
  145. {
  146. PrintBlockScope(_blocks, GlslDecl.BasicBlockAName);
  147. _sb.AppendLine();
  148. PrintBlockScope(_blocksB, GlslDecl.BasicBlockBName);
  149. }
  150. else
  151. {
  152. PrintBlockScope(_blocks, GlslDecl.BasicBlockName);
  153. }
  154. _sb.AppendLine();
  155. PrintMain();
  156. string glslCode = _sb.ToString();
  157. List<ShaderDeclInfo> textureInfo = new List<ShaderDeclInfo>();
  158. textureInfo.AddRange(_decl.Textures.Values);
  159. textureInfo.AddRange(IterateCbTextures());
  160. return new GlslProgram(glslCode, textureInfo, _decl.Uniforms.Values);
  161. }
  162. private void PrintDeclHeader()
  163. {
  164. if (_decl.ShaderType == GalShaderType.Geometry)
  165. {
  166. int maxVertices = _header.MaxOutputVertexCount;
  167. string outputTopology;
  168. switch (_header.OutputTopology)
  169. {
  170. case ShaderHeader.PointList: outputTopology = "points"; break;
  171. case ShaderHeader.LineStrip: outputTopology = "line_strip"; break;
  172. case ShaderHeader.TriangleStrip: outputTopology = "triangle_strip"; break;
  173. default: throw new InvalidOperationException();
  174. }
  175. _sb.AppendLine("#extension GL_ARB_enhanced_layouts : require");
  176. _sb.AppendLine();
  177. _sb.AppendLine("// Stubbed. Maxwell geometry shaders don't inform input geometry type");
  178. _sb.AppendLine("layout(triangles) in;" + Environment.NewLine);
  179. _sb.AppendLine($"layout({outputTopology}, max_vertices = {maxVertices}) out;");
  180. _sb.AppendLine();
  181. }
  182. }
  183. private string GetSamplerType(TextureTarget textureTarget, bool hasShadow)
  184. {
  185. string result;
  186. switch (textureTarget)
  187. {
  188. case TextureTarget.Texture1D:
  189. result = "sampler1D";
  190. break;
  191. case TextureTarget.Texture2D:
  192. result = "sampler2D";
  193. break;
  194. case TextureTarget.Texture3D:
  195. result = "sampler3D";
  196. break;
  197. case TextureTarget.TextureCubeMap:
  198. result = "samplerCube";
  199. break;
  200. case TextureTarget.TextureRectangle:
  201. result = "sampler2DRect";
  202. break;
  203. case TextureTarget.Texture1DArray:
  204. result = "sampler1DArray";
  205. break;
  206. case TextureTarget.Texture2DArray:
  207. result = "sampler2DArray";
  208. break;
  209. case TextureTarget.TextureCubeMapArray:
  210. result = "samplerCubeArray";
  211. break;
  212. case TextureTarget.TextureBuffer:
  213. result = "samplerBuffer";
  214. break;
  215. case TextureTarget.Texture2DMultisample:
  216. result = "sampler2DMS";
  217. break;
  218. case TextureTarget.Texture2DMultisampleArray:
  219. result = "sampler2DMSArray";
  220. break;
  221. default:
  222. throw new NotSupportedException();
  223. }
  224. if (hasShadow)
  225. result += "Shadow";
  226. return result;
  227. }
  228. private void PrintDeclTextures()
  229. {
  230. foreach (ShaderDeclInfo declInfo in IterateCbTextures())
  231. {
  232. TextureTarget target = ImageUtils.GetTextureTarget(declInfo.TextureTarget);
  233. _sb.AppendLine($"// {declInfo.TextureSuffix}");
  234. _sb.AppendLine("uniform " + GetSamplerType(target, (declInfo.TextureSuffix & TextureInstructionSuffix.Dc) != 0) + " " + declInfo.Name + ";");
  235. }
  236. foreach (ShaderDeclInfo declInfo in _decl.Textures.Values.OrderBy(DeclKeySelector))
  237. {
  238. TextureTarget target = ImageUtils.GetTextureTarget(declInfo.TextureTarget);
  239. _sb.AppendLine($"// {declInfo.TextureSuffix}");
  240. _sb.AppendLine("uniform " + GetSamplerType(target, (declInfo.TextureSuffix & TextureInstructionSuffix.Dc) != 0) + " " + declInfo.Name + ";");
  241. }
  242. }
  243. private IEnumerable<ShaderDeclInfo> IterateCbTextures()
  244. {
  245. HashSet<string> names = new HashSet<string>();
  246. foreach (ShaderDeclInfo declInfo in _decl.CbTextures.Values.OrderBy(DeclKeySelector))
  247. {
  248. if (names.Add(declInfo.Name))
  249. {
  250. yield return declInfo;
  251. }
  252. }
  253. }
  254. private void PrintDeclUniforms()
  255. {
  256. if (_decl.ShaderType == GalShaderType.Vertex)
  257. {
  258. //Memory layout here is [flip_x, flip_y, instance, unused]
  259. //It's using 4 bytes, not 8
  260. _sb.AppendLine("layout (std140) uniform " + GlslDecl.ExtraUniformBlockName + " {");
  261. _sb.AppendLine(IdentationStr + "vec2 " + GlslDecl.FlipUniformName + ";");
  262. _sb.AppendLine(IdentationStr + "int " + GlslDecl.InstanceUniformName + ";");
  263. _sb.AppendLine("};");
  264. _sb.AppendLine();
  265. }
  266. foreach (ShaderDeclInfo declInfo in _decl.Uniforms.Values.OrderBy(DeclKeySelector))
  267. {
  268. _sb.AppendLine($"layout (std140) uniform {declInfo.Name} {{");
  269. _sb.AppendLine($"{IdentationStr}vec4 {declInfo.Name}_data[{MaxUboSize}];");
  270. _sb.AppendLine("};");
  271. }
  272. if (_decl.Uniforms.Count > 0)
  273. {
  274. _sb.AppendLine();
  275. }
  276. }
  277. private void PrintDeclAttributes()
  278. {
  279. string geometryArray = (_decl.ShaderType == GalShaderType.Geometry) ? "[" + MaxVertexInput + "]" : "";
  280. PrintDecls(_decl.Attributes, suffix: geometryArray);
  281. }
  282. private void PrintDeclInAttributes()
  283. {
  284. if (_decl.ShaderType == GalShaderType.Fragment)
  285. {
  286. _sb.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";");
  287. }
  288. if (_decl.ShaderType == GalShaderType.Geometry)
  289. {
  290. if (_decl.InAttributes.Count > 0)
  291. {
  292. _sb.AppendLine("in Vertex {");
  293. foreach (ShaderDeclInfo declInfo in _decl.InAttributes.Values.OrderBy(DeclKeySelector))
  294. {
  295. if (declInfo.Index >= 0)
  296. {
  297. _sb.AppendLine(IdentationStr + "layout (location = " + declInfo.Index + ") vec4 " + declInfo.Name + "; ");
  298. }
  299. }
  300. _sb.AppendLine("} block_in[];" + Environment.NewLine);
  301. }
  302. }
  303. else
  304. {
  305. PrintDeclAttributes(_decl.InAttributes.Values, "in");
  306. }
  307. }
  308. private void PrintDeclOutAttributes()
  309. {
  310. if (_decl.ShaderType == GalShaderType.Fragment)
  311. {
  312. int count = 0;
  313. for (int attachment = 0; attachment < 8; attachment++)
  314. {
  315. if (_header.OmapTargets[attachment].Enabled)
  316. {
  317. _sb.AppendLine("layout (location = " + attachment + ") out vec4 " + GlslDecl.FragmentOutputName + attachment + ";");
  318. count++;
  319. }
  320. }
  321. if (count > 0)
  322. {
  323. _sb.AppendLine();
  324. }
  325. }
  326. else
  327. {
  328. _sb.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") out vec4 " + GlslDecl.PositionOutAttrName + ";");
  329. _sb.AppendLine();
  330. }
  331. PrintDeclAttributes(_decl.OutAttributes.Values, "out");
  332. }
  333. private void PrintDeclAttributes(IEnumerable<ShaderDeclInfo> decls, string inOut)
  334. {
  335. int count = 0;
  336. foreach (ShaderDeclInfo declInfo in decls.OrderBy(DeclKeySelector))
  337. {
  338. if (declInfo.Index >= 0)
  339. {
  340. _sb.AppendLine("layout (location = " + declInfo.Index + ") " + inOut + " vec4 " + declInfo.Name + ";");
  341. count++;
  342. }
  343. }
  344. if (count > 0)
  345. {
  346. _sb.AppendLine();
  347. }
  348. }
  349. private void PrintDeclGprs()
  350. {
  351. PrintDecls(_decl.Gprs);
  352. PrintDecls(_decl.GprsHalf);
  353. }
  354. private void PrintDeclPreds()
  355. {
  356. PrintDecls(_decl.Preds, "bool");
  357. }
  358. private void PrintDeclSsy()
  359. {
  360. _sb.AppendLine("uint " + GlslDecl.SsyCursorName + " = 0;");
  361. _sb.AppendLine("uint " + GlslDecl.SsyStackName + "[" + GlslDecl.SsyStackSize + "];" + Environment.NewLine);
  362. }
  363. private void PrintDecls(IReadOnlyDictionary<int, ShaderDeclInfo> dict, string customType = null, string suffix = "")
  364. {
  365. foreach (ShaderDeclInfo declInfo in dict.Values.OrderBy(DeclKeySelector))
  366. {
  367. string name;
  368. if (customType != null)
  369. {
  370. name = customType + " " + declInfo.Name + suffix + ";";
  371. }
  372. else if (declInfo.Name.Contains(GlslDecl.FragmentOutputName))
  373. {
  374. name = "layout (location = " + declInfo.Index / 4 + ") out vec4 " + declInfo.Name + suffix + ";";
  375. }
  376. else
  377. {
  378. name = GetDecl(declInfo) + suffix + ";";
  379. }
  380. _sb.AppendLine(name);
  381. }
  382. if (dict.Count > 0)
  383. {
  384. _sb.AppendLine();
  385. }
  386. }
  387. private int DeclKeySelector(ShaderDeclInfo declInfo)
  388. {
  389. return declInfo.Cbuf << 24 | declInfo.Index;
  390. }
  391. private string GetDecl(ShaderDeclInfo declInfo)
  392. {
  393. if (declInfo.Size == 4)
  394. {
  395. return "vec4 " + declInfo.Name;
  396. }
  397. else
  398. {
  399. return "float " + declInfo.Name;
  400. }
  401. }
  402. private void PrintMain()
  403. {
  404. _sb.AppendLine("void main() {");
  405. foreach (KeyValuePair<int, ShaderDeclInfo> kv in _decl.InAttributes)
  406. {
  407. if (!_decl.Attributes.TryGetValue(kv.Key, out ShaderDeclInfo attr))
  408. {
  409. continue;
  410. }
  411. ShaderDeclInfo declInfo = kv.Value;
  412. if (_decl.ShaderType == GalShaderType.Geometry)
  413. {
  414. for (int vertex = 0; vertex < MaxVertexInput; vertex++)
  415. {
  416. string dst = attr.Name + "[" + vertex + "]";
  417. string src = "block_in[" + vertex + "]." + declInfo.Name;
  418. _sb.AppendLine(IdentationStr + dst + " = " + src + ";");
  419. }
  420. }
  421. else
  422. {
  423. _sb.AppendLine(IdentationStr + attr.Name + " = " + declInfo.Name + ";");
  424. }
  425. }
  426. _sb.AppendLine(IdentationStr + "uint pc;");
  427. if (_blocksB != null)
  428. {
  429. PrintProgram(_blocks, GlslDecl.BasicBlockAName);
  430. PrintProgram(_blocksB, GlslDecl.BasicBlockBName);
  431. }
  432. else
  433. {
  434. PrintProgram(_blocks, GlslDecl.BasicBlockName);
  435. }
  436. if (_decl.ShaderType != GalShaderType.Geometry)
  437. {
  438. PrintAttrToOutput();
  439. }
  440. if (_decl.ShaderType == GalShaderType.Fragment)
  441. {
  442. if (_header.OmapDepth)
  443. {
  444. _sb.AppendLine(IdentationStr + "gl_FragDepth = " + GlslDecl.GetGprName(_header.DepthRegister) + ";");
  445. }
  446. int gprIndex = 0;
  447. for (int attachment = 0; attachment < 8; attachment++)
  448. {
  449. string output = GlslDecl.FragmentOutputName + attachment;
  450. OmapTarget target = _header.OmapTargets[attachment];
  451. for (int component = 0; component < 4; component++)
  452. {
  453. if (target.ComponentEnabled(component))
  454. {
  455. _sb.AppendLine(IdentationStr + output + "[" + component + "] = " + GlslDecl.GetGprName(gprIndex) + ";");
  456. gprIndex++;
  457. }
  458. }
  459. }
  460. }
  461. _sb.AppendLine("}");
  462. }
  463. private void PrintProgram(ShaderIrBlock[] blocks, string name)
  464. {
  465. const string ident1 = IdentationStr;
  466. const string ident2 = ident1 + IdentationStr;
  467. const string ident3 = ident2 + IdentationStr;
  468. const string ident4 = ident3 + IdentationStr;
  469. _sb.AppendLine(ident1 + "pc = " + GetBlockPosition(blocks[0]) + ";");
  470. _sb.AppendLine(ident1 + "do {");
  471. _sb.AppendLine(ident2 + "switch (pc) {");
  472. foreach (ShaderIrBlock block in blocks)
  473. {
  474. string functionName = block.Position.ToString("x8");
  475. _sb.AppendLine(ident3 + "case 0x" + functionName + ": pc = " + name + "_" + functionName + "(); break;");
  476. }
  477. _sb.AppendLine(ident3 + "default:");
  478. _sb.AppendLine(ident4 + "pc = 0;");
  479. _sb.AppendLine(ident4 + "break;");
  480. _sb.AppendLine(ident2 + "}");
  481. _sb.AppendLine(ident1 + "} while (pc != 0);");
  482. }
  483. private void PrintAttrToOutput(string identation = IdentationStr)
  484. {
  485. foreach (KeyValuePair<int, ShaderDeclInfo> kv in _decl.OutAttributes)
  486. {
  487. if (!_decl.Attributes.TryGetValue(kv.Key, out ShaderDeclInfo attr))
  488. {
  489. continue;
  490. }
  491. ShaderDeclInfo declInfo = kv.Value;
  492. string name = attr.Name;
  493. if (_decl.ShaderType == GalShaderType.Geometry)
  494. {
  495. name += "[0]";
  496. }
  497. _sb.AppendLine(identation + declInfo.Name + " = " + name + ";");
  498. }
  499. if (_decl.ShaderType == GalShaderType.Vertex)
  500. {
  501. _sb.AppendLine(identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";");
  502. }
  503. if (_decl.ShaderType != GalShaderType.Fragment)
  504. {
  505. _sb.AppendLine(identation + GlslDecl.PositionOutAttrName + " = gl_Position;");
  506. _sb.AppendLine(identation + GlslDecl.PositionOutAttrName + ".w = 1;");
  507. }
  508. }
  509. private void PrintBlockScope(ShaderIrBlock[] blocks, string name)
  510. {
  511. foreach (ShaderIrBlock block in blocks)
  512. {
  513. _sb.AppendLine("uint " + name + "_" + block.Position.ToString("x8") + "() {");
  514. PrintNodes(block, block.GetNodes());
  515. _sb.AppendLine("}" + Environment.NewLine);
  516. }
  517. }
  518. private void PrintNodes(ShaderIrBlock block, ShaderIrNode[] nodes)
  519. {
  520. foreach (ShaderIrNode node in nodes)
  521. {
  522. PrintNode(block, node, IdentationStr);
  523. }
  524. if (nodes.Length == 0)
  525. {
  526. _sb.AppendLine(IdentationStr + "return 0u;");
  527. return;
  528. }
  529. ShaderIrNode last = nodes[nodes.Length - 1];
  530. bool unconditionalFlowChange = false;
  531. if (last is ShaderIrOp op)
  532. {
  533. switch (op.Inst)
  534. {
  535. case ShaderIrInst.Bra:
  536. case ShaderIrInst.Exit:
  537. case ShaderIrInst.Sync:
  538. unconditionalFlowChange = true;
  539. break;
  540. }
  541. }
  542. if (!unconditionalFlowChange)
  543. {
  544. if (block.Next != null)
  545. {
  546. _sb.AppendLine(IdentationStr + "return " + GetBlockPosition(block.Next) + ";");
  547. }
  548. else
  549. {
  550. _sb.AppendLine(IdentationStr + "return 0u;");
  551. }
  552. }
  553. }
  554. private void PrintNode(ShaderIrBlock block, ShaderIrNode node, string identation)
  555. {
  556. if (node is ShaderIrCond cond)
  557. {
  558. string ifExpr = GetSrcExpr(cond.Pred, true);
  559. if (cond.Not)
  560. {
  561. ifExpr = "!(" + ifExpr + ")";
  562. }
  563. _sb.AppendLine(identation + "if (" + ifExpr + ") {");
  564. PrintNode(block, cond.Child, identation + IdentationStr);
  565. _sb.AppendLine(identation + "}");
  566. }
  567. else if (node is ShaderIrAsg asg)
  568. {
  569. if (IsValidOutOper(asg.Dst))
  570. {
  571. string expr = GetSrcExpr(asg.Src, true);
  572. expr = GetExprWithCast(asg.Dst, asg.Src, expr);
  573. _sb.AppendLine(identation + GetDstOperName(asg.Dst) + " = " + expr + ";");
  574. }
  575. }
  576. else if (node is ShaderIrOp op)
  577. {
  578. switch (op.Inst)
  579. {
  580. case ShaderIrInst.Bra:
  581. {
  582. _sb.AppendLine(identation + "return " + GetBlockPosition(block.Branch) + ";");
  583. break;
  584. }
  585. case ShaderIrInst.Emit:
  586. {
  587. PrintAttrToOutput(identation);
  588. _sb.AppendLine(identation + "EmitVertex();");
  589. break;
  590. }
  591. case ShaderIrInst.Ssy:
  592. {
  593. string stackIndex = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]";
  594. int targetPosition = (op.OperandA as ShaderIrOperImm).Value;
  595. string target = "0x" + targetPosition.ToString("x8") + "u";
  596. _sb.AppendLine(identation + stackIndex + " = " + target + ";");
  597. _sb.AppendLine(identation + GlslDecl.SsyCursorName + "++;");
  598. break;
  599. }
  600. case ShaderIrInst.Sync:
  601. {
  602. _sb.AppendLine(identation + GlslDecl.SsyCursorName + "--;");
  603. string target = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]";
  604. _sb.AppendLine(identation + "return " + target + ";");
  605. break;
  606. }
  607. default:
  608. _sb.AppendLine(identation + GetSrcExpr(op, true) + ";");
  609. break;
  610. }
  611. }
  612. else if (node is ShaderIrCmnt cmnt)
  613. {
  614. _sb.AppendLine(identation + "// " + cmnt.Comment);
  615. }
  616. else
  617. {
  618. throw new InvalidOperationException();
  619. }
  620. }
  621. private bool IsValidOutOper(ShaderIrNode node)
  622. {
  623. if (node is ShaderIrOperGpr gpr && gpr.IsConst)
  624. {
  625. return false;
  626. }
  627. else if (node is ShaderIrOperPred pred && pred.IsConst)
  628. {
  629. return false;
  630. }
  631. return true;
  632. }
  633. private string GetDstOperName(ShaderIrNode node)
  634. {
  635. if (node is ShaderIrOperAbuf abuf)
  636. {
  637. return GetOutAbufName(abuf);
  638. }
  639. else if (node is ShaderIrOperGpr gpr)
  640. {
  641. return GetName(gpr);
  642. }
  643. else if (node is ShaderIrOperPred pred)
  644. {
  645. return GetName(pred);
  646. }
  647. throw new ArgumentException(nameof(node));
  648. }
  649. private string GetSrcExpr(ShaderIrNode node, bool entry = false)
  650. {
  651. switch (node)
  652. {
  653. case ShaderIrOperAbuf abuf: return GetName (abuf);
  654. case ShaderIrOperCbuf cbuf: return GetName (cbuf);
  655. case ShaderIrOperGpr gpr: return GetName (gpr);
  656. case ShaderIrOperImm imm: return GetValue(imm);
  657. case ShaderIrOperImmf immf: return GetValue(immf);
  658. case ShaderIrOperPred pred: return GetName (pred);
  659. case ShaderIrOp op:
  660. string expr;
  661. if (_instsExpr.TryGetValue(op.Inst, out GetInstExpr getExpr))
  662. {
  663. expr = getExpr(op);
  664. }
  665. else
  666. {
  667. throw new NotImplementedException(op.Inst.ToString());
  668. }
  669. if (!entry && NeedsParentheses(op))
  670. {
  671. expr = "(" + expr + ")";
  672. }
  673. return expr;
  674. default: throw new ArgumentException(nameof(node));
  675. }
  676. }
  677. private static bool NeedsParentheses(ShaderIrOp op)
  678. {
  679. switch (op.Inst)
  680. {
  681. case ShaderIrInst.Ipa:
  682. case ShaderIrInst.Texq:
  683. case ShaderIrInst.Texs:
  684. case ShaderIrInst.Tld4:
  685. case ShaderIrInst.Txlf:
  686. return false;
  687. }
  688. return true;
  689. }
  690. private string GetName(ShaderIrOperCbuf cbuf)
  691. {
  692. if (!_decl.Uniforms.TryGetValue(cbuf.Index, out ShaderDeclInfo declInfo))
  693. {
  694. throw new InvalidOperationException();
  695. }
  696. if (cbuf.Offs != null)
  697. {
  698. string offset = "floatBitsToInt(" + GetSrcExpr(cbuf.Offs) + ")";
  699. string index = "(" + cbuf.Pos * 4 + " + " + offset + ")";
  700. return $"{declInfo.Name}_data[{index} / 16][({index} / 4) % 4]";
  701. }
  702. else
  703. {
  704. return $"{declInfo.Name}_data[{cbuf.Pos / 4}][{cbuf.Pos % 4}]";
  705. }
  706. }
  707. private string GetOutAbufName(ShaderIrOperAbuf abuf)
  708. {
  709. if (_decl.ShaderType == GalShaderType.Geometry)
  710. {
  711. switch (abuf.Offs)
  712. {
  713. case GlslDecl.LayerAttr: return "gl_Layer";
  714. }
  715. }
  716. return GetAttrTempName(abuf);
  717. }
  718. private string GetName(ShaderIrOperAbuf abuf)
  719. {
  720. //Handle special scalar read-only attributes here.
  721. if (_decl.ShaderType == GalShaderType.Vertex)
  722. {
  723. switch (abuf.Offs)
  724. {
  725. case GlslDecl.VertexIdAttr: return "gl_VertexID";
  726. case GlslDecl.InstanceIdAttr: return GlslDecl.InstanceUniformName;
  727. }
  728. }
  729. else if (_decl.ShaderType == GalShaderType.TessEvaluation)
  730. {
  731. switch (abuf.Offs)
  732. {
  733. case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x";
  734. case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y";
  735. case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z";
  736. }
  737. }
  738. else if (_decl.ShaderType == GalShaderType.Fragment)
  739. {
  740. switch (abuf.Offs)
  741. {
  742. case GlslDecl.PointCoordAttrX: return "gl_PointCoord.x";
  743. case GlslDecl.PointCoordAttrY: return "gl_PointCoord.y";
  744. case GlslDecl.FaceAttr: return "(gl_FrontFacing ? -1 : 0)";
  745. }
  746. }
  747. return GetAttrTempName(abuf);
  748. }
  749. private string GetAttrTempName(ShaderIrOperAbuf abuf)
  750. {
  751. int index = abuf.Offs >> 4;
  752. int elem = (abuf.Offs >> 2) & 3;
  753. string swizzle = "." + GetAttrSwizzle(elem);
  754. if (!_decl.Attributes.TryGetValue(index, out ShaderDeclInfo declInfo))
  755. {
  756. //Handle special vec4 attributes here
  757. //(for example, index 7 is always gl_Position).
  758. if (index == GlslDecl.GlPositionVec4Index)
  759. {
  760. string name =
  761. _decl.ShaderType != GalShaderType.Vertex &&
  762. _decl.ShaderType != GalShaderType.Geometry ? GlslDecl.PositionOutAttrName : "gl_Position";
  763. return name + swizzle;
  764. }
  765. else if (abuf.Offs == GlslDecl.PointSizeAttr)
  766. {
  767. return "gl_PointSize";
  768. }
  769. }
  770. if (declInfo.Index >= 32)
  771. {
  772. throw new InvalidOperationException($"Shader attribute offset {abuf.Offs} is invalid.");
  773. }
  774. if (_decl.ShaderType == GalShaderType.Geometry)
  775. {
  776. string vertex = "floatBitsToInt(" + GetSrcExpr(abuf.Vertex) + ")";
  777. return declInfo.Name + "[" + vertex + "]" + swizzle;
  778. }
  779. else
  780. {
  781. return declInfo.Name + swizzle;
  782. }
  783. }
  784. private string GetName(ShaderIrOperGpr gpr)
  785. {
  786. if (gpr.IsConst)
  787. {
  788. return "0";
  789. }
  790. if (gpr.RegisterSize == ShaderRegisterSize.Single)
  791. {
  792. return GetNameWithSwizzle(_decl.Gprs, gpr.Index);
  793. }
  794. else if (gpr.RegisterSize == ShaderRegisterSize.Half)
  795. {
  796. return GetNameWithSwizzle(_decl.GprsHalf, (gpr.Index << 1) | gpr.HalfPart);
  797. }
  798. else /* if (Gpr.RegisterSize == ShaderRegisterSize.Double) */
  799. {
  800. throw new NotImplementedException("Double types are not supported.");
  801. }
  802. }
  803. private string GetValue(ShaderIrOperImm imm)
  804. {
  805. //Only use hex is the value is too big and would likely be hard to read as int.
  806. if (imm.Value > 0xfff ||
  807. imm.Value < -0xfff)
  808. {
  809. return "0x" + imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  810. }
  811. else
  812. {
  813. return GetIntConst(imm.Value);
  814. }
  815. }
  816. private string GetValue(ShaderIrOperImmf immf)
  817. {
  818. return GetFloatConst(immf.Value);
  819. }
  820. private string GetName(ShaderIrOperPred pred)
  821. {
  822. return pred.IsConst ? "true" : GetNameWithSwizzle(_decl.Preds, pred.Index);
  823. }
  824. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> dict, int index)
  825. {
  826. int vecIndex = index & ~3;
  827. if (dict.TryGetValue(vecIndex, out ShaderDeclInfo declInfo))
  828. {
  829. if (declInfo.Size > 1 && index < vecIndex + declInfo.Size)
  830. {
  831. return declInfo.Name + "." + GetAttrSwizzle(index & 3);
  832. }
  833. }
  834. if (!dict.TryGetValue(index, out declInfo))
  835. {
  836. throw new InvalidOperationException();
  837. }
  838. return declInfo.Name;
  839. }
  840. private string GetAttrSwizzle(int elem)
  841. {
  842. return "xyzw".Substring(elem, 1);
  843. }
  844. private string GetAbsExpr(ShaderIrOp op) => GetUnaryCall(op, "abs");
  845. private string GetAddExpr(ShaderIrOp op) => GetBinaryExpr(op, "+");
  846. private string GetAndExpr(ShaderIrOp op) => GetBinaryExpr(op, "&");
  847. private string GetAsrExpr(ShaderIrOp op) => GetBinaryExpr(op, ">>");
  848. private string GetBandExpr(ShaderIrOp op) => GetBinaryExpr(op, "&&");
  849. private string GetBnotExpr(ShaderIrOp op) => GetUnaryExpr(op, "!");
  850. private string GetBorExpr(ShaderIrOp op) => GetBinaryExpr(op, "||");
  851. private string GetBxorExpr(ShaderIrOp op) => GetBinaryExpr(op, "^^");
  852. private string GetCeilExpr(ShaderIrOp op) => GetUnaryCall(op, "ceil");
  853. private string GetClampsExpr(ShaderIrOp op)
  854. {
  855. return "clamp(" + GetOperExpr(op, op.OperandA) + ", " +
  856. GetOperExpr(op, op.OperandB) + ", " +
  857. GetOperExpr(op, op.OperandC) + ")";
  858. }
  859. private string GetClampuExpr(ShaderIrOp op)
  860. {
  861. return "int(clamp(uint(" + GetOperExpr(op, op.OperandA) + "), " +
  862. "uint(" + GetOperExpr(op, op.OperandB) + "), " +
  863. "uint(" + GetOperExpr(op, op.OperandC) + ")))";
  864. }
  865. private string GetCeqExpr(ShaderIrOp op) => GetBinaryExpr(op, "==");
  866. private string GetCequExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, "==");
  867. private string GetCgeExpr(ShaderIrOp op) => GetBinaryExpr(op, ">=");
  868. private string GetCgeuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, ">=");
  869. private string GetCgtExpr(ShaderIrOp op) => GetBinaryExpr(op, ">");
  870. private string GetCgtuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, ">");
  871. private string GetCleExpr(ShaderIrOp op) => GetBinaryExpr(op, "<=");
  872. private string GetCleuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, "<=");
  873. private string GetCltExpr(ShaderIrOp op) => GetBinaryExpr(op, "<");
  874. private string GetCltuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, "<");
  875. private string GetCnanExpr(ShaderIrOp op) => GetUnaryCall(op, "isnan");
  876. private string GetCneExpr(ShaderIrOp op) => GetBinaryExpr(op, "!=");
  877. private string GetCutExpr(ShaderIrOp op) => "EndPrimitive()";
  878. private string GetCneuExpr(ShaderIrOp op) => GetBinaryExprWithNaN(op, "!=");
  879. private string GetCnumExpr(ShaderIrOp op) => GetUnaryCall(op, "!isnan");
  880. private string GetExitExpr(ShaderIrOp op) => "return 0u";
  881. private string GetFcosExpr(ShaderIrOp op) => GetUnaryCall(op, "cos");
  882. private string GetFex2Expr(ShaderIrOp op) => GetUnaryCall(op, "exp2");
  883. private string GetFfmaExpr(ShaderIrOp op) => GetTernaryExpr(op, "*", "+");
  884. private string GetFclampExpr(ShaderIrOp op) => GetTernaryCall(op, "clamp");
  885. private string GetFlg2Expr(ShaderIrOp op) => GetUnaryCall(op, "log2");
  886. private string GetFloorExpr(ShaderIrOp op) => GetUnaryCall(op, "floor");
  887. private string GetFrcpExpr(ShaderIrOp op) => GetUnaryExpr(op, "1 / ");
  888. private string GetFrsqExpr(ShaderIrOp op) => GetUnaryCall(op, "inversesqrt");
  889. private string GetFsinExpr(ShaderIrOp op) => GetUnaryCall(op, "sin");
  890. private string GetFsqrtExpr(ShaderIrOp op) => GetUnaryCall(op, "sqrt");
  891. private string GetFtosExpr(ShaderIrOp op)
  892. {
  893. return "int(" + GetOperExpr(op, op.OperandA) + ")";
  894. }
  895. private string GetFtouExpr(ShaderIrOp op)
  896. {
  897. return "int(uint(" + GetOperExpr(op, op.OperandA) + "))";
  898. }
  899. private string GetIpaExpr(ShaderIrOp op)
  900. {
  901. ShaderIrMetaIpa meta = (ShaderIrMetaIpa)op.MetaData;
  902. ShaderIrOperAbuf abuf = (ShaderIrOperAbuf)op.OperandA;
  903. if (meta.Mode == ShaderIpaMode.Pass)
  904. {
  905. int index = abuf.Offs >> 4;
  906. int elem = (abuf.Offs >> 2) & 3;
  907. if (_decl.ShaderType == GalShaderType.Fragment && index == GlslDecl.GlPositionVec4Index)
  908. {
  909. switch (elem)
  910. {
  911. case 0: return "gl_FragCoord.x";
  912. case 1: return "gl_FragCoord.y";
  913. case 2: return "gl_FragCoord.z";
  914. case 3: return "1";
  915. }
  916. }
  917. }
  918. return GetSrcExpr(op.OperandA);
  919. }
  920. private string GetKilExpr(ShaderIrOp op) => "discard";
  921. private string GetLslExpr(ShaderIrOp op) => GetBinaryExpr(op, "<<");
  922. private string GetLsrExpr(ShaderIrOp op)
  923. {
  924. return "int(uint(" + GetOperExpr(op, op.OperandA) + ") >> " +
  925. GetOperExpr(op, op.OperandB) + ")";
  926. }
  927. private string GetMaxExpr(ShaderIrOp op) => GetBinaryCall(op, "max");
  928. private string GetMinExpr(ShaderIrOp op) => GetBinaryCall(op, "min");
  929. private string GetMulExpr(ShaderIrOp op) => GetBinaryExpr(op, "*");
  930. private string GetNegExpr(ShaderIrOp op) => GetUnaryExpr(op, "-");
  931. private string GetNotExpr(ShaderIrOp op) => GetUnaryExpr(op, "~");
  932. private string GetOrExpr(ShaderIrOp op) => GetBinaryExpr(op, "|");
  933. private string GetStofExpr(ShaderIrOp op)
  934. {
  935. return "float(" + GetOperExpr(op, op.OperandA) + ")";
  936. }
  937. private string GetSubExpr(ShaderIrOp op) => GetBinaryExpr(op, "-");
  938. private string GetTexbExpr(ShaderIrOp op)
  939. {
  940. ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData;
  941. if (!_decl.CbTextures.TryGetValue(op, out ShaderDeclInfo declInfo))
  942. {
  943. throw new InvalidOperationException();
  944. }
  945. string coords = GetTexSamplerCoords(op);
  946. string ch = "rgba".Substring(meta.Elem, 1);
  947. return GetTextureOperation(op, declInfo.Name, coords, ch);
  948. }
  949. private string GetTexqExpr(ShaderIrOp op)
  950. {
  951. ShaderIrMetaTexq meta = (ShaderIrMetaTexq)op.MetaData;
  952. string ch = "xyzw".Substring(meta.Elem, 1);
  953. if (meta.Info == ShaderTexqInfo.Dimension)
  954. {
  955. string sampler = GetTexSamplerName(op);
  956. string lod = GetOperExpr(op, op.OperandA); //???
  957. return "textureSize(" + sampler + ", " + lod + ")." + ch;
  958. }
  959. else
  960. {
  961. throw new NotImplementedException(meta.Info.ToString());
  962. }
  963. }
  964. private string GetTexsExpr(ShaderIrOp op)
  965. {
  966. ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData;
  967. string sampler = GetTexSamplerName(op);
  968. string coords = GetTexSamplerCoords(op);
  969. string ch = "rgba".Substring(meta.Elem, 1);
  970. return GetTextureOperation(op, sampler, coords, ch);
  971. }
  972. private string GetTld4Expr(ShaderIrOp op)
  973. {
  974. ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData;
  975. string sampler = GetTexSamplerName(op);
  976. string coords = GetTexSamplerCoords(op);
  977. string ch = "rgba".Substring(meta.Elem, 1);
  978. return GetTextureGatherOperation(op, sampler, coords, ch);
  979. }
  980. // TODO: support AOFFI on non nvidia drivers
  981. private string GetTxlfExpr(ShaderIrOp op)
  982. {
  983. // TODO: Support all suffixes
  984. ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData;
  985. TextureInstructionSuffix suffix = meta.TextureInstructionSuffix;
  986. string sampler = GetTexSamplerName(op);
  987. string coords = GetITexSamplerCoords(op);
  988. string ch = "rgba".Substring(meta.Elem, 1);
  989. string lod = "0";
  990. if (meta.LevelOfDetail != null)
  991. {
  992. lod = GetOperExpr(op, meta.LevelOfDetail);
  993. }
  994. if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver)
  995. {
  996. string offset = GetTextureOffset(meta, GetOperExpr(op, meta.Offset));
  997. return "texelFetchOffset(" + sampler + ", " + coords + ", " + lod + ", " + offset + ")." + ch;
  998. }
  999. return "texelFetch(" + sampler + ", " + coords + ", " + lod + ")." + ch;
  1000. }
  1001. private string GetTruncExpr(ShaderIrOp op) => GetUnaryCall(op, "trunc");
  1002. private string GetUtofExpr(ShaderIrOp op)
  1003. {
  1004. return "float(uint(" + GetOperExpr(op, op.OperandA) + "))";
  1005. }
  1006. private string GetXorExpr(ShaderIrOp op) => GetBinaryExpr(op, "^");
  1007. private string GetUnaryCall(ShaderIrOp op, string funcName)
  1008. {
  1009. return funcName + "(" + GetOperExpr(op, op.OperandA) + ")";
  1010. }
  1011. private string GetBinaryCall(ShaderIrOp op, string funcName)
  1012. {
  1013. return funcName + "(" + GetOperExpr(op, op.OperandA) + ", " +
  1014. GetOperExpr(op, op.OperandB) + ")";
  1015. }
  1016. private string GetTernaryCall(ShaderIrOp op, string funcName)
  1017. {
  1018. return funcName + "(" + GetOperExpr(op, op.OperandA) + ", " +
  1019. GetOperExpr(op, op.OperandB) + ", " +
  1020. GetOperExpr(op, op.OperandC) + ")";
  1021. }
  1022. private string GetUnaryExpr(ShaderIrOp op, string opr)
  1023. {
  1024. return opr + GetOperExpr(op, op.OperandA);
  1025. }
  1026. private string GetBinaryExpr(ShaderIrOp op, string opr)
  1027. {
  1028. return GetOperExpr(op, op.OperandA) + " " + opr + " " +
  1029. GetOperExpr(op, op.OperandB);
  1030. }
  1031. private string GetBinaryExprWithNaN(ShaderIrOp op, string opr)
  1032. {
  1033. string a = GetOperExpr(op, op.OperandA);
  1034. string b = GetOperExpr(op, op.OperandB);
  1035. string nanCheck =
  1036. " || isnan(" + a + ")" +
  1037. " || isnan(" + b + ")";
  1038. return a + " " + opr + " " + b + nanCheck;
  1039. }
  1040. private string GetTernaryExpr(ShaderIrOp op, string opr1, string opr2)
  1041. {
  1042. return GetOperExpr(op, op.OperandA) + " " + opr1 + " " +
  1043. GetOperExpr(op, op.OperandB) + " " + opr2 + " " +
  1044. GetOperExpr(op, op.OperandC);
  1045. }
  1046. private string GetTexSamplerName(ShaderIrOp op)
  1047. {
  1048. ShaderIrOperImm node = (ShaderIrOperImm)op.OperandC;
  1049. int handle = ((ShaderIrOperImm)op.OperandC).Value;
  1050. if (!_decl.Textures.TryGetValue(handle, out ShaderDeclInfo declInfo))
  1051. {
  1052. throw new InvalidOperationException();
  1053. }
  1054. return declInfo.Name;
  1055. }
  1056. private string GetTexSamplerCoords(ShaderIrOp op)
  1057. {
  1058. ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData;
  1059. bool hasDepth = (meta.TextureInstructionSuffix & TextureInstructionSuffix.Dc) != 0;
  1060. int coords = ImageUtils.GetCoordsCountTextureTarget(meta.TextureTarget);
  1061. bool isArray = ImageUtils.IsArray(meta.TextureTarget);
  1062. string GetLastArgument(ShaderIrNode node)
  1063. {
  1064. string result = GetOperExpr(op, node);
  1065. // array index is actually an integer so we need to pass it correctly
  1066. if (isArray)
  1067. {
  1068. result = "float(floatBitsToInt(" + result + "))";
  1069. }
  1070. return result;
  1071. }
  1072. string lastArgument;
  1073. string depthArgument = "";
  1074. int vecSize = coords;
  1075. if (hasDepth && op.Inst != ShaderIrInst.Tld4)
  1076. {
  1077. vecSize++;
  1078. depthArgument = $", {GetOperExpr(op, meta.DepthCompare)}";
  1079. }
  1080. switch (coords)
  1081. {
  1082. case 1:
  1083. if (hasDepth)
  1084. {
  1085. return $"vec3({GetOperExpr(op, meta.Coordinates[0])}, 0.0{depthArgument})";
  1086. }
  1087. return GetOperExpr(op, meta.Coordinates[0]);
  1088. case 2:
  1089. lastArgument = GetLastArgument(meta.Coordinates[1]);
  1090. return $"vec{vecSize}({GetOperExpr(op, meta.Coordinates[0])}, {lastArgument}{depthArgument})";
  1091. case 3:
  1092. lastArgument = GetLastArgument(meta.Coordinates[2]);
  1093. return $"vec{vecSize}({GetOperExpr(op, meta.Coordinates[0])}, {GetOperExpr(op, meta.Coordinates[1])}, {lastArgument}{depthArgument})";
  1094. case 4:
  1095. lastArgument = GetLastArgument(meta.Coordinates[3]);
  1096. return $"vec4({GetOperExpr(op, meta.Coordinates[0])}, {GetOperExpr(op, meta.Coordinates[1])}, {GetOperExpr(op, meta.Coordinates[2])}, {lastArgument}){depthArgument}";
  1097. default:
  1098. throw new InvalidOperationException();
  1099. }
  1100. }
  1101. private string GetTextureOffset(ShaderIrMetaTex meta, string oper, int shift = 4, int mask = 0xF)
  1102. {
  1103. string GetOffset(string operation, int index)
  1104. {
  1105. return $"({operation} >> {index * shift}) & 0x{mask:x}";
  1106. }
  1107. int coords = ImageUtils.GetCoordsCountTextureTarget(meta.TextureTarget);
  1108. if (ImageUtils.IsArray(meta.TextureTarget))
  1109. coords -= 1;
  1110. switch (coords)
  1111. {
  1112. case 1:
  1113. return GetOffset(oper, 0);
  1114. case 2:
  1115. return "ivec2(" + GetOffset(oper, 0) + ", " + GetOffset(oper, 1) + ")";
  1116. case 3:
  1117. return "ivec3(" + GetOffset(oper, 0) + ", " + GetOffset(oper, 1) + ", " + GetOffset(oper, 2) + ")";
  1118. case 4:
  1119. return "ivec4(" + GetOffset(oper, 0) + ", " + GetOffset(oper, 1) + ", " + GetOffset(oper, 2) + ", " + GetOffset(oper, 3) + ")";
  1120. default:
  1121. throw new InvalidOperationException();
  1122. }
  1123. }
  1124. // TODO: support AOFFI on non nvidia drivers
  1125. private string GetTextureGatherOperation(ShaderIrOp op, string sampler, string coords, string ch)
  1126. {
  1127. ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData;
  1128. TextureInstructionSuffix suffix = meta.TextureInstructionSuffix;
  1129. string chString = "." + ch;
  1130. string comp = meta.Component.ToString();
  1131. if ((suffix & TextureInstructionSuffix.Dc) != 0)
  1132. {
  1133. comp = GetOperExpr(op, meta.DepthCompare);
  1134. }
  1135. if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver)
  1136. {
  1137. string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))", 8, 0x3F);
  1138. if ((suffix & TextureInstructionSuffix.Dc) != 0)
  1139. {
  1140. return "textureGatherOffset(" + sampler + ", " + coords + ", " + comp + ", " + offset + ")" + chString;
  1141. }
  1142. return "textureGatherOffset(" + sampler + ", " + coords + ", " + offset + ", " + comp + ")" + chString;
  1143. }
  1144. // TODO: Support PTP
  1145. else if ((suffix & TextureInstructionSuffix.Ptp) != 0)
  1146. {
  1147. throw new NotImplementedException();
  1148. }
  1149. return "textureGather(" + sampler + ", " + coords + ", " + comp + ")" + chString;
  1150. }
  1151. // TODO: support AOFFI on non nvidia drivers
  1152. private string GetTextureOperation(ShaderIrOp op, string sampler, string coords, string ch)
  1153. {
  1154. ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData;
  1155. TextureInstructionSuffix suffix = meta.TextureInstructionSuffix;
  1156. string chString = "." + ch;
  1157. if ((suffix & TextureInstructionSuffix.Dc) != 0)
  1158. {
  1159. chString = "";
  1160. }
  1161. // TODO: Support LBA and LLA
  1162. if ((suffix & TextureInstructionSuffix.Lz) != 0)
  1163. {
  1164. if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver)
  1165. {
  1166. string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))");
  1167. return "textureLodOffset(" + sampler + ", " + coords + ", 0.0, " + offset + ")" + chString;
  1168. }
  1169. return "textureLod(" + sampler + ", " + coords + ", 0.0)" + chString;
  1170. }
  1171. else if ((suffix & TextureInstructionSuffix.Lb) != 0)
  1172. {
  1173. if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver)
  1174. {
  1175. string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))");
  1176. return "textureOffset(" + sampler + ", " + coords + ", " + offset + ", " + GetOperExpr(op, meta.LevelOfDetail) + ")" + chString;
  1177. }
  1178. return "texture(" + sampler + ", " + coords + ", " + GetOperExpr(op, meta.LevelOfDetail) + ")" + chString;
  1179. }
  1180. else if ((suffix & TextureInstructionSuffix.Ll) != 0)
  1181. {
  1182. if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver)
  1183. {
  1184. string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))");
  1185. return "textureLodOffset(" + sampler + ", " + coords + ", " + GetOperExpr(op, meta.LevelOfDetail) + ", " + offset + ")" + chString;
  1186. }
  1187. return "textureLod(" + sampler + ", " + coords + ", " + GetOperExpr(op, meta.LevelOfDetail) + ")" + chString;
  1188. }
  1189. else if ((suffix & TextureInstructionSuffix.AOffI) != 0 && _isNvidiaDriver)
  1190. {
  1191. string offset = GetTextureOffset(meta, "floatBitsToInt((" + GetOperExpr(op, meta.Offset) + "))");
  1192. return "textureOffset(" + sampler + ", " + coords + ", " + offset + ")" + chString;
  1193. }
  1194. else
  1195. {
  1196. return "texture(" + sampler + ", " + coords + ")" + chString;
  1197. }
  1198. throw new NotImplementedException($"Texture Suffix {meta.TextureInstructionSuffix} is not implemented");
  1199. }
  1200. private string GetITexSamplerCoords(ShaderIrOp op)
  1201. {
  1202. ShaderIrMetaTex meta = (ShaderIrMetaTex)op.MetaData;
  1203. switch (ImageUtils.GetCoordsCountTextureTarget(meta.TextureTarget))
  1204. {
  1205. case 1:
  1206. return GetOperExpr(op, meta.Coordinates[0]);
  1207. case 2:
  1208. return "ivec2(" + GetOperExpr(op, meta.Coordinates[0]) + ", " + GetOperExpr(op, meta.Coordinates[1]) + ")";
  1209. case 3:
  1210. return "ivec3(" + GetOperExpr(op, meta.Coordinates[0]) + ", " + GetOperExpr(op, meta.Coordinates[1]) + ", " + GetOperExpr(op, meta.Coordinates[2]) + ")";
  1211. default:
  1212. throw new InvalidOperationException();
  1213. }
  1214. }
  1215. private string GetOperExpr(ShaderIrOp op, ShaderIrNode oper)
  1216. {
  1217. return GetExprWithCast(op, oper, GetSrcExpr(oper));
  1218. }
  1219. private static string GetExprWithCast(ShaderIrNode dst, ShaderIrNode src, string expr)
  1220. {
  1221. //Note: The "DstType" (of the cast) is the type that the operation
  1222. //uses on the source operands, while the "SrcType" is the destination
  1223. //type of the operand result (if it is a operation) or just the type
  1224. //of the variable for registers/uniforms/attributes.
  1225. OperType dstType = GetSrcNodeType(dst);
  1226. OperType srcType = GetDstNodeType(src);
  1227. if (dstType != srcType)
  1228. {
  1229. //Check for invalid casts
  1230. //(like bool to int/float and others).
  1231. if (srcType != OperType.F32 &&
  1232. srcType != OperType.I32)
  1233. {
  1234. throw new InvalidOperationException();
  1235. }
  1236. switch (src)
  1237. {
  1238. case ShaderIrOperGpr gpr:
  1239. {
  1240. //When the Gpr is ZR, just return the 0 value directly,
  1241. //since the float encoding for 0 is 0.
  1242. if (gpr.IsConst)
  1243. {
  1244. return "0";
  1245. }
  1246. break;
  1247. }
  1248. }
  1249. switch (dstType)
  1250. {
  1251. case OperType.F32: expr = "intBitsToFloat(" + expr + ")"; break;
  1252. case OperType.I32: expr = "floatBitsToInt(" + expr + ")"; break;
  1253. }
  1254. }
  1255. return expr;
  1256. }
  1257. private static string GetIntConst(int value)
  1258. {
  1259. string expr = value.ToString(CultureInfo.InvariantCulture);
  1260. return value < 0 ? "(" + expr + ")" : expr;
  1261. }
  1262. private static string GetFloatConst(float value)
  1263. {
  1264. string expr = value.ToString(CultureInfo.InvariantCulture);
  1265. return value < 0 ? "(" + expr + ")" : expr;
  1266. }
  1267. private static OperType GetDstNodeType(ShaderIrNode node)
  1268. {
  1269. //Special case instructions with the result type different
  1270. //from the input types (like integer <-> float conversion) here.
  1271. if (node is ShaderIrOp op)
  1272. {
  1273. switch (op.Inst)
  1274. {
  1275. case ShaderIrInst.Stof:
  1276. case ShaderIrInst.Txlf:
  1277. case ShaderIrInst.Utof:
  1278. return OperType.F32;
  1279. case ShaderIrInst.Ftos:
  1280. case ShaderIrInst.Ftou:
  1281. return OperType.I32;
  1282. }
  1283. }
  1284. return GetSrcNodeType(node);
  1285. }
  1286. private static OperType GetSrcNodeType(ShaderIrNode node)
  1287. {
  1288. switch (node)
  1289. {
  1290. case ShaderIrOperAbuf abuf:
  1291. return abuf.Offs == GlslDecl.LayerAttr ||
  1292. abuf.Offs == GlslDecl.InstanceIdAttr ||
  1293. abuf.Offs == GlslDecl.VertexIdAttr ||
  1294. abuf.Offs == GlslDecl.FaceAttr
  1295. ? OperType.I32
  1296. : OperType.F32;
  1297. case ShaderIrOperCbuf cbuf: return OperType.F32;
  1298. case ShaderIrOperGpr gpr: return OperType.F32;
  1299. case ShaderIrOperImm imm: return OperType.I32;
  1300. case ShaderIrOperImmf immf: return OperType.F32;
  1301. case ShaderIrOperPred pred: return OperType.Bool;
  1302. case ShaderIrOp op:
  1303. if (op.Inst > ShaderIrInst.B_Start &&
  1304. op.Inst < ShaderIrInst.B_End)
  1305. {
  1306. return OperType.Bool;
  1307. }
  1308. else if (op.Inst > ShaderIrInst.F_Start &&
  1309. op.Inst < ShaderIrInst.F_End)
  1310. {
  1311. return OperType.F32;
  1312. }
  1313. else if (op.Inst > ShaderIrInst.I_Start &&
  1314. op.Inst < ShaderIrInst.I_End)
  1315. {
  1316. return OperType.I32;
  1317. }
  1318. break;
  1319. }
  1320. throw new ArgumentException(nameof(node));
  1321. }
  1322. private static string GetBlockPosition(ShaderIrBlock block)
  1323. {
  1324. if (block != null)
  1325. {
  1326. return "0x" + block.Position.ToString("x8") + "u";
  1327. }
  1328. else
  1329. {
  1330. return "0u";
  1331. }
  1332. }
  1333. }
  1334. }