GlslDecompiler.cs 35 KB

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