TextureBindingsManager.cs 21 KB

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