Declarations.cs 29 KB

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