Declarations.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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 440 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. context.AppendLine("#extension GL_EXT_shader_image_load_formatted : enable");
  21. if (context.Config.Stage == ShaderStage.Compute)
  22. {
  23. context.AppendLine("#extension GL_ARB_compute_shader : enable");
  24. }
  25. context.AppendLine("#pragma optionNV(fastmath off)");
  26. context.AppendLine();
  27. context.AppendLine($"const int {DefaultNames.UndefinedName} = 0;");
  28. context.AppendLine();
  29. if (context.Config.Stage == ShaderStage.Geometry)
  30. {
  31. string inPrimitive = context.Config.GpuAccessor.QueryPrimitiveTopology().ToGlslString();
  32. context.AppendLine($"layout ({inPrimitive}) in;");
  33. string outPrimitive = context.Config.OutputTopology.ToGlslString();
  34. int maxOutputVertices = context.Config.MaxOutputVertices;
  35. context.AppendLine($"layout ({outPrimitive}, max_vertices = {maxOutputVertices}) out;");
  36. context.AppendLine();
  37. }
  38. if (context.Config.Stage == ShaderStage.Compute)
  39. {
  40. int localMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeLocalMemorySize(), 4);
  41. if (localMemorySize != 0)
  42. {
  43. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  44. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  45. context.AppendLine();
  46. }
  47. int sharedMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeSharedMemorySize(), 4);
  48. if (sharedMemorySize != 0)
  49. {
  50. string sharedMemorySizeStr = NumberFormatter.FormatInt(sharedMemorySize);
  51. context.AppendLine($"shared uint {DefaultNames.SharedMemoryName}[{sharedMemorySizeStr}];");
  52. context.AppendLine();
  53. }
  54. }
  55. else if (context.Config.LocalMemorySize != 0)
  56. {
  57. int localMemorySize = BitUtils.DivRoundUp(context.Config.LocalMemorySize, 4);
  58. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  59. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  60. context.AppendLine();
  61. }
  62. if (info.CBuffers.Count != 0)
  63. {
  64. DeclareUniforms(context, info);
  65. context.AppendLine();
  66. }
  67. if (info.SBuffers.Count != 0)
  68. {
  69. DeclareStorages(context, info);
  70. context.AppendLine();
  71. }
  72. if (info.Samplers.Count != 0)
  73. {
  74. DeclareSamplers(context, info);
  75. context.AppendLine();
  76. }
  77. if (info.Images.Count != 0)
  78. {
  79. DeclareImages(context, info);
  80. context.AppendLine();
  81. }
  82. if (context.Config.Stage != ShaderStage.Compute)
  83. {
  84. if (info.IAttributes.Count != 0)
  85. {
  86. DeclareInputAttributes(context, info);
  87. context.AppendLine();
  88. }
  89. if (info.OAttributes.Count != 0 || context.Config.Stage != ShaderStage.Fragment)
  90. {
  91. DeclareOutputAttributes(context, info);
  92. context.AppendLine();
  93. }
  94. }
  95. else
  96. {
  97. string localSizeX = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeX());
  98. string localSizeY = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeY());
  99. string localSizeZ = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeZ());
  100. context.AppendLine(
  101. "layout (" +
  102. $"local_size_x = {localSizeX}, " +
  103. $"local_size_y = {localSizeY}, " +
  104. $"local_size_z = {localSizeZ}) in;");
  105. context.AppendLine();
  106. }
  107. if (context.Config.Stage == ShaderStage.Fragment || context.Config.Stage == ShaderStage.Compute)
  108. {
  109. if (context.Config.Stage == ShaderStage.Fragment)
  110. {
  111. if (context.Config.GpuAccessor.QueryEarlyZForce())
  112. {
  113. context.AppendLine("layout(early_fragment_tests) in;");
  114. context.AppendLine();
  115. }
  116. context.AppendLine($"uniform bool {DefaultNames.IsBgraName}[8];");
  117. context.AppendLine();
  118. }
  119. if (DeclareRenderScale(context))
  120. {
  121. context.AppendLine();
  122. }
  123. }
  124. if ((info.HelperFunctionsMask & HelperFunctionsMask.AtomicMinMaxS32Shared) != 0)
  125. {
  126. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/AtomicMinMaxS32Shared.glsl");
  127. }
  128. if ((info.HelperFunctionsMask & HelperFunctionsMask.AtomicMinMaxS32Storage) != 0)
  129. {
  130. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/AtomicMinMaxS32Storage.glsl");
  131. }
  132. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighS32) != 0)
  133. {
  134. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighS32.glsl");
  135. }
  136. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighU32) != 0)
  137. {
  138. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighU32.glsl");
  139. }
  140. if ((info.HelperFunctionsMask & HelperFunctionsMask.Shuffle) != 0)
  141. {
  142. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/Shuffle.glsl");
  143. }
  144. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleDown) != 0)
  145. {
  146. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleDown.glsl");
  147. }
  148. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleUp) != 0)
  149. {
  150. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleUp.glsl");
  151. }
  152. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleXor) != 0)
  153. {
  154. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleXor.glsl");
  155. }
  156. if ((info.HelperFunctionsMask & HelperFunctionsMask.SwizzleAdd) != 0)
  157. {
  158. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/SwizzleAdd.glsl");
  159. }
  160. }
  161. public static void DeclareLocals(CodeGenContext context, StructuredFunction function)
  162. {
  163. foreach (AstOperand decl in function.Locals)
  164. {
  165. string name = context.OperandManager.DeclareLocal(decl);
  166. context.AppendLine(GetVarTypeName(decl.VarType) + " " + name + ";");
  167. }
  168. }
  169. public static string GetVarTypeName(VariableType type)
  170. {
  171. switch (type)
  172. {
  173. case VariableType.Bool: return "bool";
  174. case VariableType.F32: return "precise float";
  175. case VariableType.F64: return "double";
  176. case VariableType.None: return "void";
  177. case VariableType.S32: return "int";
  178. case VariableType.U32: return "uint";
  179. }
  180. throw new ArgumentException($"Invalid variable type \"{type}\".");
  181. }
  182. private static void DeclareUniforms(CodeGenContext context, StructuredProgramInfo info)
  183. {
  184. string ubSize = "[" + NumberFormatter.FormatInt(Constants.ConstantBufferSize / 16) + "]";
  185. if (info.UsesCbIndexing)
  186. {
  187. int count = info.CBuffers.Max() + 1;
  188. int[] bindings = new int[count];
  189. for (int i = 0; i < count; i++)
  190. {
  191. bindings[i] = context.Config.Counts.IncrementUniformBuffersCount();
  192. }
  193. foreach (int cbufSlot in info.CBuffers.OrderBy(x => x))
  194. {
  195. context.CBufferDescriptors.Add(new BufferDescriptor(bindings[cbufSlot], cbufSlot));
  196. }
  197. string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  198. ubName += "_" + DefaultNames.UniformNamePrefix;
  199. string blockName = $"{ubName}_{DefaultNames.BlockSuffix}";
  200. context.AppendLine($"layout (binding = {bindings[0]}, std140) uniform {blockName}");
  201. context.EnterScope();
  202. context.AppendLine("vec4 " + DefaultNames.DataName + ubSize + ";");
  203. context.LeaveScope($" {ubName}[{NumberFormatter.FormatInt(count)}];");
  204. }
  205. else
  206. {
  207. foreach (int cbufSlot in info.CBuffers.OrderBy(x => x))
  208. {
  209. int binding = context.Config.Counts.IncrementUniformBuffersCount();
  210. context.CBufferDescriptors.Add(new BufferDescriptor(binding, cbufSlot));
  211. string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  212. ubName += "_" + DefaultNames.UniformNamePrefix + cbufSlot;
  213. context.AppendLine($"layout (binding = {binding}, std140) uniform {ubName}");
  214. context.EnterScope();
  215. context.AppendLine("vec4 " + OperandManager.GetUbName(context.Config.Stage, cbufSlot, false) + ubSize + ";");
  216. context.LeaveScope(";");
  217. }
  218. }
  219. }
  220. private static void DeclareStorages(CodeGenContext context, StructuredProgramInfo info)
  221. {
  222. string sbName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  223. sbName += "_" + DefaultNames.StorageNamePrefix;
  224. string blockName = $"{sbName}_{DefaultNames.BlockSuffix}";
  225. int count = info.SBuffers.Max() + 1;
  226. int[] bindings = new int[count];
  227. for (int i = 0; i < count; i++)
  228. {
  229. bindings[i] = context.Config.Counts.IncrementStorageBuffersCount();
  230. }
  231. foreach (int sbufSlot in info.SBuffers)
  232. {
  233. context.SBufferDescriptors.Add(new BufferDescriptor(bindings[sbufSlot], sbufSlot));
  234. }
  235. context.AppendLine($"layout (binding = {bindings[0]}, std430) buffer {blockName}");
  236. context.EnterScope();
  237. context.AppendLine("uint " + DefaultNames.DataName + "[];");
  238. context.LeaveScope($" {sbName}[{NumberFormatter.FormatInt(count)}];");
  239. }
  240. private static void DeclareSamplers(CodeGenContext context, StructuredProgramInfo info)
  241. {
  242. HashSet<string> samplers = new HashSet<string>();
  243. // Texture instructions other than TextureSample (like TextureSize)
  244. // may have incomplete sampler type information. In those cases,
  245. // we prefer instead the more accurate information from the
  246. // TextureSample instruction, if both are available.
  247. foreach (AstTextureOperation texOp in info.Samplers.OrderBy(x => x.Handle * 2 + (x.Inst == Instruction.TextureSample ? 0 : 1)))
  248. {
  249. string indexExpr = NumberFormatter.FormatInt(texOp.ArraySize);
  250. string samplerName = OperandManager.GetSamplerName(context.Config.Stage, texOp, indexExpr);
  251. if ((texOp.Flags & TextureFlags.Bindless) != 0 || !samplers.Add(samplerName))
  252. {
  253. continue;
  254. }
  255. int firstBinding = -1;
  256. if ((texOp.Type & SamplerType.Indexed) != 0)
  257. {
  258. for (int index = 0; index < texOp.ArraySize; index++)
  259. {
  260. int binding = context.Config.Counts.IncrementTexturesCount();
  261. if (firstBinding < 0)
  262. {
  263. firstBinding = binding;
  264. }
  265. var desc = new TextureDescriptor(binding, texOp.Type, texOp.Format, texOp.CbufSlot, texOp.Handle + index * 2);
  266. context.TextureDescriptors.Add(desc);
  267. }
  268. }
  269. else
  270. {
  271. firstBinding = context.Config.Counts.IncrementTexturesCount();
  272. var desc = new TextureDescriptor(firstBinding, texOp.Type, texOp.Format, texOp.CbufSlot, texOp.Handle);
  273. context.TextureDescriptors.Add(desc);
  274. }
  275. string samplerTypeName = texOp.Type.ToGlslSamplerType();
  276. context.AppendLine($"layout (binding = {firstBinding}) uniform {samplerTypeName} {samplerName};");
  277. }
  278. }
  279. private static void DeclareImages(CodeGenContext context, StructuredProgramInfo info)
  280. {
  281. HashSet<string> images = new HashSet<string>();
  282. foreach (AstTextureOperation texOp in info.Images.OrderBy(x => x.Handle))
  283. {
  284. string indexExpr = NumberFormatter.FormatInt(texOp.ArraySize);
  285. string imageName = OperandManager.GetImageName(context.Config.Stage, texOp, indexExpr);
  286. if ((texOp.Flags & TextureFlags.Bindless) != 0 || !images.Add(imageName))
  287. {
  288. continue;
  289. }
  290. int firstBinding = -1;
  291. if ((texOp.Type & SamplerType.Indexed) != 0)
  292. {
  293. for (int index = 0; index < texOp.ArraySize; index++)
  294. {
  295. int binding = context.Config.Counts.IncrementImagesCount();
  296. if (firstBinding < 0)
  297. {
  298. firstBinding = binding;
  299. }
  300. var desc = new TextureDescriptor(binding, texOp.Type, texOp.Format, texOp.CbufSlot, texOp.Handle + index * 2);
  301. context.ImageDescriptors.Add(desc);
  302. }
  303. }
  304. else
  305. {
  306. firstBinding = context.Config.Counts.IncrementImagesCount();
  307. var desc = new TextureDescriptor(firstBinding, texOp.Type, texOp.Format, texOp.CbufSlot, texOp.Handle);
  308. context.ImageDescriptors.Add(desc);
  309. }
  310. string layout = texOp.Format.ToGlslFormat();
  311. if (!string.IsNullOrEmpty(layout))
  312. {
  313. layout = ", " + layout;
  314. }
  315. string imageTypeName = texOp.Type.ToGlslImageType(texOp.Format.GetComponentType());
  316. context.AppendLine($"layout (binding = {firstBinding}{layout}) uniform {imageTypeName} {imageName};");
  317. }
  318. }
  319. private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info)
  320. {
  321. string suffix = context.Config.Stage == ShaderStage.Geometry ? "[]" : string.Empty;
  322. foreach (int attr in info.IAttributes.OrderBy(x => x))
  323. {
  324. string iq = string.Empty;
  325. if (context.Config.Stage == ShaderStage.Fragment)
  326. {
  327. iq = context.Config.ImapTypes[attr].GetFirstUsedType() switch
  328. {
  329. PixelImap.Constant => "flat ",
  330. PixelImap.ScreenLinear => "noperspective ",
  331. _ => string.Empty
  332. };
  333. }
  334. string name = $"{DefaultNames.IAttributePrefix}{attr}";
  335. if ((context.Config.Flags & TranslationFlags.Feedback) != 0)
  336. {
  337. for (int c = 0; c < 4; c++)
  338. {
  339. char swzMask = "xyzw"[c];
  340. context.AppendLine($"layout (location = {attr}, component = {c}) {iq}in float {name}_{swzMask}{suffix};");
  341. }
  342. }
  343. else
  344. {
  345. context.AppendLine($"layout (location = {attr}) {iq}in vec4 {name}{suffix};");
  346. }
  347. }
  348. }
  349. private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  350. {
  351. if (context.Config.Stage == ShaderStage.Fragment)
  352. {
  353. DeclareUsedOutputAttributes(context, info);
  354. }
  355. else
  356. {
  357. DeclareAllOutputAttributes(context, info);
  358. }
  359. }
  360. private static void DeclareUsedOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  361. {
  362. foreach (int attr in info.OAttributes.OrderBy(x => x))
  363. {
  364. context.AppendLine($"layout (location = {attr}) out vec4 {DefaultNames.OAttributePrefix}{attr};");
  365. }
  366. }
  367. private static void DeclareAllOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  368. {
  369. for (int attr = 0; attr < MaxAttributes; attr++)
  370. {
  371. DeclareOutputAttribute(context, attr);
  372. }
  373. foreach (int attr in info.OAttributes.OrderBy(x => x).Where(x => x >= MaxAttributes))
  374. {
  375. DeclareOutputAttribute(context, attr);
  376. }
  377. }
  378. private static void DeclareOutputAttribute(CodeGenContext context, int attr)
  379. {
  380. string name = $"{DefaultNames.OAttributePrefix}{attr}";
  381. if ((context.Config.Flags & TranslationFlags.Feedback) != 0)
  382. {
  383. for (int c = 0; c < 4; c++)
  384. {
  385. char swzMask = "xyzw"[c];
  386. context.AppendLine($"layout (location = {attr}, component = {c}) out float {name}_{swzMask};");
  387. }
  388. }
  389. else
  390. {
  391. context.AppendLine($"layout (location = {attr}) out vec4 {name};");
  392. }
  393. }
  394. private static bool DeclareRenderScale(CodeGenContext context)
  395. {
  396. if ((context.Config.UsedFeatures & (FeatureFlags.FragCoordXY | FeatureFlags.IntegerSampling)) != 0)
  397. {
  398. string stage = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  399. int scaleElements = context.TextureDescriptors.Count + context.ImageDescriptors.Count;
  400. if (context.Config.Stage == ShaderStage.Fragment)
  401. {
  402. scaleElements++; // Also includes render target scale, for gl_FragCoord.
  403. }
  404. context.AppendLine($"uniform float {stage}_renderScale[{scaleElements}];");
  405. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.IntegerSampling))
  406. {
  407. context.AppendLine();
  408. AppendHelperFunction(context, $"Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/TexelFetchScale_{stage}.glsl");
  409. }
  410. return true;
  411. }
  412. return false;
  413. }
  414. private static void AppendHelperFunction(CodeGenContext context, string filename)
  415. {
  416. string code = EmbeddedResources.ReadAllText(filename);
  417. code = code.Replace("\t", CodeGenContext.Tab);
  418. code = code.Replace("$SHARED_MEM$", DefaultNames.SharedMemoryName);
  419. code = code.Replace("$STORAGE_MEM$", OperandManager.GetShaderStagePrefix(context.Config.Stage) + "_" + DefaultNames.StorageNamePrefix);
  420. context.AppendLine(code);
  421. context.AppendLine();
  422. }
  423. }
  424. }