Declarations.cs 21 KB

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