Declarations.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  3. using Ryujinx.Graphics.Shader.StructuredIr;
  4. using Ryujinx.Graphics.Shader.Translation;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
  9. {
  10. static class Declarations
  11. {
  12. // At least 16 attributes are guaranteed by the spec.
  13. public const int MaxAttributes = 16;
  14. public static void Declare(CodeGenContext context, StructuredProgramInfo info)
  15. {
  16. context.AppendLine("#version 430 core");
  17. context.AppendLine("#extension GL_ARB_gpu_shader_int64 : enable");
  18. context.AppendLine("#extension GL_ARB_shader_ballot : enable");
  19. context.AppendLine("#extension GL_ARB_shader_group_vote : enable");
  20. if (context.Config.Stage == ShaderStage.Compute)
  21. {
  22. context.AppendLine("#extension GL_ARB_compute_shader : enable");
  23. }
  24. context.AppendLine("#pragma optionNV(fastmath off)");
  25. context.AppendLine();
  26. context.AppendLine($"const int {DefaultNames.UndefinedName} = 0;");
  27. context.AppendLine();
  28. if (context.Config.Stage == ShaderStage.Geometry)
  29. {
  30. string inPrimitive = ((InputTopology)context.Config.QueryInfo(QueryInfoName.PrimitiveTopology)).ToGlslString();
  31. context.AppendLine($"layout ({inPrimitive}) in;");
  32. string outPrimitive = context.Config.OutputTopology.ToGlslString();
  33. int maxOutputVertices = context.Config.MaxOutputVertices;
  34. context.AppendLine($"layout ({outPrimitive}, max_vertices = {maxOutputVertices}) out;");
  35. context.AppendLine();
  36. }
  37. if (context.Config.Stage == ShaderStage.Compute)
  38. {
  39. int localMemorySize = BitUtils.DivRoundUp(context.Config.QueryInfo(QueryInfoName.ComputeLocalMemorySize), 4);
  40. if (localMemorySize != 0)
  41. {
  42. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  43. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  44. context.AppendLine();
  45. }
  46. int sharedMemorySize = BitUtils.DivRoundUp(context.Config.QueryInfo(QueryInfoName.ComputeSharedMemorySize), 4);
  47. if (sharedMemorySize != 0)
  48. {
  49. string sharedMemorySizeStr = NumberFormatter.FormatInt(sharedMemorySize);
  50. context.AppendLine($"shared uint {DefaultNames.SharedMemoryName}[{sharedMemorySizeStr}];");
  51. context.AppendLine();
  52. }
  53. }
  54. else if (context.Config.LocalMemorySize != 0)
  55. {
  56. int localMemorySize = BitUtils.DivRoundUp(context.Config.LocalMemorySize, 4);
  57. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  58. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  59. context.AppendLine();
  60. }
  61. if (info.CBuffers.Count != 0)
  62. {
  63. DeclareUniforms(context, info);
  64. context.AppendLine();
  65. }
  66. if (info.SBuffers.Count != 0)
  67. {
  68. DeclareStorages(context, info);
  69. context.AppendLine();
  70. }
  71. if (info.Samplers.Count != 0)
  72. {
  73. DeclareSamplers(context, info);
  74. context.AppendLine();
  75. }
  76. if (info.Images.Count != 0)
  77. {
  78. DeclareImages(context, info);
  79. context.AppendLine();
  80. }
  81. if (context.Config.Stage != ShaderStage.Compute)
  82. {
  83. if (info.IAttributes.Count != 0)
  84. {
  85. DeclareInputAttributes(context, info);
  86. context.AppendLine();
  87. }
  88. if (info.OAttributes.Count != 0 || context.Config.Stage != ShaderStage.Fragment)
  89. {
  90. DeclareOutputAttributes(context, info);
  91. context.AppendLine();
  92. }
  93. }
  94. else
  95. {
  96. string localSizeX = NumberFormatter.FormatInt(context.Config.QueryInfo(QueryInfoName.ComputeLocalSizeX));
  97. string localSizeY = NumberFormatter.FormatInt(context.Config.QueryInfo(QueryInfoName.ComputeLocalSizeY));
  98. string localSizeZ = NumberFormatter.FormatInt(context.Config.QueryInfo(QueryInfoName.ComputeLocalSizeZ));
  99. context.AppendLine(
  100. "layout (" +
  101. $"local_size_x = {localSizeX}, " +
  102. $"local_size_y = {localSizeY}, " +
  103. $"local_size_z = {localSizeZ}) in;");
  104. context.AppendLine();
  105. }
  106. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighS32) != 0)
  107. {
  108. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighS32.glsl");
  109. }
  110. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighU32) != 0)
  111. {
  112. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighU32.glsl");
  113. }
  114. if ((info.HelperFunctionsMask & HelperFunctionsMask.Shuffle) != 0)
  115. {
  116. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/Shuffle.glsl");
  117. }
  118. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleDown) != 0)
  119. {
  120. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleDown.glsl");
  121. }
  122. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleUp) != 0)
  123. {
  124. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleUp.glsl");
  125. }
  126. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleXor) != 0)
  127. {
  128. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleXor.glsl");
  129. }
  130. if ((info.HelperFunctionsMask & HelperFunctionsMask.SwizzleAdd) != 0)
  131. {
  132. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/SwizzleAdd.glsl");
  133. }
  134. }
  135. public static void DeclareLocals(CodeGenContext context, StructuredProgramInfo info)
  136. {
  137. foreach (AstOperand decl in info.Locals)
  138. {
  139. string name = context.OperandManager.DeclareLocal(decl);
  140. context.AppendLine(GetVarTypeName(decl.VarType) + " " + name + ";");
  141. }
  142. }
  143. private static string GetVarTypeName(VariableType type)
  144. {
  145. switch (type)
  146. {
  147. case VariableType.Bool: return "bool";
  148. case VariableType.F32: return "precise float";
  149. case VariableType.F64: return "double";
  150. case VariableType.S32: return "int";
  151. case VariableType.U32: return "uint";
  152. }
  153. throw new ArgumentException($"Invalid variable type \"{type}\".");
  154. }
  155. private static void DeclareUniforms(CodeGenContext context, StructuredProgramInfo info)
  156. {
  157. foreach (int cbufSlot in info.CBuffers.OrderBy(x => x))
  158. {
  159. string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  160. ubName += "_" + DefaultNames.UniformNamePrefix + cbufSlot;
  161. context.CBufferDescriptors.Add(new BufferDescriptor(ubName, cbufSlot));
  162. context.AppendLine("layout (std140) uniform " + ubName);
  163. context.EnterScope();
  164. string ubSize = "[" + NumberFormatter.FormatInt(Constants.ConstantBufferSize / 16) + "]";
  165. context.AppendLine("vec4 " + OperandManager.GetUbName(context.Config.Stage, cbufSlot) + ubSize + ";");
  166. context.LeaveScope(";");
  167. }
  168. }
  169. private static void DeclareStorages(CodeGenContext context, StructuredProgramInfo info)
  170. {
  171. string sbName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  172. sbName += "_" + DefaultNames.StorageNamePrefix;
  173. string blockName = $"{sbName}_{DefaultNames.BlockSuffix}";
  174. int maxSlot = 0;
  175. foreach (int sbufSlot in info.SBuffers)
  176. {
  177. context.SBufferDescriptors.Add(new BufferDescriptor($"{blockName}[{sbufSlot}]", sbufSlot));
  178. if (maxSlot < sbufSlot)
  179. {
  180. maxSlot = sbufSlot;
  181. }
  182. }
  183. context.AppendLine("layout (std430) buffer " + blockName);
  184. context.EnterScope();
  185. context.AppendLine("uint " + DefaultNames.DataName + "[];");
  186. string arraySize = NumberFormatter.FormatInt(maxSlot + 1);
  187. context.LeaveScope($" {sbName}[{arraySize}];");
  188. }
  189. private static void DeclareSamplers(CodeGenContext context, StructuredProgramInfo info)
  190. {
  191. Dictionary<string, AstTextureOperation> samplers = new Dictionary<string, AstTextureOperation>();
  192. // Texture instructions other than TextureSample (like TextureSize)
  193. // may have incomplete sampler type information. In those cases,
  194. // we prefer instead the more accurate information from the
  195. // TextureSample instruction, if both are available.
  196. foreach (AstTextureOperation texOp in info.Samplers.OrderBy(x => x.Handle * 2 + (x.Inst == Instruction.TextureSample ? 0 : 1)))
  197. {
  198. string indexExpr = NumberFormatter.FormatInt(texOp.ArraySize);
  199. string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);
  200. if (!samplers.TryAdd(samplerName, texOp))
  201. {
  202. continue;
  203. }
  204. string samplerTypeName = GetSamplerTypeName(texOp.Type);
  205. context.AppendLine("uniform " + samplerTypeName + " " + samplerName + ";");
  206. }
  207. foreach (KeyValuePair<string, AstTextureOperation> kv in samplers)
  208. {
  209. string samplerName = kv.Key;
  210. AstTextureOperation texOp = kv.Value;
  211. TextureDescriptor desc;
  212. if ((texOp.Flags & TextureFlags.Bindless) != 0)
  213. {
  214. AstOperand operand = texOp.GetSource(0) as AstOperand;
  215. desc = new TextureDescriptor(samplerName, texOp.Type, operand.CbufSlot, operand.CbufOffset);
  216. context.TextureDescriptors.Add(desc);
  217. }
  218. else if ((texOp.Type & SamplerType.Indexed) != 0)
  219. {
  220. for (int index = 0; index < texOp.ArraySize; index++)
  221. {
  222. string indexExpr = NumberFormatter.FormatInt(index);
  223. string indexedSamplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);
  224. desc = new TextureDescriptor(indexedSamplerName, texOp.Type, texOp.Handle + index * 2);
  225. context.TextureDescriptors.Add(desc);
  226. }
  227. }
  228. else
  229. {
  230. desc = new TextureDescriptor(samplerName, texOp.Type, texOp.Handle);
  231. context.TextureDescriptors.Add(desc);
  232. }
  233. }
  234. }
  235. private static void DeclareImages(CodeGenContext context, StructuredProgramInfo info)
  236. {
  237. Dictionary<string, AstTextureOperation> images = new Dictionary<string, AstTextureOperation>();
  238. foreach (AstTextureOperation texOp in info.Images.OrderBy(x => x.Handle))
  239. {
  240. string indexExpr = NumberFormatter.FormatInt(texOp.ArraySize);
  241. string imageName = OperandManager.GetImageName(context.Config.Stage, texOp, indexExpr);
  242. if (!images.TryAdd(imageName, texOp))
  243. {
  244. continue;
  245. }
  246. string imageTypeName = GetImageTypeName(texOp.Type);
  247. context.AppendLine("writeonly uniform " + imageTypeName + " " + imageName + ";");
  248. }
  249. foreach (KeyValuePair<string, AstTextureOperation> kv in images)
  250. {
  251. string imageName = kv.Key;
  252. AstTextureOperation texOp = kv.Value;
  253. if ((texOp.Type & SamplerType.Indexed) != 0)
  254. {
  255. for (int index = 0; index < texOp.ArraySize; index++)
  256. {
  257. string indexExpr = NumberFormatter.FormatInt(index);
  258. string indexedSamplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);
  259. var desc = new TextureDescriptor(indexedSamplerName, texOp.Type, texOp.Handle + index * 2);
  260. context.TextureDescriptors.Add(desc);
  261. }
  262. }
  263. else
  264. {
  265. var desc = new TextureDescriptor(imageName, texOp.Type, texOp.Handle);
  266. context.ImageDescriptors.Add(desc);
  267. }
  268. }
  269. }
  270. private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info)
  271. {
  272. string suffix = context.Config.Stage == ShaderStage.Geometry ? "[]" : string.Empty;
  273. foreach (int attr in info.IAttributes.OrderBy(x => x))
  274. {
  275. string iq = string.Empty;
  276. if (context.Config.Stage == ShaderStage.Fragment)
  277. {
  278. iq = context.Config.ImapTypes[attr].GetFirstUsedType() switch
  279. {
  280. PixelImap.Constant => "flat ",
  281. PixelImap.ScreenLinear => "noperspective ",
  282. _ => string.Empty
  283. };
  284. }
  285. context.AppendLine($"layout (location = {attr}) {iq}in vec4 {DefaultNames.IAttributePrefix}{attr}{suffix};");
  286. }
  287. }
  288. private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  289. {
  290. if (context.Config.Stage == ShaderStage.Fragment)
  291. {
  292. DeclareUsedOutputAttributes(context, info);
  293. }
  294. else
  295. {
  296. DeclareAllOutputAttributes(context, info);
  297. }
  298. }
  299. private static void DeclareUsedOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  300. {
  301. foreach (int attr in info.OAttributes.OrderBy(x => x))
  302. {
  303. context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
  304. }
  305. }
  306. private static void DeclareAllOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  307. {
  308. for (int attr = 0; attr < MaxAttributes; attr++)
  309. {
  310. context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
  311. }
  312. foreach (int attr in info.OAttributes.OrderBy(x => x).Where(x => x >= MaxAttributes))
  313. {
  314. context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
  315. }
  316. }
  317. private static void AppendHelperFunction(CodeGenContext context, string filename)
  318. {
  319. string code = EmbeddedResources.ReadAllText(filename);
  320. context.AppendLine(code.Replace("\t", CodeGenContext.Tab));
  321. context.AppendLine();
  322. }
  323. private static string GetSamplerTypeName(SamplerType type)
  324. {
  325. string typeName;
  326. switch (type & SamplerType.Mask)
  327. {
  328. case SamplerType.Texture1D: typeName = "sampler1D"; break;
  329. case SamplerType.TextureBuffer: typeName = "samplerBuffer"; break;
  330. case SamplerType.Texture2D: typeName = "sampler2D"; break;
  331. case SamplerType.Texture3D: typeName = "sampler3D"; break;
  332. case SamplerType.TextureCube: typeName = "samplerCube"; break;
  333. default: throw new ArgumentException($"Invalid sampler type \"{type}\".");
  334. }
  335. if ((type & SamplerType.Multisample) != 0)
  336. {
  337. typeName += "MS";
  338. }
  339. if ((type & SamplerType.Array) != 0)
  340. {
  341. typeName += "Array";
  342. }
  343. if ((type & SamplerType.Shadow) != 0)
  344. {
  345. typeName += "Shadow";
  346. }
  347. return typeName;
  348. }
  349. private static string GetImageTypeName(SamplerType type)
  350. {
  351. string typeName;
  352. switch (type & SamplerType.Mask)
  353. {
  354. case SamplerType.Texture1D: typeName = "image1D"; break;
  355. case SamplerType.TextureBuffer: typeName = "imageBuffer"; break;
  356. case SamplerType.Texture2D: typeName = "image2D"; break;
  357. case SamplerType.Texture3D: typeName = "image3D"; break;
  358. case SamplerType.TextureCube: typeName = "imageCube"; break;
  359. default: throw new ArgumentException($"Invalid sampler type \"{type}\".");
  360. }
  361. if ((type & SamplerType.Multisample) != 0)
  362. {
  363. typeName += "MS";
  364. }
  365. if ((type & SamplerType.Array) != 0)
  366. {
  367. typeName += "Array";
  368. }
  369. return typeName;
  370. }
  371. }
  372. }