GlslDecompiler.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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 static string[] ElemTypes = new string[] { "float", "vec2", "vec3", "vec4" };
  20. private GlslDecl Decl;
  21. private StringBuilder SB;
  22. public GlslDecompiler()
  23. {
  24. InstsExpr = new Dictionary<ShaderIrInst, GetInstExpr>()
  25. {
  26. { ShaderIrInst.Abs, GetAbsExpr },
  27. { ShaderIrInst.Add, GetAddExpr },
  28. { ShaderIrInst.And, GetAndExpr },
  29. { ShaderIrInst.Asr, GetAsrExpr },
  30. { ShaderIrInst.Band, GetBandExpr },
  31. { ShaderIrInst.Bnot, GetBnotExpr },
  32. { ShaderIrInst.Ceil, GetCeilExpr },
  33. { ShaderIrInst.Ceq, GetCeqExpr },
  34. { ShaderIrInst.Cge, GetCgeExpr },
  35. { ShaderIrInst.Cgt, GetCgtExpr },
  36. { ShaderIrInst.Clamps, GetClampsExpr },
  37. { ShaderIrInst.Clampu, GetClampuExpr },
  38. { ShaderIrInst.Cle, GetCleExpr },
  39. { ShaderIrInst.Clt, GetCltExpr },
  40. { ShaderIrInst.Cne, GetCneExpr },
  41. { ShaderIrInst.Exit, GetExitExpr },
  42. { ShaderIrInst.Fabs, GetAbsExpr },
  43. { ShaderIrInst.Fadd, GetAddExpr },
  44. { ShaderIrInst.Fceq, GetCeqExpr },
  45. { ShaderIrInst.Fcge, GetCgeExpr },
  46. { ShaderIrInst.Fcgt, GetCgtExpr },
  47. { ShaderIrInst.Fclamp, GetFclampExpr },
  48. { ShaderIrInst.Fcle, GetCleExpr },
  49. { ShaderIrInst.Fclt, GetCltExpr },
  50. { ShaderIrInst.Fcne, GetCneExpr },
  51. { ShaderIrInst.Fcos, GetFcosExpr },
  52. { ShaderIrInst.Fex2, GetFex2Expr },
  53. { ShaderIrInst.Ffma, GetFfmaExpr },
  54. { ShaderIrInst.Flg2, GetFlg2Expr },
  55. { ShaderIrInst.Floor, GetFloorExpr },
  56. { ShaderIrInst.Fmax, GetFmaxExpr },
  57. { ShaderIrInst.Fmin, GetFminExpr },
  58. { ShaderIrInst.Fmul, GetMulExpr },
  59. { ShaderIrInst.Fneg, GetNegExpr },
  60. { ShaderIrInst.Frcp, GetFrcpExpr },
  61. { ShaderIrInst.Frsq, GetFrsqExpr },
  62. { ShaderIrInst.Fsin, GetFsinExpr },
  63. { ShaderIrInst.Ftos, GetFtosExpr },
  64. { ShaderIrInst.Ftou, GetFtouExpr },
  65. { ShaderIrInst.Ipa, GetIpaExpr },
  66. { ShaderIrInst.Kil, GetKilExpr },
  67. { ShaderIrInst.Lsl, GetLslExpr },
  68. { ShaderIrInst.Lsr, GetLsrExpr },
  69. { ShaderIrInst.Mul, GetMulExpr },
  70. { ShaderIrInst.Neg, GetNegExpr },
  71. { ShaderIrInst.Not, GetNotExpr },
  72. { ShaderIrInst.Or, GetOrExpr },
  73. { ShaderIrInst.Stof, GetStofExpr },
  74. { ShaderIrInst.Sub, GetSubExpr },
  75. { ShaderIrInst.Texq, GetTexqExpr },
  76. { ShaderIrInst.Texs, GetTexsExpr },
  77. { ShaderIrInst.Trunc, GetTruncExpr },
  78. { ShaderIrInst.Txlf, GetTxlfExpr },
  79. { ShaderIrInst.Utof, GetUtofExpr },
  80. { ShaderIrInst.Xor, GetXorExpr }
  81. };
  82. }
  83. public GlslProgram Decompile(int[] Code, GalShaderType ShaderType)
  84. {
  85. ShaderIrBlock Block = ShaderDecoder.DecodeBasicBlock(Code, 0);
  86. ShaderIrNode[] Nodes = Block.GetNodes();
  87. Decl = new GlslDecl(Nodes, ShaderType);
  88. SB = new StringBuilder();
  89. SB.AppendLine("#version 410 core");
  90. PrintDeclTextures();
  91. PrintDeclUniforms();
  92. PrintDeclInAttributes();
  93. PrintDeclOutAttributes();
  94. PrintDeclGprs();
  95. PrintDeclPreds();
  96. PrintBlockScope(Nodes, 0, Nodes.Length, "void main()", 1);
  97. string GlslCode = SB.ToString();
  98. return new GlslProgram(
  99. GlslCode,
  100. Decl.Textures.Values,
  101. Decl.Uniforms.Values);
  102. }
  103. private void PrintDeclTextures()
  104. {
  105. PrintDecls(Decl.Textures, "uniform sampler2D");
  106. }
  107. private void PrintDeclUniforms()
  108. {
  109. if (Decl.ShaderType == GalShaderType.Vertex)
  110. {
  111. SB.AppendLine("uniform vec2 " + GalConsts.FlipUniformName + ";");
  112. }
  113. foreach (ShaderDeclInfo DeclInfo in Decl.Uniforms.Values.OrderBy(DeclKeySelector))
  114. {
  115. SB.AppendLine($"uniform {GetDecl(DeclInfo)}[{DeclInfo.Index + 1}];");
  116. }
  117. if (Decl.Uniforms.Count > 0)
  118. {
  119. SB.AppendLine();
  120. }
  121. }
  122. private void PrintDeclInAttributes()
  123. {
  124. if (Decl.ShaderType == GalShaderType.Fragment)
  125. {
  126. SB.AppendLine("in vec4 " + GlslDecl.PositionOutAttrName + ";");
  127. }
  128. PrintDeclAttributes(Decl.InAttributes.Values, "in");
  129. }
  130. private void PrintDeclOutAttributes()
  131. {
  132. if (Decl.ShaderType == GalShaderType.Vertex)
  133. {
  134. SB.AppendLine("out vec4 " + GlslDecl.PositionOutAttrName + ";");
  135. }
  136. PrintDeclAttributes(Decl.OutAttributes.Values, "out");
  137. }
  138. private void PrintDeclAttributes(IEnumerable<ShaderDeclInfo> Decls, string InOut)
  139. {
  140. int Count = 0;
  141. foreach (ShaderDeclInfo DeclInfo in Decls.OrderBy(DeclKeySelector))
  142. {
  143. if (DeclInfo.Index >= 0)
  144. {
  145. SB.AppendLine("layout (location = " + DeclInfo.Index + ") " + InOut + " " + GetDecl(DeclInfo) + ";");
  146. Count++;
  147. }
  148. }
  149. if (Count > 0)
  150. {
  151. SB.AppendLine();
  152. }
  153. }
  154. private void PrintDeclGprs()
  155. {
  156. PrintDecls(Decl.Gprs);
  157. }
  158. private void PrintDeclPreds()
  159. {
  160. PrintDecls(Decl.Preds, "bool");
  161. }
  162. private void PrintDecls(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, string CustomType = null)
  163. {
  164. foreach (ShaderDeclInfo DeclInfo in Dict.Values.OrderBy(DeclKeySelector))
  165. {
  166. string Name;
  167. if (CustomType != null)
  168. {
  169. Name = CustomType + " " + DeclInfo.Name + ";";
  170. }
  171. else if (DeclInfo.Name == GlslDecl.FragmentOutputName)
  172. {
  173. Name = "layout (location = 0) out " + GetDecl(DeclInfo) + ";" + Environment.NewLine;
  174. }
  175. else
  176. {
  177. Name = GetDecl(DeclInfo) + ";";
  178. }
  179. SB.AppendLine(Name);
  180. }
  181. if (Dict.Count > 0)
  182. {
  183. SB.AppendLine();
  184. }
  185. }
  186. private int DeclKeySelector(ShaderDeclInfo DeclInfo)
  187. {
  188. return DeclInfo.Cbuf << 24 | DeclInfo.Index;
  189. }
  190. private string GetDecl(ShaderDeclInfo DeclInfo)
  191. {
  192. return ElemTypes[DeclInfo.Size - 1] + " " + DeclInfo.Name;
  193. }
  194. private void PrintBlockScope(
  195. ShaderIrNode[] Nodes,
  196. int Start,
  197. int Count,
  198. string ScopeName,
  199. int IdentationLevel)
  200. {
  201. string Identation = string.Empty;
  202. for (int Index = 0; Index < IdentationLevel - 1; Index++)
  203. {
  204. Identation += IdentationStr;
  205. }
  206. if (ScopeName != string.Empty)
  207. {
  208. ScopeName += " ";
  209. }
  210. SB.AppendLine(Identation + ScopeName + "{");
  211. string LastLine = Identation + "}";
  212. if (IdentationLevel > 0)
  213. {
  214. Identation += IdentationStr;
  215. }
  216. for (int Index = Start; Index < Start + Count; Index++)
  217. {
  218. ShaderIrNode Node = Nodes[Index];
  219. if (Node is ShaderIrCond Cond)
  220. {
  221. string IfExpr = GetSrcExpr(Cond.Pred, true);
  222. if (Cond.Not)
  223. {
  224. IfExpr = "!(" + IfExpr + ")";
  225. }
  226. if (Cond.Child is ShaderIrOp Op && Op.Inst == ShaderIrInst.Bra)
  227. {
  228. ShaderIrLabel Label = (ShaderIrLabel)Op.OperandA;
  229. int Target = FindLabel(Nodes, Label, Index + 1);
  230. int IfCount = Target - Index - 1;
  231. string SubScopeName = "if (!" + IfExpr + ")";
  232. if (Nodes[Index + IfCount] is ShaderIrOp LastOp && LastOp.Inst == ShaderIrInst.Bra)
  233. {
  234. Target = FindLabel(Nodes, (ShaderIrLabel)LastOp.OperandA, Index + 1);
  235. int ElseCount = Target - (Index + 1 + IfCount);
  236. PrintBlockScope(Nodes, Index + 1, IfCount - 1, SubScopeName, IdentationLevel + 1);
  237. PrintBlockScope(Nodes, Index + 1 + IfCount, ElseCount, "else", IdentationLevel + 1);
  238. Index += IfCount + ElseCount;
  239. }
  240. else
  241. {
  242. PrintBlockScope(Nodes, Index + 1, IfCount, SubScopeName, IdentationLevel + 1);
  243. Index += IfCount;
  244. }
  245. }
  246. else
  247. {
  248. string SubScopeName = "if (" + IfExpr + ")";
  249. ShaderIrNode[] Child = new ShaderIrNode[] { Cond.Child };
  250. PrintBlockScope(Child, 0, 1, SubScopeName, IdentationLevel + 1);
  251. }
  252. }
  253. else if (Node is ShaderIrAsg Asg)
  254. {
  255. if (IsValidOutOper(Asg.Dst))
  256. {
  257. string Expr = GetSrcExpr(Asg.Src, true);
  258. Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr);
  259. SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";");
  260. }
  261. }
  262. else if (Node is ShaderIrOp Op)
  263. {
  264. if (Op.Inst == ShaderIrInst.Exit)
  265. {
  266. //Do everything that needs to be done before
  267. //the shader ends here.
  268. if (Decl.ShaderType == GalShaderType.Vertex)
  269. {
  270. SB.AppendLine(Identation + "gl_Position.xy *= flip;");
  271. SB.AppendLine(Identation + GlslDecl.PositionOutAttrName + " = gl_Position;");
  272. }
  273. }
  274. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  275. }
  276. else if (Node is ShaderIrLabel Label)
  277. {
  278. //TODO: Add support for loops here.
  279. }
  280. else if (Node is ShaderIrCmnt Cmnt)
  281. {
  282. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  283. }
  284. else
  285. {
  286. throw new InvalidOperationException();
  287. }
  288. }
  289. SB.AppendLine(LastLine);
  290. }
  291. private int FindLabel(ShaderIrNode[] Nodes, ShaderIrLabel Label, int Start)
  292. {
  293. int Target;
  294. for (Target = Start; Target < Nodes.Length; Target++)
  295. {
  296. if (Nodes[Target] == Label)
  297. {
  298. return Target;
  299. }
  300. }
  301. throw new InvalidOperationException();
  302. }
  303. private bool IsValidOutOper(ShaderIrNode Node)
  304. {
  305. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  306. {
  307. return false;
  308. }
  309. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  310. {
  311. return false;
  312. }
  313. return true;
  314. }
  315. private string GetDstOperName(ShaderIrNode Node)
  316. {
  317. if (Node is ShaderIrOperAbuf Abuf)
  318. {
  319. return GetOutAbufName(Abuf);
  320. }
  321. else if (Node is ShaderIrOperGpr Gpr)
  322. {
  323. return GetName(Gpr);
  324. }
  325. else if (Node is ShaderIrOperPred Pred)
  326. {
  327. return GetName(Pred);
  328. }
  329. throw new ArgumentException(nameof(Node));
  330. }
  331. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  332. {
  333. switch (Node)
  334. {
  335. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  336. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  337. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  338. case ShaderIrOperImm Imm: return GetValue(Imm);
  339. case ShaderIrOperImmf Immf: return GetValue(Immf);
  340. case ShaderIrOperPred Pred: return GetName (Pred);
  341. case ShaderIrOp Op:
  342. string Expr;
  343. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  344. {
  345. Expr = GetExpr(Op);
  346. }
  347. else
  348. {
  349. throw new NotImplementedException(Op.Inst.ToString());
  350. }
  351. if (!Entry && NeedsParentheses(Op))
  352. {
  353. Expr = "(" + Expr + ")";
  354. }
  355. return Expr;
  356. default: throw new ArgumentException(nameof(Node));
  357. }
  358. }
  359. private static bool NeedsParentheses(ShaderIrOp Op)
  360. {
  361. switch (Op.Inst)
  362. {
  363. case ShaderIrInst.Frcp:
  364. return true;
  365. case ShaderIrInst.Ipa:
  366. case ShaderIrInst.Texq:
  367. case ShaderIrInst.Texs:
  368. case ShaderIrInst.Txlf:
  369. return false;
  370. }
  371. return Op.OperandB != null ||
  372. Op.OperandC != null;
  373. }
  374. private string GetName(ShaderIrOperCbuf Cbuf)
  375. {
  376. if (!Decl.Uniforms.TryGetValue(Cbuf.Index, out ShaderDeclInfo DeclInfo))
  377. {
  378. throw new InvalidOperationException();
  379. }
  380. if (Cbuf.Offs != null)
  381. {
  382. //Note: We assume that the register value is always a multiple of 4.
  383. //This may not be aways the case.
  384. string Offset = "(floatBitsToInt(" + GetSrcExpr(Cbuf.Offs) + ") >> 2)";
  385. return DeclInfo.Name + "[" + Cbuf.Pos + " + " + Offset + "]";
  386. }
  387. else
  388. {
  389. return DeclInfo.Name + "[" + Cbuf.Pos + "]";
  390. }
  391. }
  392. private string GetOutAbufName(ShaderIrOperAbuf Abuf)
  393. {
  394. return GetName(Decl.OutAttributes, Abuf);
  395. }
  396. private string GetName(ShaderIrOperAbuf Abuf)
  397. {
  398. if (Abuf.Offs == GlslDecl.VertexIdAttr)
  399. {
  400. return "gl_VertexID";
  401. }
  402. return GetName(Decl.InAttributes, Abuf);
  403. }
  404. private string GetName(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, ShaderIrOperAbuf Abuf)
  405. {
  406. int Index = Abuf.Offs >> 4;
  407. int Elem = (Abuf.Offs >> 2) & 3;
  408. if (!Dict.TryGetValue(Index, out ShaderDeclInfo DeclInfo))
  409. {
  410. throw new InvalidOperationException();
  411. }
  412. return DeclInfo.Size > 1 ? DeclInfo.Name + "." + GetAttrSwizzle(Elem) : DeclInfo.Name;
  413. }
  414. private string GetName(ShaderIrOperGpr Gpr)
  415. {
  416. return Gpr.IsConst ? "0" : GetNameWithSwizzle(Decl.Gprs, Gpr.Index);
  417. }
  418. private string GetValue(ShaderIrOperImm Imm)
  419. {
  420. //Only use hex is the value is too big and would likely be hard to read as int.
  421. if (Imm.Value > 0xfff ||
  422. Imm.Value < -0xfff)
  423. {
  424. return "0x" + Imm.Value.ToString("x8", CultureInfo.InvariantCulture);
  425. }
  426. else
  427. {
  428. return Imm.Value.ToString(CultureInfo.InvariantCulture);
  429. }
  430. }
  431. private string GetValue(ShaderIrOperImmf Immf)
  432. {
  433. return Immf.Value.ToString(CultureInfo.InvariantCulture);
  434. }
  435. private string GetName(ShaderIrOperPred Pred)
  436. {
  437. return Pred.IsConst ? "true" : GetNameWithSwizzle(Decl.Preds, Pred.Index);
  438. }
  439. private string GetNameWithSwizzle(IReadOnlyDictionary<int, ShaderDeclInfo> Dict, int Index)
  440. {
  441. int VecIndex = Index >> 2;
  442. if (Dict.TryGetValue(VecIndex, out ShaderDeclInfo DeclInfo))
  443. {
  444. if (DeclInfo.Size > 1 && Index < VecIndex + DeclInfo.Size)
  445. {
  446. return DeclInfo.Name + "." + GetAttrSwizzle(Index & 3);
  447. }
  448. }
  449. if (!Dict.TryGetValue(Index, out DeclInfo))
  450. {
  451. throw new InvalidOperationException();
  452. }
  453. return DeclInfo.Name;
  454. }
  455. private string GetAttrSwizzle(int Elem)
  456. {
  457. return "xyzw".Substring(Elem, 1);
  458. }
  459. private string GetAbsExpr(ShaderIrOp Op) => GetUnaryCall(Op, "abs");
  460. private string GetAddExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "+");
  461. private string GetAndExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&");
  462. private string GetAsrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">>");
  463. private string GetBandExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "&&");
  464. private string GetBnotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "!");
  465. private string GetCeilExpr(ShaderIrOp Op) => GetUnaryCall(Op, "ceil");
  466. private string GetClampsExpr(ShaderIrOp Op)
  467. {
  468. return "clamp(" + GetOperExpr(Op, Op.OperandA) + ", " +
  469. GetOperExpr(Op, Op.OperandB) + ", " +
  470. GetOperExpr(Op, Op.OperandC) + ")";
  471. }
  472. private string GetClampuExpr(ShaderIrOp Op)
  473. {
  474. return "int(clamp(uint(" + GetOperExpr(Op, Op.OperandA) + "), " +
  475. "uint(" + GetOperExpr(Op, Op.OperandB) + "), " +
  476. "uint(" + GetOperExpr(Op, Op.OperandC) + ")))";
  477. }
  478. private string GetCltExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<");
  479. private string GetCeqExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "==");
  480. private string GetCleExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<=");
  481. private string GetCgtExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">");
  482. private string GetCneExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "!=");
  483. private string GetCgeExpr(ShaderIrOp Op) => GetBinaryExpr(Op, ">=");
  484. private string GetExitExpr(ShaderIrOp Op) => "return";
  485. private string GetFcosExpr(ShaderIrOp Op) => GetUnaryCall(Op, "cos");
  486. private string GetFex2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "exp2");
  487. private string GetFfmaExpr(ShaderIrOp Op) => GetTernaryExpr(Op, "*", "+");
  488. private string GetFclampExpr(ShaderIrOp Op) => GetTernaryCall(Op, "clamp");
  489. private string GetFlg2Expr(ShaderIrOp Op) => GetUnaryCall(Op, "log2");
  490. private string GetFloorExpr(ShaderIrOp Op) => GetUnaryCall(Op, "floor");
  491. private string GetFmaxExpr(ShaderIrOp Op) => GetBinaryCall(Op, "max");
  492. private string GetFminExpr(ShaderIrOp Op) => GetBinaryCall(Op, "min");
  493. private string GetFrcpExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "1 / ");
  494. private string GetFrsqExpr(ShaderIrOp Op) => GetUnaryCall(Op, "inversesqrt");
  495. private string GetFsinExpr(ShaderIrOp Op) => GetUnaryCall(Op, "sin");
  496. private string GetFtosExpr(ShaderIrOp Op)
  497. {
  498. return "int(" + GetOperExpr(Op, Op.OperandA) + ")";
  499. }
  500. private string GetFtouExpr(ShaderIrOp Op)
  501. {
  502. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  503. }
  504. private string GetIpaExpr(ShaderIrOp Op) => GetSrcExpr(Op.OperandA);
  505. private string GetKilExpr(ShaderIrOp Op) => "discard";
  506. private string GetLslExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "<<");
  507. private string GetLsrExpr(ShaderIrOp Op)
  508. {
  509. return "int(uint(" + GetOperExpr(Op, Op.OperandA) + ") >> " +
  510. GetOperExpr(Op, Op.OperandB) + ")";
  511. }
  512. private string GetMulExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "*");
  513. private string GetNegExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "-");
  514. private string GetNotExpr(ShaderIrOp Op) => GetUnaryExpr(Op, "~");
  515. private string GetOrExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "|");
  516. private string GetStofExpr(ShaderIrOp Op)
  517. {
  518. return "float(" + GetOperExpr(Op, Op.OperandA) + ")";
  519. }
  520. private string GetSubExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "-");
  521. private string GetTexqExpr(ShaderIrOp Op)
  522. {
  523. ShaderIrMetaTexq Meta = (ShaderIrMetaTexq)Op.MetaData;
  524. string Ch = "xyzw".Substring(Meta.Elem, 1);
  525. if (Meta.Info == ShaderTexqInfo.Dimension)
  526. {
  527. string Sampler = GetTexSamplerName(Op);
  528. string Lod = GetOperExpr(Op, Op.OperandA); //???
  529. return "textureSize(" + Sampler + ", " + Lod + ")." + Ch;
  530. }
  531. else
  532. {
  533. throw new NotImplementedException(Meta.Info.ToString());
  534. }
  535. }
  536. private string GetTexsExpr(ShaderIrOp Op)
  537. {
  538. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  539. string Sampler = GetTexSamplerName(Op);
  540. string Coords = GetTexSamplerCoords(Op);
  541. string Ch = "rgba".Substring(Meta.Elem, 1);
  542. return "texture(" + Sampler + ", " + Coords + ")." + Ch;
  543. }
  544. private string GetTxlfExpr(ShaderIrOp Op)
  545. {
  546. ShaderIrMetaTex Meta = (ShaderIrMetaTex)Op.MetaData;
  547. string Sampler = GetTexSamplerName(Op);
  548. string Coords = GetITexSamplerCoords(Op);
  549. string Ch = "rgba".Substring(Meta.Elem, 1);
  550. return "texelFetch(" + Sampler + ", " + Coords + ", 0)." + Ch;
  551. }
  552. private string GetTruncExpr(ShaderIrOp Op) => GetUnaryCall(Op, "trunc");
  553. private string GetUtofExpr(ShaderIrOp Op)
  554. {
  555. return "float(uint(" + GetOperExpr(Op, Op.OperandA) + "))";
  556. }
  557. private string GetXorExpr(ShaderIrOp Op) => GetBinaryExpr(Op, "^");
  558. private string GetUnaryCall(ShaderIrOp Op, string FuncName)
  559. {
  560. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ")";
  561. }
  562. private string GetBinaryCall(ShaderIrOp Op, string FuncName)
  563. {
  564. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  565. GetOperExpr(Op, Op.OperandB) + ")";
  566. }
  567. private string GetTernaryCall(ShaderIrOp Op, string FuncName)
  568. {
  569. return FuncName + "(" + GetOperExpr(Op, Op.OperandA) + ", " +
  570. GetOperExpr(Op, Op.OperandB) + ", " +
  571. GetOperExpr(Op, Op.OperandC) + ")";
  572. }
  573. private string GetUnaryExpr(ShaderIrOp Op, string Opr)
  574. {
  575. return Opr + GetOperExpr(Op, Op.OperandA);
  576. }
  577. private string GetBinaryExpr(ShaderIrOp Op, string Opr)
  578. {
  579. return GetOperExpr(Op, Op.OperandA) + " " + Opr + " " +
  580. GetOperExpr(Op, Op.OperandB);
  581. }
  582. private string GetTernaryExpr(ShaderIrOp Op, string Opr1, string Opr2)
  583. {
  584. return GetOperExpr(Op, Op.OperandA) + " " + Opr1 + " " +
  585. GetOperExpr(Op, Op.OperandB) + " " + Opr2 + " " +
  586. GetOperExpr(Op, Op.OperandC);
  587. }
  588. private string GetTexSamplerName(ShaderIrOp Op)
  589. {
  590. ShaderIrOperImm Node = (ShaderIrOperImm)Op.OperandC;
  591. int Handle = ((ShaderIrOperImm)Op.OperandC).Value;
  592. if (!Decl.Textures.TryGetValue(Handle, out ShaderDeclInfo DeclInfo))
  593. {
  594. throw new InvalidOperationException();
  595. }
  596. return DeclInfo.Name;
  597. }
  598. private string GetTexSamplerCoords(ShaderIrOp Op)
  599. {
  600. return "vec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  601. GetOperExpr(Op, Op.OperandB) + ")";
  602. }
  603. private string GetITexSamplerCoords(ShaderIrOp Op)
  604. {
  605. return "ivec2(" + GetOperExpr(Op, Op.OperandA) + ", " +
  606. GetOperExpr(Op, Op.OperandB) + ")";
  607. }
  608. private string GetOperExpr(ShaderIrOp Op, ShaderIrNode Oper)
  609. {
  610. return GetExprWithCast(Op, Oper, GetSrcExpr(Oper));
  611. }
  612. private static string GetExprWithCast(ShaderIrNode Dst, ShaderIrNode Src, string Expr)
  613. {
  614. //Note: The "DstType" (of the cast) is the type that the operation
  615. //uses on the source operands, while the "SrcType" is the destination
  616. //type of the operand result (if it is a operation) or just the type
  617. //of the variable for registers/uniforms/attributes.
  618. OperType DstType = GetSrcNodeType(Dst);
  619. OperType SrcType = GetDstNodeType(Src);
  620. if (DstType != SrcType)
  621. {
  622. //Check for invalid casts
  623. //(like bool to int/float and others).
  624. if (SrcType != OperType.F32 &&
  625. SrcType != OperType.I32)
  626. {
  627. throw new InvalidOperationException();
  628. }
  629. switch (Src)
  630. {
  631. case ShaderIrOperGpr Gpr:
  632. {
  633. //When the Gpr is ZR, just return the 0 value directly,
  634. //since the float encoding for 0 is 0.
  635. if (Gpr.IsConst)
  636. {
  637. return "0";
  638. }
  639. break;
  640. }
  641. case ShaderIrOperImm Imm:
  642. {
  643. //For integer immediates being used as float,
  644. //it's better (for readability) to just return the float value.
  645. if (DstType == OperType.F32)
  646. {
  647. float Value = BitConverter.Int32BitsToSingle(Imm.Value);
  648. if (!float.IsNaN(Value) && !float.IsInfinity(Value))
  649. {
  650. return Value.ToString(CultureInfo.InvariantCulture);
  651. }
  652. }
  653. break;
  654. }
  655. }
  656. switch (DstType)
  657. {
  658. case OperType.F32: Expr = "intBitsToFloat(" + Expr + ")"; break;
  659. case OperType.I32: Expr = "floatBitsToInt(" + Expr + ")"; break;
  660. }
  661. }
  662. return Expr;
  663. }
  664. private static OperType GetDstNodeType(ShaderIrNode Node)
  665. {
  666. //Special case instructions with the result type different
  667. //from the input types (like integer <-> float conversion) here.
  668. if (Node is ShaderIrOp Op)
  669. {
  670. switch (Op.Inst)
  671. {
  672. case ShaderIrInst.Stof:
  673. case ShaderIrInst.Txlf:
  674. case ShaderIrInst.Utof:
  675. return OperType.F32;
  676. case ShaderIrInst.Ftos:
  677. case ShaderIrInst.Ftou:
  678. return OperType.I32;
  679. }
  680. }
  681. return GetSrcNodeType(Node);
  682. }
  683. private static OperType GetSrcNodeType(ShaderIrNode Node)
  684. {
  685. switch (Node)
  686. {
  687. case ShaderIrOperAbuf Abuf:
  688. return Abuf.Offs == GlslDecl.VertexIdAttr
  689. ? OperType.I32
  690. : OperType.F32;
  691. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  692. case ShaderIrOperGpr Gpr: return OperType.F32;
  693. case ShaderIrOperImm Imm: return OperType.I32;
  694. case ShaderIrOperImmf Immf: return OperType.F32;
  695. case ShaderIrOperPred Pred: return OperType.Bool;
  696. case ShaderIrOp Op:
  697. if (Op.Inst > ShaderIrInst.B_Start &&
  698. Op.Inst < ShaderIrInst.B_End)
  699. {
  700. return OperType.Bool;
  701. }
  702. else if (Op.Inst > ShaderIrInst.F_Start &&
  703. Op.Inst < ShaderIrInst.F_End)
  704. {
  705. return OperType.F32;
  706. }
  707. else if (Op.Inst > ShaderIrInst.I_Start &&
  708. Op.Inst < ShaderIrInst.I_End)
  709. {
  710. return OperType.I32;
  711. }
  712. break;
  713. }
  714. throw new ArgumentException(nameof(Node));
  715. }
  716. }
  717. }