GlslDecompiler.cs 38 KB

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