Declarations.cs 30 KB

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