GlslGenerator.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. using Ryujinx.Graphics.Shader.CodeGen.Glsl.Instructions;
  2. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  3. using Ryujinx.Graphics.Shader.StructuredIr;
  4. using Ryujinx.Graphics.Shader.Translation;
  5. using System;
  6. using static Ryujinx.Graphics.Shader.CodeGen.Glsl.TypeConversion;
  7. namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
  8. {
  9. static class GlslGenerator
  10. {
  11. private const string MainFunctionName = "main";
  12. public static GlslProgram Generate(StructuredProgramInfo info, ShaderConfig config)
  13. {
  14. CodeGenContext context = new CodeGenContext(info, config);
  15. Declarations.Declare(context, info);
  16. if (info.Functions.Count != 0)
  17. {
  18. for (int i = 1; i < info.Functions.Count; i++)
  19. {
  20. context.AppendLine($"{GetFunctionSignature(info.Functions[i])};");
  21. }
  22. context.AppendLine();
  23. for (int i = 1; i < info.Functions.Count; i++)
  24. {
  25. PrintFunction(context, info, info.Functions[i]);
  26. context.AppendLine();
  27. }
  28. }
  29. PrintFunction(context, info, info.Functions[0], MainFunctionName);
  30. return new GlslProgram(
  31. context.CBufferDescriptors.ToArray(),
  32. context.SBufferDescriptors.ToArray(),
  33. context.TextureDescriptors.ToArray(),
  34. context.ImageDescriptors.ToArray(),
  35. context.GetCode());
  36. }
  37. private static void PrintFunction(CodeGenContext context, StructuredProgramInfo info, StructuredFunction function, string funcName = null)
  38. {
  39. context.CurrentFunction = function;
  40. context.AppendLine(GetFunctionSignature(function, funcName));
  41. context.EnterScope();
  42. Declarations.DeclareLocals(context, function);
  43. if (funcName == MainFunctionName)
  44. {
  45. // Some games will leave some elements of gl_Position uninitialized,
  46. // in those cases, the elements will contain undefined values according
  47. // to the spec, but on NVIDIA they seems to be always initialized to (0, 0, 0, 1),
  48. // so we do explicit initialization to avoid UB on non-NVIDIA gpus.
  49. if (context.Config.Stage == ShaderStage.Vertex)
  50. {
  51. context.AppendLine("gl_Position = vec4(0.0, 0.0, 0.0, 1.0);");
  52. }
  53. // Ensure that unused attributes are set, otherwise the downstream
  54. // compiler may eliminate them.
  55. // (Not needed for fragment shader as it is the last stage).
  56. if (context.Config.Stage != ShaderStage.Compute &&
  57. context.Config.Stage != ShaderStage.Fragment)
  58. {
  59. for (int attr = 0; attr < Declarations.MaxAttributes; attr++)
  60. {
  61. if (info.OAttributes.Contains(attr))
  62. {
  63. continue;
  64. }
  65. if ((context.Config.Flags & TranslationFlags.Feedback) != 0)
  66. {
  67. context.AppendLine($"{DefaultNames.OAttributePrefix}{attr}_x = 0;");
  68. context.AppendLine($"{DefaultNames.OAttributePrefix}{attr}_y = 0;");
  69. context.AppendLine($"{DefaultNames.OAttributePrefix}{attr}_z = 0;");
  70. context.AppendLine($"{DefaultNames.OAttributePrefix}{attr}_w = 0;");
  71. }
  72. else
  73. {
  74. context.AppendLine($"{DefaultNames.OAttributePrefix}{attr} = vec4(0);");
  75. }
  76. }
  77. }
  78. }
  79. PrintBlock(context, function.MainBlock);
  80. context.LeaveScope();
  81. }
  82. private static string GetFunctionSignature(StructuredFunction function, string funcName = null)
  83. {
  84. string[] args = new string[function.InArguments.Length + function.OutArguments.Length];
  85. for (int i = 0; i < function.InArguments.Length; i++)
  86. {
  87. args[i] = $"{Declarations.GetVarTypeName(function.InArguments[i])} {OperandManager.GetArgumentName(i)}";
  88. }
  89. for (int i = 0; i < function.OutArguments.Length; i++)
  90. {
  91. int j = i + function.InArguments.Length;
  92. args[j] = $"out {Declarations.GetVarTypeName(function.OutArguments[i])} {OperandManager.GetArgumentName(j)}";
  93. }
  94. return $"{Declarations.GetVarTypeName(function.ReturnType)} {funcName ?? function.Name}({string.Join(", ", args)})";
  95. }
  96. private static void PrintBlock(CodeGenContext context, AstBlock block)
  97. {
  98. AstBlockVisitor visitor = new AstBlockVisitor(block);
  99. visitor.BlockEntered += (sender, e) =>
  100. {
  101. switch (e.Block.Type)
  102. {
  103. case AstBlockType.DoWhile:
  104. context.AppendLine("do");
  105. break;
  106. case AstBlockType.Else:
  107. context.AppendLine("else");
  108. break;
  109. case AstBlockType.ElseIf:
  110. context.AppendLine($"else if ({GetCondExpr(context, e.Block.Condition)})");
  111. break;
  112. case AstBlockType.If:
  113. context.AppendLine($"if ({GetCondExpr(context, e.Block.Condition)})");
  114. break;
  115. default: throw new InvalidOperationException($"Found unexpected block type \"{e.Block.Type}\".");
  116. }
  117. context.EnterScope();
  118. };
  119. visitor.BlockLeft += (sender, e) =>
  120. {
  121. context.LeaveScope();
  122. if (e.Block.Type == AstBlockType.DoWhile)
  123. {
  124. context.AppendLine($"while ({GetCondExpr(context, e.Block.Condition)});");
  125. }
  126. };
  127. foreach (IAstNode node in visitor.Visit())
  128. {
  129. if (node is AstOperation operation)
  130. {
  131. context.AppendLine(InstGen.GetExpression(context, operation) + ";");
  132. }
  133. else if (node is AstAssignment assignment)
  134. {
  135. VariableType srcType = OperandManager.GetNodeDestType(context, assignment.Source);
  136. VariableType dstType = OperandManager.GetNodeDestType(context, assignment.Destination);
  137. string dest;
  138. if (assignment.Destination is AstOperand operand && operand.Type == OperandType.Attribute)
  139. {
  140. dest = OperandManager.GetOutAttributeName(operand, context.Config);
  141. }
  142. else
  143. {
  144. dest = InstGen.GetExpression(context, assignment.Destination);
  145. }
  146. string src = ReinterpretCast(context, assignment.Source, srcType, dstType);
  147. context.AppendLine(dest + " = " + src + ";");
  148. }
  149. else if (node is AstComment comment)
  150. {
  151. context.AppendLine("// " + comment.Comment);
  152. }
  153. else
  154. {
  155. throw new InvalidOperationException($"Found unexpected node type \"{node?.GetType().Name ?? "null"}\".");
  156. }
  157. }
  158. }
  159. private static string GetCondExpr(CodeGenContext context, IAstNode cond)
  160. {
  161. VariableType srcType = OperandManager.GetNodeDestType(context, cond);
  162. return ReinterpretCast(context, cond, srcType, VariableType.Bool);
  163. }
  164. }
  165. }