TextureManager.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.Engine.Types;
  3. using Ryujinx.Graphics.Gpu.Shader;
  4. using System;
  5. namespace Ryujinx.Graphics.Gpu.Image
  6. {
  7. /// <summary>
  8. /// Texture manager.
  9. /// </summary>
  10. class TextureManager : IDisposable
  11. {
  12. private readonly GpuContext _context;
  13. private readonly GpuChannel _channel;
  14. private readonly TextureBindingsManager _cpBindingsManager;
  15. private readonly TextureBindingsManager _gpBindingsManager;
  16. private readonly TexturePoolCache _texturePoolCache;
  17. private readonly SamplerPoolCache _samplerPoolCache;
  18. private readonly Texture[] _rtColors;
  19. private readonly ITexture[] _rtHostColors;
  20. private Texture _rtDepthStencil;
  21. private ITexture _rtHostDs;
  22. public int ClipRegionWidth { get; private set; }
  23. public int ClipRegionHeight { get; private set; }
  24. /// <summary>
  25. /// The scaling factor applied to all currently bound render targets.
  26. /// </summary>
  27. public float RenderTargetScale { get; private set; } = 1f;
  28. /// <summary>
  29. /// Creates a new instance of the texture manager.
  30. /// </summary>
  31. /// <param name="context">GPU context that the texture manager belongs to</param>
  32. /// <param name="channel">GPU channel that the texture manager belongs to</param>
  33. public TextureManager(GpuContext context, GpuChannel channel)
  34. {
  35. _context = context;
  36. _channel = channel;
  37. TexturePoolCache texturePoolCache = new(context);
  38. SamplerPoolCache samplerPoolCache = new(context);
  39. float[] scales = new float[64];
  40. new Span<float>(scales).Fill(1f);
  41. _cpBindingsManager = new TextureBindingsManager(context, channel, texturePoolCache, samplerPoolCache, scales, isCompute: true);
  42. _gpBindingsManager = new TextureBindingsManager(context, channel, texturePoolCache, samplerPoolCache, scales, isCompute: false);
  43. _texturePoolCache = texturePoolCache;
  44. _samplerPoolCache = samplerPoolCache;
  45. _rtColors = new Texture[Constants.TotalRenderTargets];
  46. _rtHostColors = new ITexture[Constants.TotalRenderTargets];
  47. }
  48. /// <summary>
  49. /// Sets the texture and image bindings for the compute pipeline.
  50. /// </summary>
  51. /// <param name="bindings">Bindings for the active shader</param>
  52. public void SetComputeBindings(CachedShaderBindings bindings)
  53. {
  54. _cpBindingsManager.SetBindings(bindings);
  55. }
  56. /// <summary>
  57. /// Sets the texture and image bindings for the graphics pipeline.
  58. /// </summary>
  59. /// <param name="bindings">Bindings for the active shader</param>
  60. public void SetGraphicsBindings(CachedShaderBindings bindings)
  61. {
  62. _gpBindingsManager.SetBindings(bindings);
  63. }
  64. /// <summary>
  65. /// Sets the texture constant buffer index on the compute pipeline.
  66. /// </summary>
  67. /// <param name="index">The texture constant buffer index</param>
  68. public void SetComputeTextureBufferIndex(int index)
  69. {
  70. _cpBindingsManager.SetTextureBufferIndex(index);
  71. }
  72. /// <summary>
  73. /// Sets the texture constant buffer index on the graphics pipeline.
  74. /// </summary>
  75. /// <param name="index">The texture constant buffer index</param>
  76. public void SetGraphicsTextureBufferIndex(int index)
  77. {
  78. _gpBindingsManager.SetTextureBufferIndex(index);
  79. }
  80. /// <summary>
  81. /// Sets the current sampler pool on the compute pipeline.
  82. /// </summary>
  83. /// <param name="gpuVa">The start GPU virtual address of the sampler pool</param>
  84. /// <param name="maximumId">The maximum ID of the sampler pool</param>
  85. /// <param name="samplerIndex">The indexing type of the sampler pool</param>
  86. public void SetComputeSamplerPool(ulong gpuVa, int maximumId, SamplerIndex samplerIndex)
  87. {
  88. _cpBindingsManager.SetSamplerPool(gpuVa, maximumId, samplerIndex);
  89. }
  90. /// <summary>
  91. /// Sets the current sampler pool on the graphics pipeline.
  92. /// </summary>
  93. /// <param name="gpuVa">The start GPU virtual address of the sampler pool</param>
  94. /// <param name="maximumId">The maximum ID of the sampler pool</param>
  95. /// <param name="samplerIndex">The indexing type of the sampler pool</param>
  96. public void SetGraphicsSamplerPool(ulong gpuVa, int maximumId, SamplerIndex samplerIndex)
  97. {
  98. _gpBindingsManager.SetSamplerPool(gpuVa, maximumId, samplerIndex);
  99. }
  100. /// <summary>
  101. /// Sets the current texture pool on the compute pipeline.
  102. /// </summary>
  103. /// <param name="gpuVa">The start GPU virtual address of the texture pool</param>
  104. /// <param name="maximumId">The maximum ID of the texture pool</param>
  105. public void SetComputeTexturePool(ulong gpuVa, int maximumId)
  106. {
  107. _cpBindingsManager.SetTexturePool(gpuVa, maximumId);
  108. }
  109. /// <summary>
  110. /// Sets the current texture pool on the graphics pipeline.
  111. /// </summary>
  112. /// <param name="gpuVa">The start GPU virtual address of the texture pool</param>
  113. /// <param name="maximumId">The maximum ID of the texture pool</param>
  114. public void SetGraphicsTexturePool(ulong gpuVa, int maximumId)
  115. {
  116. _gpBindingsManager.SetTexturePool(gpuVa, maximumId);
  117. }
  118. /// <summary>
  119. /// Check if a texture's scale must be updated to match the configured resolution scale.
  120. /// </summary>
  121. /// <param name="texture">The texture to check</param>
  122. /// <returns>True if the scale needs updating, false if the scale is up to date</returns>
  123. private static bool ScaleNeedsUpdated(Texture texture)
  124. {
  125. return texture != null && !(texture.ScaleMode == TextureScaleMode.Blacklisted || texture.ScaleMode == TextureScaleMode.Undesired) && texture.ScaleFactor != GraphicsConfig.ResScale;
  126. }
  127. /// <summary>
  128. /// Sets the render target color buffer.
  129. /// </summary>
  130. /// <param name="index">The index of the color buffer to set (up to 8)</param>
  131. /// <param name="color">The color buffer texture</param>
  132. /// <returns>True if render target scale must be updated.</returns>
  133. public bool SetRenderTargetColor(int index, Texture color)
  134. {
  135. bool hasValue = color != null;
  136. bool changesScale = (hasValue != (_rtColors[index] != null)) || (hasValue && RenderTargetScale != color.ScaleFactor);
  137. if (_rtColors[index] != color)
  138. {
  139. _rtColors[index]?.SignalModifying(false);
  140. if (color != null)
  141. {
  142. color.SynchronizeMemory();
  143. color.SignalModifying(true);
  144. }
  145. _rtColors[index] = color;
  146. }
  147. return changesScale || ScaleNeedsUpdated(color);
  148. }
  149. /// <summary>
  150. /// Sets the render target depth-stencil buffer.
  151. /// </summary>
  152. /// <param name="depthStencil">The depth-stencil buffer texture</param>
  153. /// <returns>True if render target scale must be updated.</returns>
  154. public bool SetRenderTargetDepthStencil(Texture depthStencil)
  155. {
  156. bool hasValue = depthStencil != null;
  157. bool changesScale = (hasValue != (_rtDepthStencil != null)) || (hasValue && RenderTargetScale != depthStencil.ScaleFactor);
  158. if (_rtDepthStencil != depthStencil)
  159. {
  160. _rtDepthStencil?.SignalModifying(false);
  161. if (depthStencil != null)
  162. {
  163. depthStencil.SynchronizeMemory();
  164. depthStencil.SignalModifying(true);
  165. }
  166. _rtDepthStencil = depthStencil;
  167. }
  168. return changesScale || ScaleNeedsUpdated(depthStencil);
  169. }
  170. /// <summary>
  171. /// Sets the host clip region, which should be the intersection of all render target texture sizes.
  172. /// </summary>
  173. /// <param name="width">Width of the clip region, defined as the minimum width across all bound textures</param>
  174. /// <param name="height">Height of the clip region, defined as the minimum height across all bound textures</param>
  175. public void SetClipRegion(int width, int height)
  176. {
  177. ClipRegionWidth = width;
  178. ClipRegionHeight = height;
  179. }
  180. /// <summary>
  181. /// Gets the first available bound colour target, or the depth stencil target if not present.
  182. /// </summary>
  183. /// <returns>The first bound colour target, otherwise the depth stencil target</returns>
  184. public Texture GetAnyRenderTarget()
  185. {
  186. return _rtColors[0] ?? _rtDepthStencil;
  187. }
  188. /// <summary>
  189. /// Updates the Render Target scale, given the currently bound render targets.
  190. /// This will update scale to match the configured scale, scale textures that are eligible but not scaled,
  191. /// and propagate blacklisted status from one texture to the ones bound with it.
  192. /// </summary>
  193. /// <param name="singleUse">If this is not -1, it indicates that only the given indexed target will be used.</param>
  194. public void UpdateRenderTargetScale(int singleUse)
  195. {
  196. // Make sure all scales for render targets are at the highest they should be. Blacklisted targets should propagate their scale to the other targets.
  197. bool mismatch = false;
  198. bool blacklisted = false;
  199. bool hasUpscaled = false;
  200. bool hasUndesired = false;
  201. float targetScale = GraphicsConfig.ResScale;
  202. void ConsiderTarget(Texture target)
  203. {
  204. if (target == null)
  205. {
  206. return;
  207. }
  208. float scale = target.ScaleFactor;
  209. switch (target.ScaleMode)
  210. {
  211. case TextureScaleMode.Blacklisted:
  212. mismatch |= scale != 1f;
  213. blacklisted = true;
  214. break;
  215. case TextureScaleMode.Eligible:
  216. mismatch = true; // We must make a decision.
  217. break;
  218. case TextureScaleMode.Undesired:
  219. hasUndesired = true;
  220. mismatch |= scale != 1f || hasUpscaled; // If another target is upscaled, scale this one up too.
  221. break;
  222. case TextureScaleMode.Scaled:
  223. hasUpscaled = true;
  224. mismatch |= hasUndesired || scale != targetScale; // If the target scale has changed, reset the scale for all targets.
  225. break;
  226. }
  227. }
  228. if (singleUse != -1)
  229. {
  230. // If only one target is in use (by a clear, for example) the others do not need to be checked for mismatching scale.
  231. ConsiderTarget(_rtColors[singleUse]);
  232. }
  233. else
  234. {
  235. foreach (Texture color in _rtColors)
  236. {
  237. ConsiderTarget(color);
  238. }
  239. }
  240. ConsiderTarget(_rtDepthStencil);
  241. mismatch |= blacklisted && hasUpscaled;
  242. if (blacklisted || (hasUndesired && !hasUpscaled))
  243. {
  244. targetScale = 1f;
  245. }
  246. if (mismatch)
  247. {
  248. if (blacklisted)
  249. {
  250. // Propagate the blacklisted state to the other textures.
  251. foreach (Texture color in _rtColors)
  252. {
  253. color?.BlacklistScale();
  254. }
  255. _rtDepthStencil?.BlacklistScale();
  256. }
  257. else
  258. {
  259. // Set the scale of the other textures.
  260. foreach (Texture color in _rtColors)
  261. {
  262. color?.SetScale(targetScale);
  263. }
  264. _rtDepthStencil?.SetScale(targetScale);
  265. }
  266. }
  267. RenderTargetScale = targetScale;
  268. }
  269. /// <summary>
  270. /// Gets a texture and a sampler from their respective pools from a texture ID and a sampler ID.
  271. /// </summary>
  272. /// <param name="textureId">ID of the texture</param>
  273. /// <param name="samplerId">ID of the sampler</param>
  274. public (Texture, Sampler) GetGraphicsTextureAndSampler(int textureId, int samplerId)
  275. {
  276. return _gpBindingsManager.GetTextureAndSampler(textureId, samplerId);
  277. }
  278. /// <summary>
  279. /// Commits bindings on the compute pipeline.
  280. /// </summary>
  281. /// <param name="specState">Specialization state for the bound shader</param>
  282. /// <returns>True if all bound textures match the current shader specialization state, false otherwise</returns>
  283. public bool CommitComputeBindings(ShaderSpecializationState specState)
  284. {
  285. // Every time we switch between graphics and compute work,
  286. // we must rebind everything.
  287. // Since compute work happens less often, we always do that
  288. // before and after the compute dispatch.
  289. _texturePoolCache.Tick();
  290. _samplerPoolCache.Tick();
  291. _cpBindingsManager.Rebind();
  292. bool result = _cpBindingsManager.CommitBindings(specState);
  293. _gpBindingsManager.Rebind();
  294. return result;
  295. }
  296. /// <summary>
  297. /// Commits bindings on the graphics pipeline.
  298. /// </summary>
  299. /// <param name="specState">Specialization state for the bound shader</param>
  300. /// <returns>True if all bound textures match the current shader specialization state, false otherwise</returns>
  301. public bool CommitGraphicsBindings(ShaderSpecializationState specState)
  302. {
  303. _texturePoolCache.Tick();
  304. _samplerPoolCache.Tick();
  305. bool result = _gpBindingsManager.CommitBindings(specState);
  306. UpdateRenderTargets();
  307. return result;
  308. }
  309. /// <summary>
  310. /// Returns a texture pool from the cache, with the given address and maximum id.
  311. /// </summary>
  312. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  313. /// <param name="maximumId">Maximum ID of the texture pool</param>
  314. /// <returns>The texture pool</returns>
  315. public TexturePool GetTexturePool(ulong poolGpuVa, int maximumId)
  316. {
  317. ulong poolAddress = _channel.MemoryManager.Translate(poolGpuVa);
  318. TexturePool texturePool = _texturePoolCache.FindOrCreate(_channel, poolAddress, maximumId);
  319. return texturePool;
  320. }
  321. /// <summary>
  322. /// Gets a texture descriptor used on the compute pipeline.
  323. /// </summary>
  324. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  325. /// <param name="bufferIndex">Index of the constant buffer with texture handles</param>
  326. /// <param name="maximumId">Maximum ID of the texture pool</param>
  327. /// <param name="handle">Shader "fake" handle of the texture</param>
  328. /// <param name="cbufSlot">Shader constant buffer slot of the texture</param>
  329. /// <returns>The texture descriptor</returns>
  330. public TextureDescriptor GetComputeTextureDescriptor(ulong poolGpuVa, int bufferIndex, int maximumId, int handle, int cbufSlot)
  331. {
  332. return _cpBindingsManager.GetTextureDescriptor(poolGpuVa, bufferIndex, maximumId, 0, handle, cbufSlot);
  333. }
  334. /// <summary>
  335. /// Gets a texture descriptor used on the graphics pipeline.
  336. /// </summary>
  337. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  338. /// <param name="bufferIndex">Index of the constant buffer with texture handles</param>
  339. /// <param name="maximumId">Maximum ID of the texture pool</param>
  340. /// <param name="stageIndex">Index of the shader stage where the texture is bound</param>
  341. /// <param name="handle">Shader "fake" handle of the texture</param>
  342. /// <param name="cbufSlot">Shader constant buffer slot of the texture</param>
  343. /// <returns>The texture descriptor</returns>
  344. public TextureDescriptor GetGraphicsTextureDescriptor(
  345. ulong poolGpuVa,
  346. int bufferIndex,
  347. int maximumId,
  348. int stageIndex,
  349. int handle,
  350. int cbufSlot)
  351. {
  352. return _gpBindingsManager.GetTextureDescriptor(poolGpuVa, bufferIndex, maximumId, stageIndex, handle, cbufSlot);
  353. }
  354. /// <summary>
  355. /// Update host framebuffer attachments based on currently bound render target buffers.
  356. /// </summary>
  357. public void UpdateRenderTargets()
  358. {
  359. bool anyChanged = false;
  360. if (_rtHostDs != _rtDepthStencil?.HostTexture)
  361. {
  362. _rtHostDs = _rtDepthStencil?.HostTexture;
  363. anyChanged = true;
  364. }
  365. for (int index = 0; index < _rtColors.Length; index++)
  366. {
  367. ITexture hostTexture = _rtColors[index]?.HostTexture;
  368. if (_rtHostColors[index] != hostTexture)
  369. {
  370. _rtHostColors[index] = hostTexture;
  371. anyChanged = true;
  372. }
  373. }
  374. if (anyChanged)
  375. {
  376. _context.Renderer.Pipeline.SetRenderTargets(_rtHostColors, _rtHostDs);
  377. }
  378. }
  379. /// <summary>
  380. /// Update host framebuffer attachments based on currently bound render target buffers.
  381. /// </summary>
  382. /// <remarks>
  383. /// All color attachments will be unbound.
  384. /// </remarks>
  385. public void UpdateRenderTargetDepthStencil()
  386. {
  387. new Span<ITexture>(_rtHostColors).Clear();
  388. _rtHostDs = _rtDepthStencil?.HostTexture;
  389. _context.Renderer.Pipeline.SetRenderTargets(_rtHostColors, _rtHostDs);
  390. }
  391. /// <summary>
  392. /// Forces the texture and sampler pools to be re-loaded from the cache on next use.
  393. /// </summary>
  394. public void ReloadPools()
  395. {
  396. _cpBindingsManager.ReloadPools();
  397. _gpBindingsManager.ReloadPools();
  398. }
  399. /// <summary>
  400. /// Forces all textures, samplers, images and render targets to be rebound the next time
  401. /// CommitGraphicsBindings is called.
  402. /// </summary>
  403. public void Rebind()
  404. {
  405. _gpBindingsManager.Rebind();
  406. for (int index = 0; index < _rtHostColors.Length; index++)
  407. {
  408. _rtHostColors[index] = null;
  409. }
  410. _rtHostDs = null;
  411. }
  412. /// <summary>
  413. /// Disposes the texture manager.
  414. /// It's an error to use the texture manager after disposal.
  415. /// </summary>
  416. public void Dispose()
  417. {
  418. // Textures are owned by the texture cache, so we shouldn't dispose the texture pool cache.
  419. _samplerPoolCache.Dispose();
  420. for (int i = 0; i < _rtColors.Length; i++)
  421. {
  422. _rtColors[i]?.DecrementReferenceCount();
  423. _rtColors[i] = null;
  424. }
  425. _rtDepthStencil?.DecrementReferenceCount();
  426. _rtDepthStencil = null;
  427. }
  428. }
  429. }