ShaderConfig.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Numerics;
  6. namespace Ryujinx.Graphics.Shader.Translation
  7. {
  8. class ShaderConfig
  9. {
  10. // TODO: Non-hardcoded array size.
  11. public const int SamplerArraySize = 4;
  12. public ShaderStage Stage { get; }
  13. public bool GpPassthrough { get; }
  14. public int ThreadsPerInputPrimitive { get; }
  15. public OutputTopology OutputTopology { get; }
  16. public int MaxOutputVertices { get; }
  17. public int LocalMemorySize { get; }
  18. public ImapPixelType[] ImapTypes { get; }
  19. public int OmapTargets { get; }
  20. public bool OmapSampleMask { get; }
  21. public bool OmapDepth { get; }
  22. public IGpuAccessor GpuAccessor { get; }
  23. public TranslationOptions Options { get; }
  24. public bool TransformFeedbackEnabled { get; }
  25. public int Size { get; private set; }
  26. public byte ClipDistancesWritten { get; private set; }
  27. public FeatureFlags UsedFeatures { get; private set; }
  28. public HashSet<int> TextureHandlesForCache { get; }
  29. private readonly TranslationCounts _counts;
  30. public bool NextUsesFixedFuncAttributes { get; private set; }
  31. public int UsedInputAttributes { get; private set; }
  32. public int UsedOutputAttributes { get; private set; }
  33. public int UsedInputAttributesPerPatch { get; private set; }
  34. public int UsedOutputAttributesPerPatch { get; private set; }
  35. public int PassthroughAttributes { get; private set; }
  36. private int _nextUsedInputAttributes;
  37. private int _thisUsedInputAttributes;
  38. public UInt128 NextInputAttributesComponents { get; private set; }
  39. public UInt128 ThisInputAttributesComponents { get; private set; }
  40. public UInt128 NextInputAttributesPerPatchComponents { get; private set; }
  41. public UInt128 ThisInputAttributesPerPatchComponents { get; private set; }
  42. private int _usedConstantBuffers;
  43. private int _usedStorageBuffers;
  44. private int _usedStorageBuffersWrite;
  45. private struct TextureInfo : IEquatable<TextureInfo>
  46. {
  47. public int CbufSlot { get; }
  48. public int Handle { get; }
  49. public bool Indexed { get; }
  50. public TextureFormat Format { get; }
  51. public TextureInfo(int cbufSlot, int handle, bool indexed, TextureFormat format)
  52. {
  53. CbufSlot = cbufSlot;
  54. Handle = handle;
  55. Indexed = indexed;
  56. Format = format;
  57. }
  58. public override bool Equals(object obj)
  59. {
  60. return obj is TextureInfo other && Equals(other);
  61. }
  62. public bool Equals(TextureInfo other)
  63. {
  64. return CbufSlot == other.CbufSlot && Handle == other.Handle && Indexed == other.Indexed && Format == other.Format;
  65. }
  66. public override int GetHashCode()
  67. {
  68. return HashCode.Combine(CbufSlot, Handle, Indexed, Format);
  69. }
  70. }
  71. private struct TextureMeta
  72. {
  73. public bool AccurateType;
  74. public SamplerType Type;
  75. public TextureUsageFlags UsageFlags;
  76. }
  77. private readonly Dictionary<TextureInfo, TextureMeta> _usedTextures;
  78. private readonly Dictionary<TextureInfo, TextureMeta> _usedImages;
  79. private BufferDescriptor[] _cachedConstantBufferDescriptors;
  80. private BufferDescriptor[] _cachedStorageBufferDescriptors;
  81. private TextureDescriptor[] _cachedTextureDescriptors;
  82. private TextureDescriptor[] _cachedImageDescriptors;
  83. public int FirstConstantBufferBinding { get; private set; }
  84. public int FirstStorageBufferBinding { get; private set; }
  85. public ShaderConfig(IGpuAccessor gpuAccessor, TranslationOptions options, TranslationCounts counts)
  86. {
  87. Stage = ShaderStage.Compute;
  88. GpuAccessor = gpuAccessor;
  89. Options = options;
  90. _counts = counts;
  91. TextureHandlesForCache = new HashSet<int>();
  92. _usedTextures = new Dictionary<TextureInfo, TextureMeta>();
  93. _usedImages = new Dictionary<TextureInfo, TextureMeta>();
  94. }
  95. public ShaderConfig(ShaderHeader header, IGpuAccessor gpuAccessor, TranslationOptions options, TranslationCounts counts) : this(gpuAccessor, options, counts)
  96. {
  97. Stage = header.Stage;
  98. GpPassthrough = header.Stage == ShaderStage.Geometry && header.GpPassthrough;
  99. ThreadsPerInputPrimitive = header.ThreadsPerInputPrimitive;
  100. OutputTopology = header.OutputTopology;
  101. MaxOutputVertices = header.MaxOutputVertexCount;
  102. LocalMemorySize = header.ShaderLocalMemoryLowSize + header.ShaderLocalMemoryHighSize;
  103. ImapTypes = header.ImapTypes;
  104. OmapTargets = header.OmapTargets;
  105. OmapSampleMask = header.OmapSampleMask;
  106. OmapDepth = header.OmapDepth;
  107. TransformFeedbackEnabled = gpuAccessor.QueryTransformFeedbackEnabled();
  108. }
  109. public int GetDepthRegister()
  110. {
  111. // The depth register is always two registers after the last color output.
  112. return BitOperations.PopCount((uint)OmapTargets) + 1;
  113. }
  114. public TextureFormat GetTextureFormat(int handle, int cbufSlot = -1)
  115. {
  116. // When the formatted load extension is supported, we don't need to
  117. // specify a format, we can just declare it without a format and the GPU will handle it.
  118. if (GpuAccessor.QueryHostSupportsImageLoadFormatted())
  119. {
  120. return TextureFormat.Unknown;
  121. }
  122. var format = GpuAccessor.QueryTextureFormat(handle, cbufSlot);
  123. if (format == TextureFormat.Unknown)
  124. {
  125. GpuAccessor.Log($"Unknown format for texture {handle}.");
  126. format = TextureFormat.R8G8B8A8Unorm;
  127. }
  128. return format;
  129. }
  130. private bool FormatSupportsAtomic(TextureFormat format)
  131. {
  132. return format == TextureFormat.R32Sint || format == TextureFormat.R32Uint;
  133. }
  134. public TextureFormat GetTextureFormatAtomic(int handle, int cbufSlot = -1)
  135. {
  136. // Atomic image instructions do not support GL_EXT_shader_image_load_formatted,
  137. // and must have a type specified. Default to R32Sint if not available.
  138. var format = GpuAccessor.QueryTextureFormat(handle, cbufSlot);
  139. if (!FormatSupportsAtomic(format))
  140. {
  141. GpuAccessor.Log($"Unsupported format for texture {handle}: {format}.");
  142. format = TextureFormat.R32Sint;
  143. }
  144. return format;
  145. }
  146. public void SizeAdd(int size)
  147. {
  148. Size += size;
  149. }
  150. public void InheritFrom(ShaderConfig other)
  151. {
  152. ClipDistancesWritten |= other.ClipDistancesWritten;
  153. UsedFeatures |= other.UsedFeatures;
  154. TextureHandlesForCache.UnionWith(other.TextureHandlesForCache);
  155. UsedInputAttributes |= other.UsedInputAttributes;
  156. UsedOutputAttributes |= other.UsedOutputAttributes;
  157. _usedConstantBuffers |= other._usedConstantBuffers;
  158. _usedStorageBuffers |= other._usedStorageBuffers;
  159. _usedStorageBuffersWrite |= other._usedStorageBuffersWrite;
  160. foreach (var kv in other._usedTextures)
  161. {
  162. if (!_usedTextures.TryAdd(kv.Key, kv.Value))
  163. {
  164. _usedTextures[kv.Key] = MergeTextureMeta(kv.Value, _usedTextures[kv.Key]);
  165. }
  166. }
  167. foreach (var kv in other._usedImages)
  168. {
  169. if (!_usedImages.TryAdd(kv.Key, kv.Value))
  170. {
  171. _usedImages[kv.Key] = MergeTextureMeta(kv.Value, _usedImages[kv.Key]);
  172. }
  173. }
  174. }
  175. public void SetInputUserAttributeFixedFunc(int index)
  176. {
  177. UsedInputAttributes |= 1 << index;
  178. }
  179. public void SetOutputUserAttributeFixedFunc(int index)
  180. {
  181. UsedOutputAttributes |= 1 << index;
  182. }
  183. public void SetInputUserAttribute(int index, int component, bool perPatch)
  184. {
  185. if (perPatch)
  186. {
  187. UsedInputAttributesPerPatch |= 1 << index;
  188. ThisInputAttributesPerPatchComponents |= UInt128.Pow2(index * 4 + component);
  189. }
  190. else
  191. {
  192. int mask = 1 << index;
  193. UsedInputAttributes |= mask;
  194. _thisUsedInputAttributes |= mask;
  195. ThisInputAttributesComponents |= UInt128.Pow2(index * 4 + component);
  196. }
  197. }
  198. public void SetOutputUserAttribute(int index, bool perPatch)
  199. {
  200. if (perPatch)
  201. {
  202. UsedOutputAttributesPerPatch |= 1 << index;
  203. }
  204. else
  205. {
  206. UsedOutputAttributes |= 1 << index;
  207. }
  208. }
  209. public void MergeFromtNextStage(ShaderConfig config)
  210. {
  211. NextInputAttributesComponents = config.ThisInputAttributesComponents;
  212. NextInputAttributesPerPatchComponents = config.ThisInputAttributesPerPatchComponents;
  213. NextUsesFixedFuncAttributes = config.UsedFeatures.HasFlag(FeatureFlags.FixedFuncAttr);
  214. MergeOutputUserAttributes(config.UsedInputAttributes, config.UsedInputAttributesPerPatch);
  215. }
  216. public void MergeOutputUserAttributes(int mask, int maskPerPatch)
  217. {
  218. _nextUsedInputAttributes = mask;
  219. if (GpPassthrough)
  220. {
  221. PassthroughAttributes = mask & ~UsedOutputAttributes;
  222. }
  223. else
  224. {
  225. UsedOutputAttributes |= mask;
  226. UsedOutputAttributesPerPatch |= maskPerPatch;
  227. }
  228. }
  229. public bool IsUsedOutputAttribute(int attr)
  230. {
  231. // The check for fixed function attributes on the next stage is conservative,
  232. // returning false if the output is just not used by the next stage is also valid.
  233. if (NextUsesFixedFuncAttributes &&
  234. attr >= AttributeConsts.UserAttributeBase &&
  235. attr < AttributeConsts.UserAttributeEnd)
  236. {
  237. int index = (attr - AttributeConsts.UserAttributeBase) >> 4;
  238. return (_nextUsedInputAttributes & (1 << index)) != 0;
  239. }
  240. return true;
  241. }
  242. public int GetFreeUserAttribute(bool isOutput, int index)
  243. {
  244. int useMask = isOutput ? _nextUsedInputAttributes : _thisUsedInputAttributes;
  245. int bit = -1;
  246. while (useMask != -1)
  247. {
  248. bit = BitOperations.TrailingZeroCount(~useMask);
  249. if (bit == 32)
  250. {
  251. bit = -1;
  252. break;
  253. }
  254. else if (index < 1)
  255. {
  256. break;
  257. }
  258. useMask |= 1 << bit;
  259. index--;
  260. }
  261. return bit;
  262. }
  263. public void SetAllInputUserAttributes()
  264. {
  265. UsedInputAttributes |= Constants.AllAttributesMask;
  266. ThisInputAttributesComponents |= ~UInt128.Zero >> (128 - Constants.MaxAttributes * 4);
  267. }
  268. public void SetAllOutputUserAttributes()
  269. {
  270. UsedOutputAttributes |= Constants.AllAttributesMask;
  271. }
  272. public void SetClipDistanceWritten(int index)
  273. {
  274. ClipDistancesWritten |= (byte)(1 << index);
  275. }
  276. public void SetUsedFeature(FeatureFlags flags)
  277. {
  278. UsedFeatures |= flags;
  279. }
  280. public Operand CreateCbuf(int slot, int offset)
  281. {
  282. SetUsedConstantBuffer(slot);
  283. return OperandHelper.Cbuf(slot, offset);
  284. }
  285. public void SetUsedConstantBuffer(int slot)
  286. {
  287. _usedConstantBuffers |= 1 << slot;
  288. }
  289. public void SetUsedStorageBuffer(int slot, bool write)
  290. {
  291. int mask = 1 << slot;
  292. _usedStorageBuffers |= mask;
  293. if (write)
  294. {
  295. _usedStorageBuffersWrite |= mask;
  296. }
  297. }
  298. public void SetUsedTexture(
  299. Instruction inst,
  300. SamplerType type,
  301. TextureFormat format,
  302. TextureFlags flags,
  303. int cbufSlot,
  304. int handle)
  305. {
  306. inst &= Instruction.Mask;
  307. bool isImage = inst == Instruction.ImageLoad || inst == Instruction.ImageStore || inst == Instruction.ImageAtomic;
  308. bool isWrite = inst == Instruction.ImageStore || inst == Instruction.ImageAtomic;
  309. bool accurateType = inst != Instruction.Lod && inst != Instruction.TextureSize;
  310. bool coherent = flags.HasFlag(TextureFlags.Coherent);
  311. if (isImage)
  312. {
  313. SetUsedTextureOrImage(_usedImages, cbufSlot, handle, type, format, true, isWrite, false, coherent);
  314. }
  315. else
  316. {
  317. bool intCoords = flags.HasFlag(TextureFlags.IntCoords) || inst == Instruction.TextureSize;
  318. SetUsedTextureOrImage(_usedTextures, cbufSlot, handle, type, TextureFormat.Unknown, intCoords, false, accurateType, coherent);
  319. }
  320. }
  321. private void SetUsedTextureOrImage(
  322. Dictionary<TextureInfo, TextureMeta> dict,
  323. int cbufSlot,
  324. int handle,
  325. SamplerType type,
  326. TextureFormat format,
  327. bool intCoords,
  328. bool write,
  329. bool accurateType,
  330. bool coherent)
  331. {
  332. var dimensions = type.GetDimensions();
  333. var isIndexed = type.HasFlag(SamplerType.Indexed);
  334. var usageFlags = TextureUsageFlags.None;
  335. if (intCoords)
  336. {
  337. usageFlags |= TextureUsageFlags.NeedsScaleValue;
  338. var canScale = Stage.SupportsRenderScale() && !isIndexed && !write && dimensions == 2;
  339. if (!canScale)
  340. {
  341. // Resolution scaling cannot be applied to this texture right now.
  342. // Flag so that we know to blacklist scaling on related textures when binding them.
  343. usageFlags |= TextureUsageFlags.ResScaleUnsupported;
  344. }
  345. }
  346. if (write)
  347. {
  348. usageFlags |= TextureUsageFlags.ImageStore;
  349. }
  350. if (coherent)
  351. {
  352. usageFlags |= TextureUsageFlags.ImageCoherent;
  353. }
  354. int arraySize = isIndexed ? SamplerArraySize : 1;
  355. for (int layer = 0; layer < arraySize; layer++)
  356. {
  357. var info = new TextureInfo(cbufSlot, handle + layer * 2, isIndexed, format);
  358. var meta = new TextureMeta()
  359. {
  360. AccurateType = accurateType,
  361. Type = type,
  362. UsageFlags = usageFlags
  363. };
  364. if (dict.TryGetValue(info, out var existingMeta))
  365. {
  366. dict[info] = MergeTextureMeta(meta, existingMeta);
  367. }
  368. else
  369. {
  370. dict.Add(info, meta);
  371. }
  372. }
  373. }
  374. private static TextureMeta MergeTextureMeta(TextureMeta meta, TextureMeta existingMeta)
  375. {
  376. meta.UsageFlags |= existingMeta.UsageFlags;
  377. // If the texture we have has inaccurate type information, then
  378. // we prefer the most accurate one.
  379. if (existingMeta.AccurateType)
  380. {
  381. meta.AccurateType = true;
  382. meta.Type = existingMeta.Type;
  383. }
  384. return meta;
  385. }
  386. public BufferDescriptor[] GetConstantBufferDescriptors()
  387. {
  388. if (_cachedConstantBufferDescriptors != null)
  389. {
  390. return _cachedConstantBufferDescriptors;
  391. }
  392. int usedMask = _usedConstantBuffers;
  393. if (UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  394. {
  395. usedMask |= (int)GpuAccessor.QueryConstantBufferUse();
  396. }
  397. FirstConstantBufferBinding = _counts.UniformBuffersCount;
  398. return _cachedConstantBufferDescriptors = GetBufferDescriptors(
  399. usedMask,
  400. 0,
  401. UsedFeatures.HasFlag(FeatureFlags.CbIndexing),
  402. _counts.IncrementUniformBuffersCount);
  403. }
  404. public BufferDescriptor[] GetStorageBufferDescriptors()
  405. {
  406. if (_cachedStorageBufferDescriptors != null)
  407. {
  408. return _cachedStorageBufferDescriptors;
  409. }
  410. FirstStorageBufferBinding = _counts.StorageBuffersCount;
  411. return _cachedStorageBufferDescriptors = GetBufferDescriptors(
  412. _usedStorageBuffers,
  413. _usedStorageBuffersWrite,
  414. true,
  415. _counts.IncrementStorageBuffersCount);
  416. }
  417. private static BufferDescriptor[] GetBufferDescriptors(
  418. int usedMask,
  419. int writtenMask,
  420. bool isArray,
  421. Func<int> getBindingCallback)
  422. {
  423. var descriptors = new BufferDescriptor[BitOperations.PopCount((uint)usedMask)];
  424. int lastSlot = -1;
  425. for (int i = 0; i < descriptors.Length; i++)
  426. {
  427. int slot = BitOperations.TrailingZeroCount(usedMask);
  428. if (isArray)
  429. {
  430. // The next array entries also consumes bindings, even if they are unused.
  431. for (int j = lastSlot + 1; j < slot; j++)
  432. {
  433. getBindingCallback();
  434. }
  435. }
  436. lastSlot = slot;
  437. descriptors[i] = new BufferDescriptor(getBindingCallback(), slot);
  438. if ((writtenMask & (1 << slot)) != 0)
  439. {
  440. descriptors[i].SetFlag(BufferUsageFlags.Write);
  441. }
  442. usedMask &= ~(1 << slot);
  443. }
  444. return descriptors;
  445. }
  446. public TextureDescriptor[] GetTextureDescriptors()
  447. {
  448. return _cachedTextureDescriptors ??= GetTextureOrImageDescriptors(_usedTextures, _counts.IncrementTexturesCount);
  449. }
  450. public TextureDescriptor[] GetImageDescriptors()
  451. {
  452. return _cachedImageDescriptors ??= GetTextureOrImageDescriptors(_usedImages, _counts.IncrementImagesCount);
  453. }
  454. private static TextureDescriptor[] GetTextureOrImageDescriptors(Dictionary<TextureInfo, TextureMeta> dict, Func<int> getBindingCallback)
  455. {
  456. var descriptors = new TextureDescriptor[dict.Count];
  457. int i = 0;
  458. foreach (var kv in dict.OrderBy(x => x.Key.Indexed).OrderBy(x => x.Key.Handle))
  459. {
  460. var info = kv.Key;
  461. var meta = kv.Value;
  462. int binding = getBindingCallback();
  463. descriptors[i] = new TextureDescriptor(binding, meta.Type, info.Format, info.CbufSlot, info.Handle);
  464. descriptors[i].SetFlag(meta.UsageFlags);
  465. i++;
  466. }
  467. return descriptors;
  468. }
  469. }
  470. }