ShaderConfig.cs 14 KB

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