TextureBindingsManager.cs 24 KB

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