TextureBindingsArrayCache.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Gpu.Engine.Types;
  3. using Ryujinx.Graphics.Gpu.Memory;
  4. using Ryujinx.Graphics.Shader;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Runtime.InteropServices;
  9. namespace Ryujinx.Graphics.Gpu.Image
  10. {
  11. /// <summary>
  12. /// Texture bindings array cache.
  13. /// </summary>
  14. class TextureBindingsArrayCache
  15. {
  16. /// <summary>
  17. /// Minimum timestamp delta until texture array can be removed from the cache.
  18. /// </summary>
  19. private const int MinDeltaForRemoval = 20000;
  20. private readonly GpuContext _context;
  21. private readonly GpuChannel _channel;
  22. /// <summary>
  23. /// Array cache entry key.
  24. /// </summary>
  25. private readonly struct CacheEntryFromPoolKey : IEquatable<CacheEntryFromPoolKey>
  26. {
  27. /// <summary>
  28. /// Whether the entry is for an image.
  29. /// </summary>
  30. public readonly bool IsImage;
  31. /// <summary>
  32. /// Whether the entry is for a sampler.
  33. /// </summary>
  34. public readonly bool IsSampler;
  35. /// <summary>
  36. /// Texture or image target type.
  37. /// </summary>
  38. public readonly Target Target;
  39. /// <summary>
  40. /// Number of entries of the array.
  41. /// </summary>
  42. public readonly int ArrayLength;
  43. private readonly TexturePool _texturePool;
  44. private readonly SamplerPool _samplerPool;
  45. /// <summary>
  46. /// Creates a new array cache entry.
  47. /// </summary>
  48. /// <param name="isImage">Whether the entry is for an image</param>
  49. /// <param name="bindingInfo">Binding information for the array</param>
  50. /// <param name="texturePool">Texture pool where the array textures are located</param>
  51. /// <param name="samplerPool">Sampler pool where the array samplers are located</param>
  52. public CacheEntryFromPoolKey(bool isImage, TextureBindingInfo bindingInfo, TexturePool texturePool, SamplerPool samplerPool)
  53. {
  54. IsImage = isImage;
  55. IsSampler = bindingInfo.IsSamplerOnly;
  56. Target = bindingInfo.Target;
  57. ArrayLength = bindingInfo.ArrayLength;
  58. _texturePool = texturePool;
  59. _samplerPool = samplerPool;
  60. }
  61. /// <summary>
  62. /// Checks if the pool matches the cached pool.
  63. /// </summary>
  64. /// <param name="texturePool">Texture or sampler pool instance</param>
  65. /// <returns>True if the pool matches, false otherwise</returns>
  66. public bool MatchesPool<T>(IPool<T> pool)
  67. {
  68. return _texturePool == pool || _samplerPool == pool;
  69. }
  70. /// <summary>
  71. /// Checks if the texture and sampler pools matches the cached pools.
  72. /// </summary>
  73. /// <param name="texturePool">Texture pool instance</param>
  74. /// <param name="samplerPool">Sampler pool instance</param>
  75. /// <returns>True if the pools match, false otherwise</returns>
  76. private bool MatchesPools(TexturePool texturePool, SamplerPool samplerPool)
  77. {
  78. return _texturePool == texturePool && _samplerPool == samplerPool;
  79. }
  80. public bool Equals(CacheEntryFromPoolKey other)
  81. {
  82. return IsImage == other.IsImage &&
  83. IsSampler == other.IsSampler &&
  84. Target == other.Target &&
  85. ArrayLength == other.ArrayLength &&
  86. MatchesPools(other._texturePool, other._samplerPool);
  87. }
  88. public override bool Equals(object obj)
  89. {
  90. return obj is CacheEntryFromBufferKey other && Equals(other);
  91. }
  92. public override int GetHashCode()
  93. {
  94. return HashCode.Combine(_texturePool, _samplerPool, IsSampler);
  95. }
  96. }
  97. /// <summary>
  98. /// Array cache entry key.
  99. /// </summary>
  100. private readonly struct CacheEntryFromBufferKey : IEquatable<CacheEntryFromBufferKey>
  101. {
  102. /// <summary>
  103. /// Whether the entry is for an image.
  104. /// </summary>
  105. public readonly bool IsImage;
  106. /// <summary>
  107. /// Texture or image target type.
  108. /// </summary>
  109. public readonly Target Target;
  110. /// <summary>
  111. /// Word offset of the first handle on the constant buffer.
  112. /// </summary>
  113. public readonly int HandleIndex;
  114. /// <summary>
  115. /// Number of entries of the array.
  116. /// </summary>
  117. public readonly int ArrayLength;
  118. private readonly TexturePool _texturePool;
  119. private readonly SamplerPool _samplerPool;
  120. private readonly BufferBounds _textureBufferBounds;
  121. /// <summary>
  122. /// Creates a new array cache entry.
  123. /// </summary>
  124. /// <param name="isImage">Whether the entry is for an image</param>
  125. /// <param name="bindingInfo">Binding information for the array</param>
  126. /// <param name="texturePool">Texture pool where the array textures are located</param>
  127. /// <param name="samplerPool">Sampler pool where the array samplers are located</param>
  128. /// <param name="textureBufferBounds">Constant buffer bounds with the texture handles</param>
  129. public CacheEntryFromBufferKey(
  130. bool isImage,
  131. TextureBindingInfo bindingInfo,
  132. TexturePool texturePool,
  133. SamplerPool samplerPool,
  134. ref BufferBounds textureBufferBounds)
  135. {
  136. IsImage = isImage;
  137. Target = bindingInfo.Target;
  138. HandleIndex = bindingInfo.Handle;
  139. ArrayLength = bindingInfo.ArrayLength;
  140. _texturePool = texturePool;
  141. _samplerPool = samplerPool;
  142. _textureBufferBounds = textureBufferBounds;
  143. }
  144. /// <summary>
  145. /// Checks if the texture and sampler pools matches the cached pools.
  146. /// </summary>
  147. /// <param name="texturePool">Texture pool instance</param>
  148. /// <param name="samplerPool">Sampler pool instance</param>
  149. /// <returns>True if the pools match, false otherwise</returns>
  150. private bool MatchesPools(TexturePool texturePool, SamplerPool samplerPool)
  151. {
  152. return _texturePool == texturePool && _samplerPool == samplerPool;
  153. }
  154. /// <summary>
  155. /// Checks if the cached constant buffer address and size matches.
  156. /// </summary>
  157. /// <param name="textureBufferBounds">New buffer address and size</param>
  158. /// <returns>True if the address and size matches, false otherwise</returns>
  159. private bool MatchesBufferBounds(BufferBounds textureBufferBounds)
  160. {
  161. return _textureBufferBounds.Equals(textureBufferBounds);
  162. }
  163. public bool Equals(CacheEntryFromBufferKey other)
  164. {
  165. return IsImage == other.IsImage &&
  166. Target == other.Target &&
  167. HandleIndex == other.HandleIndex &&
  168. ArrayLength == other.ArrayLength &&
  169. MatchesPools(other._texturePool, other._samplerPool) &&
  170. MatchesBufferBounds(other._textureBufferBounds);
  171. }
  172. public override bool Equals(object obj)
  173. {
  174. return obj is CacheEntryFromBufferKey other && Equals(other);
  175. }
  176. public override int GetHashCode()
  177. {
  178. return _textureBufferBounds.Range.GetHashCode();
  179. }
  180. }
  181. /// <summary>
  182. /// Array cache entry from pool.
  183. /// </summary>
  184. private class CacheEntry
  185. {
  186. /// <summary>
  187. /// All cached textures, along with their invalidated sequence number as value.
  188. /// </summary>
  189. public readonly Dictionary<Texture, int> Textures;
  190. /// <summary>
  191. /// Backend texture array if the entry is for a texture, otherwise null.
  192. /// </summary>
  193. public readonly ITextureArray TextureArray;
  194. /// <summary>
  195. /// Backend image array if the entry is for an image, otherwise null.
  196. /// </summary>
  197. public readonly IImageArray ImageArray;
  198. /// <summary>
  199. /// Texture pool where the array textures are located.
  200. /// </summary>
  201. protected readonly TexturePool TexturePool;
  202. /// <summary>
  203. /// Sampler pool where the array samplers are located.
  204. /// </summary>
  205. protected readonly SamplerPool SamplerPool;
  206. private int _texturePoolSequence;
  207. private int _samplerPoolSequence;
  208. /// <summary>
  209. /// Creates a new array cache entry.
  210. /// </summary>
  211. /// <param name="texturePool">Texture pool where the array textures are located</param>
  212. /// <param name="samplerPool">Sampler pool where the array samplers are located</param>
  213. private CacheEntry(TexturePool texturePool, SamplerPool samplerPool)
  214. {
  215. Textures = new Dictionary<Texture, int>();
  216. TexturePool = texturePool;
  217. SamplerPool = samplerPool;
  218. }
  219. /// <summary>
  220. /// Creates a new array cache entry.
  221. /// </summary>
  222. /// <param name="array">Backend texture array</param>
  223. /// <param name="texturePool">Texture pool where the array textures are located</param>
  224. /// <param name="samplerPool">Sampler pool where the array samplers are located</param>
  225. public CacheEntry(ITextureArray array, TexturePool texturePool, SamplerPool samplerPool) : this(texturePool, samplerPool)
  226. {
  227. TextureArray = array;
  228. }
  229. /// <summary>
  230. /// Creates a new array cache entry.
  231. /// </summary>
  232. /// <param name="array">Backend image array</param>
  233. /// <param name="texturePool">Texture pool where the array textures are located</param>
  234. /// <param name="samplerPool">Sampler pool where the array samplers are located</param>
  235. public CacheEntry(IImageArray array, TexturePool texturePool, SamplerPool samplerPool) : this(texturePool, samplerPool)
  236. {
  237. ImageArray = array;
  238. }
  239. /// <summary>
  240. /// Synchronizes memory for all textures in the array.
  241. /// </summary>
  242. /// <param name="isStore">Indicates if the texture may be modified by the access</param>
  243. /// <param name="blacklistScale">Indicates if the texture should be blacklisted for scaling</param>
  244. public void SynchronizeMemory(bool isStore, bool blacklistScale)
  245. {
  246. foreach (Texture texture in Textures.Keys)
  247. {
  248. texture.SynchronizeMemory();
  249. if (isStore)
  250. {
  251. texture.SignalModified();
  252. }
  253. if (blacklistScale && texture.ScaleMode != TextureScaleMode.Blacklisted)
  254. {
  255. // Scaling textures used on arrays is currently not supported.
  256. texture.BlacklistScale();
  257. }
  258. }
  259. }
  260. /// <summary>
  261. /// Clears all cached texture instances.
  262. /// </summary>
  263. public virtual void Reset()
  264. {
  265. Textures.Clear();
  266. }
  267. /// <summary>
  268. /// Checks if any texture has been deleted since the last call to this method.
  269. /// </summary>
  270. /// <returns>True if one or more textures have been deleted, false otherwise</returns>
  271. public bool ValidateTextures()
  272. {
  273. foreach ((Texture texture, int invalidatedSequence) in Textures)
  274. {
  275. if (texture.InvalidatedSequence != invalidatedSequence)
  276. {
  277. return false;
  278. }
  279. }
  280. return true;
  281. }
  282. /// <summary>
  283. /// Checks if the cached texture or sampler pool has been modified since the last call to this method.
  284. /// </summary>
  285. /// <returns>True if any used entries of the pool might have been modified, false otherwise</returns>
  286. public bool TexturePoolModified()
  287. {
  288. return TexturePool.WasModified(ref _texturePoolSequence);
  289. }
  290. /// <summary>
  291. /// Checks if the cached texture or sampler pool has been modified since the last call to this method.
  292. /// </summary>
  293. /// <returns>True if any used entries of the pool might have been modified, false otherwise</returns>
  294. public bool SamplerPoolModified()
  295. {
  296. return SamplerPool.WasModified(ref _samplerPoolSequence);
  297. }
  298. }
  299. /// <summary>
  300. /// Array cache entry from constant buffer.
  301. /// </summary>
  302. private class CacheEntryFromBuffer : CacheEntry
  303. {
  304. /// <summary>
  305. /// Key for this entry on the cache.
  306. /// </summary>
  307. public readonly CacheEntryFromBufferKey Key;
  308. /// <summary>
  309. /// Linked list node used on the texture bindings array cache.
  310. /// </summary>
  311. public LinkedListNode<CacheEntryFromBuffer> CacheNode;
  312. /// <summary>
  313. /// Timestamp set on the last use of the array by the cache.
  314. /// </summary>
  315. public int CacheTimestamp;
  316. /// <summary>
  317. /// All pool texture IDs along with their textures.
  318. /// </summary>
  319. public readonly Dictionary<int, (Texture, TextureDescriptor)> TextureIds;
  320. /// <summary>
  321. /// All pool sampler IDs along with their samplers.
  322. /// </summary>
  323. public readonly Dictionary<int, (Sampler, SamplerDescriptor)> SamplerIds;
  324. private int[] _cachedTextureBuffer;
  325. private int[] _cachedSamplerBuffer;
  326. private int _lastSequenceNumber;
  327. /// <summary>
  328. /// Creates a new array cache entry.
  329. /// </summary>
  330. /// <param name="key">Key for this entry on the cache</param>
  331. /// <param name="array">Backend texture array</param>
  332. /// <param name="texturePool">Texture pool where the array textures are located</param>
  333. /// <param name="samplerPool">Sampler pool where the array samplers are located</param>
  334. public CacheEntryFromBuffer(ref CacheEntryFromBufferKey key, ITextureArray array, TexturePool texturePool, SamplerPool samplerPool) : base(array, texturePool, samplerPool)
  335. {
  336. Key = key;
  337. _lastSequenceNumber = -1;
  338. TextureIds = new Dictionary<int, (Texture, TextureDescriptor)>();
  339. SamplerIds = new Dictionary<int, (Sampler, SamplerDescriptor)>();
  340. }
  341. /// <summary>
  342. /// Creates a new array cache entry.
  343. /// </summary>
  344. /// <param name="key">Key for this entry on the cache</param>
  345. /// <param name="array">Backend image array</param>
  346. /// <param name="texturePool">Texture pool where the array textures are located</param>
  347. /// <param name="samplerPool">Sampler pool where the array samplers are located</param>
  348. public CacheEntryFromBuffer(ref CacheEntryFromBufferKey key, IImageArray array, TexturePool texturePool, SamplerPool samplerPool) : base(array, texturePool, samplerPool)
  349. {
  350. Key = key;
  351. _lastSequenceNumber = -1;
  352. TextureIds = new Dictionary<int, (Texture, TextureDescriptor)>();
  353. SamplerIds = new Dictionary<int, (Sampler, SamplerDescriptor)>();
  354. }
  355. /// <inheritdoc/>
  356. public override void Reset()
  357. {
  358. base.Reset();
  359. TextureIds.Clear();
  360. SamplerIds.Clear();
  361. }
  362. /// <summary>
  363. /// Updates the cached constant buffer data.
  364. /// </summary>
  365. /// <param name="cachedTextureBuffer">Constant buffer data with the texture handles (and sampler handles, if they are combined)</param>
  366. /// <param name="cachedSamplerBuffer">Constant buffer data with the sampler handles</param>
  367. /// <param name="separateSamplerBuffer">Whether <paramref name="cachedTextureBuffer"/> and <paramref name="cachedSamplerBuffer"/> comes from different buffers</param>
  368. public void UpdateData(ReadOnlySpan<int> cachedTextureBuffer, ReadOnlySpan<int> cachedSamplerBuffer, bool separateSamplerBuffer)
  369. {
  370. _cachedTextureBuffer = cachedTextureBuffer.ToArray();
  371. _cachedSamplerBuffer = separateSamplerBuffer ? cachedSamplerBuffer.ToArray() : _cachedTextureBuffer;
  372. }
  373. /// <summary>
  374. /// Checks if the sequence number matches the one used on the last call to this method.
  375. /// </summary>
  376. /// <param name="currentSequenceNumber">Current sequence number</param>
  377. /// <returns>True if the sequence numbers match, false otherwise</returns>
  378. public bool MatchesSequenceNumber(int currentSequenceNumber)
  379. {
  380. if (_lastSequenceNumber == currentSequenceNumber)
  381. {
  382. return true;
  383. }
  384. _lastSequenceNumber = currentSequenceNumber;
  385. return false;
  386. }
  387. /// <summary>
  388. /// Checks if the buffer data matches the cached data.
  389. /// </summary>
  390. /// <param name="cachedTextureBuffer">New texture buffer data</param>
  391. /// <param name="cachedSamplerBuffer">New sampler buffer data</param>
  392. /// <param name="separateSamplerBuffer">Whether <paramref name="cachedTextureBuffer"/> and <paramref name="cachedSamplerBuffer"/> comes from different buffers</param>
  393. /// <param name="samplerWordOffset">Word offset of the sampler constant buffer handle that is used</param>
  394. /// <returns>True if the data matches, false otherwise</returns>
  395. public bool MatchesBufferData(
  396. ReadOnlySpan<int> cachedTextureBuffer,
  397. ReadOnlySpan<int> cachedSamplerBuffer,
  398. bool separateSamplerBuffer,
  399. int samplerWordOffset)
  400. {
  401. if (_cachedTextureBuffer != null && cachedTextureBuffer.Length > _cachedTextureBuffer.Length)
  402. {
  403. cachedTextureBuffer = cachedTextureBuffer[.._cachedTextureBuffer.Length];
  404. }
  405. if (!_cachedTextureBuffer.AsSpan().SequenceEqual(cachedTextureBuffer))
  406. {
  407. return false;
  408. }
  409. if (separateSamplerBuffer)
  410. {
  411. if (_cachedSamplerBuffer == null ||
  412. _cachedSamplerBuffer.Length <= samplerWordOffset ||
  413. cachedSamplerBuffer.Length <= samplerWordOffset)
  414. {
  415. return false;
  416. }
  417. int oldValue = _cachedSamplerBuffer[samplerWordOffset];
  418. int newValue = cachedSamplerBuffer[samplerWordOffset];
  419. return oldValue == newValue;
  420. }
  421. return true;
  422. }
  423. /// <summary>
  424. /// Checks if the cached texture or sampler pool has been modified since the last call to this method.
  425. /// </summary>
  426. /// <returns>True if any used entries of the pools might have been modified, false otherwise</returns>
  427. public bool PoolsModified()
  428. {
  429. bool texturePoolModified = TexturePoolModified();
  430. bool samplerPoolModified = SamplerPoolModified();
  431. // If both pools were not modified since the last check, we have nothing else to check.
  432. if (!texturePoolModified && !samplerPoolModified)
  433. {
  434. return false;
  435. }
  436. // If the pools were modified, let's check if any of the entries we care about changed.
  437. // Check if any of our cached textures changed on the pool.
  438. foreach ((int textureId, (Texture texture, TextureDescriptor descriptor)) in TextureIds)
  439. {
  440. if (TexturePool.GetCachedItem(textureId) != texture ||
  441. (texture == null && TexturePool.IsValidId(textureId) && !TexturePool.GetDescriptorRef(textureId).Equals(descriptor)))
  442. {
  443. return true;
  444. }
  445. }
  446. // Check if any of our cached samplers changed on the pool.
  447. foreach ((int samplerId, (Sampler sampler, SamplerDescriptor descriptor)) in SamplerIds)
  448. {
  449. if (SamplerPool.GetCachedItem(samplerId) != sampler ||
  450. (sampler == null && SamplerPool.IsValidId(samplerId) && !SamplerPool.GetDescriptorRef(samplerId).Equals(descriptor)))
  451. {
  452. return true;
  453. }
  454. }
  455. return false;
  456. }
  457. }
  458. private readonly Dictionary<CacheEntryFromBufferKey, CacheEntryFromBuffer> _cacheFromBuffer;
  459. private readonly Dictionary<CacheEntryFromPoolKey, CacheEntry> _cacheFromPool;
  460. private readonly LinkedList<CacheEntryFromBuffer> _lruCache;
  461. private int _currentTimestamp;
  462. /// <summary>
  463. /// Creates a new instance of the texture bindings array cache.
  464. /// </summary>
  465. /// <param name="context">GPU context</param>
  466. /// <param name="channel">GPU channel</param>
  467. public TextureBindingsArrayCache(GpuContext context, GpuChannel channel)
  468. {
  469. _context = context;
  470. _channel = channel;
  471. _cacheFromBuffer = new Dictionary<CacheEntryFromBufferKey, CacheEntryFromBuffer>();
  472. _cacheFromPool = new Dictionary<CacheEntryFromPoolKey, CacheEntry>();
  473. _lruCache = new LinkedList<CacheEntryFromBuffer>();
  474. }
  475. /// <summary>
  476. /// Updates a texture array bindings and textures.
  477. /// </summary>
  478. /// <param name="texturePool">Texture pool</param>
  479. /// <param name="samplerPool">Sampler pool</param>
  480. /// <param name="stage">Shader stage where the array is used</param>
  481. /// <param name="stageIndex">Shader stage index where the array is used</param>
  482. /// <param name="textureBufferIndex">Texture constant buffer index</param>
  483. /// <param name="samplerIndex">Sampler handles source</param>
  484. /// <param name="bindingInfo">Array binding information</param>
  485. public void UpdateTextureArray(
  486. TexturePool texturePool,
  487. SamplerPool samplerPool,
  488. ShaderStage stage,
  489. int stageIndex,
  490. int textureBufferIndex,
  491. SamplerIndex samplerIndex,
  492. TextureBindingInfo bindingInfo)
  493. {
  494. Update(texturePool, samplerPool, stage, stageIndex, textureBufferIndex, isImage: false, samplerIndex, bindingInfo);
  495. }
  496. /// <summary>
  497. /// Updates a image array bindings and textures.
  498. /// </summary>
  499. /// <param name="texturePool">Texture pool</param>
  500. /// <param name="stage">Shader stage where the array is used</param>
  501. /// <param name="stageIndex">Shader stage index where the array is used</param>
  502. /// <param name="textureBufferIndex">Texture constant buffer index</param>
  503. /// <param name="bindingInfo">Array binding information</param>
  504. public void UpdateImageArray(TexturePool texturePool, ShaderStage stage, int stageIndex, int textureBufferIndex, TextureBindingInfo bindingInfo)
  505. {
  506. Update(texturePool, null, stage, stageIndex, textureBufferIndex, isImage: true, SamplerIndex.ViaHeaderIndex, bindingInfo);
  507. }
  508. /// <summary>
  509. /// Updates a texture or image array bindings and textures.
  510. /// </summary>
  511. /// <param name="texturePool">Texture pool</param>
  512. /// <param name="samplerPool">Sampler pool</param>
  513. /// <param name="stage">Shader stage where the array is used</param>
  514. /// <param name="stageIndex">Shader stage index where the array is used</param>
  515. /// <param name="textureBufferIndex">Texture constant buffer index</param>
  516. /// <param name="isImage">Whether the array is a image or texture array</param>
  517. /// <param name="samplerIndex">Sampler handles source</param>
  518. /// <param name="bindingInfo">Array binding information</param>
  519. private void Update(
  520. TexturePool texturePool,
  521. SamplerPool samplerPool,
  522. ShaderStage stage,
  523. int stageIndex,
  524. int textureBufferIndex,
  525. bool isImage,
  526. SamplerIndex samplerIndex,
  527. TextureBindingInfo bindingInfo)
  528. {
  529. if (IsDirectHandleType(bindingInfo.Handle))
  530. {
  531. UpdateFromPool(texturePool, samplerPool, stage, isImage, bindingInfo);
  532. }
  533. else
  534. {
  535. UpdateFromBuffer(texturePool, samplerPool, stage, stageIndex, textureBufferIndex, isImage, samplerIndex, bindingInfo);
  536. }
  537. }
  538. /// <summary>
  539. /// Updates a texture or image array bindings and textures from a texture or sampler pool.
  540. /// </summary>
  541. /// <param name="texturePool">Texture pool</param>
  542. /// <param name="samplerPool">Sampler pool</param>
  543. /// <param name="stage">Shader stage where the array is used</param>
  544. /// <param name="isImage">Whether the array is a image or texture array</param>
  545. /// <param name="bindingInfo">Array binding information</param>
  546. private void UpdateFromPool(TexturePool texturePool, SamplerPool samplerPool, ShaderStage stage, bool isImage, TextureBindingInfo bindingInfo)
  547. {
  548. CacheEntry entry = GetOrAddEntry(texturePool, samplerPool, bindingInfo, isImage, out bool isNewEntry);
  549. bool isSampler = bindingInfo.IsSamplerOnly;
  550. bool poolModified = isSampler ? entry.SamplerPoolModified() : entry.TexturePoolModified();
  551. bool isStore = bindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore);
  552. bool resScaleUnsupported = bindingInfo.Flags.HasFlag(TextureUsageFlags.ResScaleUnsupported);
  553. if (!poolModified && !isNewEntry && entry.ValidateTextures())
  554. {
  555. entry.SynchronizeMemory(isStore, resScaleUnsupported);
  556. if (isImage)
  557. {
  558. _context.Renderer.Pipeline.SetImageArray(stage, bindingInfo.Binding, entry.ImageArray);
  559. }
  560. else
  561. {
  562. _context.Renderer.Pipeline.SetTextureArray(stage, bindingInfo.Binding, entry.TextureArray);
  563. }
  564. return;
  565. }
  566. if (!isNewEntry)
  567. {
  568. entry.Reset();
  569. }
  570. int length = (isSampler ? samplerPool.MaximumId : texturePool.MaximumId) + 1;
  571. length = Math.Min(length, bindingInfo.ArrayLength);
  572. Format[] formats = isImage ? new Format[bindingInfo.ArrayLength] : null;
  573. ISampler[] samplers = isImage ? null : new ISampler[bindingInfo.ArrayLength];
  574. ITexture[] textures = new ITexture[bindingInfo.ArrayLength];
  575. for (int index = 0; index < length; index++)
  576. {
  577. Texture texture = null;
  578. Sampler sampler = null;
  579. if (isSampler)
  580. {
  581. sampler = samplerPool?.Get(index);
  582. }
  583. else
  584. {
  585. ref readonly TextureDescriptor descriptor = ref texturePool.GetForBinding(index, out texture);
  586. if (texture != null)
  587. {
  588. entry.Textures[texture] = texture.InvalidatedSequence;
  589. if (isStore)
  590. {
  591. texture.SignalModified();
  592. }
  593. if (resScaleUnsupported && texture.ScaleMode != TextureScaleMode.Blacklisted)
  594. {
  595. // Scaling textures used on arrays is currently not supported.
  596. texture.BlacklistScale();
  597. }
  598. }
  599. }
  600. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  601. ISampler hostSampler = sampler?.GetHostSampler(texture);
  602. Format format = bindingInfo.Format;
  603. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  604. {
  605. // Ensure that the buffer texture is using the correct buffer as storage.
  606. // Buffers are frequently re-created to accommodate larger data, so we need to re-bind
  607. // to ensure we're not using a old buffer that was already deleted.
  608. if (isImage)
  609. {
  610. if (format == 0 && texture != null)
  611. {
  612. format = texture.Format;
  613. }
  614. _channel.BufferManager.SetBufferTextureStorage(stage, entry.ImageArray, hostTexture, texture.Range, bindingInfo, index, format);
  615. }
  616. else
  617. {
  618. _channel.BufferManager.SetBufferTextureStorage(stage, entry.TextureArray, hostTexture, texture.Range, bindingInfo, index, format);
  619. }
  620. }
  621. else if (isImage)
  622. {
  623. if (format == 0 && texture != null)
  624. {
  625. format = texture.Format;
  626. }
  627. formats[index] = format;
  628. textures[index] = hostTexture;
  629. }
  630. else
  631. {
  632. samplers[index] = hostSampler;
  633. textures[index] = hostTexture;
  634. }
  635. }
  636. if (isImage)
  637. {
  638. entry.ImageArray.SetFormats(0, formats);
  639. entry.ImageArray.SetImages(0, textures);
  640. _context.Renderer.Pipeline.SetImageArray(stage, bindingInfo.Binding, entry.ImageArray);
  641. }
  642. else
  643. {
  644. entry.TextureArray.SetSamplers(0, samplers);
  645. entry.TextureArray.SetTextures(0, textures);
  646. _context.Renderer.Pipeline.SetTextureArray(stage, bindingInfo.Binding, entry.TextureArray);
  647. }
  648. }
  649. /// <summary>
  650. /// Updates a texture or image array bindings and textures from constant buffer handles.
  651. /// </summary>
  652. /// <param name="texturePool">Texture pool</param>
  653. /// <param name="samplerPool">Sampler pool</param>
  654. /// <param name="stage">Shader stage where the array is used</param>
  655. /// <param name="stageIndex">Shader stage index where the array is used</param>
  656. /// <param name="textureBufferIndex">Texture constant buffer index</param>
  657. /// <param name="isImage">Whether the array is a image or texture array</param>
  658. /// <param name="samplerIndex">Sampler handles source</param>
  659. /// <param name="bindingInfo">Array binding information</param>
  660. private void UpdateFromBuffer(
  661. TexturePool texturePool,
  662. SamplerPool samplerPool,
  663. ShaderStage stage,
  664. int stageIndex,
  665. int textureBufferIndex,
  666. bool isImage,
  667. SamplerIndex samplerIndex,
  668. TextureBindingInfo bindingInfo)
  669. {
  670. (textureBufferIndex, int samplerBufferIndex) = TextureHandle.UnpackSlots(bindingInfo.CbufSlot, textureBufferIndex);
  671. bool separateSamplerBuffer = textureBufferIndex != samplerBufferIndex;
  672. bool isCompute = stage == ShaderStage.Compute;
  673. ref BufferBounds textureBufferBounds = ref _channel.BufferManager.GetUniformBufferBounds(isCompute, stageIndex, textureBufferIndex);
  674. ref BufferBounds samplerBufferBounds = ref _channel.BufferManager.GetUniformBufferBounds(isCompute, stageIndex, samplerBufferIndex);
  675. CacheEntryFromBuffer entry = GetOrAddEntry(
  676. texturePool,
  677. samplerPool,
  678. bindingInfo,
  679. isImage,
  680. ref textureBufferBounds,
  681. out bool isNewEntry);
  682. bool poolsModified = entry.PoolsModified();
  683. bool isStore = bindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore);
  684. bool resScaleUnsupported = bindingInfo.Flags.HasFlag(TextureUsageFlags.ResScaleUnsupported);
  685. ReadOnlySpan<int> cachedTextureBuffer;
  686. ReadOnlySpan<int> cachedSamplerBuffer;
  687. if (!poolsModified && !isNewEntry && entry.ValidateTextures())
  688. {
  689. if (entry.MatchesSequenceNumber(_context.SequenceNumber))
  690. {
  691. entry.SynchronizeMemory(isStore, resScaleUnsupported);
  692. if (isImage)
  693. {
  694. _context.Renderer.Pipeline.SetImageArray(stage, bindingInfo.Binding, entry.ImageArray);
  695. }
  696. else
  697. {
  698. _context.Renderer.Pipeline.SetTextureArray(stage, bindingInfo.Binding, entry.TextureArray);
  699. }
  700. return;
  701. }
  702. cachedTextureBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(textureBufferBounds.Range));
  703. if (separateSamplerBuffer)
  704. {
  705. cachedSamplerBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(samplerBufferBounds.Range));
  706. }
  707. else
  708. {
  709. cachedSamplerBuffer = cachedTextureBuffer;
  710. }
  711. (_, int samplerWordOffset, _) = TextureHandle.UnpackOffsets(bindingInfo.Handle);
  712. if (entry.MatchesBufferData(cachedTextureBuffer, cachedSamplerBuffer, separateSamplerBuffer, samplerWordOffset))
  713. {
  714. entry.SynchronizeMemory(isStore, resScaleUnsupported);
  715. if (isImage)
  716. {
  717. _context.Renderer.Pipeline.SetImageArray(stage, bindingInfo.Binding, entry.ImageArray);
  718. }
  719. else
  720. {
  721. _context.Renderer.Pipeline.SetTextureArray(stage, bindingInfo.Binding, entry.TextureArray);
  722. }
  723. return;
  724. }
  725. }
  726. else
  727. {
  728. cachedTextureBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(textureBufferBounds.Range));
  729. if (separateSamplerBuffer)
  730. {
  731. cachedSamplerBuffer = MemoryMarshal.Cast<byte, int>(_channel.MemoryManager.Physical.GetSpan(samplerBufferBounds.Range));
  732. }
  733. else
  734. {
  735. cachedSamplerBuffer = cachedTextureBuffer;
  736. }
  737. }
  738. if (!isNewEntry)
  739. {
  740. entry.Reset();
  741. }
  742. entry.UpdateData(cachedTextureBuffer, cachedSamplerBuffer, separateSamplerBuffer);
  743. Format[] formats = isImage ? new Format[bindingInfo.ArrayLength] : null;
  744. ISampler[] samplers = isImage ? null : new ISampler[bindingInfo.ArrayLength];
  745. ITexture[] textures = new ITexture[bindingInfo.ArrayLength];
  746. for (int index = 0; index < bindingInfo.ArrayLength; index++)
  747. {
  748. int handleIndex = bindingInfo.Handle + index * (Constants.TextureHandleSizeInBytes / sizeof(int));
  749. int packedId = TextureHandle.ReadPackedId(handleIndex, cachedTextureBuffer, cachedSamplerBuffer);
  750. int textureId = TextureHandle.UnpackTextureId(packedId);
  751. int samplerId;
  752. if (samplerIndex == SamplerIndex.ViaHeaderIndex)
  753. {
  754. samplerId = textureId;
  755. }
  756. else
  757. {
  758. samplerId = TextureHandle.UnpackSamplerId(packedId);
  759. }
  760. ref readonly TextureDescriptor descriptor = ref texturePool.GetForBinding(textureId, out Texture texture);
  761. if (texture != null)
  762. {
  763. entry.Textures[texture] = texture.InvalidatedSequence;
  764. if (isStore)
  765. {
  766. texture.SignalModified();
  767. }
  768. if (resScaleUnsupported && texture.ScaleMode != TextureScaleMode.Blacklisted)
  769. {
  770. // Scaling textures used on arrays is currently not supported.
  771. texture.BlacklistScale();
  772. }
  773. }
  774. Sampler sampler = samplerPool?.Get(samplerId);
  775. entry.TextureIds[textureId] = (texture, descriptor);
  776. entry.SamplerIds[samplerId] = (sampler, samplerPool?.GetDescriptorRef(samplerId) ?? default);
  777. ITexture hostTexture = texture?.GetTargetTexture(bindingInfo.Target);
  778. ISampler hostSampler = sampler?.GetHostSampler(texture);
  779. Format format = bindingInfo.Format;
  780. if (hostTexture != null && texture.Target == Target.TextureBuffer)
  781. {
  782. // Ensure that the buffer texture is using the correct buffer as storage.
  783. // Buffers are frequently re-created to accommodate larger data, so we need to re-bind
  784. // to ensure we're not using a old buffer that was already deleted.
  785. if (isImage)
  786. {
  787. if (format == 0 && texture != null)
  788. {
  789. format = texture.Format;
  790. }
  791. _channel.BufferManager.SetBufferTextureStorage(stage, entry.ImageArray, hostTexture, texture.Range, bindingInfo, index, format);
  792. }
  793. else
  794. {
  795. _channel.BufferManager.SetBufferTextureStorage(stage, entry.TextureArray, hostTexture, texture.Range, bindingInfo, index, format);
  796. }
  797. }
  798. else if (isImage)
  799. {
  800. if (format == 0 && texture != null)
  801. {
  802. format = texture.Format;
  803. }
  804. formats[index] = format;
  805. textures[index] = hostTexture;
  806. }
  807. else
  808. {
  809. samplers[index] = hostSampler;
  810. textures[index] = hostTexture;
  811. }
  812. }
  813. if (isImage)
  814. {
  815. entry.ImageArray.SetFormats(0, formats);
  816. entry.ImageArray.SetImages(0, textures);
  817. _context.Renderer.Pipeline.SetImageArray(stage, bindingInfo.Binding, entry.ImageArray);
  818. }
  819. else
  820. {
  821. entry.TextureArray.SetSamplers(0, samplers);
  822. entry.TextureArray.SetTextures(0, textures);
  823. _context.Renderer.Pipeline.SetTextureArray(stage, bindingInfo.Binding, entry.TextureArray);
  824. }
  825. }
  826. /// <summary>
  827. /// Gets a cached texture entry from pool, or creates a new one if not found.
  828. /// </summary>
  829. /// <param name="texturePool">Texture pool</param>
  830. /// <param name="samplerPool">Sampler pool</param>
  831. /// <param name="bindingInfo">Array binding information</param>
  832. /// <param name="isImage">Whether the array is a image or texture array</param>
  833. /// <param name="isNew">Whether a new entry was created, or an existing one was returned</param>
  834. /// <returns>Cache entry</returns>
  835. private CacheEntry GetOrAddEntry(
  836. TexturePool texturePool,
  837. SamplerPool samplerPool,
  838. TextureBindingInfo bindingInfo,
  839. bool isImage,
  840. out bool isNew)
  841. {
  842. CacheEntryFromPoolKey key = new CacheEntryFromPoolKey(isImage, bindingInfo, texturePool, samplerPool);
  843. isNew = !_cacheFromPool.TryGetValue(key, out CacheEntry entry);
  844. if (isNew)
  845. {
  846. int arrayLength = bindingInfo.ArrayLength;
  847. if (isImage)
  848. {
  849. IImageArray array = _context.Renderer.CreateImageArray(arrayLength, bindingInfo.Target == Target.TextureBuffer);
  850. _cacheFromPool.Add(key, entry = new CacheEntry(array, texturePool, samplerPool));
  851. }
  852. else
  853. {
  854. ITextureArray array = _context.Renderer.CreateTextureArray(arrayLength, bindingInfo.Target == Target.TextureBuffer);
  855. _cacheFromPool.Add(key, entry = new CacheEntry(array, texturePool, samplerPool));
  856. }
  857. }
  858. return entry;
  859. }
  860. /// <summary>
  861. /// Gets a cached texture entry from constant buffer, or creates a new one if not found.
  862. /// </summary>
  863. /// <param name="texturePool">Texture pool</param>
  864. /// <param name="samplerPool">Sampler pool</param>
  865. /// <param name="bindingInfo">Array binding information</param>
  866. /// <param name="isImage">Whether the array is a image or texture array</param>
  867. /// <param name="textureBufferBounds">Constant buffer bounds with the texture handles</param>
  868. /// <param name="isNew">Whether a new entry was created, or an existing one was returned</param>
  869. /// <returns>Cache entry</returns>
  870. private CacheEntryFromBuffer GetOrAddEntry(
  871. TexturePool texturePool,
  872. SamplerPool samplerPool,
  873. TextureBindingInfo bindingInfo,
  874. bool isImage,
  875. ref BufferBounds textureBufferBounds,
  876. out bool isNew)
  877. {
  878. CacheEntryFromBufferKey key = new CacheEntryFromBufferKey(
  879. isImage,
  880. bindingInfo,
  881. texturePool,
  882. samplerPool,
  883. ref textureBufferBounds);
  884. isNew = !_cacheFromBuffer.TryGetValue(key, out CacheEntryFromBuffer entry);
  885. if (isNew)
  886. {
  887. int arrayLength = bindingInfo.ArrayLength;
  888. if (isImage)
  889. {
  890. IImageArray array = _context.Renderer.CreateImageArray(arrayLength, bindingInfo.Target == Target.TextureBuffer);
  891. _cacheFromBuffer.Add(key, entry = new CacheEntryFromBuffer(ref key, array, texturePool, samplerPool));
  892. }
  893. else
  894. {
  895. ITextureArray array = _context.Renderer.CreateTextureArray(arrayLength, bindingInfo.Target == Target.TextureBuffer);
  896. _cacheFromBuffer.Add(key, entry = new CacheEntryFromBuffer(ref key, array, texturePool, samplerPool));
  897. }
  898. }
  899. if (entry.CacheNode != null)
  900. {
  901. _lruCache.Remove(entry.CacheNode);
  902. _lruCache.AddLast(entry.CacheNode);
  903. }
  904. else
  905. {
  906. entry.CacheNode = _lruCache.AddLast(entry);
  907. }
  908. entry.CacheTimestamp = ++_currentTimestamp;
  909. RemoveLeastUsedEntries();
  910. return entry;
  911. }
  912. /// <summary>
  913. /// Remove entries from the cache that have not been used for some time.
  914. /// </summary>
  915. private void RemoveLeastUsedEntries()
  916. {
  917. LinkedListNode<CacheEntryFromBuffer> nextNode = _lruCache.First;
  918. while (nextNode != null && _currentTimestamp - nextNode.Value.CacheTimestamp >= MinDeltaForRemoval)
  919. {
  920. LinkedListNode<CacheEntryFromBuffer> toRemove = nextNode;
  921. nextNode = nextNode.Next;
  922. _cacheFromBuffer.Remove(toRemove.Value.Key);
  923. _lruCache.Remove(toRemove);
  924. }
  925. }
  926. /// <summary>
  927. /// Removes all cached texture arrays matching the specified texture pool.
  928. /// </summary>
  929. /// <param name="pool">Texture pool</param>
  930. public void RemoveAllWithPool<T>(IPool<T> pool)
  931. {
  932. List<CacheEntryFromPoolKey> keysToRemove = null;
  933. foreach (CacheEntryFromPoolKey key in _cacheFromPool.Keys)
  934. {
  935. if (key.MatchesPool(pool))
  936. {
  937. (keysToRemove ??= new()).Add(key);
  938. }
  939. }
  940. if (keysToRemove != null)
  941. {
  942. foreach (CacheEntryFromPoolKey key in keysToRemove)
  943. {
  944. _cacheFromPool.Remove(key);
  945. }
  946. }
  947. }
  948. /// <summary>
  949. /// Checks if a handle indicates the binding should have all its textures sourced directly from a pool.
  950. /// </summary>
  951. /// <param name="handle">Handle to check</param>
  952. /// <returns>True if the handle represents direct pool access, false otherwise</returns>
  953. private static bool IsDirectHandleType(int handle)
  954. {
  955. (_, _, TextureHandleType type) = TextureHandle.UnpackOffsets(handle);
  956. return type == TextureHandleType.Direct;
  957. }
  958. }
  959. }