TextureBindingsManager.cs 38 KB

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