Declarations.cs 21 KB

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