ShaderConfig.cs 20 KB

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