TextureManager.cs 22 KB

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