Declarations.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Shader.StructuredIr;
  3. using Ryujinx.Graphics.Shader.Translation;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Numerics;
  8. namespace Ryujinx.Graphics.Shader.CodeGen.Glsl
  9. {
  10. static class Declarations
  11. {
  12. public static void Declare(CodeGenContext context, StructuredProgramInfo info)
  13. {
  14. context.AppendLine(context.Config.Options.TargetApi == TargetApi.Vulkan ? "#version 460 core" : "#version 450 core");
  15. context.AppendLine("#extension GL_ARB_gpu_shader_int64 : enable");
  16. if (context.Config.GpuAccessor.QueryHostSupportsShaderBallot())
  17. {
  18. context.AppendLine("#extension GL_ARB_shader_ballot : enable");
  19. }
  20. else
  21. {
  22. context.AppendLine("#extension GL_KHR_shader_subgroup_basic : enable");
  23. context.AppendLine("#extension GL_KHR_shader_subgroup_ballot : enable");
  24. }
  25. context.AppendLine("#extension GL_ARB_shader_group_vote : enable");
  26. context.AppendLine("#extension GL_EXT_shader_image_load_formatted : enable");
  27. context.AppendLine("#extension GL_EXT_texture_shadow_lod : enable");
  28. if (context.Config.Stage == ShaderStage.Compute)
  29. {
  30. context.AppendLine("#extension GL_ARB_compute_shader : enable");
  31. }
  32. else if (context.Config.Stage == ShaderStage.Fragment)
  33. {
  34. if (context.Config.GpuAccessor.QueryHostSupportsFragmentShaderInterlock())
  35. {
  36. context.AppendLine("#extension GL_ARB_fragment_shader_interlock : enable");
  37. }
  38. else if (context.Config.GpuAccessor.QueryHostSupportsFragmentShaderOrderingIntel())
  39. {
  40. context.AppendLine("#extension GL_INTEL_fragment_shader_ordering : enable");
  41. }
  42. }
  43. else
  44. {
  45. if (context.Config.Stage == ShaderStage.Vertex)
  46. {
  47. context.AppendLine("#extension GL_ARB_shader_draw_parameters : enable");
  48. }
  49. context.AppendLine("#extension GL_ARB_shader_viewport_layer_array : enable");
  50. }
  51. if (context.Config.GpPassthrough && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  52. {
  53. context.AppendLine("#extension GL_NV_geometry_shader_passthrough : enable");
  54. }
  55. if (context.Config.GpuAccessor.QueryHostSupportsViewportMask())
  56. {
  57. context.AppendLine("#extension GL_NV_viewport_array2 : enable");
  58. }
  59. context.AppendLine("#pragma optionNV(fastmath off)");
  60. context.AppendLine();
  61. context.AppendLine($"const int {DefaultNames.UndefinedName} = 0;");
  62. context.AppendLine();
  63. if (context.Config.Stage == ShaderStage.Compute)
  64. {
  65. int localMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeLocalMemorySize(), 4);
  66. if (localMemorySize != 0)
  67. {
  68. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  69. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  70. context.AppendLine();
  71. }
  72. int sharedMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeSharedMemorySize(), 4);
  73. if (sharedMemorySize != 0)
  74. {
  75. string sharedMemorySizeStr = NumberFormatter.FormatInt(sharedMemorySize);
  76. context.AppendLine($"shared uint {DefaultNames.SharedMemoryName}[{sharedMemorySizeStr}];");
  77. context.AppendLine();
  78. }
  79. }
  80. else if (context.Config.LocalMemorySize != 0)
  81. {
  82. int localMemorySize = BitUtils.DivRoundUp(context.Config.LocalMemorySize, 4);
  83. string localMemorySizeStr = NumberFormatter.FormatInt(localMemorySize);
  84. context.AppendLine($"uint {DefaultNames.LocalMemoryName}[{localMemorySizeStr}];");
  85. context.AppendLine();
  86. }
  87. var cBufferDescriptors = context.Config.GetConstantBufferDescriptors();
  88. if (cBufferDescriptors.Length != 0)
  89. {
  90. DeclareUniforms(context, cBufferDescriptors);
  91. context.AppendLine();
  92. }
  93. var sBufferDescriptors = context.Config.GetStorageBufferDescriptors();
  94. if (sBufferDescriptors.Length != 0)
  95. {
  96. DeclareStorages(context, sBufferDescriptors);
  97. context.AppendLine();
  98. }
  99. var textureDescriptors = context.Config.GetTextureDescriptors();
  100. if (textureDescriptors.Length != 0)
  101. {
  102. DeclareSamplers(context, textureDescriptors);
  103. context.AppendLine();
  104. }
  105. var imageDescriptors = context.Config.GetImageDescriptors();
  106. if (imageDescriptors.Length != 0)
  107. {
  108. DeclareImages(context, imageDescriptors);
  109. context.AppendLine();
  110. }
  111. if (context.Config.Stage != ShaderStage.Compute)
  112. {
  113. if (context.Config.Stage == ShaderStage.Geometry)
  114. {
  115. InputTopology inputTopology = context.Config.GpuAccessor.QueryPrimitiveTopology();
  116. string inPrimitive = inputTopology.ToGlslString();
  117. context.AppendLine($"layout (invocations = {context.Config.ThreadsPerInputPrimitive}, {inPrimitive}) in;");
  118. if (context.Config.GpPassthrough && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  119. {
  120. context.AppendLine($"layout (passthrough) in gl_PerVertex");
  121. context.EnterScope();
  122. context.AppendLine("vec4 gl_Position;");
  123. context.AppendLine("float gl_PointSize;");
  124. context.AppendLine("float gl_ClipDistance[];");
  125. context.LeaveScope(";");
  126. }
  127. else
  128. {
  129. string outPrimitive = context.Config.OutputTopology.ToGlslString();
  130. int maxOutputVertices = context.Config.GpPassthrough
  131. ? inputTopology.ToInputVertices()
  132. : context.Config.MaxOutputVertices;
  133. context.AppendLine($"layout ({outPrimitive}, max_vertices = {maxOutputVertices}) out;");
  134. }
  135. context.AppendLine();
  136. }
  137. else if (context.Config.Stage == ShaderStage.TessellationControl)
  138. {
  139. int threadsPerInputPrimitive = context.Config.ThreadsPerInputPrimitive;
  140. context.AppendLine($"layout (vertices = {threadsPerInputPrimitive}) out;");
  141. context.AppendLine();
  142. }
  143. else if (context.Config.Stage == ShaderStage.TessellationEvaluation)
  144. {
  145. bool tessCw = context.Config.GpuAccessor.QueryTessCw();
  146. if (context.Config.Options.TargetApi == TargetApi.Vulkan)
  147. {
  148. // We invert the front face on Vulkan backend, so we need to do that here aswell.
  149. tessCw = !tessCw;
  150. }
  151. string patchType = context.Config.GpuAccessor.QueryTessPatchType().ToGlsl();
  152. string spacing = context.Config.GpuAccessor.QueryTessSpacing().ToGlsl();
  153. string windingOrder = tessCw ? "cw" : "ccw";
  154. context.AppendLine($"layout ({patchType}, {spacing}, {windingOrder}) in;");
  155. context.AppendLine();
  156. }
  157. if (context.Config.UsedInputAttributes != 0 || context.Config.GpPassthrough)
  158. {
  159. DeclareInputAttributes(context, info);
  160. context.AppendLine();
  161. }
  162. if (context.Config.UsedOutputAttributes != 0 || context.Config.Stage != ShaderStage.Fragment)
  163. {
  164. DeclareOutputAttributes(context, info);
  165. context.AppendLine();
  166. }
  167. if (context.Config.UsedInputAttributesPerPatch.Count != 0)
  168. {
  169. DeclareInputAttributesPerPatch(context, context.Config.UsedInputAttributesPerPatch);
  170. context.AppendLine();
  171. }
  172. if (context.Config.UsedOutputAttributesPerPatch.Count != 0)
  173. {
  174. DeclareUsedOutputAttributesPerPatch(context, context.Config.UsedOutputAttributesPerPatch);
  175. context.AppendLine();
  176. }
  177. if (context.Config.TransformFeedbackEnabled && context.Config.LastInVertexPipeline)
  178. {
  179. var tfOutput = context.Config.GetTransformFeedbackOutput(AttributeConsts.PositionX);
  180. if (tfOutput.Valid)
  181. {
  182. context.AppendLine($"layout (xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}) out gl_PerVertex");
  183. context.EnterScope();
  184. context.AppendLine("vec4 gl_Position;");
  185. context.LeaveScope(context.Config.Stage == ShaderStage.TessellationControl ? " gl_out[];" : ";");
  186. }
  187. }
  188. }
  189. else
  190. {
  191. string localSizeX = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeX());
  192. string localSizeY = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeY());
  193. string localSizeZ = NumberFormatter.FormatInt(context.Config.GpuAccessor.QueryComputeLocalSizeZ());
  194. context.AppendLine(
  195. "layout (" +
  196. $"local_size_x = {localSizeX}, " +
  197. $"local_size_y = {localSizeY}, " +
  198. $"local_size_z = {localSizeZ}) in;");
  199. context.AppendLine();
  200. }
  201. bool isFragment = context.Config.Stage == ShaderStage.Fragment;
  202. if (isFragment || context.Config.Stage == ShaderStage.Compute || context.Config.Stage == ShaderStage.Vertex)
  203. {
  204. if (isFragment && context.Config.GpuAccessor.QueryEarlyZForce())
  205. {
  206. context.AppendLine("layout(early_fragment_tests) in;");
  207. context.AppendLine();
  208. }
  209. if ((context.Config.UsedFeatures & (FeatureFlags.FragCoordXY | FeatureFlags.IntegerSampling)) != 0)
  210. {
  211. string stage = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  212. int scaleElements = context.Config.GetTextureDescriptors().Length + context.Config.GetImageDescriptors().Length;
  213. if (isFragment)
  214. {
  215. scaleElements++; // Also includes render target scale, for gl_FragCoord.
  216. }
  217. DeclareSupportUniformBlock(context, context.Config.Stage, scaleElements);
  218. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.IntegerSampling) && scaleElements != 0)
  219. {
  220. AppendHelperFunction(context, $"Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/TexelFetchScale_{stage}.glsl");
  221. context.AppendLine();
  222. }
  223. }
  224. else if (isFragment || context.Config.Stage == ShaderStage.Vertex)
  225. {
  226. DeclareSupportUniformBlock(context, context.Config.Stage, 0);
  227. }
  228. }
  229. if ((info.HelperFunctionsMask & HelperFunctionsMask.AtomicMinMaxS32Shared) != 0)
  230. {
  231. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/AtomicMinMaxS32Shared.glsl");
  232. }
  233. if ((info.HelperFunctionsMask & HelperFunctionsMask.AtomicMinMaxS32Storage) != 0)
  234. {
  235. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/AtomicMinMaxS32Storage.glsl");
  236. }
  237. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighS32) != 0)
  238. {
  239. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighS32.glsl");
  240. }
  241. if ((info.HelperFunctionsMask & HelperFunctionsMask.MultiplyHighU32) != 0)
  242. {
  243. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/MultiplyHighU32.glsl");
  244. }
  245. if ((info.HelperFunctionsMask & HelperFunctionsMask.Shuffle) != 0)
  246. {
  247. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/Shuffle.glsl");
  248. }
  249. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleDown) != 0)
  250. {
  251. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleDown.glsl");
  252. }
  253. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleUp) != 0)
  254. {
  255. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleUp.glsl");
  256. }
  257. if ((info.HelperFunctionsMask & HelperFunctionsMask.ShuffleXor) != 0)
  258. {
  259. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/ShuffleXor.glsl");
  260. }
  261. if ((info.HelperFunctionsMask & HelperFunctionsMask.StoreSharedSmallInt) != 0)
  262. {
  263. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/StoreSharedSmallInt.glsl");
  264. }
  265. if ((info.HelperFunctionsMask & HelperFunctionsMask.StoreStorageSmallInt) != 0)
  266. {
  267. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/StoreStorageSmallInt.glsl");
  268. }
  269. if ((info.HelperFunctionsMask & HelperFunctionsMask.SwizzleAdd) != 0)
  270. {
  271. AppendHelperFunction(context, "Ryujinx.Graphics.Shader/CodeGen/Glsl/HelperFunctions/SwizzleAdd.glsl");
  272. }
  273. }
  274. private static string GetTfLayout(TransformFeedbackOutput tfOutput)
  275. {
  276. if (tfOutput.Valid)
  277. {
  278. return $"layout (xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}) ";
  279. }
  280. return string.Empty;
  281. }
  282. public static void DeclareLocals(CodeGenContext context, StructuredFunction function)
  283. {
  284. foreach (AstOperand decl in function.Locals)
  285. {
  286. string name = context.OperandManager.DeclareLocal(decl);
  287. context.AppendLine(GetVarTypeName(context, decl.VarType) + " " + name + ";");
  288. }
  289. }
  290. public static string GetVarTypeName(CodeGenContext context, AggregateType type, bool precise = true)
  291. {
  292. if (context.Config.GpuAccessor.QueryHostReducedPrecision())
  293. {
  294. precise = false;
  295. }
  296. return type switch
  297. {
  298. AggregateType.Void => "void",
  299. AggregateType.Bool => "bool",
  300. AggregateType.FP32 => precise ? "precise float" : "float",
  301. AggregateType.FP64 => "double",
  302. AggregateType.S32 => "int",
  303. AggregateType.U32 => "uint",
  304. AggregateType.Vector2 | AggregateType.Bool => "bvec2",
  305. AggregateType.Vector2 | AggregateType.FP32 => precise ? "precise vec2" : "vec2",
  306. AggregateType.Vector2 | AggregateType.FP64 => "dvec2",
  307. AggregateType.Vector2 | AggregateType.S32 => "ivec2",
  308. AggregateType.Vector2 | AggregateType.U32 => "uvec2",
  309. AggregateType.Vector3 | AggregateType.Bool => "bvec3",
  310. AggregateType.Vector3 | AggregateType.FP32 => precise ? "precise vec3" : "vec3",
  311. AggregateType.Vector3 | AggregateType.FP64 => "dvec3",
  312. AggregateType.Vector3 | AggregateType.S32 => "ivec3",
  313. AggregateType.Vector3 | AggregateType.U32 => "uvec3",
  314. AggregateType.Vector4 | AggregateType.Bool => "bvec4",
  315. AggregateType.Vector4 | AggregateType.FP32 => precise ? "precise vec4" : "vec4",
  316. AggregateType.Vector4 | AggregateType.FP64 => "dvec4",
  317. AggregateType.Vector4 | AggregateType.S32 => "ivec4",
  318. AggregateType.Vector4 | AggregateType.U32 => "uvec4",
  319. _ => throw new ArgumentException($"Invalid variable type \"{type}\".")
  320. };
  321. }
  322. private static void DeclareUniforms(CodeGenContext context, BufferDescriptor[] descriptors)
  323. {
  324. string ubSize = "[" + NumberFormatter.FormatInt(Constants.ConstantBufferSize / 16) + "]";
  325. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  326. {
  327. string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  328. ubName += "_" + DefaultNames.UniformNamePrefix;
  329. string blockName = $"{ubName}_{DefaultNames.BlockSuffix}";
  330. context.AppendLine($"layout (binding = {context.Config.FirstConstantBufferBinding}, std140) uniform {blockName}");
  331. context.EnterScope();
  332. context.AppendLine("vec4 " + DefaultNames.DataName + ubSize + ";");
  333. context.LeaveScope($" {ubName}[{NumberFormatter.FormatInt(descriptors.Max(x => x.Slot) + 1)}];");
  334. }
  335. else
  336. {
  337. foreach (var descriptor in descriptors)
  338. {
  339. string ubName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  340. ubName += "_" + DefaultNames.UniformNamePrefix + descriptor.Slot;
  341. context.AppendLine($"layout (binding = {descriptor.Binding}, std140) uniform {ubName}");
  342. context.EnterScope();
  343. context.AppendLine("vec4 " + OperandManager.GetUbName(context.Config.Stage, descriptor.Slot, false) + ubSize + ";");
  344. context.LeaveScope(";");
  345. }
  346. }
  347. }
  348. private static void DeclareStorages(CodeGenContext context, BufferDescriptor[] descriptors)
  349. {
  350. string sbName = OperandManager.GetShaderStagePrefix(context.Config.Stage);
  351. sbName += "_" + DefaultNames.StorageNamePrefix;
  352. string blockName = $"{sbName}_{DefaultNames.BlockSuffix}";
  353. string layout = context.Config.Options.TargetApi == TargetApi.Vulkan ? ", set = 1" : string.Empty;
  354. context.AppendLine($"layout (binding = {context.Config.FirstStorageBufferBinding}{layout}, std430) buffer {blockName}");
  355. context.EnterScope();
  356. context.AppendLine("uint " + DefaultNames.DataName + "[];");
  357. context.LeaveScope($" {sbName}[{NumberFormatter.FormatInt(descriptors.Max(x => x.Slot) + 1)}];");
  358. }
  359. private static void DeclareSamplers(CodeGenContext context, TextureDescriptor[] descriptors)
  360. {
  361. int arraySize = 0;
  362. foreach (var descriptor in descriptors)
  363. {
  364. if (descriptor.Type.HasFlag(SamplerType.Indexed))
  365. {
  366. if (arraySize == 0)
  367. {
  368. arraySize = ShaderConfig.SamplerArraySize;
  369. }
  370. else if (--arraySize != 0)
  371. {
  372. continue;
  373. }
  374. }
  375. string indexExpr = NumberFormatter.FormatInt(arraySize);
  376. string samplerName = OperandManager.GetSamplerName(
  377. context.Config.Stage,
  378. descriptor.CbufSlot,
  379. descriptor.HandleIndex,
  380. descriptor.Type.HasFlag(SamplerType.Indexed),
  381. indexExpr);
  382. string samplerTypeName = descriptor.Type.ToGlslSamplerType();
  383. string layout = string.Empty;
  384. if (context.Config.Options.TargetApi == TargetApi.Vulkan)
  385. {
  386. layout = ", set = 2";
  387. }
  388. context.AppendLine($"layout (binding = {descriptor.Binding}{layout}) uniform {samplerTypeName} {samplerName};");
  389. }
  390. }
  391. private static void DeclareImages(CodeGenContext context, TextureDescriptor[] descriptors)
  392. {
  393. int arraySize = 0;
  394. foreach (var descriptor in descriptors)
  395. {
  396. if (descriptor.Type.HasFlag(SamplerType.Indexed))
  397. {
  398. if (arraySize == 0)
  399. {
  400. arraySize = ShaderConfig.SamplerArraySize;
  401. }
  402. else if (--arraySize != 0)
  403. {
  404. continue;
  405. }
  406. }
  407. string indexExpr = NumberFormatter.FormatInt(arraySize);
  408. string imageName = OperandManager.GetImageName(
  409. context.Config.Stage,
  410. descriptor.CbufSlot,
  411. descriptor.HandleIndex,
  412. descriptor.Format,
  413. descriptor.Type.HasFlag(SamplerType.Indexed),
  414. indexExpr);
  415. string imageTypeName = descriptor.Type.ToGlslImageType(descriptor.Format.GetComponentType());
  416. if (descriptor.Flags.HasFlag(TextureUsageFlags.ImageCoherent))
  417. {
  418. imageTypeName = "coherent " + imageTypeName;
  419. }
  420. string layout = descriptor.Format.ToGlslFormat();
  421. if (!string.IsNullOrEmpty(layout))
  422. {
  423. layout = ", " + layout;
  424. }
  425. if (context.Config.Options.TargetApi == TargetApi.Vulkan)
  426. {
  427. layout = $", set = 3{layout}";
  428. }
  429. context.AppendLine($"layout (binding = {descriptor.Binding}{layout}) uniform {imageTypeName} {imageName};");
  430. }
  431. }
  432. private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info)
  433. {
  434. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.IaIndexing))
  435. {
  436. string suffix = context.Config.Stage == ShaderStage.Geometry ? "[]" : string.Empty;
  437. context.AppendLine($"layout (location = 0) in vec4 {DefaultNames.IAttributePrefix}{suffix}[{Constants.MaxAttributes}];");
  438. }
  439. else
  440. {
  441. int usedAttributes = context.Config.UsedInputAttributes | context.Config.PassthroughAttributes;
  442. while (usedAttributes != 0)
  443. {
  444. int index = BitOperations.TrailingZeroCount(usedAttributes);
  445. DeclareInputAttribute(context, info, index);
  446. usedAttributes &= ~(1 << index);
  447. }
  448. }
  449. }
  450. private static void DeclareInputAttributesPerPatch(CodeGenContext context, HashSet<int> attrs)
  451. {
  452. foreach (int attr in attrs.Order())
  453. {
  454. DeclareInputAttributePerPatch(context, attr);
  455. }
  456. }
  457. private static void DeclareInputAttribute(CodeGenContext context, StructuredProgramInfo info, int attr)
  458. {
  459. string suffix = IsArrayAttributeGlsl(context.Config.Stage, isOutAttr: false) ? "[]" : string.Empty;
  460. string iq = string.Empty;
  461. if (context.Config.Stage == ShaderStage.Fragment)
  462. {
  463. iq = context.Config.ImapTypes[attr].GetFirstUsedType() switch
  464. {
  465. PixelImap.Constant => "flat ",
  466. PixelImap.ScreenLinear => "noperspective ",
  467. _ => string.Empty
  468. };
  469. }
  470. string name = $"{DefaultNames.IAttributePrefix}{attr}";
  471. if (context.Config.TransformFeedbackEnabled && context.Config.Stage == ShaderStage.Fragment)
  472. {
  473. int components = context.Config.GetTransformFeedbackOutputComponents(attr, 0);
  474. if (components > 1)
  475. {
  476. string type = components switch
  477. {
  478. 2 => "vec2",
  479. 3 => "vec3",
  480. 4 => "vec4",
  481. _ => "float"
  482. };
  483. context.AppendLine($"layout (location = {attr}) in {type} {name};");
  484. }
  485. for (int c = components > 1 ? components : 0; c < 4; c++)
  486. {
  487. char swzMask = "xyzw"[c];
  488. context.AppendLine($"layout (location = {attr}, component = {c}) {iq}in float {name}_{swzMask}{suffix};");
  489. }
  490. }
  491. else
  492. {
  493. bool passthrough = (context.Config.PassthroughAttributes & (1 << attr)) != 0;
  494. string pass = passthrough && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough() ? "passthrough, " : string.Empty;
  495. string type;
  496. if (context.Config.Stage == ShaderStage.Vertex)
  497. {
  498. type = context.Config.GpuAccessor.QueryAttributeType(attr).ToVec4Type();
  499. }
  500. else
  501. {
  502. type = AttributeType.Float.ToVec4Type();
  503. }
  504. context.AppendLine($"layout ({pass}location = {attr}) {iq}in {type} {name}{suffix};");
  505. }
  506. }
  507. private static void DeclareInputAttributePerPatch(CodeGenContext context, int attr)
  508. {
  509. int location = context.Config.GetPerPatchAttributeLocation(attr);
  510. string name = $"{DefaultNames.PerPatchAttributePrefix}{attr}";
  511. context.AppendLine($"layout (location = {location}) patch in vec4 {name};");
  512. }
  513. private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info)
  514. {
  515. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.OaIndexing))
  516. {
  517. context.AppendLine($"layout (location = 0) out vec4 {DefaultNames.OAttributePrefix}[{Constants.MaxAttributes}];");
  518. }
  519. else
  520. {
  521. int usedAttributes = context.Config.UsedOutputAttributes;
  522. if (context.Config.Stage == ShaderStage.Fragment && context.Config.GpuAccessor.QueryDualSourceBlendEnable())
  523. {
  524. int firstOutput = BitOperations.TrailingZeroCount(usedAttributes);
  525. int mask = 3 << firstOutput;
  526. if ((usedAttributes & mask) == mask)
  527. {
  528. usedAttributes &= ~mask;
  529. DeclareOutputDualSourceBlendAttribute(context, firstOutput);
  530. }
  531. }
  532. while (usedAttributes != 0)
  533. {
  534. int index = BitOperations.TrailingZeroCount(usedAttributes);
  535. DeclareOutputAttribute(context, index);
  536. usedAttributes &= ~(1 << index);
  537. }
  538. }
  539. }
  540. private static void DeclareOutputAttribute(CodeGenContext context, int attr)
  541. {
  542. string suffix = IsArrayAttributeGlsl(context.Config.Stage, isOutAttr: true) ? "[]" : string.Empty;
  543. string name = $"{DefaultNames.OAttributePrefix}{attr}{suffix}";
  544. if (context.Config.TransformFeedbackEnabled && context.Config.LastInVertexPipeline)
  545. {
  546. int components = context.Config.GetTransformFeedbackOutputComponents(attr, 0);
  547. if (components > 1)
  548. {
  549. string type = components switch
  550. {
  551. 2 => "vec2",
  552. 3 => "vec3",
  553. 4 => "vec4",
  554. _ => "float"
  555. };
  556. string xfb = string.Empty;
  557. var tfOutput = context.Config.GetTransformFeedbackOutput(attr, 0);
  558. if (tfOutput.Valid)
  559. {
  560. xfb = $", xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}";
  561. }
  562. context.AppendLine($"layout (location = {attr}{xfb}) out {type} {name};");
  563. }
  564. for (int c = components > 1 ? components : 0; c < 4; c++)
  565. {
  566. char swzMask = "xyzw"[c];
  567. string xfb = string.Empty;
  568. var tfOutput = context.Config.GetTransformFeedbackOutput(attr, c);
  569. if (tfOutput.Valid)
  570. {
  571. xfb = $", xfb_buffer = {tfOutput.Buffer}, xfb_offset = {tfOutput.Offset}, xfb_stride = {tfOutput.Stride}";
  572. }
  573. context.AppendLine($"layout (location = {attr}, component = {c}{xfb}) out float {name}_{swzMask};");
  574. }
  575. }
  576. else
  577. {
  578. string type = context.Config.Stage != ShaderStage.Fragment ? "vec4" :
  579. context.Config.GpuAccessor.QueryFragmentOutputType(attr) switch
  580. {
  581. AttributeType.Sint => "ivec4",
  582. AttributeType.Uint => "uvec4",
  583. _ => "vec4"
  584. };
  585. if (context.Config.GpuAccessor.QueryHostReducedPrecision() && context.Config.Stage == ShaderStage.Vertex && attr == 0)
  586. {
  587. context.AppendLine($"layout (location = {attr}) invariant out {type} {name};");
  588. }
  589. else
  590. {
  591. context.AppendLine($"layout (location = {attr}) out {type} {name};");
  592. }
  593. }
  594. }
  595. private static void DeclareOutputDualSourceBlendAttribute(CodeGenContext context, int attr)
  596. {
  597. string name = $"{DefaultNames.OAttributePrefix}{attr}";
  598. string name2 = $"{DefaultNames.OAttributePrefix}{(attr + 1)}";
  599. context.AppendLine($"layout (location = {attr}, index = 0) out vec4 {name};");
  600. context.AppendLine($"layout (location = {attr}, index = 1) out vec4 {name2};");
  601. }
  602. private static bool IsArrayAttributeGlsl(ShaderStage stage, bool isOutAttr)
  603. {
  604. if (isOutAttr)
  605. {
  606. return stage == ShaderStage.TessellationControl;
  607. }
  608. else
  609. {
  610. return stage == ShaderStage.TessellationControl ||
  611. stage == ShaderStage.TessellationEvaluation ||
  612. stage == ShaderStage.Geometry;
  613. }
  614. }
  615. private static void DeclareUsedOutputAttributesPerPatch(CodeGenContext context, HashSet<int> attrs)
  616. {
  617. foreach (int attr in attrs.Order())
  618. {
  619. DeclareOutputAttributePerPatch(context, attr);
  620. }
  621. }
  622. private static void DeclareOutputAttributePerPatch(CodeGenContext context, int attr)
  623. {
  624. int location = context.Config.GetPerPatchAttributeLocation(attr);
  625. string name = $"{DefaultNames.PerPatchAttributePrefix}{attr}";
  626. context.AppendLine($"layout (location = {location}) patch out vec4 {name};");
  627. }
  628. private static void DeclareSupportUniformBlock(CodeGenContext context, ShaderStage stage, int scaleElements)
  629. {
  630. bool needsSupportBlock = stage == ShaderStage.Fragment ||
  631. (context.Config.LastInVertexPipeline && context.Config.GpuAccessor.QueryViewportTransformDisable());
  632. if (!needsSupportBlock && scaleElements == 0)
  633. {
  634. return;
  635. }
  636. context.AppendLine($"layout (binding = 0, std140) uniform {DefaultNames.SupportBlockName}");
  637. context.EnterScope();
  638. switch (stage)
  639. {
  640. case ShaderStage.Fragment:
  641. case ShaderStage.Vertex:
  642. context.AppendLine($"uint {DefaultNames.SupportBlockAlphaTestName};");
  643. context.AppendLine($"bool {DefaultNames.SupportBlockIsBgraName}[{SupportBuffer.FragmentIsBgraCount}];");
  644. context.AppendLine($"vec4 {DefaultNames.SupportBlockViewportInverse};");
  645. context.AppendLine($"int {DefaultNames.SupportBlockFragmentScaleCount};");
  646. break;
  647. case ShaderStage.Compute:
  648. context.AppendLine($"uint s_reserved[{SupportBuffer.ComputeRenderScaleOffset / SupportBuffer.FieldSize}];");
  649. break;
  650. }
  651. context.AppendLine($"float {DefaultNames.SupportBlockRenderScaleName}[{SupportBuffer.RenderScaleMaxCount}];");
  652. context.LeaveScope(";");
  653. context.AppendLine();
  654. }
  655. private static void AppendHelperFunction(CodeGenContext context, string filename)
  656. {
  657. string code = EmbeddedResources.ReadAllText(filename);
  658. code = code.Replace("\t", CodeGenContext.Tab);
  659. code = code.Replace("$SHARED_MEM$", DefaultNames.SharedMemoryName);
  660. code = code.Replace("$STORAGE_MEM$", OperandManager.GetShaderStagePrefix(context.Config.Stage) + "_" + DefaultNames.StorageNamePrefix);
  661. if (context.Config.GpuAccessor.QueryHostSupportsShaderBallot())
  662. {
  663. code = code.Replace("$SUBGROUP_INVOCATION$", "gl_SubGroupInvocationARB");
  664. code = code.Replace("$SUBGROUP_BROADCAST$", "readInvocationARB");
  665. }
  666. else
  667. {
  668. code = code.Replace("$SUBGROUP_INVOCATION$", "gl_SubgroupInvocationID");
  669. code = code.Replace("$SUBGROUP_BROADCAST$", "subgroupBroadcast");
  670. }
  671. context.AppendLine(code);
  672. context.AppendLine();
  673. }
  674. }
  675. }