TextureBindingsManager.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Gpu.Engine.Types;
  4. using Ryujinx.Graphics.Shader;
  5. using System;
  6. namespace Ryujinx.Graphics.Gpu.Image
  7. {
  8. /// <summary>
  9. /// Texture bindings manager.
  10. /// </summary>
  11. class TextureBindingsManager : IDisposable
  12. {
  13. private const int HandleHigh = 16;
  14. private const int HandleMask = (1 << HandleHigh) - 1;
  15. private const int SlotHigh = 16;
  16. private const int SlotMask = (1 << SlotHigh) - 1;
  17. private readonly GpuContext _context;
  18. private readonly bool _isCompute;
  19. private SamplerPool _samplerPool;
  20. private SamplerIndex _samplerIndex;
  21. private ulong _texturePoolAddress;
  22. private int _texturePoolMaximumId;
  23. private readonly GpuChannel _channel;
  24. private readonly TexturePoolCache _texturePoolCache;
  25. private readonly TextureBindingInfo[][] _textureBindings;
  26. private readonly TextureBindingInfo[][] _imageBindings;
  27. private struct TextureStatePerStage
  28. {
  29. public ITexture Texture;
  30. public ISampler Sampler;
  31. }
  32. private readonly TextureStatePerStage[][] _textureState;
  33. private readonly TextureStatePerStage[][] _imageState;
  34. private int _textureBufferIndex;
  35. private bool _rebind;
  36. private readonly float[] _scales;
  37. private bool _scaleChanged;
  38. /// <summary>
  39. /// Constructs a new instance of the texture bindings manager.
  40. /// </summary>
  41. /// <param name="context">The GPU context that the texture bindings manager belongs to</param>
  42. /// <param name="channel">The GPU channel that the texture bindings manager belongs to</param>
  43. /// <param name="poolCache">Texture pools cache used to get texture pools from</param>
  44. /// <param name="isCompute">True if the bindings manager is used for the compute engine</param>
  45. public TextureBindingsManager(GpuContext context, GpuChannel channel, TexturePoolCache poolCache, bool isCompute)
  46. {
  47. _context = context;
  48. _channel = channel;
  49. _texturePoolCache = poolCache;
  50. _isCompute = isCompute;
  51. int stages = isCompute ? 1 : Constants.ShaderStages;
  52. _textureBindings = new TextureBindingInfo[stages][];
  53. _imageBindings = new TextureBindingInfo[stages][];
  54. _textureState = new TextureStatePerStage[stages][];
  55. _imageState = new TextureStatePerStage[stages][];
  56. _scales = new float[64];
  57. for (int i = 0; i < 64; i++)
  58. {
  59. _scales[i] = 1f;
  60. }
  61. }
  62. /// <summary>
  63. /// Binds textures for a given shader stage.
  64. /// </summary>
  65. /// <param name="stage">Shader stage number, or 0 for compute shaders</param>
  66. /// <param name="bindings">Texture bindings</param>
  67. public void SetTextures(int stage, TextureBindingInfo[] bindings)
  68. {
  69. _textureBindings[stage] = bindings;
  70. _textureState[stage] = new TextureStatePerStage[bindings.Length];
  71. }
  72. /// <summary>
  73. /// Binds images for a given shader stage.
  74. /// </summary>
  75. /// <param name="stage">Shader stage number, or 0 for compute shaders</param>
  76. /// <param name="bindings">Image bindings</param>
  77. public void SetImages(int stage, TextureBindingInfo[] bindings)
  78. {
  79. _imageBindings[stage] = bindings;
  80. _imageState[stage] = new TextureStatePerStage[bindings.Length];
  81. }
  82. /// <summary>
  83. /// Sets the textures constant buffer index.
  84. /// The constant buffer specified holds the texture handles.
  85. /// </summary>
  86. /// <param name="index">Constant buffer index</param>
  87. public void SetTextureBufferIndex(int index)
  88. {
  89. _textureBufferIndex = index;
  90. }
  91. /// <summary>
  92. /// Sets the current texture sampler pool to be used.
  93. /// </summary>
  94. /// <param name="gpuVa">Start GPU virtual address of the pool</param>
  95. /// <param name="maximumId">Maximum ID of the pool (total count minus one)</param>
  96. /// <param name="samplerIndex">Type of the sampler pool indexing used for bound samplers</param>
  97. public void SetSamplerPool(ulong gpuVa, int maximumId, SamplerIndex samplerIndex)
  98. {
  99. if (gpuVa != 0)
  100. {
  101. ulong address = _channel.MemoryManager.Translate(gpuVa);
  102. if (_samplerPool != null && _samplerPool.Address == address && _samplerPool.MaximumId >= maximumId)
  103. {
  104. return;
  105. }
  106. _samplerPool?.Dispose();
  107. _samplerPool = new SamplerPool(_context, _channel.MemoryManager.Physical, address, maximumId);
  108. }
  109. else
  110. {
  111. _samplerPool?.Dispose();
  112. _samplerPool = null;
  113. }
  114. _samplerIndex = samplerIndex;
  115. }
  116. /// <summary>
  117. /// Sets the current texture pool to be used.
  118. /// </summary>
  119. /// <param name="gpuVa">Start GPU virtual address of the pool</param>
  120. /// <param name="maximumId">Maximum ID of the pool (total count minus one)</param>
  121. public void SetTexturePool(ulong gpuVa, int maximumId)
  122. {
  123. if (gpuVa != 0)
  124. {
  125. ulong address = _channel.MemoryManager.Translate(gpuVa);
  126. _texturePoolAddress = address;
  127. _texturePoolMaximumId = maximumId;
  128. }
  129. else
  130. {
  131. _texturePoolAddress = 0;
  132. _texturePoolMaximumId = 0;
  133. }
  134. }
  135. /// <summary>
  136. /// Updates the texture scale for a given texture or image.
  137. /// </summary>
  138. /// <param name="texture">Start GPU virtual address of the pool</param>
  139. /// <param name="binding">The related texture binding</param>
  140. /// <param name="index">The texture/image binding index</param>
  141. /// <param name="stage">The active shader stage</param>
  142. /// <returns>True if the given texture has become blacklisted, indicating that its host texture may have changed.</returns>
  143. private bool UpdateScale(Texture texture, TextureBindingInfo binding, int index, ShaderStage stage)
  144. {
  145. float result = 1f;
  146. bool changed = false;
  147. if ((binding.Flags & TextureUsageFlags.NeedsScaleValue) != 0 && texture != null)
  148. {
  149. switch (stage)
  150. {
  151. case ShaderStage.Fragment:
  152. if ((binding.Flags & TextureUsageFlags.ResScaleUnsupported) != 0)
  153. {
  154. changed |= texture.ScaleMode != TextureScaleMode.Blacklisted;
  155. texture.BlacklistScale();
  156. break;
  157. }
  158. float scale = texture.ScaleFactor;
  159. if (scale != 1)
  160. {
  161. Texture activeTarget = _channel.TextureManager.GetAnyRenderTarget();
  162. if (activeTarget != null && activeTarget.Info.Width / (float)texture.Info.Width == activeTarget.Info.Height / (float)texture.Info.Height)
  163. {
  164. // If the texture's size is a multiple of the sampler size, enable interpolation using gl_FragCoord. (helps "invent" new integer values between scaled pixels)
  165. result = -scale;
  166. break;
  167. }
  168. }
  169. result = scale;
  170. break;
  171. case ShaderStage.Compute:
  172. if ((binding.Flags & TextureUsageFlags.ResScaleUnsupported) != 0)
  173. {
  174. changed |= texture.ScaleMode != TextureScaleMode.Blacklisted;
  175. texture.BlacklistScale();
  176. }
  177. result = texture.ScaleFactor;
  178. break;
  179. }
  180. }
  181. if (result != _scales[index])
  182. {
  183. _scaleChanged = true;
  184. _scales[index] = result;
  185. }
  186. return changed;
  187. }
  188. /// <summary>
  189. /// Uploads texture and image scales to the backend when they are used.
  190. /// </summary>
  191. /// <param name="stage">Current shader stage</param>
  192. /// <param name="stageIndex">Shader stage index</param>
  193. private void CommitRenderScale(ShaderStage stage, int stageIndex)
  194. {
  195. if (_scaleChanged)
  196. {
  197. _context.Renderer.Pipeline.UpdateRenderScale(stage, _scales, _textureBindings[stageIndex]?.Length ?? 0, _imageBindings[stageIndex]?.Length ?? 0);
  198. _scaleChanged = false;
  199. }
  200. }
  201. /// <summary>
  202. /// Ensures that the bindings are visible to the host GPU.
  203. /// Note: this actually performs the binding using the host graphics API.
  204. /// </summary>
  205. public void CommitBindings()
  206. {
  207. ulong texturePoolAddress = _texturePoolAddress;
  208. TexturePool texturePool = texturePoolAddress != 0
  209. ? _texturePoolCache.FindOrCreate(_channel, texturePoolAddress, _texturePoolMaximumId)
  210. : null;
  211. if (_isCompute)
  212. {
  213. CommitTextureBindings(texturePool, ShaderStage.Compute, 0);
  214. CommitImageBindings (texturePool, ShaderStage.Compute, 0);
  215. CommitRenderScale(ShaderStage.Compute, 0);
  216. }
  217. else
  218. {
  219. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  220. {
  221. int stageIndex = (int)stage - 1;
  222. CommitTextureBindings(texturePool, stage, stageIndex);
  223. CommitImageBindings (texturePool, stage, stageIndex);
  224. CommitRenderScale(stage, stageIndex);
  225. }
  226. }
  227. _rebind = false;
  228. }
  229. /// <summary>
  230. /// Ensures that the texture bindings are visible to the host GPU.
  231. /// Note: this actually performs the binding using the host graphics API.
  232. /// </summary>
  233. /// <param name="pool">The current texture pool</param>
  234. /// <param name="stage">The shader stage using the textures to be bound</param>
  235. /// <param name="stageIndex">The stage number of the specified shader stage</param>
  236. private void CommitTextureBindings(TexturePool pool, ShaderStage stage, int stageIndex)
  237. {
  238. if (_textureBindings[stageIndex] == null || _textureBindings[stageIndex].Length == 0)
  239. {
  240. return;
  241. }
  242. var samplerPool = _samplerPool;
  243. if (pool == null)
  244. {
  245. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses textures, but texture pool was not set.");
  246. return;
  247. }
  248. if (samplerPool == null)
  249. {
  250. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses textures, but sampler pool was not set.");
  251. return;
  252. }
  253. for (int index = 0; index < _textureBindings[stageIndex].Length; index++)
  254. {
  255. TextureBindingInfo bindingInfo = _textureBindings[stageIndex][index];
  256. int textureBufferIndex;
  257. int samplerBufferIndex;
  258. if (bindingInfo.CbufSlot < 0)
  259. {
  260. textureBufferIndex = _textureBufferIndex;
  261. samplerBufferIndex = textureBufferIndex;
  262. }
  263. else
  264. {
  265. textureBufferIndex = bindingInfo.CbufSlot & SlotMask;
  266. samplerBufferIndex = ((bindingInfo.CbufSlot >> SlotHigh) != 0) ? (bindingInfo.CbufSlot >> SlotHigh) - 1 : textureBufferIndex;
  267. }
  268. int packedId = ReadPackedId(stageIndex, bindingInfo.Handle, textureBufferIndex, samplerBufferIndex);
  269. int textureId = UnpackTextureId(packedId);
  270. int samplerId;
  271. if (_samplerIndex == SamplerIndex.ViaHeaderIndex)
  272. {
  273. samplerId = textureId;
  274. }
  275. else
  276. {
  277. samplerId = UnpackSamplerId(packedId);
  278. }
  279. Texture texture = pool.Get(textureId);
  280. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  281. if (_textureState[stageIndex][index].Texture != hostTexture || _rebind)
  282. {
  283. if (UpdateScale(texture, bindingInfo, index, stage))
  284. {
  285. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  286. }
  287. _textureState[stageIndex][index].Texture = hostTexture;
  288. _context.Renderer.Pipeline.SetTexture(bindingInfo.Binding, hostTexture);
  289. }
  290. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  291. {
  292. // Ensure that the buffer texture is using the correct buffer as storage.
  293. // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
  294. // to ensure we're not using a old buffer that was already deleted.
  295. _channel.BufferManager.SetBufferTextureStorage(hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, bindingInfo.Format, false);
  296. }
  297. Sampler sampler = samplerPool.Get(samplerId);
  298. ISampler hostSampler = sampler?.HostSampler;
  299. if (_textureState[stageIndex][index].Sampler != hostSampler || _rebind)
  300. {
  301. _textureState[stageIndex][index].Sampler = hostSampler;
  302. _context.Renderer.Pipeline.SetSampler(bindingInfo.Binding, hostSampler);
  303. }
  304. }
  305. }
  306. /// <summary>
  307. /// Ensures that the image bindings are visible to the host GPU.
  308. /// Note: this actually performs the binding using the host graphics API.
  309. /// </summary>
  310. /// <param name="pool">The current texture pool</param>
  311. /// <param name="stage">The shader stage using the textures to be bound</param>
  312. /// <param name="stageIndex">The stage number of the specified shader stage</param>
  313. private void CommitImageBindings(TexturePool pool, ShaderStage stage, int stageIndex)
  314. {
  315. if (_imageBindings[stageIndex] == null)
  316. {
  317. return;
  318. }
  319. if (pool == null && _imageBindings[stageIndex].Length != 0)
  320. {
  321. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses images, but texture pool was not set.");
  322. return;
  323. }
  324. // Scales for images appear after the texture ones.
  325. int baseScaleIndex = _textureBindings[stageIndex]?.Length ?? 0;
  326. for (int index = 0; index < _imageBindings[stageIndex].Length; index++)
  327. {
  328. TextureBindingInfo bindingInfo = _imageBindings[stageIndex][index];
  329. int textureBufferIndex;
  330. int samplerBufferIndex;
  331. if (bindingInfo.CbufSlot < 0)
  332. {
  333. textureBufferIndex = _textureBufferIndex;
  334. samplerBufferIndex = textureBufferIndex;
  335. }
  336. else
  337. {
  338. textureBufferIndex = bindingInfo.CbufSlot & SlotMask;
  339. samplerBufferIndex = ((bindingInfo.CbufSlot >> SlotHigh) != 0) ? (bindingInfo.CbufSlot >> SlotHigh) - 1 : textureBufferIndex;
  340. }
  341. int packedId = ReadPackedId(stageIndex, bindingInfo.Handle, textureBufferIndex, samplerBufferIndex);
  342. int textureId = UnpackTextureId(packedId);
  343. Texture texture = pool.Get(textureId);
  344. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  345. bool isStore = bindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore);
  346. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  347. {
  348. // Ensure that the buffer texture is using the correct buffer as storage.
  349. // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
  350. // to ensure we're not using a old buffer that was already deleted.
  351. Format format = bindingInfo.Format;
  352. if (format == 0 && texture != null)
  353. {
  354. format = texture.Format;
  355. }
  356. _channel.BufferManager.SetBufferTextureStorage(hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, format, true);
  357. }
  358. else if (isStore)
  359. {
  360. texture?.SignalModified();
  361. }
  362. if (_imageState[stageIndex][index].Texture != hostTexture || _rebind)
  363. {
  364. if (UpdateScale(texture, bindingInfo, baseScaleIndex + index, stage))
  365. {
  366. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  367. }
  368. _imageState[stageIndex][index].Texture = hostTexture;
  369. Format format = bindingInfo.Format;
  370. if (format == 0 && texture != null)
  371. {
  372. format = texture.Format;
  373. }
  374. _context.Renderer.Pipeline.SetImage(bindingInfo.Binding, hostTexture, format);
  375. }
  376. }
  377. }
  378. /// <summary>
  379. /// Gets the texture descriptor for a given texture handle.
  380. /// </summary>
  381. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  382. /// <param name="bufferIndex">Index of the constant buffer with texture handles</param>
  383. /// <param name="maximumId">Maximum ID of the texture pool</param>
  384. /// <param name="stageIndex">The stage number where the texture is bound</param>
  385. /// <param name="handle">The texture handle</param>
  386. /// <param name="cbufSlot">The texture handle's constant buffer slot</param>
  387. /// <returns>The texture descriptor for the specified texture</returns>
  388. public TextureDescriptor GetTextureDescriptor(
  389. ulong poolGpuVa,
  390. int bufferIndex,
  391. int maximumId,
  392. int stageIndex,
  393. int handle,
  394. int cbufSlot)
  395. {
  396. int textureBufferIndex = cbufSlot < 0 ? bufferIndex : cbufSlot & SlotMask;
  397. int packedId = ReadPackedId(stageIndex, handle, textureBufferIndex, textureBufferIndex);
  398. int textureId = UnpackTextureId(packedId);
  399. ulong poolAddress = _channel.MemoryManager.Translate(poolGpuVa);
  400. TexturePool texturePool = _texturePoolCache.FindOrCreate(_channel, poolAddress, maximumId);
  401. return texturePool.GetDescriptor(textureId);
  402. }
  403. /// <summary>
  404. /// Reads a packed texture and sampler ID (basically, the real texture handle)
  405. /// from the texture constant buffer.
  406. /// </summary>
  407. /// <param name="stageIndex">The number of the shader stage where the texture is bound</param>
  408. /// <param name="wordOffset">A word offset of the handle on the buffer (the "fake" shader handle)</param>
  409. /// <param name="textureBufferIndex">Index of the constant buffer holding the texture handles</param>
  410. /// <param name="samplerBufferIndex">Index of the constant buffer holding the sampler handles</param>
  411. /// <returns>The packed texture and sampler ID (the real texture handle)</returns>
  412. private int ReadPackedId(int stageIndex, int wordOffset, int textureBufferIndex, int samplerBufferIndex)
  413. {
  414. ulong textureBufferAddress = _isCompute
  415. ? _channel.BufferManager.GetComputeUniformBufferAddress(textureBufferIndex)
  416. : _channel.BufferManager.GetGraphicsUniformBufferAddress(stageIndex, textureBufferIndex);
  417. int handle = _channel.MemoryManager.Physical.Read<int>(textureBufferAddress + (ulong)(wordOffset & HandleMask) * 4);
  418. // The "wordOffset" (which is really the immediate value used on texture instructions on the shader)
  419. // is a 13-bit value. However, in order to also support separate samplers and textures (which uses
  420. // bindless textures on the shader), we extend it with another value on the higher 16 bits with
  421. // another offset for the sampler.
  422. // The shader translator has code to detect separate texture and sampler uses with a bindless texture,
  423. // turn that into a regular texture access and produce those special handles with values on the higher 16 bits.
  424. if (wordOffset >> HandleHigh != 0)
  425. {
  426. ulong samplerBufferAddress = _isCompute
  427. ? _channel.BufferManager.GetComputeUniformBufferAddress(samplerBufferIndex)
  428. : _channel.BufferManager.GetGraphicsUniformBufferAddress(stageIndex, samplerBufferIndex);
  429. handle |= _channel.MemoryManager.Physical.Read<int>(samplerBufferAddress + (ulong)((wordOffset >> HandleHigh) - 1) * 4);
  430. }
  431. return handle;
  432. }
  433. /// <summary>
  434. /// Unpacks the texture ID from the real texture handle.
  435. /// </summary>
  436. /// <param name="packedId">The real texture handle</param>
  437. /// <returns>The texture ID</returns>
  438. private static int UnpackTextureId(int packedId)
  439. {
  440. return (packedId >> 0) & 0xfffff;
  441. }
  442. /// <summary>
  443. /// Unpacks the sampler ID from the real texture handle.
  444. /// </summary>
  445. /// <param name="packedId">The real texture handle</param>
  446. /// <returns>The sampler ID</returns>
  447. private static int UnpackSamplerId(int packedId)
  448. {
  449. return (packedId >> 20) & 0xfff;
  450. }
  451. /// <summary>
  452. /// Force all bound textures and images to be rebound the next time CommitBindings is called.
  453. /// </summary>
  454. public void Rebind()
  455. {
  456. _rebind = true;
  457. }
  458. /// <summary>
  459. /// Disposes all textures and samplers in the cache.
  460. /// </summary>
  461. public void Dispose()
  462. {
  463. _samplerPool?.Dispose();
  464. }
  465. }
  466. }