TextureBindingsManager.cs 24 KB

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