TextureBindingsManager.cs 24 KB

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