Declarations.cs 30 KB

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