ShaderConfig.cs 20 KB

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