GlslDecompiler.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Ryujinx.Graphics.Gal.Shader
  7. {
  8. public class GlslDecompiler
  9. {
  10. private delegate string GetInstExpr(ShaderIrOp Op);
  11. private Dictionary<ShaderIrInst, GetInstExpr> InstsExpr;
  12. private enum OperType
  13. {
  14. Bool,
  15. F32,
  16. I32
  17. }
  18. private const string IdentationStr = " ";
  19. private const int MaxVertexInput = 3;
  20. private GlslDecl Decl;
  21. private ShaderHeader Header, HeaderB;
  22. private ShaderIrBlock[] Blocks, BlocksB;
  23. private StringBuilder SB;
  24. public int MaxUboSize { get; }
  25. public GlslDecompiler(int MaxUboSize)
  26. {
  27. InstsExpr = new Dictionary<ShaderIrInst, GetInstExpr>()
  28. {
  29. { ShaderIrInst.Abs, GetAbsExpr },
  30. { ShaderIrInst.Add, GetAddExpr },
  31. { ShaderIrInst.And, GetAndExpr },
  32. { ShaderIrInst.Asr, GetAsrExpr },
  33. { ShaderIrInst.Band, GetBandExpr },
  34. { ShaderIrInst.Bnot, GetBnotExpr },
  35. { ShaderIrInst.Bor, GetBorExpr },
  36. { ShaderIrInst.Bxor, GetBxorExpr },
  37. { ShaderIrInst.Ceil, GetCeilExpr },
  38. { ShaderIrInst.Ceq, GetCeqExpr },
  39. { ShaderIrInst.Cge, GetCgeExpr },
  40. { ShaderIrInst.Cgt, GetCgtExpr },
  41. { ShaderIrInst.Clamps, GetClampsExpr },
  42. { ShaderIrInst.Clampu, GetClampuExpr },
  43. { ShaderIrInst.Cle, GetCleExpr },
  44. { ShaderIrInst.Clt, GetCltExpr },
  45. { ShaderIrInst.Cne, GetCneExpr },
  46. { ShaderIrInst.Cut, GetCutExpr },
  47. { ShaderIrInst.Exit, GetExitExpr },
  48. { ShaderIrInst.Fabs, GetAbsExpr },
  49. { ShaderIrInst.Fadd, GetAddExpr },
  50. { ShaderIrInst.Fceq, GetCeqExpr },
  51. { ShaderIrInst.Fcequ, GetCequExpr },
  52. { ShaderIrInst.Fcge, GetCgeExpr },
  53. { ShaderIrInst.Fcgeu, GetCgeuExpr },
  54. { ShaderIrInst.Fcgt, GetCgtExpr },
  55. { ShaderIrInst.Fcgtu, GetCgtuExpr },
  56. { ShaderIrInst.Fclamp, GetFclampExpr },
  57. { ShaderIrInst.Fcle, GetCleExpr },
  58. { ShaderIrInst.Fcleu, GetCleuExpr },
  59. { ShaderIrInst.Fclt, GetCltExpr },
  60. { ShaderIrInst.Fcltu, GetCltuExpr },
  61. { ShaderIrInst.Fcnan, GetCnanExpr },
  62. { ShaderIrInst.Fcne, GetCneExpr },
  63. { ShaderIrInst.Fcneu, GetCneuExpr },
  64. { ShaderIrInst.Fcnum, GetCnumExpr },
  65. { ShaderIrInst.Fcos, GetFcosExpr },
  66. { ShaderIrInst.Fex2, GetFex2Expr },
  67. { ShaderIrInst.Ffma, GetFfmaExpr },
  68. { ShaderIrInst.Flg2, GetFlg2Expr },
  69. { ShaderIrInst.Floor, GetFloorExpr },
  70. { ShaderIrInst.Fmax, GetMaxExpr },
  71. { ShaderIrInst.Fmin, GetMinExpr },
  72. { ShaderIrInst.Fmul, GetMulExpr },
  73. { ShaderIrInst.Fneg, GetNegExpr },
  74. { ShaderIrInst.Frcp, GetFrcpExpr },
  75. { ShaderIrInst.Frsq, GetFrsqExpr },
  76. { ShaderIrInst.Fsin, GetFsinExpr },
  77. { ShaderIrInst.Fsqrt, GetFsqrtExpr },
  78. { ShaderIrInst.Ftos, GetFtosExpr },
  79. { ShaderIrInst.Ftou, GetFtouExpr },
  80. { ShaderIrInst.Ipa, GetIpaExpr },
  81. { ShaderIrInst.Kil, GetKilExpr },
  82. { ShaderIrInst.Lsl, GetLslExpr },
  83. { ShaderIrInst.Lsr, GetLsrExpr },
  84. { ShaderIrInst.Max, GetMaxExpr },
  85. { ShaderIrInst.Min, GetMinExpr },
  86. { ShaderIrInst.Mul, GetMulExpr },
  87. { ShaderIrInst.Neg, GetNegExpr },
  88. { ShaderIrInst.Not, GetNotExpr },
  89. { ShaderIrInst.Or, GetOrExpr },
  90. { ShaderIrInst.Stof, GetStofExpr },
  91. { ShaderIrInst.Sub, GetSubExpr },
  92. { ShaderIrInst.Texb, GetTexbExpr },
  93. { ShaderIrInst.Texq, GetTexqExpr },
  94. { ShaderIrInst.Texs, GetTexsExpr },
  95. { ShaderIrInst.Trunc, GetTruncExpr },
  96. { ShaderIrInst.Txlf, GetTxlfExpr },
  97. { ShaderIrInst.Utof, GetUtofExpr },
  98. { ShaderIrInst.Xor, GetXorExpr }
  99. };
  100. this.MaxUboSize = MaxUboSize / 16;
  101. }
  102. public GlslProgram Decompile(
  103. IGalMemory Memory,
  104. long VpAPosition,
  105. long VpBPosition,
  106. GalShaderType ShaderType)
  107. {
  108. Header = new ShaderHeader(Memory, VpAPosition);
  109. HeaderB = new ShaderHeader(Memory, VpBPosition);
  110. Blocks = ShaderDecoder.Decode(Memory, VpAPosition);
  111. BlocksB = ShaderDecoder.Decode(Memory, VpBPosition);
  112. GlslDecl DeclVpA = new GlslDecl(Blocks, ShaderType, Header);
  113. GlslDecl DeclVpB = new GlslDecl(BlocksB, ShaderType, HeaderB);
  114. Decl = GlslDecl.Merge(DeclVpA, DeclVpB);
  115. return Decompile();
  116. }
  117. public GlslProgram Decompile(IGalMemory Memory, long Position, GalShaderType ShaderType)
  118. {
  119. Header = new ShaderHeader(Memory, Position);
  120. HeaderB = null;
  121. Blocks = ShaderDecoder.Decode(Memory, Position);
  122. BlocksB = null;
  123. Decl = new GlslDecl(Blocks, ShaderType, Header);
  124. return Decompile();
  125. }
  126. private GlslProgram Decompile()
  127. {
  128. SB = new StringBuilder();
  129. SB.AppendLine("#version 410 core");
  130. PrintDeclHeader();
  131. PrintDeclTextures();
  132. PrintDeclUniforms();
  133. PrintDeclAttributes();
  134. PrintDeclInAttributes();
  135. PrintDeclOutAttributes();
  136. PrintDeclGprs();
  137. PrintDeclPreds();
  138. PrintDeclSsy();
  139. if (BlocksB != null)
  140. {
  141. PrintBlockScope(Blocks, GlslDecl.BasicBlockAName);
  142. SB.AppendLine();
  143. PrintBlockScope(BlocksB, GlslDecl.BasicBlockBName);
  144. }
  145. else
  146. {
  147. PrintBlockScope(Blocks, GlslDecl.BasicBlockName);
  148. }
  149. SB.AppendLine();
  150. PrintMain();
  151. string GlslCode = SB.ToString();
  152. List<ShaderDeclInfo> TextureInfo = new List<ShaderDeclInfo>();
  153. TextureInfo.AddRange(Decl.Textures.Values);
  154. TextureInfo.AddRange(IterateCbTextures());
  155. return new GlslProgram(GlslCode, TextureInfo, Decl.Uniforms.Values);
  156. }
  157. private void PrintDeclHeader()
  158. {
  159. if (Decl.ShaderType == GalShaderType.Geometry)
  160. {
  161. int MaxVertices = Header.MaxOutputVertexCount;
  162. string OutputTopology;
  163. switch (Header.OutputTopology)
  164. {
  165. case ShaderHeader.PointList: OutputTopology = "points"; break;
  166. case ShaderHeader.LineStrip: OutputTopology = "line_strip"; break;
  167. case ShaderHeader.TriangleStrip: OutputTopology = "triangle_strip"; break;
  168. default: throw new InvalidOperationException();
  169. }
  170. SB.AppendLine("#extension GL_ARB_enhanced_layouts : require");
  171. SB.AppendLine();
  172. SB.AppendLine("// Stubbed. Maxwell geometry shaders don't inform input geometry type");
  173. SB.AppendLine("layout(triangles) in;" + Environment.NewLine);
  174. SB.AppendLine($"layout({OutputTopology}, max_vertices = {MaxVertices}) out;");
  175. SB.AppendLine();
  176. }
  177. }
  178. private void PrintDeclTextures()
  179. {
  180. foreach (ShaderDeclInfo DeclInfo in IterateCbTextures())
  181. {
  182. SB.AppendLine("uniform sampler2D " + DeclInfo.Name + ";");
  183. }
  184. PrintDecls(Decl.Textures, "uniform sampler2D");
  185. }
  186. private IEnumerable<ShaderDeclInfo> IterateCbTextures()
  187. {
  188. HashSet<string> Names = new HashSet<string>();
  189. foreach (ShaderDeclInfo DeclInfo in Decl.CbTextures.Values.OrderBy(DeclKeySelector))
  190. {
  191. if (Names.Add(DeclInfo.Name))
  192. {
  193. yield return DeclInfo;
  194. }
  195. }
  196. }
  197. private void PrintDeclUniforms()
  198. {
  199. if (Decl.ShaderType == GalShaderType.Vertex)
  200. {
  201. //Memory layout here is [flip_x, flip_y, instance, unused]
  202. //It's using 4 bytes, not 8
  203. SB.AppendLine("layout (std140) uniform " + GlslDecl.ExtraUniformBlockName + " {");
  204. SB.AppendLine(IdentationStr + "vec2 " + GlslDecl.FlipUniformName + ";");
  205. SB.AppendLine(IdentationStr + "int " + GlslDecl.InstanceUniformName + ";");
  206. SB.AppendLine("};");
  207. SB.AppendLine();
  208. }
  209. foreach (ShaderDeclInfo DeclInfo in Decl.Uniforms.Values.OrderBy(DeclKeySelector))
  210. {
  211. SB.AppendLine($"layout (std140) uniform {DeclInfo.Name} {{");
  212. SB.AppendLine($"{IdentationStr}vec4 {DeclInfo.Name}_data[{MaxUboSize}];");
  213. SB.AppendLine("};");
  214. }
  215. if (Decl.Uniforms.Count > 0)
  216. {
  217. SB.AppendLine();
  218. }
  219. }
  220. private void PrintDeclAttributes()
  221. {
  222. string GeometryArray = (Decl.ShaderType == GalShaderType.Geometry) ? "[" + MaxVertexInput + "]" : "";
  223. PrintDecls(Decl.Attributes, Suffix: GeometryArray);
  224. }
  225. private void PrintDeclInAttributes()
  226. {
  227. if (Decl.ShaderType == GalShaderType.Fragment)
  228. {
  229. SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") in vec4 " + GlslDecl.PositionOutAttrName + ";");
  230. }
  231. if (Decl.ShaderType == GalShaderType.Geometry)
  232. {
  233. if (Decl.InAttributes.Count > 0)
  234. {
  235. SB.AppendLine("in Vertex {");
  236. foreach (ShaderDeclInfo DeclInfo in Decl.InAttributes.Values.OrderBy(DeclKeySelector))
  237. {
  238. if (DeclInfo.Index >= 0)
  239. {
  240. SB.AppendLine(IdentationStr + "layout (location = " + DeclInfo.Index + ") vec4 " + DeclInfo.Name + "; ");
  241. }
  242. }
  243. SB.AppendLine("} block_in[];" + Environment.NewLine);
  244. }
  245. }
  246. else
  247. {
  248. PrintDeclAttributes(Decl.InAttributes.Values, "in");
  249. }
  250. }
  251. private void PrintDeclOutAttributes()
  252. {
  253. if (Decl.ShaderType == GalShaderType.Fragment)
  254. {
  255. int Count = 0;
  256. for (int Attachment = 0; Attachment < 8; Attachment++)
  257. {
  258. if (Header.OmapTargets[Attachment].Enabled)
  259. {
  260. SB.AppendLine("layout (location = " + Attachment + ") out vec4 " + GlslDecl.FragmentOutputName + Attachment + ";");
  261. Count++;
  262. }
  263. }
  264. if (Count > 0)
  265. {
  266. SB.AppendLine();
  267. }
  268. }
  269. else
  270. {
  271. SB.AppendLine("layout (location = " + GlslDecl.PositionOutAttrLocation + ") out vec4 " + GlslDecl.PositionOutAttrName + ";");
  272. SB.AppendLine();
  273. }
  274. PrintDeclAttributes(Decl.OutAttributes.Values, "out");
  275. }
  276. private void PrintDeclAttributes(IEnumerable<ShaderDeclInfo> Decls, string InOut)
  277. {
  278. int Count = 0;
  279. foreach (ShaderDeclInfo DeclInfo in Decls.OrderBy(DeclKeySelector))
  280. {
  281. if (DeclInfo.Index >= 0)
  282. {
  283. SB.AppendLine("layout (location = " + DeclInfo.Index + ") " + InOut + " vec4 " + DeclInfo.Name + ";");
  284. Count++;
  285. }
  286. }
  287. if (Count > 0)
  288. {
  289. SB.AppendLine();
  290. }
  291. }
  292. private void PrintDeclGprs()
  293. {
  294. PrintDecls(Decl.Gprs);
  295. PrintDecls(Decl.GprsHalf);
  296. }
  297. private void PrintDeclPreds()
  298. {
  299. PrintDecls(Decl.Preds, "bool");
  300. }
  301. private void PrintDeclSsy()
  302. {
  303. SB.AppendLine("uint " + GlslDecl.SsyCursorName + " = 0;");
  304. SB.AppendLine("uint " + GlslDecl.SsyStackName + "[" + GlslDecl.SsyStackSize + "];" + Environment.NewLine);
  305. }
  306. private void PrintDecls(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, string CustomType = null, string Suffix = "")
  307. {
  308. foreach (ShaderDeclInfo DeclInfo in Dict.Values.OrderBy(DeclKeySelector))
  309. {
  310. string Name;
  311. if (CustomType != null)
  312. {
  313. Name = CustomType + " " + DeclInfo.Name + Suffix + ";";
  314. }
  315. else if (DeclInfo.Name.Contains(GlslDecl.FragmentOutputName))
  316. {
  317. Name = "layout (location = " + DeclInfo.Index / 4 + ") out vec4 " + DeclInfo.Name + Suffix + ";";
  318. }
  319. else
  320. {
  321. Name = GetDecl(DeclInfo) + Suffix + ";";
  322. }
  323. SB.AppendLine(Name);
  324. }
  325. if (Dict.Count > 0)
  326. {
  327. SB.AppendLine();
  328. }
  329. }
  330. private int DeclKeySelector(ShaderDeclInfo DeclInfo)
  331. {
  332. return DeclInfo.Cbuf << 24 | DeclInfo.Index;
  333. }
  334. private string GetDecl(ShaderDeclInfo DeclInfo)
  335. {
  336. if (DeclInfo.Size == 4)
  337. {
  338. return "vec4 " + DeclInfo.Name;
  339. }
  340. else
  341. {
  342. return "float " + DeclInfo.Name;
  343. }
  344. }
  345. private void PrintMain()
  346. {
  347. SB.AppendLine("void main() {");
  348. foreach (KeyValuePair<int, ShaderDeclInfo> KV in Decl.InAttributes)
  349. {
  350. if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr))
  351. {
  352. continue;
  353. }
  354. ShaderDeclInfo DeclInfo = KV.Value;
  355. if (Decl.ShaderType == GalShaderType.Geometry)
  356. {
  357. for (int Vertex = 0; Vertex < MaxVertexInput; Vertex++)
  358. {
  359. string Dst = Attr.Name + "[" + Vertex + "]";
  360. string Src = "block_in[" + Vertex + "]." + DeclInfo.Name;
  361. SB.AppendLine(IdentationStr + Dst + " = " + Src + ";");
  362. }
  363. }
  364. else
  365. {
  366. SB.AppendLine(IdentationStr + Attr.Name + " = " + DeclInfo.Name + ";");
  367. }
  368. }
  369. SB.AppendLine(IdentationStr + "uint pc;");
  370. if (BlocksB != null)
  371. {
  372. PrintProgram(Blocks, GlslDecl.BasicBlockAName);
  373. PrintProgram(BlocksB, GlslDecl.BasicBlockBName);
  374. }
  375. else
  376. {
  377. PrintProgram(Blocks, GlslDecl.BasicBlockName);
  378. }
  379. if (Decl.ShaderType != GalShaderType.Geometry)
  380. {
  381. PrintAttrToOutput();
  382. }
  383. if (Decl.ShaderType == GalShaderType.Fragment)
  384. {
  385. if (Header.OmapDepth)
  386. {
  387. SB.AppendLine(IdentationStr + "gl_FragDepth = " + GlslDecl.GetGprName(Header.DepthRegister) + ";");
  388. }
  389. int GprIndex = 0;
  390. for (int Attachment = 0; Attachment < 8; Attachment++)
  391. {
  392. string Output = GlslDecl.FragmentOutputName + Attachment;
  393. OmapTarget Target = Header.OmapTargets[Attachment];
  394. for (int Component = 0; Component < 4; Component++)
  395. {
  396. if (Target.ComponentEnabled(Component))
  397. {
  398. SB.AppendLine(IdentationStr + Output + "[" + Component + "] = " + GlslDecl.GetGprName(GprIndex) + ";");
  399. GprIndex++;
  400. }
  401. }
  402. }
  403. }
  404. SB.AppendLine("}");
  405. }
  406. private void PrintProgram(ShaderIrBlock[] Blocks, string Name)
  407. {
  408. const string Ident1 = IdentationStr;
  409. const string Ident2 = Ident1 + IdentationStr;
  410. const string Ident3 = Ident2 + IdentationStr;
  411. const string Ident4 = Ident3 + IdentationStr;
  412. SB.AppendLine(Ident1 + "pc = " + GetBlockPosition(Blocks[0]) + ";");
  413. SB.AppendLine(Ident1 + "do {");
  414. SB.AppendLine(Ident2 + "switch (pc) {");
  415. foreach (ShaderIrBlock Block in Blocks)
  416. {
  417. string FunctionName = Block.Position.ToString("x8");
  418. SB.AppendLine(Ident3 + "case 0x" + FunctionName + ": pc = " + Name + "_" + FunctionName + "(); break;");
  419. }
  420. SB.AppendLine(Ident3 + "default:");
  421. SB.AppendLine(Ident4 + "pc = 0;");
  422. SB.AppendLine(Ident4 + "break;");
  423. SB.AppendLine(Ident2 + "}");
  424. SB.AppendLine(Ident1 + "} while (pc != 0);");
  425. }
  426. private void PrintAttrToOutput(string Identation = IdentationStr)
  427. {
  428. foreach (KeyValuePair<int, ShaderDeclInfo> KV in Decl.OutAttributes)
  429. {
  430. if (!Decl.Attributes.TryGetValue(KV.Key, out ShaderDeclInfo Attr))
  431. {
  432. continue;
  433. }
  434. ShaderDeclInfo DeclInfo = KV.Value;
  435. string Name = Attr.Name;
  436. if (Decl.ShaderType == GalShaderType.Geometry)
  437. {
  438. Name += "[0]";
  439. }
  440. SB.AppendLine(Identation + DeclInfo.Name + " = " + Name + ";");
  441. }
  442. if (Decl.ShaderType == GalShaderType.Vertex)
  443. {
  444. SB.AppendLine(Identation + "gl_Position.xy *= " + GlslDecl.FlipUniformName + ";");
  445. }
  446. if (Decl.ShaderType != GalShaderType.Fragment)
  447. {
  448. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + " = gl_Position;");
  449. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + ".w = 1;");
  450. }
  451. }
  452. private void PrintBlockScope(ShaderIrBlock[] Blocks, string Name)
  453. {
  454. foreach (ShaderIrBlock Block in Blocks)
  455. {
  456. SB.AppendLine("uint " + Name + "_" + Block.Position.ToString("x8") + "() {");
  457. PrintNodes(Block, Block.GetNodes());
  458. SB.AppendLine("}" + Environment.NewLine);
  459. }
  460. }
  461. private void PrintNodes(ShaderIrBlock Block, ShaderIrNode[] Nodes)
  462. {
  463. foreach (ShaderIrNode Node in Nodes)
  464. {
  465. PrintNode(Block, Node, IdentationStr);
  466. }
  467. if (Nodes.Length == 0)
  468. {
  469. SB.AppendLine(IdentationStr + "return 0u;");
  470. return;
  471. }
  472. ShaderIrNode Last = Nodes[Nodes.Length - 1];
  473. bool UnconditionalFlowChange = false;
  474. if (Last is ShaderIrOp Op)
  475. {
  476. switch (Op.Inst)
  477. {
  478. case ShaderIrInst.Bra:
  479. case ShaderIrInst.Exit:
  480. case ShaderIrInst.Sync:
  481. UnconditionalFlowChange = true;
  482. break;
  483. }
  484. }
  485. if (!UnconditionalFlowChange)
  486. {
  487. if (Block.Next != null)
  488. {
  489. SB.AppendLine(IdentationStr + "return " + GetBlockPosition(Block.Next) + ";");
  490. }
  491. else
  492. {
  493. SB.AppendLine(IdentationStr + "return 0u;");
  494. }
  495. }
  496. }
  497. private void PrintNode(ShaderIrBlock Block, ShaderIrNode Node, string Identation)
  498. {
  499. if (Node is ShaderIrCond Cond)
  500. {
  501. string IfExpr = GetSrcExpr(Cond.Pred, true);
  502. if (Cond.Not)
  503. {
  504. IfExpr = "!(" + IfExpr + ")";
  505. }
  506. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  507. PrintNode(Block, Cond.Child, Identation + IdentationStr);
  508. SB.AppendLine(Identation + "}");
  509. }
  510. else if (Node is ShaderIrAsg Asg)
  511. {
  512. if (IsValidOutOper(Asg.Dst))
  513. {
  514. string Expr = GetSrcExpr(Asg.Src, true);
  515. Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr);
  516. SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";");
  517. }
  518. }
  519. else if (Node is ShaderIrOp Op)
  520. {
  521. switch (Op.Inst)
  522. {
  523. case ShaderIrInst.Bra:
  524. {
  525. SB.AppendLine(Identation + "return " + GetBlockPosition(Block.Branch) + ";");
  526. break;
  527. }
  528. case ShaderIrInst.Emit:
  529. {
  530. PrintAttrToOutput(Identation);
  531. SB.AppendLine(Identation + "EmitVertex();");
  532. break;
  533. }
  534. case ShaderIrInst.Ssy:
  535. {
  536. string StackIndex = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]";
  537. int TargetPosition = (Op.OperandA as ShaderIrOperImm).Value;
  538. string Target = "0x" + TargetPosition.ToString("x8") + "u";
  539. SB.AppendLine(Identation + StackIndex + " = " + Target + ";");
  540. SB.AppendLine(Identation + GlslDecl.SsyCursorName + "++;");
  541. break;
  542. }
  543. case ShaderIrInst.Sync:
  544. {
  545. SB.AppendLine(Identation + GlslDecl.SsyCursorName + "--;");
  546. string Target = GlslDecl.SsyStackName + "[" + GlslDecl.SsyCursorName + "]";
  547. SB.AppendLine(Identation + "return " + Target + ";");
  548. break;
  549. }
  550. default:
  551. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  552. break;
  553. }
  554. }
  555. else if (Node is ShaderIrCmnt Cmnt)
  556. {
  557. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  558. }
  559. else
  560. {
  561. throw new InvalidOperationException();
  562. }
  563. }
  564. private bool IsValidOutOper(ShaderIrNode Node)
  565. {
  566. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  567. {
  568. return false;
  569. }
  570. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  571. {
  572. return false;
  573. }
  574. return true;
  575. }
  576. private string GetDstOperName(ShaderIrNode Node)
  577. {
  578. if (Node is ShaderIrOperAbuf Abuf)
  579. {
  580. return GetOutAbufName(Abuf);
  581. }
  582. else if (Node is ShaderIrOperGpr Gpr)
  583. {
  584. return GetName(Gpr);
  585. }
  586. else if (Node is ShaderIrOperPred Pred)
  587. {
  588. return GetName(Pred);
  589. }
  590. throw new ArgumentException(nameof(Node));
  591. }
  592. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  593. {
  594. switch (Node)
  595. {
  596. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  597. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  598. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  599. case ShaderIrOperImm Imm: return GetValue(Imm);
  600. case ShaderIrOperImmf Immf: return GetValue(Immf);
  601. case ShaderIrOperPred Pred: return GetName (Pred);
  602. case ShaderIrOp Op:
  603. string Expr;
  604. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  605. {
  606. Expr = GetExpr(Op);
  607. }
  608. else
  609. {
  610. throw new NotImplementedException(Op.Inst.ToString());
  611. }
  612. if (!Entry && NeedsParentheses(Op))
  613. {
  614. Expr = "(" + Expr + ")";
  615. }
  616. return Expr;
  617. default: throw new ArgumentException(nameof(Node));
  618. }
  619. }
  620. private static bool NeedsParentheses(ShaderIrOp Op)
  621. {
  622. switch (Op.Inst)
  623. {
  624. case ShaderIrInst.Ipa:
  625. case ShaderIrInst.Texq:
  626. case ShaderIrInst.Texs:
  627. case ShaderIrInst.Txlf:
  628. return false;
  629. }
  630. return true;
  631. }
  632. private string GetName(ShaderIrOperCbuf Cbuf)
  633. {
  634. if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo))
  635. {
  636. throw new InvalidOperationException();
  637. }
  638. if (Cbuf.Offs != null)
  639. {
  640. string Offset = "floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ")";
  641. string Index = "(" + Cbuf.Pos * 4 + " + " + Offset + ")";
  642. return $"{DeclInfo.Name}_data[{Index} / 16][({Index} / 4) % 4]";
  643. }
  644. else
  645. {
  646. return $"{DeclInfo.Name}_data[{Cbuf.Pos / 4}][{Cbuf.Pos % 4}]";
  647. }
  648. }
  649. private string GetOutAbufName(ShaderIrOperAbuf Abuf)
  650. {
  651. if (Decl.ShaderType == GalShaderType.Geometry)
  652. {
  653. switch (Abuf.Offs)
  654. {
  655. case GlslDecl.LayerAttr: return "gl_Layer";
  656. }
  657. }
  658. return GetAttrTempName(Abuf);
  659. }
  660. private string GetName(ShaderIrOperAbuf Abuf)
  661. {
  662. //Handle special scalar read-only attributes here.
  663. if (Decl.ShaderType == GalShaderType.Vertex)
  664. {
  665. switch (Abuf.Offs)
  666. {
  667. case GlslDecl.VertexIdAttr: return "gl_VertexID";
  668. case GlslDecl.InstanceIdAttr: return GlslDecl.InstanceUniformName;
  669. }
  670. }
  671. else if (Decl.ShaderType == GalShaderType.TessEvaluation)
  672. {
  673. switch (Abuf.Offs)
  674. {
  675. case GlslDecl.TessCoordAttrX: return "gl_TessCoord.x";
  676. case GlslDecl.TessCoordAttrY: return "gl_TessCoord.y";
  677. case GlslDecl.TessCoordAttrZ: return "gl_TessCoord.z";
  678. }
  679. }
  680. else if (Decl.ShaderType == GalShaderType.Fragment)
  681. {
  682. switch (Abuf.Offs)
  683. {
  684. case GlslDecl.PointCoordAttrX: return "gl_PointCoord.x";
  685. case GlslDecl.PointCoordAttrY: return "gl_PointCoord.y";
  686. //Note: It's a guess that Maxwell's face is 1 when gl_FrontFacing == true
  687. case GlslDecl.FaceAttr: return "(gl_FrontFacing ? 1 : 0)";
  688. }
  689. }
  690. return GetAttrTempName(Abuf);
  691. }
  692. private string GetAttrTempName(ShaderIrOperAbuf Abuf)
  693. {
  694. int Index = Abuf.Offs >> 4;
  695. int Elem = (Abuf.Offs >> 2) & 3;
  696. string Swizzle = "." + GetAttrSwizzle(Elem);
  697. if (!Decl.Attributes.TryGetValue(Index, out ShaderDeclInfo DeclInfo))
  698. {
  699. //Handle special vec4 attributes here
  700. //(for example, index 7 is always gl_Position).
  701. if (Index == GlslDecl.GlPositionVec4Index)
  702. {
  703. string Name =
  704. Decl.ShaderType != GalShaderType.Vertex &&
  705. Decl.ShaderType != GalShaderType.Geometry ? GlslDecl.PositionOutAttrName : "gl_Position";
  706. return Name + Swizzle;
  707. }
  708. else if (Abuf.Offs == GlslDecl.PointSizeAttr)
  709. {
  710. return "gl_PointSize";
  711. }
  712. }
  713. if (DeclInfo.Index >= 32)
  714. {
  715. throw new InvalidOperationException($"Shader attribute offset {Abuf.Offs} is invalid.");
  716. }
  717. if (Decl.ShaderType == GalShaderType.Geometry)
  718. {
  719. string Vertex = "floatBitsToInt(" + GetSrcExpr(Abuf.Vertex) + ")";
  720. return DeclInfo.Name + "[" + Vertex + "]" + Swizzle;
  721. }
  722. else
  723. {
  724. return DeclInfo.Name + Swizzle;
  725. }
  726. }
  727. private string GetName(ShaderIrOperGpr Gpr)
  728. {
  729. if (Gpr.IsConst)
  730. {
  731. return "0";
  732. }
  733. if (Gpr.RegisterSize == ShaderRegisterSize.Single)
  734. {
  735. return GetNameWithSwizzle(Decl.Gprs, Gpr.Index);
  736. }
  737. else if (Gpr.RegisterSize == ShaderRegisterSize.Half)
  738. {
  739. return GetNameWithSwizzle(Decl.GprsHalf, (Gpr.Index << 1) | Gpr.HalfPart);
  740. }
  741. else /* if (Gpr.RegisterSize == ShaderRegisterSize.Double) */
  742. {
  743. throw new NotImplementedException("Double types are not supported.");
  744. }
  745. }
  746. private string GetValue(ShaderIrOperImm Imm)
  747. {
  748. //Only use hex is the value is too big and would likely be hard to read as int.
  749. if (Imm.Value > 0xfff ||
  750. Imm.Value < -0xfff)
  751. {
  752. return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  753. }
  754. else
  755. {
  756. return GetIntConst(Imm.Value);
  757. }
  758. }
  759. private string GetValue(ShaderIrOperImmf Immf)
  760. {
  761. return GetFloatConst(Immf.Value);
  762. }
  763. private string GetName(ShaderIrOperPred Pred)
  764. {
  765. return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index);
  766. }
  767. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, int Index)
  768. {
  769. int VecIndex = Index & ~3;
  770. if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo))
  771. {
  772. if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size)
  773. {
  774. return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3);
  775. }
  776. }
  777. if (!Dict.TryGetValue(Index, out DeclInfo))
  778. {
  779. throw new InvalidOperationException();
  780. }
  781. return DeclInfo.Name;
  782. }
  783. private string GetAttrSwizzle(int Elem)
  784. {
  785. return "xyzw".Substring(Elem, 1);
  786. }
  787. private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs");
  788. private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+");
  789. private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&");
  790. private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>");
  791. private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&");
  792. private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!");
  793. private string GetBorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "||");
  794. private string GetBxorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^^");
  795. private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil");
  796. private string GetClampsExpr(ShaderIrOp Op)
  797. {
  798. return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " +
  799. GetOperExpr(Op, Op.OperandB) + ", " +
  800. GetOperExpr(Op, Op.OperandC) + ")";
  801. }
  802. private string GetClampuExpr(ShaderIrOp Op)
  803. {
  804. return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " +
  805. "uint(" + GetOperExpr(Op, Op.OperandB) + "), " +
  806. "uint(" + GetOperExpr(Op, Op.OperandC) + ")))";
  807. }
  808. private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "==");
  809. private string GetCequExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "==");
  810. private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">=");
  811. private string GetCgeuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">=");
  812. private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">");
  813. private string GetCgtuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, ">");
  814. private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<=");
  815. private string GetCleuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<=");
  816. private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<");
  817. private string GetCltuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "<");
  818. private string GetCnanExpr(ShaderIrOp Op) => GetUnaryCall(Op, "isnan");
  819. private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!=");
  820. private string GetCutExpr(ShaderIrOp Op) => "EndPrimitive()";
  821. private string GetCneuExpr(ShaderIrOp Op) => GetBinaryExprWithNaN(Op, "!=");
  822. private string GetCnumExpr(ShaderIrOp Op) => GetUnaryCall(Op, "!isnan");
  823. private string GetExitExpr(ShaderIrOp Op) => "return 0u";
  824. private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos");
  825. private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2");
  826. private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+");
  827. private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp");
  828. private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2");
  829. private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor");
  830. private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / ");
  831. private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt");
  832. private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin");
  833. private string GetFsqrtExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sqrt");
  834. private string GetFtosExpr(ShaderIrOp Op)
  835. {
  836. return "int(" + GetOperExpr(Op, Op.OperandA) + ")";
  837. }
  838. private string GetFtouExpr(ShaderIrOp Op)
  839. {
  840. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  841. }
  842. private string GetIpaExpr(ShaderIrOp Op)
  843. {
  844. ShaderIrMetaIpa Meta = (ShaderIrMetaIpa)Op.MetaData;
  845. ShaderIrOperAbuf Abuf = (ShaderIrOperAbuf)Op.OperandA;
  846. if (Meta.Mode == ShaderIpaMode.Pass)
  847. {
  848. int Index = Abuf.Offs >> 4;
  849. int Elem = (Abuf.Offs >> 2) & 3;
  850. if (Decl.ShaderType == GalShaderType.Fragment && Index == GlslDecl.GlPositionVec4Index)
  851. {
  852. switch (Elem)
  853. {
  854. case 0: return "gl_FragCoord.x";
  855. case 1: return "gl_FragCoord.y";
  856. case 2: return "gl_FragCoord.z";
  857. case 3: return "1";
  858. }
  859. }
  860. }
  861. return GetSrcExpr(Op.OperandA);
  862. }
  863. private string GetKilExpr(ShaderIrOp Op) => "discard";
  864. private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<");
  865. private string GetLsrExpr(ShaderIrOp Op)
  866. {
  867. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " +
  868. GetOperExpr(Op, Op.OperandB) + ")";
  869. }
  870. private string GetMaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max");
  871. private string GetMinExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min");
  872. private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*");
  873. private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-");
  874. private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~");
  875. private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|");
  876. private string GetStofExpr(ShaderIrOp Op)
  877. {
  878. return "float(" + GetOperExpr(Op, Op.OperandA) + ")";
  879. }
  880. private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-");
  881. private string GetTexbExpr(ShaderIrOp Op)
  882. {
  883. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  884. if (!Decl.CbTextures.TryGetValue(Op, out ShaderDeclInfo DeclInfo))
  885. {
  886. throw new InvalidOperationException();
  887. }
  888. string Coords = GetTexSamplerCoords(Op);
  889. string Ch = "rgba".Substring(Meta.Elem, 1);
  890. return "texture(" + DeclInfo.Name + ", " + Coords + ")." + Ch;
  891. }
  892. private string GetTexqExpr(ShaderIrOp Op)
  893. {
  894. ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData;
  895. string Ch = "xyzw".Substring(Meta.Elem, 1);
  896. if (Meta.Info == ShaderTexqInfo.Dimension)
  897. {
  898. string Sampler = GetTexSamplerName(Op);
  899. string Lod = GetOperExpr(Op, Op.OperandA); //???
  900. return "textureSize(" + Sampler + ", " + Lod + ")." + Ch;
  901. }
  902. else
  903. {
  904. throw new NotImplementedException(Meta.Info.ToString());
  905. }
  906. }
  907. private string GetTexsExpr(ShaderIrOp Op)
  908. {
  909. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  910. string Sampler = GetTexSamplerName(Op);
  911. string Coords = GetTexSamplerCoords(Op);
  912. string Ch = "rgba".Substring(Meta.Elem, 1);
  913. return "texture(" + Sampler + ", " + Coords + ")." + Ch;
  914. }
  915. private string GetTxlfExpr(ShaderIrOp Op)
  916. {
  917. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  918. string Sampler = GetTexSamplerName(Op);
  919. string Coords = GetITexSamplerCoords(Op);
  920. string Ch = "rgba".Substring(Meta.Elem, 1);
  921. return "texelFetch(" + Sampler + ", " + Coords + ", 0)." + Ch;
  922. }
  923. private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc");
  924. private string GetUtofExpr(ShaderIrOp Op)
  925. {
  926. return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  927. }
  928. private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^");
  929. private string GetUnaryCall(ShaderIrOp Op, string FuncName)
  930. {
  931. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")";
  932. }
  933. private string GetBinaryCall(ShaderIrOp Op, string FuncName)
  934. {
  935. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  936. GetOperExpr(Op, Op.OperandB) + ")";
  937. }
  938. private string GetTernaryCall(ShaderIrOp Op, string FuncName)
  939. {
  940. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  941. GetOperExpr(Op, Op.OperandB) + ", " +
  942. GetOperExpr(Op, Op.OperandC) + ")";
  943. }
  944. private string GetUnaryExpr(ShaderIrOp Op, string Opr)
  945. {
  946. return Opr + GetOperExpr(Op, Op.OperandA);
  947. }
  948. private string GetBinaryExpr(ShaderIrOp Op, string Opr)
  949. {
  950. return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " +
  951. GetOperExpr(Op, Op.OperandB);
  952. }
  953. private string GetBinaryExprWithNaN(ShaderIrOp Op, string Opr)
  954. {
  955. string A = GetOperExpr(Op, Op.OperandA);
  956. string B = GetOperExpr(Op, Op.OperandB);
  957. string NaNCheck =
  958. " || isnan(" + A + ")" +
  959. " || isnan(" + B + ")";
  960. return A + " " + Opr + " " + B + NaNCheck;
  961. }
  962. private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2)
  963. {
  964. return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " +
  965. GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " +
  966. GetOperExpr(Op, Op.OperandC);
  967. }
  968. private string GetTexSamplerName(ShaderIrOp Op)
  969. {
  970. ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC;
  971. int Handle = ((ShaderIrOperImm)Op.OperandC).Value;
  972. if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo))
  973. {
  974. throw new InvalidOperationException();
  975. }
  976. return DeclInfo.Name;
  977. }
  978. private string GetTexSamplerCoords(ShaderIrOp Op)
  979. {
  980. return "vec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  981. GetOperExpr(Op, Op.OperandB) + ")";
  982. }
  983. private string GetITexSamplerCoords(ShaderIrOp Op)
  984. {
  985. return "ivec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  986. GetOperExpr(Op, Op.OperandB) + ")";
  987. }
  988. private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper)
  989. {
  990. return GetExprWithCast(Op, Oper, GetSrcExpr(Oper));
  991. }
  992. private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr)
  993. {
  994. //Note: The "DstType" (of the cast) is the type that the operation
  995. //uses on the source operands, while the "SrcType" is the destination
  996. //type of the operand result (if it is a operation) or just the type
  997. //of the variable for registers/uniforms/attributes.
  998. OperType DstType = GetSrcNodeType(Dst);
  999. OperType SrcType = GetDstNodeType(Src);
  1000. if (DstType != SrcType)
  1001. {
  1002. //Check for invalid casts
  1003. //(like bool to int/float and others).
  1004. if (SrcType != OperType.F32 &&
  1005. SrcType != OperType.I32)
  1006. {
  1007. throw new InvalidOperationException();
  1008. }
  1009. switch (Src)
  1010. {
  1011. case ShaderIrOperGpr Gpr:
  1012. {
  1013. //When the Gpr is ZR, just return the 0 value directly,
  1014. //since the float encoding for 0 is 0.
  1015. if (Gpr.IsConst)
  1016. {
  1017. return "0";
  1018. }
  1019. break;
  1020. }
  1021. case ShaderIrOperImm Imm:
  1022. {
  1023. //For integer immediates being used as float,
  1024. //it's better (for readability) to just return the float value.
  1025. if (DstType == OperType.F32)
  1026. {
  1027. float Value = BitConverter.Int32BitsToSingle(Imm.Value);
  1028. if (!float.IsNaN(Value) && !float.IsInfinity(Value))
  1029. {
  1030. return GetFloatConst(Value);
  1031. }
  1032. }
  1033. break;
  1034. }
  1035. }
  1036. switch (DstType)
  1037. {
  1038. case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break;
  1039. case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break;
  1040. }
  1041. }
  1042. return Expr;
  1043. }
  1044. private static string GetIntConst(int Value)
  1045. {
  1046. string Expr = Value.ToString(CultureInfo.InvariantCulture);
  1047. return Value < 0 ? "(" + Expr + ")" : Expr;
  1048. }
  1049. private static string GetFloatConst(float Value)
  1050. {
  1051. string Expr = Value.ToString(CultureInfo.InvariantCulture);
  1052. return Value < 0 ? "(" + Expr + ")" : Expr;
  1053. }
  1054. private static OperType GetDstNodeType(ShaderIrNode Node)
  1055. {
  1056. //Special case instructions with the result type different
  1057. //from the input types (like integer <-> float conversion) here.
  1058. if (Node is ShaderIrOp Op)
  1059. {
  1060. switch (Op.Inst)
  1061. {
  1062. case ShaderIrInst.Stof:
  1063. case ShaderIrInst.Txlf:
  1064. case ShaderIrInst.Utof:
  1065. return OperType.F32;
  1066. case ShaderIrInst.Ftos:
  1067. case ShaderIrInst.Ftou:
  1068. return OperType.I32;
  1069. }
  1070. }
  1071. return GetSrcNodeType(Node);
  1072. }
  1073. private static OperType GetSrcNodeType(ShaderIrNode Node)
  1074. {
  1075. switch (Node)
  1076. {
  1077. case ShaderIrOperAbuf Abuf:
  1078. return Abuf.Offs == GlslDecl.LayerAttr ||
  1079. Abuf.Offs == GlslDecl.InstanceIdAttr ||
  1080. Abuf.Offs == GlslDecl.VertexIdAttr ||
  1081. Abuf.Offs == GlslDecl.FaceAttr
  1082. ? OperType.I32
  1083. : OperType.F32;
  1084. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  1085. case ShaderIrOperGpr Gpr: return OperType.F32;
  1086. case ShaderIrOperImm Imm: return OperType.I32;
  1087. case ShaderIrOperImmf Immf: return OperType.F32;
  1088. case ShaderIrOperPred Pred: return OperType.Bool;
  1089. case ShaderIrOp Op:
  1090. if (Op.Inst > ShaderIrInst.B_Start &&
  1091. Op.Inst < ShaderIrInst.B_End)
  1092. {
  1093. return OperType.Bool;
  1094. }
  1095. else if (Op.Inst > ShaderIrInst.F_Start &&
  1096. Op.Inst < ShaderIrInst.F_End)
  1097. {
  1098. return OperType.F32;
  1099. }
  1100. else if (Op.Inst > ShaderIrInst.I_Start &&
  1101. Op.Inst < ShaderIrInst.I_End)
  1102. {
  1103. return OperType.I32;
  1104. }
  1105. break;
  1106. }
  1107. throw new ArgumentException(nameof(Node));
  1108. }
  1109. private static string GetBlockPosition(ShaderIrBlock Block)
  1110. {
  1111. if (Block != null)
  1112. {
  1113. return "0x" + Block.Position.ToString("x8") + "u";
  1114. }
  1115. else
  1116. {
  1117. return "0u";
  1118. }
  1119. }
  1120. }
  1121. }