ShaderConfig.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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 OutputTopology OutputTopology { get; }
  15. public int MaxOutputVertices { get; }
  16. public int LocalMemorySize { get; }
  17. public ImapPixelType[] ImapTypes { get; }
  18. public OmapTarget[] OmapTargets { get; }
  19. public bool OmapSampleMask { get; }
  20. public bool OmapDepth { get; }
  21. public IGpuAccessor GpuAccessor { get; }
  22. public TranslationOptions Options { get; }
  23. public int Size { get; private set; }
  24. public byte ClipDistancesWritten { get; private set; }
  25. public FeatureFlags UsedFeatures { get; private set; }
  26. public HashSet<int> TextureHandlesForCache { get; }
  27. private readonly TranslationCounts _counts;
  28. public int UsedInputAttributes { get; private set; }
  29. public int UsedOutputAttributes { get; private set; }
  30. public int PassthroughAttributes { get; private set; }
  31. private int _usedConstantBuffers;
  32. private int _usedStorageBuffers;
  33. private int _usedStorageBuffersWrite;
  34. private struct TextureInfo : IEquatable<TextureInfo>
  35. {
  36. public int CbufSlot { get; }
  37. public int Handle { get; }
  38. public bool Indexed { get; }
  39. public TextureFormat Format { get; }
  40. public TextureInfo(int cbufSlot, int handle, bool indexed, TextureFormat format)
  41. {
  42. CbufSlot = cbufSlot;
  43. Handle = handle;
  44. Indexed = indexed;
  45. Format = format;
  46. }
  47. public override bool Equals(object obj)
  48. {
  49. return obj is TextureInfo other && Equals(other);
  50. }
  51. public bool Equals(TextureInfo other)
  52. {
  53. return CbufSlot == other.CbufSlot && Handle == other.Handle && Indexed == other.Indexed && Format == other.Format;
  54. }
  55. public override int GetHashCode()
  56. {
  57. return HashCode.Combine(CbufSlot, Handle, Indexed, Format);
  58. }
  59. }
  60. private struct TextureMeta
  61. {
  62. public bool AccurateType;
  63. public SamplerType Type;
  64. public TextureUsageFlags UsageFlags;
  65. }
  66. private readonly Dictionary<TextureInfo, TextureMeta> _usedTextures;
  67. private readonly Dictionary<TextureInfo, TextureMeta> _usedImages;
  68. private BufferDescriptor[] _cachedConstantBufferDescriptors;
  69. private BufferDescriptor[] _cachedStorageBufferDescriptors;
  70. private TextureDescriptor[] _cachedTextureDescriptors;
  71. private TextureDescriptor[] _cachedImageDescriptors;
  72. public int FirstConstantBufferBinding { get; private set; }
  73. public int FirstStorageBufferBinding { get; private set; }
  74. public ShaderConfig(IGpuAccessor gpuAccessor, TranslationOptions options, TranslationCounts counts)
  75. {
  76. Stage = ShaderStage.Compute;
  77. GpuAccessor = gpuAccessor;
  78. Options = options;
  79. _counts = counts;
  80. TextureHandlesForCache = new HashSet<int>();
  81. _usedTextures = new Dictionary<TextureInfo, TextureMeta>();
  82. _usedImages = new Dictionary<TextureInfo, TextureMeta>();
  83. }
  84. public ShaderConfig(ShaderHeader header, IGpuAccessor gpuAccessor, TranslationOptions options, TranslationCounts counts) : this(gpuAccessor, options, counts)
  85. {
  86. Stage = header.Stage;
  87. GpPassthrough = header.Stage == ShaderStage.Geometry && header.GpPassthrough;
  88. OutputTopology = header.OutputTopology;
  89. MaxOutputVertices = header.MaxOutputVertexCount;
  90. LocalMemorySize = header.ShaderLocalMemoryLowSize + header.ShaderLocalMemoryHighSize;
  91. ImapTypes = header.ImapTypes;
  92. OmapTargets = header.OmapTargets;
  93. OmapSampleMask = header.OmapSampleMask;
  94. OmapDepth = header.OmapDepth;
  95. }
  96. public int GetDepthRegister()
  97. {
  98. int count = 0;
  99. for (int index = 0; index < OmapTargets.Length; index++)
  100. {
  101. for (int component = 0; component < 4; component++)
  102. {
  103. if (OmapTargets[index].ComponentEnabled(component))
  104. {
  105. count++;
  106. }
  107. }
  108. }
  109. // The depth register is always two registers after the last color output.
  110. return count + 1;
  111. }
  112. public TextureFormat GetTextureFormat(int handle, int cbufSlot = -1)
  113. {
  114. // When the formatted load extension is supported, we don't need to
  115. // specify a format, we can just declare it without a format and the GPU will handle it.
  116. if (GpuAccessor.QueryHostSupportsImageLoadFormatted())
  117. {
  118. return TextureFormat.Unknown;
  119. }
  120. var format = GpuAccessor.QueryTextureFormat(handle, cbufSlot);
  121. if (format == TextureFormat.Unknown)
  122. {
  123. GpuAccessor.Log($"Unknown format for texture {handle}.");
  124. format = TextureFormat.R8G8B8A8Unorm;
  125. }
  126. return format;
  127. }
  128. public void SizeAdd(int size)
  129. {
  130. Size += size;
  131. }
  132. public void InheritFrom(ShaderConfig other)
  133. {
  134. ClipDistancesWritten |= other.ClipDistancesWritten;
  135. UsedFeatures |= other.UsedFeatures;
  136. TextureHandlesForCache.UnionWith(other.TextureHandlesForCache);
  137. UsedInputAttributes |= other.UsedInputAttributes;
  138. UsedOutputAttributes |= other.UsedOutputAttributes;
  139. _usedConstantBuffers |= other._usedConstantBuffers;
  140. _usedStorageBuffers |= other._usedStorageBuffers;
  141. _usedStorageBuffersWrite |= other._usedStorageBuffersWrite;
  142. foreach (var kv in other._usedTextures)
  143. {
  144. if (!_usedTextures.TryAdd(kv.Key, kv.Value))
  145. {
  146. _usedTextures[kv.Key] = MergeTextureMeta(kv.Value, _usedTextures[kv.Key]);
  147. }
  148. }
  149. foreach (var kv in other._usedImages)
  150. {
  151. if (!_usedImages.TryAdd(kv.Key, kv.Value))
  152. {
  153. _usedImages[kv.Key] = MergeTextureMeta(kv.Value, _usedImages[kv.Key]);
  154. }
  155. }
  156. }
  157. public void SetInputUserAttribute(int index)
  158. {
  159. UsedInputAttributes |= 1 << index;
  160. }
  161. public void SetOutputUserAttribute(int index)
  162. {
  163. UsedOutputAttributes |= 1 << index;
  164. }
  165. public void MergeOutputUserAttributes(int mask)
  166. {
  167. if (GpPassthrough)
  168. {
  169. PassthroughAttributes = mask & ~UsedOutputAttributes;
  170. }
  171. else
  172. {
  173. UsedOutputAttributes |= mask;
  174. }
  175. }
  176. public void SetClipDistanceWritten(int index)
  177. {
  178. ClipDistancesWritten |= (byte)(1 << index);
  179. }
  180. public void SetUsedFeature(FeatureFlags flags)
  181. {
  182. UsedFeatures |= flags;
  183. }
  184. public Operand CreateCbuf(int slot, int offset)
  185. {
  186. SetUsedConstantBuffer(slot);
  187. return OperandHelper.Cbuf(slot, offset);
  188. }
  189. public void SetUsedConstantBuffer(int slot)
  190. {
  191. _usedConstantBuffers |= 1 << slot;
  192. }
  193. public void SetUsedStorageBuffer(int slot, bool write)
  194. {
  195. int mask = 1 << slot;
  196. _usedStorageBuffers |= mask;
  197. if (write)
  198. {
  199. _usedStorageBuffersWrite |= mask;
  200. }
  201. }
  202. public void SetUsedTexture(
  203. Instruction inst,
  204. SamplerType type,
  205. TextureFormat format,
  206. TextureFlags flags,
  207. int cbufSlot,
  208. int handle)
  209. {
  210. inst &= Instruction.Mask;
  211. bool isImage = inst == Instruction.ImageLoad || inst == Instruction.ImageStore;
  212. bool isWrite = inst == Instruction.ImageStore;
  213. bool accurateType = inst != Instruction.TextureSize && inst != Instruction.Lod;
  214. if (isImage)
  215. {
  216. SetUsedTextureOrImage(_usedImages, cbufSlot, handle, type, format, true, isWrite, false);
  217. }
  218. else
  219. {
  220. bool intCoords = flags.HasFlag(TextureFlags.IntCoords) || inst == Instruction.TextureSize;
  221. SetUsedTextureOrImage(_usedTextures, cbufSlot, handle, type, TextureFormat.Unknown, intCoords, false, accurateType);
  222. }
  223. }
  224. private void SetUsedTextureOrImage(
  225. Dictionary<TextureInfo, TextureMeta> dict,
  226. int cbufSlot,
  227. int handle,
  228. SamplerType type,
  229. TextureFormat format,
  230. bool intCoords,
  231. bool write,
  232. bool accurateType)
  233. {
  234. var dimensions = type.GetDimensions();
  235. var isIndexed = type.HasFlag(SamplerType.Indexed);
  236. var usageFlags = TextureUsageFlags.None;
  237. if (intCoords)
  238. {
  239. usageFlags |= TextureUsageFlags.NeedsScaleValue;
  240. var canScale = (Stage == ShaderStage.Fragment || Stage == ShaderStage.Compute) && !isIndexed && !write && dimensions == 2;
  241. if (!canScale)
  242. {
  243. // Resolution scaling cannot be applied to this texture right now.
  244. // Flag so that we know to blacklist scaling on related textures when binding them.
  245. usageFlags |= TextureUsageFlags.ResScaleUnsupported;
  246. }
  247. }
  248. if (write)
  249. {
  250. usageFlags |= TextureUsageFlags.ImageStore;
  251. }
  252. int arraySize = isIndexed ? SamplerArraySize : 1;
  253. for (int layer = 0; layer < arraySize; layer++)
  254. {
  255. var info = new TextureInfo(cbufSlot, handle + layer * 2, isIndexed, format);
  256. var meta = new TextureMeta()
  257. {
  258. AccurateType = accurateType,
  259. Type = type,
  260. UsageFlags = usageFlags
  261. };
  262. if (dict.TryGetValue(info, out var existingMeta))
  263. {
  264. dict[info] = MergeTextureMeta(meta, existingMeta);
  265. }
  266. else
  267. {
  268. dict.Add(info, meta);
  269. }
  270. }
  271. }
  272. private static TextureMeta MergeTextureMeta(TextureMeta meta, TextureMeta existingMeta)
  273. {
  274. meta.UsageFlags |= existingMeta.UsageFlags;
  275. // If the texture we have has inaccurate type information, then
  276. // we prefer the most accurate one.
  277. if (existingMeta.AccurateType)
  278. {
  279. meta.AccurateType = true;
  280. meta.Type = existingMeta.Type;
  281. }
  282. return meta;
  283. }
  284. public BufferDescriptor[] GetConstantBufferDescriptors()
  285. {
  286. if (_cachedConstantBufferDescriptors != null)
  287. {
  288. return _cachedConstantBufferDescriptors;
  289. }
  290. int usedMask = _usedConstantBuffers;
  291. if (UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  292. {
  293. usedMask |= (int)GpuAccessor.QueryConstantBufferUse();
  294. }
  295. FirstConstantBufferBinding = _counts.UniformBuffersCount;
  296. return _cachedConstantBufferDescriptors = GetBufferDescriptors(
  297. usedMask,
  298. 0,
  299. UsedFeatures.HasFlag(FeatureFlags.CbIndexing),
  300. _counts.IncrementUniformBuffersCount);
  301. }
  302. public BufferDescriptor[] GetStorageBufferDescriptors()
  303. {
  304. if (_cachedStorageBufferDescriptors != null)
  305. {
  306. return _cachedStorageBufferDescriptors;
  307. }
  308. FirstStorageBufferBinding = _counts.StorageBuffersCount;
  309. return _cachedStorageBufferDescriptors = GetBufferDescriptors(
  310. _usedStorageBuffers,
  311. _usedStorageBuffersWrite,
  312. true,
  313. _counts.IncrementStorageBuffersCount);
  314. }
  315. private static BufferDescriptor[] GetBufferDescriptors(
  316. int usedMask,
  317. int writtenMask,
  318. bool isArray,
  319. Func<int> getBindingCallback)
  320. {
  321. var descriptors = new BufferDescriptor[BitOperations.PopCount((uint)usedMask)];
  322. int lastSlot = -1;
  323. for (int i = 0; i < descriptors.Length; i++)
  324. {
  325. int slot = BitOperations.TrailingZeroCount(usedMask);
  326. if (isArray)
  327. {
  328. // The next array entries also consumes bindings, even if they are unused.
  329. for (int j = lastSlot + 1; j < slot; j++)
  330. {
  331. getBindingCallback();
  332. }
  333. }
  334. lastSlot = slot;
  335. descriptors[i] = new BufferDescriptor(getBindingCallback(), slot);
  336. if ((writtenMask & (1 << slot)) != 0)
  337. {
  338. descriptors[i].SetFlag(BufferUsageFlags.Write);
  339. }
  340. usedMask &= ~(1 << slot);
  341. }
  342. return descriptors;
  343. }
  344. public TextureDescriptor[] GetTextureDescriptors()
  345. {
  346. return _cachedTextureDescriptors ??= GetTextureOrImageDescriptors(_usedTextures, _counts.IncrementTexturesCount);
  347. }
  348. public TextureDescriptor[] GetImageDescriptors()
  349. {
  350. return _cachedImageDescriptors ??= GetTextureOrImageDescriptors(_usedImages, _counts.IncrementImagesCount);
  351. }
  352. private static TextureDescriptor[] GetTextureOrImageDescriptors(Dictionary<TextureInfo, TextureMeta> dict, Func<int> getBindingCallback)
  353. {
  354. var descriptors = new TextureDescriptor[dict.Count];
  355. int i = 0;
  356. foreach (var kv in dict.OrderBy(x => x.Key.Indexed).OrderBy(x => x.Key.Handle))
  357. {
  358. var info = kv.Key;
  359. var meta = kv.Value;
  360. int binding = getBindingCallback();
  361. descriptors[i] = new TextureDescriptor(binding, meta.Type, info.Format, info.CbufSlot, info.Handle);
  362. descriptors[i].SetFlag(meta.UsageFlags);
  363. i++;
  364. }
  365. return descriptors;
  366. }
  367. }
  368. }