ShaderConfig.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. }
  267. public void SetAllOutputUserAttributes()
  268. {
  269. UsedOutputAttributes |= Constants.AllAttributesMask;
  270. }
  271. public void SetClipDistanceWritten(int index)
  272. {
  273. ClipDistancesWritten |= (byte)(1 << index);
  274. }
  275. public void SetUsedFeature(FeatureFlags flags)
  276. {
  277. UsedFeatures |= flags;
  278. }
  279. public Operand CreateCbuf(int slot, int offset)
  280. {
  281. SetUsedConstantBuffer(slot);
  282. return OperandHelper.Cbuf(slot, offset);
  283. }
  284. public void SetUsedConstantBuffer(int slot)
  285. {
  286. _usedConstantBuffers |= 1 << slot;
  287. }
  288. public void SetUsedStorageBuffer(int slot, bool write)
  289. {
  290. int mask = 1 << slot;
  291. _usedStorageBuffers |= mask;
  292. if (write)
  293. {
  294. _usedStorageBuffersWrite |= mask;
  295. }
  296. }
  297. public void SetUsedTexture(
  298. Instruction inst,
  299. SamplerType type,
  300. TextureFormat format,
  301. TextureFlags flags,
  302. int cbufSlot,
  303. int handle)
  304. {
  305. inst &= Instruction.Mask;
  306. bool isImage = inst == Instruction.ImageLoad || inst == Instruction.ImageStore || inst == Instruction.ImageAtomic;
  307. bool isWrite = inst == Instruction.ImageStore || inst == Instruction.ImageAtomic;
  308. bool accurateType = inst != Instruction.Lod && inst != Instruction.TextureSize;
  309. bool coherent = flags.HasFlag(TextureFlags.Coherent);
  310. if (isImage)
  311. {
  312. SetUsedTextureOrImage(_usedImages, cbufSlot, handle, type, format, true, isWrite, false, coherent);
  313. }
  314. else
  315. {
  316. bool intCoords = flags.HasFlag(TextureFlags.IntCoords) || inst == Instruction.TextureSize;
  317. SetUsedTextureOrImage(_usedTextures, cbufSlot, handle, type, TextureFormat.Unknown, intCoords, false, accurateType, coherent);
  318. }
  319. }
  320. private void SetUsedTextureOrImage(
  321. Dictionary<TextureInfo, TextureMeta> dict,
  322. int cbufSlot,
  323. int handle,
  324. SamplerType type,
  325. TextureFormat format,
  326. bool intCoords,
  327. bool write,
  328. bool accurateType,
  329. bool coherent)
  330. {
  331. var dimensions = type.GetDimensions();
  332. var isIndexed = type.HasFlag(SamplerType.Indexed);
  333. var usageFlags = TextureUsageFlags.None;
  334. if (intCoords)
  335. {
  336. usageFlags |= TextureUsageFlags.NeedsScaleValue;
  337. var canScale = Stage.SupportsRenderScale() && !isIndexed && !write && dimensions == 2;
  338. if (!canScale)
  339. {
  340. // Resolution scaling cannot be applied to this texture right now.
  341. // Flag so that we know to blacklist scaling on related textures when binding them.
  342. usageFlags |= TextureUsageFlags.ResScaleUnsupported;
  343. }
  344. }
  345. if (write)
  346. {
  347. usageFlags |= TextureUsageFlags.ImageStore;
  348. }
  349. if (coherent)
  350. {
  351. usageFlags |= TextureUsageFlags.ImageCoherent;
  352. }
  353. int arraySize = isIndexed ? SamplerArraySize : 1;
  354. for (int layer = 0; layer < arraySize; layer++)
  355. {
  356. var info = new TextureInfo(cbufSlot, handle + layer * 2, isIndexed, format);
  357. var meta = new TextureMeta()
  358. {
  359. AccurateType = accurateType,
  360. Type = type,
  361. UsageFlags = usageFlags
  362. };
  363. if (dict.TryGetValue(info, out var existingMeta))
  364. {
  365. dict[info] = MergeTextureMeta(meta, existingMeta);
  366. }
  367. else
  368. {
  369. dict.Add(info, meta);
  370. }
  371. }
  372. }
  373. private static TextureMeta MergeTextureMeta(TextureMeta meta, TextureMeta existingMeta)
  374. {
  375. meta.UsageFlags |= existingMeta.UsageFlags;
  376. // If the texture we have has inaccurate type information, then
  377. // we prefer the most accurate one.
  378. if (existingMeta.AccurateType)
  379. {
  380. meta.AccurateType = true;
  381. meta.Type = existingMeta.Type;
  382. }
  383. return meta;
  384. }
  385. public BufferDescriptor[] GetConstantBufferDescriptors()
  386. {
  387. if (_cachedConstantBufferDescriptors != null)
  388. {
  389. return _cachedConstantBufferDescriptors;
  390. }
  391. int usedMask = _usedConstantBuffers;
  392. if (UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  393. {
  394. usedMask |= (int)GpuAccessor.QueryConstantBufferUse();
  395. }
  396. FirstConstantBufferBinding = _counts.UniformBuffersCount;
  397. return _cachedConstantBufferDescriptors = GetBufferDescriptors(
  398. usedMask,
  399. 0,
  400. UsedFeatures.HasFlag(FeatureFlags.CbIndexing),
  401. _counts.IncrementUniformBuffersCount);
  402. }
  403. public BufferDescriptor[] GetStorageBufferDescriptors()
  404. {
  405. if (_cachedStorageBufferDescriptors != null)
  406. {
  407. return _cachedStorageBufferDescriptors;
  408. }
  409. FirstStorageBufferBinding = _counts.StorageBuffersCount;
  410. return _cachedStorageBufferDescriptors = GetBufferDescriptors(
  411. _usedStorageBuffers,
  412. _usedStorageBuffersWrite,
  413. true,
  414. _counts.IncrementStorageBuffersCount);
  415. }
  416. private static BufferDescriptor[] GetBufferDescriptors(
  417. int usedMask,
  418. int writtenMask,
  419. bool isArray,
  420. Func<int> getBindingCallback)
  421. {
  422. var descriptors = new BufferDescriptor[BitOperations.PopCount((uint)usedMask)];
  423. int lastSlot = -1;
  424. for (int i = 0; i < descriptors.Length; i++)
  425. {
  426. int slot = BitOperations.TrailingZeroCount(usedMask);
  427. if (isArray)
  428. {
  429. // The next array entries also consumes bindings, even if they are unused.
  430. for (int j = lastSlot + 1; j < slot; j++)
  431. {
  432. getBindingCallback();
  433. }
  434. }
  435. lastSlot = slot;
  436. descriptors[i] = new BufferDescriptor(getBindingCallback(), slot);
  437. if ((writtenMask & (1 << slot)) != 0)
  438. {
  439. descriptors[i].SetFlag(BufferUsageFlags.Write);
  440. }
  441. usedMask &= ~(1 << slot);
  442. }
  443. return descriptors;
  444. }
  445. public TextureDescriptor[] GetTextureDescriptors()
  446. {
  447. return _cachedTextureDescriptors ??= GetTextureOrImageDescriptors(_usedTextures, _counts.IncrementTexturesCount);
  448. }
  449. public TextureDescriptor[] GetImageDescriptors()
  450. {
  451. return _cachedImageDescriptors ??= GetTextureOrImageDescriptors(_usedImages, _counts.IncrementImagesCount);
  452. }
  453. private static TextureDescriptor[] GetTextureOrImageDescriptors(Dictionary<TextureInfo, TextureMeta> dict, Func<int> getBindingCallback)
  454. {
  455. var descriptors = new TextureDescriptor[dict.Count];
  456. int i = 0;
  457. foreach (var kv in dict.OrderBy(x => x.Key.Indexed).OrderBy(x => x.Key.Handle))
  458. {
  459. var info = kv.Key;
  460. var meta = kv.Value;
  461. int binding = getBindingCallback();
  462. descriptors[i] = new TextureDescriptor(binding, meta.Type, info.Format, info.CbufSlot, info.Handle);
  463. descriptors[i].SetFlag(meta.UsageFlags);
  464. i++;
  465. }
  466. return descriptors;
  467. }
  468. }
  469. }