GlslDecompiler.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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.Vertex)
  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. SB.AppendLine(IdentationStr + GlslDecl.PositionOutAttrName + " = gl_Position;");
  280. SB.AppendLine(IdentationStr + GlslDecl.PositionOutAttrName + ".w = 1;");
  281. }
  282. SB.AppendLine("}");
  283. }
  284. private void PrintBlockScope(
  285. ShaderIrBlock Block,
  286. ShaderIrBlock EndBlock,
  287. ShaderIrBlock LoopBlock,
  288. string ScopeName,
  289. string Identation,
  290. bool IsDoWhile = false)
  291. {
  292. string UpIdent = Identation.Substring(0, Identation.Length - IdentationStr.Length);
  293. if (IsDoWhile)
  294. {
  295. SB.AppendLine(UpIdent + "do {");
  296. }
  297. else
  298. {
  299. SB.AppendLine(UpIdent + ScopeName + " {");
  300. }
  301. while (Block != null && Block != EndBlock)
  302. {
  303. ShaderIrNode[] Nodes = Block.GetNodes();
  304. Block = PrintNodes(Block, EndBlock, LoopBlock, Identation, Nodes);
  305. }
  306. if (IsDoWhile)
  307. {
  308. SB.AppendLine(UpIdent + "} " + ScopeName + ";");
  309. }
  310. else
  311. {
  312. SB.AppendLine(UpIdent + "}");
  313. }
  314. }
  315. private ShaderIrBlock PrintNodes(
  316. ShaderIrBlock Block,
  317. ShaderIrBlock EndBlock,
  318. ShaderIrBlock LoopBlock,
  319. string Identation,
  320. params ShaderIrNode[] Nodes)
  321. {
  322. /*
  323. * Notes about control flow and if-else/loop generation:
  324. * The code assumes that the program has sane control flow,
  325. * that is, there's no jumps to a location after another jump or
  326. * jump target (except for the end of an if-else block), and backwards
  327. * jumps to a location before the last loop dominator.
  328. * Such cases needs to be transformed on a step before the GLSL code
  329. * generation to ensure that we have sane graphs to work with.
  330. * TODO: Such transformation is not yet implemented.
  331. */
  332. string NewIdent = Identation + IdentationStr;
  333. ShaderIrBlock LoopTail = GetLoopTailBlock(Block);
  334. if (LoopTail != null && LoopBlock != Block)
  335. {
  336. //Shoock! kuma shock! We have a loop here!
  337. //The entire sequence needs to be inside a do-while block.
  338. ShaderIrBlock LoopEnd = GetDownBlock(LoopTail);
  339. PrintBlockScope(Block, LoopEnd, Block, "while (false)", NewIdent, IsDoWhile: true);
  340. return LoopEnd;
  341. }
  342. foreach (ShaderIrNode Node in Nodes)
  343. {
  344. if (Node is ShaderIrCond Cond)
  345. {
  346. string IfExpr = GetSrcExpr(Cond.Pred, true);
  347. if (Cond.Not)
  348. {
  349. IfExpr = "!(" + IfExpr + ")";
  350. }
  351. if (Cond.Child is ShaderIrOp Op && Op.Inst == ShaderIrInst.Bra)
  352. {
  353. //Branch is a loop branch and would result in infinite recursion.
  354. if (Block.Branch.Position <= Block.Position)
  355. {
  356. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  357. SB.AppendLine(Identation + IdentationStr + "continue;");
  358. SB.AppendLine(Identation + "}");
  359. continue;
  360. }
  361. string SubScopeName = "if (!" + IfExpr + ")";
  362. PrintBlockScope(Block.Next, Block.Branch, LoopBlock, SubScopeName, NewIdent);
  363. ShaderIrBlock IfElseEnd = GetUpBlock(Block.Branch).Branch;
  364. if (IfElseEnd?.Position > Block.Branch.Position)
  365. {
  366. PrintBlockScope(Block.Branch, IfElseEnd, LoopBlock, "else", NewIdent);
  367. return IfElseEnd;
  368. }
  369. return Block.Branch;
  370. }
  371. else
  372. {
  373. SB.AppendLine(Identation + "if (" + IfExpr + ") {");
  374. PrintNodes(Block, EndBlock, LoopBlock, NewIdent, Cond.Child);
  375. SB.AppendLine(Identation + "}");
  376. }
  377. }
  378. else if (Node is ShaderIrAsg Asg)
  379. {
  380. if (IsValidOutOper(Asg.Dst))
  381. {
  382. string Expr = GetSrcExpr(Asg.Src, true);
  383. Expr = GetExprWithCast(Asg.Dst, Asg.Src, Expr);
  384. SB.AppendLine(Identation + GetDstOperName(Asg.Dst) + " = " + Expr + ";");
  385. }
  386. }
  387. else if (Node is ShaderIrOp Op)
  388. {
  389. if (Op.Inst == ShaderIrInst.Bra)
  390. {
  391. if (Block.Branch.Position <= Block.Position)
  392. {
  393. SB.AppendLine(Identation + "continue;");
  394. }
  395. continue;
  396. }
  397. SB.AppendLine(Identation + GetSrcExpr(Op, true) + ";");
  398. }
  399. else if (Node is ShaderIrCmnt Cmnt)
  400. {
  401. SB.AppendLine(Identation + "// " + Cmnt.Comment);
  402. }
  403. else
  404. {
  405. throw new InvalidOperationException();
  406. }
  407. }
  408. return Block.Next;
  409. }
  410. private ShaderIrBlock GetUpBlock(ShaderIrBlock Block)
  411. {
  412. return Blocks.FirstOrDefault(x => x.EndPosition == Block.Position);
  413. }
  414. private ShaderIrBlock GetDownBlock(ShaderIrBlock Block)
  415. {
  416. return Blocks.FirstOrDefault(x => x.Position == Block.EndPosition);
  417. }
  418. private ShaderIrBlock GetLoopTailBlock(ShaderIrBlock LoopHead)
  419. {
  420. ShaderIrBlock Tail = null;
  421. foreach (ShaderIrBlock Block in LoopHead.Sources)
  422. {
  423. if (Block.Position >= LoopHead.Position)
  424. {
  425. if (Tail == null || Tail.Position < Block.Position)
  426. {
  427. Tail = Block;
  428. }
  429. }
  430. }
  431. return Tail;
  432. }
  433. private bool IsValidOutOper(ShaderIrNode Node)
  434. {
  435. if (Node is ShaderIrOperGpr Gpr && Gpr.IsConst)
  436. {
  437. return false;
  438. }
  439. else if (Node is ShaderIrOperPred Pred && Pred.IsConst)
  440. {
  441. return false;
  442. }
  443. return true;
  444. }
  445. private string GetDstOperName(ShaderIrNode Node)
  446. {
  447. if (Node is ShaderIrOperAbuf Abuf)
  448. {
  449. return GetOutAbufName(Abuf);
  450. }
  451. else if (Node is ShaderIrOperGpr Gpr)
  452. {
  453. return GetName(Gpr);
  454. }
  455. else if (Node is ShaderIrOperPred Pred)
  456. {
  457. return GetName(Pred);
  458. }
  459. throw new ArgumentException(nameof(Node));
  460. }
  461. private string GetSrcExpr(ShaderIrNode Node, bool Entry = false)
  462. {
  463. switch (Node)
  464. {
  465. case ShaderIrOperAbuf Abuf: return GetName (Abuf);
  466. case ShaderIrOperCbuf Cbuf: return GetName (Cbuf);
  467. case ShaderIrOperGpr Gpr: return GetName (Gpr);
  468. case ShaderIrOperImm Imm: return GetValue(Imm);
  469. case ShaderIrOperImmf Immf: return GetValue(Immf);
  470. case ShaderIrOperPred Pred: return GetName (Pred);
  471. case ShaderIrOp Op:
  472. string Expr;
  473. if (InstsExpr.TryGetValue(Op.Inst, out GetInstExpr GetExpr))
  474. {
  475. Expr = GetExpr(Op);
  476. }
  477. else
  478. {
  479. throw new NotImplementedException(Op.Inst.ToString());
  480. }
  481. if (!Entry && NeedsParentheses(Op))
  482. {
  483. Expr = "(" + Expr + ")";
  484. }
  485. return Expr;
  486. default: throw new ArgumentException(nameof(Node));
  487. }
  488. }
  489. private static bool NeedsParentheses(ShaderIrOp Op)
  490. {
  491. switch (Op.Inst)
  492. {
  493. case ShaderIrInst.Frcp:
  494. return true;
  495. case ShaderIrInst.Ipa:
  496. case ShaderIrInst.Texq:
  497. case ShaderIrInst.Texs:
  498. case ShaderIrInst.Txlf:
  499. return false;
  500. }
  501. return Op.OperandB != null ||
  502. Op.OperandC != null;
  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 Imm.Value.ToString(CultureInfo.InvariantCulture);
  590. }
  591. }
  592. private string GetValue(ShaderIrOperImmf Immf)
  593. {
  594. return Immf.Value.ToString(CultureInfo.InvariantCulture);
  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 Value.ToString(CultureInfo.InvariantCulture);
  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 OperType GetDstNodeType(ShaderIrNode Node)
  846. {
  847. //Special case instructions with the result type different
  848. //from the input types (like integer <-> float conversion) here.
  849. if (Node is ShaderIrOp Op)
  850. {
  851. switch (Op.Inst)
  852. {
  853. case ShaderIrInst.Stof:
  854. case ShaderIrInst.Txlf:
  855. case ShaderIrInst.Utof:
  856. return OperType.F32;
  857. case ShaderIrInst.Ftos:
  858. case ShaderIrInst.Ftou:
  859. return OperType.I32;
  860. }
  861. }
  862. return GetSrcNodeType(Node);
  863. }
  864. private static OperType GetSrcNodeType(ShaderIrNode Node)
  865. {
  866. switch (Node)
  867. {
  868. case ShaderIrOperAbuf Abuf:
  869. return Abuf.Offs == GlslDecl.VertexIdAttr ||
  870. Abuf.Offs == GlslDecl.InstanceIdAttr ||
  871. Abuf.Offs == GlslDecl.FaceAttr
  872. ? OperType.I32
  873. : OperType.F32;
  874. case ShaderIrOperCbuf Cbuf: return OperType.F32;
  875. case ShaderIrOperGpr Gpr: return OperType.F32;
  876. case ShaderIrOperImm Imm: return OperType.I32;
  877. case ShaderIrOperImmf Immf: return OperType.F32;
  878. case ShaderIrOperPred Pred: return OperType.Bool;
  879. case ShaderIrOp Op:
  880. if (Op.Inst > ShaderIrInst.B_Start &&
  881. Op.Inst < ShaderIrInst.B_End)
  882. {
  883. return OperType.Bool;
  884. }
  885. else if (Op.Inst > ShaderIrInst.F_Start &&
  886. Op.Inst < ShaderIrInst.F_End)
  887. {
  888. return OperType.F32;
  889. }
  890. else if (Op.Inst > ShaderIrInst.I_Start &&
  891. Op.Inst < ShaderIrInst.I_End)
  892. {
  893. return OperType.I32;
  894. }
  895. break;
  896. }
  897. throw new ArgumentException(nameof(Node));
  898. }
  899. }
  900. }