TextureBindingsManager.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Gpu.Engine.Types;
  4. using Ryujinx.Graphics.Gpu.Memory;
  5. using Ryujinx.Graphics.Gpu.Shader;
  6. using Ryujinx.Graphics.Shader;
  7. using System;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. namespace Ryujinx.Graphics.Gpu.Image
  11. {
  12. /// <summary>
  13. /// Texture bindings manager.
  14. /// </summary>
  15. class TextureBindingsManager : IDisposable
  16. {
  17. private const int InitialTextureStateSize = 32;
  18. private const int InitialImageStateSize = 8;
  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. public int TextureHandle;
  34. public int SamplerHandle;
  35. public int InvalidatedSequence;
  36. public Texture CachedTexture;
  37. public Sampler CachedSampler;
  38. }
  39. private TextureStatePerStage[] _textureState;
  40. private TextureStatePerStage[] _imageState;
  41. private int[] _textureBindingsCount;
  42. private int[] _imageBindingsCount;
  43. private int _texturePoolSequence;
  44. private int _samplerPoolSequence;
  45. private int _textureBufferIndex;
  46. private readonly float[] _scales;
  47. private bool _scaleChanged;
  48. private int _lastFragmentTotal;
  49. /// <summary>
  50. /// Constructs a new instance of the texture bindings manager.
  51. /// </summary>
  52. /// <param name="context">The GPU context that the texture bindings manager belongs to</param>
  53. /// <param name="channel">The GPU channel that the texture bindings manager belongs to</param>
  54. /// <param name="poolCache">Texture pools cache used to get texture pools from</param>
  55. /// <param name="scales">Array where the scales for the currently bound textures are stored</param>
  56. /// <param name="isCompute">True if the bindings manager is used for the compute engine</param>
  57. public TextureBindingsManager(GpuContext context, GpuChannel channel, TexturePoolCache poolCache, float[] scales, bool isCompute)
  58. {
  59. _context = context;
  60. _channel = channel;
  61. _texturePoolCache = poolCache;
  62. _scales = scales;
  63. _isCompute = isCompute;
  64. int stages = isCompute ? 1 : Constants.ShaderStages;
  65. _textureBindings = new TextureBindingInfo[stages][];
  66. _imageBindings = new TextureBindingInfo[stages][];
  67. _textureState = new TextureStatePerStage[InitialTextureStateSize];
  68. _imageState = new TextureStatePerStage[InitialImageStateSize];
  69. _textureBindingsCount = new int[stages];
  70. _imageBindingsCount = new int[stages];
  71. for (int stage = 0; stage < stages; stage++)
  72. {
  73. _textureBindings[stage] = new TextureBindingInfo[InitialTextureStateSize];
  74. _imageBindings[stage] = new TextureBindingInfo[InitialImageStateSize];
  75. }
  76. }
  77. /// <summary>
  78. /// Rents the texture bindings array for a given stage, so that they can be modified.
  79. /// </summary>
  80. /// <param name="stage">Shader stage number, or 0 for compute shaders</param>
  81. /// <param name="count">The number of bindings needed</param>
  82. /// <returns>The texture bindings array</returns>
  83. public TextureBindingInfo[] RentTextureBindings(int stage, int count)
  84. {
  85. if (count > _textureBindings[stage].Length)
  86. {
  87. Array.Resize(ref _textureBindings[stage], count);
  88. }
  89. _textureBindingsCount[stage] = count;
  90. return _textureBindings[stage];
  91. }
  92. /// <summary>
  93. /// Rents the image bindings array for a given stage, so that they can be modified.
  94. /// </summary>
  95. /// <param name="stage">Shader stage number, or 0 for compute shaders</param>
  96. /// <param name="count">The number of bindings needed</param>
  97. /// <returns>The image bindings array</returns>
  98. public TextureBindingInfo[] RentImageBindings(int stage, int count)
  99. {
  100. if (count > _imageBindings[stage].Length)
  101. {
  102. Array.Resize(ref _imageBindings[stage], count);
  103. }
  104. _imageBindingsCount[stage] = count;
  105. return _imageBindings[stage];
  106. }
  107. /// <summary>
  108. /// Sets the max binding indexes for textures and images.
  109. /// </summary>
  110. /// <param name="maxTextureBinding">The maximum texture binding</param>
  111. /// <param name="maxImageBinding">The maximum image binding</param>
  112. public void SetMaxBindings(int maxTextureBinding, int maxImageBinding)
  113. {
  114. if (maxTextureBinding >= _textureState.Length)
  115. {
  116. Array.Resize(ref _textureState, maxTextureBinding + 1);
  117. }
  118. if (maxImageBinding >= _imageState.Length)
  119. {
  120. Array.Resize(ref _imageState, maxImageBinding + 1);
  121. }
  122. }
  123. /// <summary>
  124. /// Sets the textures constant buffer index.
  125. /// The constant buffer specified holds the texture handles.
  126. /// </summary>
  127. /// <param name="index">Constant buffer index</param>
  128. public void SetTextureBufferIndex(int index)
  129. {
  130. _textureBufferIndex = index;
  131. }
  132. /// <summary>
  133. /// Sets the current texture sampler pool to be used.
  134. /// </summary>
  135. /// <param name="gpuVa">Start GPU virtual address of the pool</param>
  136. /// <param name="maximumId">Maximum ID of the pool (total count minus one)</param>
  137. /// <param name="samplerIndex">Type of the sampler pool indexing used for bound samplers</param>
  138. public void SetSamplerPool(ulong gpuVa, int maximumId, SamplerIndex samplerIndex)
  139. {
  140. if (gpuVa != 0)
  141. {
  142. ulong address = _channel.MemoryManager.Translate(gpuVa);
  143. if (_samplerPool != null && _samplerPool.Address == address && _samplerPool.MaximumId >= maximumId)
  144. {
  145. return;
  146. }
  147. _samplerPool?.Dispose();
  148. _samplerPool = new SamplerPool(_context, _channel.MemoryManager.Physical, address, maximumId);
  149. }
  150. else
  151. {
  152. _samplerPool?.Dispose();
  153. _samplerPool = null;
  154. }
  155. _samplerIndex = samplerIndex;
  156. }
  157. /// <summary>
  158. /// Sets the current texture pool to be used.
  159. /// </summary>
  160. /// <param name="gpuVa">Start GPU virtual address of the pool</param>
  161. /// <param name="maximumId">Maximum ID of the pool (total count minus one)</param>
  162. public void SetTexturePool(ulong gpuVa, int maximumId)
  163. {
  164. if (gpuVa != 0)
  165. {
  166. ulong address = _channel.MemoryManager.Translate(gpuVa);
  167. _texturePoolAddress = address;
  168. _texturePoolMaximumId = maximumId;
  169. }
  170. else
  171. {
  172. _texturePoolAddress = 0;
  173. _texturePoolMaximumId = 0;
  174. }
  175. }
  176. /// <summary>
  177. /// Gets a texture and a sampler from their respective pools from a texture ID and a sampler ID.
  178. /// </summary>
  179. /// <param name="textureId">ID of the texture</param>
  180. /// <param name="samplerId">ID of the sampler</param>
  181. public (Texture, Sampler) GetTextureAndSampler(int textureId, int samplerId)
  182. {
  183. ulong texturePoolAddress = _texturePoolAddress;
  184. TexturePool texturePool = texturePoolAddress != 0
  185. ? _texturePoolCache.FindOrCreate(_channel, texturePoolAddress, _texturePoolMaximumId)
  186. : null;
  187. return (texturePool.Get(textureId), _samplerPool.Get(samplerId));
  188. }
  189. /// <summary>
  190. /// Updates the texture scale for a given texture or image.
  191. /// </summary>
  192. /// <param name="texture">Start GPU virtual address of the pool</param>
  193. /// <param name="binding">The related texture binding</param>
  194. /// <param name="index">The texture/image binding index</param>
  195. /// <param name="stage">The active shader stage</param>
  196. /// <returns>True if the given texture has become blacklisted, indicating that its host texture may have changed.</returns>
  197. private bool UpdateScale(Texture texture, TextureBindingInfo binding, int index, ShaderStage stage)
  198. {
  199. float result = 1f;
  200. bool changed = false;
  201. if ((binding.Flags & TextureUsageFlags.NeedsScaleValue) != 0 && texture != null)
  202. {
  203. if ((binding.Flags & TextureUsageFlags.ResScaleUnsupported) != 0)
  204. {
  205. changed = texture.ScaleMode != TextureScaleMode.Blacklisted;
  206. texture.BlacklistScale();
  207. }
  208. else
  209. {
  210. switch (stage)
  211. {
  212. case ShaderStage.Fragment:
  213. float scale = texture.ScaleFactor;
  214. if (scale != 1)
  215. {
  216. Texture activeTarget = _channel.TextureManager.GetAnyRenderTarget();
  217. if (activeTarget != null && (activeTarget.Info.Width / (float)texture.Info.Width) == (activeTarget.Info.Height / (float)texture.Info.Height))
  218. {
  219. // 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)
  220. result = -scale;
  221. break;
  222. }
  223. }
  224. result = scale;
  225. break;
  226. case ShaderStage.Vertex:
  227. int fragmentIndex = (int)ShaderStage.Fragment - 1;
  228. index += _textureBindingsCount[fragmentIndex] + _imageBindingsCount[fragmentIndex];
  229. result = texture.ScaleFactor;
  230. break;
  231. case ShaderStage.Compute:
  232. result = texture.ScaleFactor;
  233. break;
  234. }
  235. }
  236. }
  237. if (result != _scales[index])
  238. {
  239. _scaleChanged = true;
  240. _scales[index] = result;
  241. }
  242. return changed;
  243. }
  244. /// <summary>
  245. /// Uploads texture and image scales to the backend when they are used.
  246. /// </summary>
  247. private void CommitRenderScale()
  248. {
  249. // Stage 0 total: Compute or Vertex.
  250. int total = _textureBindingsCount[0] + _imageBindingsCount[0];
  251. int fragmentIndex = (int)ShaderStage.Fragment - 1;
  252. int fragmentTotal = _isCompute ? 0 : (_textureBindingsCount[fragmentIndex] + _imageBindingsCount[fragmentIndex]);
  253. if (total != 0 && fragmentTotal != _lastFragmentTotal)
  254. {
  255. // Must update scales in the support buffer if:
  256. // - Vertex stage has bindings.
  257. // - Fragment stage binding count has been updated since last render scale update.
  258. _scaleChanged = true;
  259. }
  260. if (_scaleChanged)
  261. {
  262. if (!_isCompute)
  263. {
  264. total += fragmentTotal; // Add the fragment bindings to the total.
  265. }
  266. _lastFragmentTotal = fragmentTotal;
  267. _context.Renderer.Pipeline.UpdateRenderScale(_scales, total, fragmentTotal);
  268. _scaleChanged = false;
  269. }
  270. }
  271. /// <summary>
  272. /// Ensures that the bindings are visible to the host GPU.
  273. /// Note: this actually performs the binding using the host graphics API.
  274. /// </summary>
  275. /// <param name="specState">Specialization state for the bound shader</param>
  276. /// <returns>True if all bound textures match the current shader specialiation state, false otherwise</returns>
  277. public bool CommitBindings(ShaderSpecializationState specState)
  278. {
  279. ulong texturePoolAddress = _texturePoolAddress;
  280. TexturePool texturePool = texturePoolAddress != 0
  281. ? _texturePoolCache.FindOrCreate(_channel, texturePoolAddress, _texturePoolMaximumId)
  282. : null;
  283. // Check if the texture pool has been modified since bindings were last committed.
  284. // If it wasn't, then it's possible to avoid looking up textures again when the handle remains the same.
  285. bool poolModified = false;
  286. if (texturePool != null)
  287. {
  288. int texturePoolSequence = texturePool.CheckModified();
  289. if (_texturePoolSequence != texturePoolSequence)
  290. {
  291. poolModified = true;
  292. _texturePoolSequence = texturePoolSequence;
  293. }
  294. }
  295. if (_samplerPool != null)
  296. {
  297. int samplerPoolSequence = _samplerPool.CheckModified();
  298. if (_samplerPoolSequence != samplerPoolSequence)
  299. {
  300. poolModified = true;
  301. _samplerPoolSequence = samplerPoolSequence;
  302. }
  303. }
  304. bool specStateMatches = true;
  305. if (_isCompute)
  306. {
  307. specStateMatches &= CommitTextureBindings(texturePool, ShaderStage.Compute, 0, poolModified, specState);
  308. specStateMatches &= CommitImageBindings(texturePool, ShaderStage.Compute, 0, poolModified, specState);
  309. }
  310. else
  311. {
  312. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  313. {
  314. int stageIndex = (int)stage - 1;
  315. specStateMatches &= CommitTextureBindings(texturePool, stage, stageIndex, poolModified, specState);
  316. specStateMatches &= CommitImageBindings(texturePool, stage, stageIndex, poolModified, specState);
  317. }
  318. }
  319. CommitRenderScale();
  320. return specStateMatches;
  321. }
  322. /// <summary>
  323. /// Fetch the constant buffers used for a texture to cache.
  324. /// </summary>
  325. /// <param name="stageIndex">Stage index of the constant buffer</param>
  326. /// <param name="cachedTextureBufferIndex">The currently cached texture buffer index</param>
  327. /// <param name="cachedSamplerBufferIndex">The currently cached sampler buffer index</param>
  328. /// <param name="cachedTextureBuffer">The currently cached texture buffer data</param>
  329. /// <param name="cachedSamplerBuffer">The currently cached sampler buffer data</param>
  330. /// <param name="textureBufferIndex">The new texture buffer index</param>
  331. /// <param name="samplerBufferIndex">The new sampler buffer index</param>
  332. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  333. private void UpdateCachedBuffer(
  334. int stageIndex,
  335. ref int cachedTextureBufferIndex,
  336. ref int cachedSamplerBufferIndex,
  337. ref ReadOnlySpan<int> cachedTextureBuffer,
  338. ref ReadOnlySpan<int> cachedSamplerBuffer,
  339. int textureBufferIndex,
  340. int samplerBufferIndex)
  341. {
  342. if (textureBufferIndex != cachedTextureBufferIndex)
  343. {
  344. ref BufferBounds bounds = ref _channel.BufferManager.GetUniformBufferBounds(_isCompute, stageIndex, textureBufferIndex);
  345. cachedTextureBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(bounds.Address, (int)bounds.Size));
  346. cachedTextureBufferIndex = textureBufferIndex;
  347. if (samplerBufferIndex == textureBufferIndex)
  348. {
  349. cachedSamplerBuffer = cachedTextureBuffer;
  350. cachedSamplerBufferIndex = samplerBufferIndex;
  351. }
  352. }
  353. if (samplerBufferIndex != cachedSamplerBufferIndex)
  354. {
  355. ref BufferBounds bounds = ref _channel.BufferManager.GetUniformBufferBounds(_isCompute, stageIndex, samplerBufferIndex);
  356. cachedSamplerBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(bounds.Address, (int)bounds.Size));
  357. cachedSamplerBufferIndex = samplerBufferIndex;
  358. }
  359. }
  360. /// <summary>
  361. /// Ensures that the texture bindings are visible to the host GPU.
  362. /// Note: this actually performs the binding using the host graphics API.
  363. /// </summary>
  364. /// <param name="pool">The current texture pool</param>
  365. /// <param name="stage">The shader stage using the textures to be bound</param>
  366. /// <param name="stageIndex">The stage number of the specified shader stage</param
  367. /// <param name="poolModified">True if either the texture or sampler pool was modified, false otherwise</param>
  368. /// <param name="specState">Specialization state for the bound shader</param>
  369. /// <returns>True if all bound textures match the current shader specialiation state, false otherwise</returns>
  370. private bool CommitTextureBindings(TexturePool pool, ShaderStage stage, int stageIndex, bool poolModified, ShaderSpecializationState specState)
  371. {
  372. int textureCount = _textureBindingsCount[stageIndex];
  373. if (textureCount == 0)
  374. {
  375. return true;
  376. }
  377. var samplerPool = _samplerPool;
  378. if (pool == null)
  379. {
  380. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses textures, but texture pool was not set.");
  381. return true;
  382. }
  383. bool specStateMatches = true;
  384. int cachedTextureBufferIndex = -1;
  385. int cachedSamplerBufferIndex = -1;
  386. ReadOnlySpan<int> cachedTextureBuffer = Span<int>.Empty;
  387. ReadOnlySpan<int> cachedSamplerBuffer = Span<int>.Empty;
  388. for (int index = 0; index < textureCount; index++)
  389. {
  390. TextureBindingInfo bindingInfo = _textureBindings[stageIndex][index];
  391. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(bindingInfo.CbufSlot, _textureBufferIndex);
  392. UpdateCachedBuffer(stageIndex, ref cachedTextureBufferIndex, ref cachedSamplerBufferIndex, ref cachedTextureBuffer, ref cachedSamplerBuffer, textureBufferIndex, samplerBufferIndex);
  393. int packedId = TextureHandle.ReadPackedId(bindingInfo.Handle, cachedTextureBuffer, cachedSamplerBuffer);
  394. int textureId = TextureHandle.UnpackTextureId(packedId);
  395. int samplerId;
  396. if (_samplerIndex == SamplerIndex.ViaHeaderIndex)
  397. {
  398. samplerId = textureId;
  399. }
  400. else
  401. {
  402. samplerId = TextureHandle.UnpackSamplerId(packedId);
  403. }
  404. ref TextureStatePerStage state = ref _textureState[bindingInfo.Binding];
  405. if (!poolModified &&
  406. state.TextureHandle == textureId &&
  407. state.SamplerHandle == samplerId &&
  408. state.CachedTexture != null &&
  409. state.CachedTexture.InvalidatedSequence == state.InvalidatedSequence &&
  410. state.CachedSampler?.IsDisposed != true)
  411. {
  412. // The texture is already bound.
  413. state.CachedTexture.SynchronizeMemory();
  414. continue;
  415. }
  416. state.TextureHandle = textureId;
  417. state.SamplerHandle = samplerId;
  418. ref readonly TextureDescriptor descriptor = ref pool.GetForBinding(textureId, out Texture texture);
  419. specStateMatches &= specState.MatchesTexture(stage, index, descriptor);
  420. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  421. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  422. {
  423. // Ensure that the buffer texture is using the correct buffer as storage.
  424. // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
  425. // to ensure we're not using a old buffer that was already deleted.
  426. _channel.BufferManager.SetBufferTextureStorage(hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, bindingInfo.Format, false);
  427. }
  428. else
  429. {
  430. if (state.Texture != hostTexture)
  431. {
  432. if (UpdateScale(texture, bindingInfo, index, stage))
  433. {
  434. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  435. }
  436. state.Texture = hostTexture;
  437. _context.Renderer.Pipeline.SetTexture(bindingInfo.Binding, hostTexture);
  438. }
  439. Sampler sampler = samplerPool?.Get(samplerId);
  440. state.CachedSampler = sampler;
  441. ISampler hostSampler = sampler?.GetHostSampler(texture);
  442. if (state.Sampler != hostSampler)
  443. {
  444. state.Sampler = hostSampler;
  445. _context.Renderer.Pipeline.SetSampler(bindingInfo.Binding, hostSampler);
  446. }
  447. state.CachedTexture = texture;
  448. state.InvalidatedSequence = texture?.InvalidatedSequence ?? 0;
  449. }
  450. }
  451. return specStateMatches;
  452. }
  453. /// <summary>
  454. /// Ensures that the image bindings are visible to the host GPU.
  455. /// Note: this actually performs the binding using the host graphics API.
  456. /// </summary>
  457. /// <param name="pool">The current texture pool</param>
  458. /// <param name="stage">The shader stage using the textures to be bound</param>
  459. /// <param name="stageIndex">The stage number of the specified shader stage</param>
  460. /// <param name="poolModified">True if either the texture or sampler pool was modified, false otherwise</param>
  461. /// <param name="specState">Specialization state for the bound shader</param>
  462. /// <returns>True if all bound images match the current shader specialiation state, false otherwise</returns>
  463. private bool CommitImageBindings(TexturePool pool, ShaderStage stage, int stageIndex, bool poolModified, ShaderSpecializationState specState)
  464. {
  465. int imageCount = _imageBindingsCount[stageIndex];
  466. if (imageCount == 0)
  467. {
  468. return true;
  469. }
  470. if (pool == null)
  471. {
  472. Logger.Error?.Print(LogClass.Gpu, $"Shader stage \"{stage}\" uses images, but texture pool was not set.");
  473. return true;
  474. }
  475. // Scales for images appear after the texture ones.
  476. int baseScaleIndex = _textureBindingsCount[stageIndex];
  477. int cachedTextureBufferIndex = -1;
  478. int cachedSamplerBufferIndex = -1;
  479. ReadOnlySpan<int> cachedTextureBuffer = Span<int>.Empty;
  480. ReadOnlySpan<int> cachedSamplerBuffer = Span<int>.Empty;
  481. bool specStateMatches = true;
  482. for (int index = 0; index < imageCount; index++)
  483. {
  484. TextureBindingInfo bindingInfo = _imageBindings[stageIndex][index];
  485. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(bindingInfo.CbufSlot, _textureBufferIndex);
  486. UpdateCachedBuffer(stageIndex, ref cachedTextureBufferIndex, ref cachedSamplerBufferIndex, ref cachedTextureBuffer, ref cachedSamplerBuffer, textureBufferIndex, samplerBufferIndex);
  487. int packedId = TextureHandle.ReadPackedId(bindingInfo.Handle, cachedTextureBuffer, cachedSamplerBuffer);
  488. int textureId = TextureHandle.UnpackTextureId(packedId);
  489. ref TextureStatePerStage state = ref _imageState[bindingInfo.Binding];
  490. bool isStore = bindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore);
  491. if (!poolModified &&
  492. state.TextureHandle == textureId &&
  493. state.CachedTexture != null &&
  494. state.CachedTexture.InvalidatedSequence == state.InvalidatedSequence)
  495. {
  496. // The texture is already bound.
  497. state.CachedTexture.SynchronizeMemory();
  498. if (isStore)
  499. {
  500. state.CachedTexture?.SignalModified();
  501. }
  502. continue;
  503. }
  504. state.TextureHandle = textureId;
  505. ref readonly TextureDescriptor descriptor = ref pool.GetForBinding(textureId, out Texture texture);
  506. specStateMatches &= specState.MatchesImage(stage, index, descriptor);
  507. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  508. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  509. {
  510. // Ensure that the buffer texture is using the correct buffer as storage.
  511. // Buffers are frequently re-created to accomodate larger data, so we need to re-bind
  512. // to ensure we're not using a old buffer that was already deleted.
  513. Format format = bindingInfo.Format;
  514. if (format == 0 && texture != null)
  515. {
  516. format = texture.Format;
  517. }
  518. _channel.BufferManager.SetBufferTextureStorage(hostTexture, texture.Range.GetSubRange(0).Address, texture.Size, bindingInfo, format, true);
  519. }
  520. else
  521. {
  522. if (isStore)
  523. {
  524. texture?.SignalModified();
  525. }
  526. if (state.Texture != hostTexture)
  527. {
  528. if (UpdateScale(texture, bindingInfo, baseScaleIndex + index, stage))
  529. {
  530. hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  531. }
  532. state.Texture = hostTexture;
  533. Format format = bindingInfo.Format;
  534. if (format == 0 && texture != null)
  535. {
  536. format = texture.Format;
  537. }
  538. _context.Renderer.Pipeline.SetImage(bindingInfo.Binding, hostTexture, format);
  539. }
  540. state.CachedTexture = texture;
  541. state.InvalidatedSequence = texture?.InvalidatedSequence ?? 0;
  542. }
  543. }
  544. return specStateMatches;
  545. }
  546. /// <summary>
  547. /// Gets the texture descriptor for a given texture handle.
  548. /// </summary>
  549. /// <param name="poolGpuVa">GPU virtual address of the texture pool</param>
  550. /// <param name="bufferIndex">Index of the constant buffer with texture handles</param>
  551. /// <param name="maximumId">Maximum ID of the texture pool</param>
  552. /// <param name="stageIndex">The stage number where the texture is bound</param>
  553. /// <param name="handle">The texture handle</param>
  554. /// <param name="cbufSlot">The texture handle's constant buffer slot</param>
  555. /// <returns>The texture descriptor for the specified texture</returns>
  556. public TextureDescriptor GetTextureDescriptor(
  557. ulong poolGpuVa,
  558. int bufferIndex,
  559. int maximumId,
  560. int stageIndex,
  561. int handle,
  562. int cbufSlot)
  563. {
  564. (int textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(cbufSlot, bufferIndex);
  565. int packedId = ReadPackedId(stageIndex, handle, textureBufferIndex, samplerBufferIndex);
  566. int textureId = TextureHandle.UnpackTextureId(packedId);
  567. ulong poolAddress = _channel.MemoryManager.Translate(poolGpuVa);
  568. TexturePool texturePool = _texturePoolCache.FindOrCreate(_channel, poolAddress, maximumId);
  569. return texturePool.GetDescriptor(textureId);
  570. }
  571. /// <summary>
  572. /// Reads a packed texture and sampler ID (basically, the real texture handle)
  573. /// from the texture constant buffer.
  574. /// </summary>
  575. /// <param name="stageIndex">The number of the shader stage where the texture is bound</param>
  576. /// <param name="wordOffset">A word offset of the handle on the buffer (the "fake" shader handle)</param>
  577. /// <param name="textureBufferIndex">Index of the constant buffer holding the texture handles</param>
  578. /// <param name="samplerBufferIndex">Index of the constant buffer holding the sampler handles</param>
  579. /// <returns>The packed texture and sampler ID (the real texture handle)</returns>
  580. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  581. private int ReadPackedId(int stageIndex, int wordOffset, int textureBufferIndex, int samplerBufferIndex)
  582. {
  583. (int textureWordOffset, int samplerWordOffset, TextureHandleType handleType) = TextureHandle.UnpackOffsets(wordOffset);
  584. ulong textureBufferAddress = _isCompute
  585. ? _channel.BufferManager.GetComputeUniformBufferAddress(textureBufferIndex)
  586. : _channel.BufferManager.GetGraphicsUniformBufferAddress(stageIndex, textureBufferIndex);
  587. int handle = _channel.MemoryManager.Physical.Read<int>(textureBufferAddress + (uint)textureWordOffset * 4);
  588. // The "wordOffset" (which is really the immediate value used on texture instructions on the shader)
  589. // is a 13-bit value. However, in order to also support separate samplers and textures (which uses
  590. // bindless textures on the shader), we extend it with another value on the higher 16 bits with
  591. // another offset for the sampler.
  592. // The shader translator has code to detect separate texture and sampler uses with a bindless texture,
  593. // turn that into a regular texture access and produce those special handles with values on the higher 16 bits.
  594. if (handleType != TextureHandleType.CombinedSampler)
  595. {
  596. ulong samplerBufferAddress = _isCompute
  597. ? _channel.BufferManager.GetComputeUniformBufferAddress(samplerBufferIndex)
  598. : _channel.BufferManager.GetGraphicsUniformBufferAddress(stageIndex, samplerBufferIndex);
  599. int samplerHandle = _channel.MemoryManager.Physical.Read<int>(samplerBufferAddress + (uint)samplerWordOffset * 4);
  600. if (handleType == TextureHandleType.SeparateSamplerId)
  601. {
  602. samplerHandle <<= 20;
  603. }
  604. handle |= samplerHandle;
  605. }
  606. return handle;
  607. }
  608. /// <summary>
  609. /// Force all bound textures and images to be rebound the next time CommitBindings is called.
  610. /// </summary>
  611. public void Rebind()
  612. {
  613. Array.Clear(_textureState);
  614. Array.Clear(_imageState);
  615. }
  616. /// <summary>
  617. /// Disposes all textures and samplers in the cache.
  618. /// </summary>
  619. public void Dispose()
  620. {
  621. _samplerPool?.Dispose();
  622. }
  623. }
  624. }