TextureGroup.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. using Ryujinx.Common;
  2. using Ryujinx.Cpu.Tracking;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Texture;
  5. using Ryujinx.Memory.Range;
  6. using System;
  7. using System.Collections.Generic;
  8. namespace Ryujinx.Graphics.Gpu.Image
  9. {
  10. /// <summary>
  11. /// A texture group represents a group of textures that belong to the same storage.
  12. /// When views are created, this class will track memory accesses for them separately.
  13. /// The group iteratively adds more granular tracking as views of different kinds are added.
  14. /// Note that a texture group can be absorbed into another when it becomes a view parent.
  15. /// </summary>
  16. class TextureGroup : IDisposable
  17. {
  18. private const int StrideAlignment = 32;
  19. private const int GobAlignment = 64;
  20. private delegate void HandlesCallbackDelegate(int baseHandle, int regionCount, bool split = false);
  21. /// <summary>
  22. /// The storage texture associated with this group.
  23. /// </summary>
  24. public Texture Storage { get; }
  25. /// <summary>
  26. /// Indicates if the texture has copy dependencies. If true, then all modifications
  27. /// must be signalled to the group, rather than skipping ones still to be flushed.
  28. /// </summary>
  29. public bool HasCopyDependencies { get; set; }
  30. private GpuContext _context;
  31. private int[] _allOffsets;
  32. private int[] _sliceSizes;
  33. private bool _is3D;
  34. private bool _hasMipViews;
  35. private bool _hasLayerViews;
  36. private int _layers;
  37. private int _levels;
  38. private MultiRange TextureRange => Storage.Range;
  39. /// <summary>
  40. /// The views list from the storage texture.
  41. /// </summary>
  42. private List<Texture> _views;
  43. private TextureGroupHandle[] _handles;
  44. private bool[] _loadNeeded;
  45. /// <summary>
  46. /// Create a new texture group.
  47. /// </summary>
  48. /// <param name="context">GPU context that the texture group belongs to</param>
  49. /// <param name="storage">The storage texture for this group</param>
  50. public TextureGroup(GpuContext context, Texture storage)
  51. {
  52. Storage = storage;
  53. _context = context;
  54. _is3D = storage.Info.Target == Target.Texture3D;
  55. _layers = storage.Info.GetSlices();
  56. _levels = storage.Info.Levels;
  57. }
  58. /// <summary>
  59. /// Initialize a new texture group's dirty regions and offsets.
  60. /// </summary>
  61. /// <param name="size">Size info for the storage texture</param>
  62. /// <param name="hasLayerViews">True if the storage will have layer views</param>
  63. /// <param name="hasMipViews">True if the storage will have mip views</param>
  64. public void Initialize(ref SizeInfo size, bool hasLayerViews, bool hasMipViews)
  65. {
  66. _allOffsets = size.AllOffsets;
  67. _sliceSizes = size.SliceSizes;
  68. (_hasLayerViews, _hasMipViews) = PropagateGranularity(hasLayerViews, hasMipViews);
  69. RecalculateHandleRegions();
  70. }
  71. /// <summary>
  72. /// Consume the dirty flags for a given texture. The state is shared between views of the same layers and levels.
  73. /// </summary>
  74. /// <param name="texture">The texture being used</param>
  75. /// <returns>True if a flag was dirty, false otherwise</returns>
  76. public bool ConsumeDirty(Texture texture)
  77. {
  78. bool dirty = false;
  79. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  80. {
  81. for (int i = 0; i < regionCount; i++)
  82. {
  83. TextureGroupHandle group = _handles[baseHandle + i];
  84. foreach (CpuRegionHandle handle in group.Handles)
  85. {
  86. if (handle.Dirty)
  87. {
  88. handle.Reprotect();
  89. dirty = true;
  90. }
  91. }
  92. }
  93. });
  94. return dirty;
  95. }
  96. /// <summary>
  97. /// Synchronize memory for a given texture.
  98. /// If overlapping tracking handles are dirty, fully or partially synchronize the texture data.
  99. /// </summary>
  100. /// <param name="texture">The texture being used</param>
  101. public void SynchronizeMemory(Texture texture)
  102. {
  103. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  104. {
  105. bool dirty = false;
  106. bool anyModified = false;
  107. bool anyUnmapped = false;
  108. for (int i = 0; i < regionCount; i++)
  109. {
  110. TextureGroupHandle group = _handles[baseHandle + i];
  111. bool modified = group.Modified;
  112. bool handleDirty = false;
  113. bool handleModified = false;
  114. bool handleUnmapped = false;
  115. foreach (CpuRegionHandle handle in group.Handles)
  116. {
  117. if (handle.Dirty)
  118. {
  119. handle.Reprotect();
  120. handleDirty = true;
  121. }
  122. else
  123. {
  124. handleUnmapped |= handle.Unmapped;
  125. handleModified |= modified;
  126. }
  127. }
  128. // Evaluate if any copy dependencies need to be fulfilled. A few rules:
  129. // If the copy handle needs to be synchronized, prefer our own state.
  130. // If we need to be synchronized and there is a copy present, prefer the copy.
  131. if (group.NeedsCopy && group.Copy())
  132. {
  133. anyModified |= true; // The copy target has been modified.
  134. handleDirty = false;
  135. }
  136. else
  137. {
  138. anyModified |= handleModified;
  139. dirty |= handleDirty;
  140. }
  141. anyUnmapped |= handleUnmapped;
  142. if (group.NeedsCopy)
  143. {
  144. // The texture we copied from is still being written to. Copy from it again the next time this texture is used.
  145. texture.SignalGroupDirty();
  146. }
  147. _loadNeeded[baseHandle + i] = handleDirty && !handleUnmapped;
  148. }
  149. if (dirty)
  150. {
  151. if (anyUnmapped || (_handles.Length > 1 && (anyModified || split)))
  152. {
  153. // Partial texture invalidation. Only update the layers/levels with dirty flags of the storage.
  154. SynchronizePartial(baseHandle, regionCount);
  155. }
  156. else
  157. {
  158. // Full texture invalidation.
  159. texture.SynchronizeFull();
  160. }
  161. }
  162. });
  163. }
  164. /// <summary>
  165. /// Synchronize part of the storage texture, represented by a given range of handles.
  166. /// Only handles marked by the _loadNeeded array will be synchronized.
  167. /// </summary>
  168. /// <param name="baseHandle">The base index of the range of handles</param>
  169. /// <param name="regionCount">The number of handles to synchronize</param>
  170. private void SynchronizePartial(int baseHandle, int regionCount)
  171. {
  172. for (int i = 0; i < regionCount; i++)
  173. {
  174. if (_loadNeeded[baseHandle + i])
  175. {
  176. var info = GetHandleInformation(baseHandle + i);
  177. int offsetIndex = info.Index;
  178. // Only one of these will be greater than 1, as partial sync is only called when there are sub-image views.
  179. for (int layer = 0; layer < info.Layers; layer++)
  180. {
  181. for (int level = 0; level < info.Levels; level++)
  182. {
  183. int offset = _allOffsets[offsetIndex];
  184. int endOffset = (offsetIndex + 1 == _allOffsets.Length) ? (int)Storage.Size : _allOffsets[offsetIndex + 1];
  185. int size = endOffset - offset;
  186. ReadOnlySpan<byte> data = _context.PhysicalMemory.GetSpan(Storage.Range.GetSlice((ulong)offset, (ulong)size));
  187. data = Storage.ConvertToHostCompatibleFormat(data, info.BaseLevel, true);
  188. Storage.SetData(data, info.BaseLayer, info.BaseLevel);
  189. offsetIndex++;
  190. }
  191. }
  192. }
  193. }
  194. }
  195. /// <summary>
  196. /// Signal that a texture in the group has been modified by the GPU.
  197. /// </summary>
  198. /// <param name="texture">The texture that has been modified</param>
  199. /// <param name="registerAction">True if the flushing read action should be registered, false otherwise</param>
  200. public void SignalModified(Texture texture, bool registerAction)
  201. {
  202. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  203. {
  204. for (int i = 0; i < regionCount; i++)
  205. {
  206. TextureGroupHandle group = _handles[baseHandle + i];
  207. group.SignalModified();
  208. if (registerAction)
  209. {
  210. RegisterAction(group);
  211. }
  212. }
  213. });
  214. }
  215. /// <summary>
  216. /// Signal that a texture in the group is actively bound, or has been unbound by the GPU.
  217. /// </summary>
  218. /// <param name="texture">The texture that has been modified</param>
  219. /// <param name="bound">True if this texture is being bound, false if unbound</param>
  220. /// <param name="registerAction">True if the flushing read action should be registered, false otherwise</param>
  221. public void SignalModifying(Texture texture, bool bound, bool registerAction)
  222. {
  223. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  224. {
  225. for (int i = 0; i < regionCount; i++)
  226. {
  227. TextureGroupHandle group = _handles[baseHandle + i];
  228. group.SignalModifying(bound);
  229. if (registerAction)
  230. {
  231. RegisterAction(group);
  232. }
  233. }
  234. });
  235. }
  236. /// <summary>
  237. /// Register a read/write action to flush for a texture group.
  238. /// </summary>
  239. /// <param name="group">The group to register an action for</param>
  240. public void RegisterAction(TextureGroupHandle group)
  241. {
  242. foreach (CpuRegionHandle handle in group.Handles)
  243. {
  244. handle.RegisterAction((address, size) => FlushAction(group, address, size));
  245. }
  246. }
  247. /// <summary>
  248. /// Propagates the mip/layer view flags depending on the texture type.
  249. /// When the most granular type of subresource has views, the other type of subresource must be segmented granularly too.
  250. /// </summary>
  251. /// <param name="hasLayerViews">True if the storage has layer views</param>
  252. /// <param name="hasMipViews">True if the storage has mip views</param>
  253. /// <returns>The input values after propagation</returns>
  254. private (bool HasLayerViews, bool HasMipViews) PropagateGranularity(bool hasLayerViews, bool hasMipViews)
  255. {
  256. if (_is3D)
  257. {
  258. hasMipViews |= hasLayerViews;
  259. }
  260. else
  261. {
  262. hasLayerViews |= hasMipViews;
  263. }
  264. return (hasLayerViews, hasMipViews);
  265. }
  266. /// <summary>
  267. /// Evaluate the range of tracking handles which a view texture overlaps with.
  268. /// </summary>
  269. /// <param name="texture">The texture to get handles for</param>
  270. /// <param name="callback">
  271. /// A function to be called with the base index of the range of handles for the given texture, and the number of handles it covers.
  272. /// This can be called for multiple disjoint ranges, if required.
  273. /// </param>
  274. private void EvaluateRelevantHandles(Texture texture, HandlesCallbackDelegate callback)
  275. {
  276. if (texture == Storage || !(_hasMipViews || _hasLayerViews))
  277. {
  278. callback(0, _handles.Length);
  279. return;
  280. }
  281. EvaluateRelevantHandles(texture.FirstLayer, texture.FirstLevel, texture.Info.GetSlices(), texture.Info.Levels, callback);
  282. }
  283. /// <summary>
  284. /// Evaluate the range of tracking handles which a view texture overlaps with,
  285. /// using the view's position and slice/level counts.
  286. /// </summary>
  287. /// <param name="firstLayer">The first layer of the texture</param>
  288. /// <param name="firstLevel">The first level of the texture</param>
  289. /// <param name="slices">The slice count of the texture</param>
  290. /// <param name="levels">The level count of the texture</param>
  291. /// <param name="callback">
  292. /// A function to be called with the base index of the range of handles for the given texture, and the number of handles it covers.
  293. /// This can be called for multiple disjoint ranges, if required.
  294. /// </param>
  295. private void EvaluateRelevantHandles(int firstLayer, int firstLevel, int slices, int levels, HandlesCallbackDelegate callback)
  296. {
  297. int targetLayerHandles = _hasLayerViews ? slices : 1;
  298. int targetLevelHandles = _hasMipViews ? levels : 1;
  299. if (_is3D)
  300. {
  301. // Future mip levels come after all layers of the last mip level. Each mipmap has less layers (depth) than the last.
  302. if (!_hasLayerViews)
  303. {
  304. // When there are no layer views, the mips are at a consistent offset.
  305. callback(firstLevel, targetLevelHandles);
  306. }
  307. else
  308. {
  309. (int levelIndex, int layerCount) = Get3DLevelRange(firstLevel);
  310. if (levels > 1 && slices < _layers)
  311. {
  312. // The given texture only covers some of the depth of multiple mips. (a "depth slice")
  313. // Callback with each mip's range separately.
  314. // Can assume that the group is fully subdivided (both slices and levels > 1 for storage)
  315. while (levels-- > 1)
  316. {
  317. callback(firstLayer + levelIndex, slices);
  318. levelIndex += layerCount;
  319. layerCount = Math.Max(layerCount >> 1, 1);
  320. slices = Math.Max(layerCount >> 1, 1);
  321. }
  322. }
  323. else
  324. {
  325. int totalSize = Math.Min(layerCount, slices);
  326. while (levels-- > 1)
  327. {
  328. layerCount = Math.Max(layerCount >> 1, 1);
  329. totalSize += layerCount;
  330. }
  331. callback(firstLayer + levelIndex, totalSize);
  332. }
  333. }
  334. }
  335. else
  336. {
  337. // Future layers come after all mipmaps of the last.
  338. int levelHandles = _hasMipViews ? _levels : 1;
  339. if (slices > 1 && levels < _levels)
  340. {
  341. // The given texture only covers some of the mipmaps of multiple slices. (a "mip slice")
  342. // Callback with each layer's range separately.
  343. // Can assume that the group is fully subdivided (both slices and levels > 1 for storage)
  344. for (int i = 0; i < slices; i++)
  345. {
  346. callback(firstLevel + (firstLayer + i) * levelHandles, targetLevelHandles, true);
  347. }
  348. }
  349. else
  350. {
  351. callback(firstLevel + firstLayer * levelHandles, targetLevelHandles + (targetLayerHandles - 1) * levelHandles);
  352. }
  353. }
  354. }
  355. /// <summary>
  356. /// Get the range of offsets for a given mip level of a 3D texture.
  357. /// </summary>
  358. /// <param name="level">The level to return</param>
  359. /// <returns>Start index and count of offsets for the given level</returns>
  360. private (int Index, int Count) Get3DLevelRange(int level)
  361. {
  362. int index = 0;
  363. int count = _layers; // Depth. Halves with each mip level.
  364. while (level-- > 0)
  365. {
  366. index += count;
  367. count = Math.Max(count >> 1, 1);
  368. }
  369. return (index, count);
  370. }
  371. /// <summary>
  372. /// Get view information for a single tracking handle.
  373. /// </summary>
  374. /// <param name="handleIndex">The index of the handle</param>
  375. /// <returns>The layers and levels that the handle covers, and its index in the offsets array</returns>
  376. private (int BaseLayer, int BaseLevel, int Levels, int Layers, int Index) GetHandleInformation(int handleIndex)
  377. {
  378. int baseLayer;
  379. int baseLevel;
  380. int levels = _hasMipViews ? 1 : _levels;
  381. int layers = _hasLayerViews ? 1 : _layers;
  382. int index;
  383. if (_is3D)
  384. {
  385. if (_hasLayerViews)
  386. {
  387. // NOTE: Will also have mip views, or only one level in storage.
  388. index = handleIndex;
  389. baseLevel = 0;
  390. int layerLevels = _levels;
  391. while (handleIndex >= layerLevels)
  392. {
  393. handleIndex -= layerLevels;
  394. baseLevel++;
  395. layerLevels = Math.Max(layerLevels >> 1, 1);
  396. }
  397. baseLayer = handleIndex;
  398. }
  399. else
  400. {
  401. baseLayer = 0;
  402. baseLevel = handleIndex;
  403. (index, _) = Get3DLevelRange(baseLevel);
  404. }
  405. }
  406. else
  407. {
  408. baseLevel = _hasMipViews ? handleIndex % _levels : 0;
  409. baseLayer = _hasMipViews ? handleIndex / _levels : handleIndex;
  410. index = baseLevel + baseLayer * _levels;
  411. }
  412. return (baseLayer, baseLevel, levels, layers, index);
  413. }
  414. /// <summary>
  415. /// Gets the layer and level for a given view.
  416. /// </summary>
  417. /// <param name="index">The index of the view</param>
  418. /// <returns>The layer and level of the specified view</returns>
  419. private (int BaseLayer, int BaseLevel) GetLayerLevelForView(int index)
  420. {
  421. if (_is3D)
  422. {
  423. int baseLevel = 0;
  424. int layerLevels = _layers;
  425. while (index >= layerLevels)
  426. {
  427. index -= layerLevels;
  428. baseLevel++;
  429. layerLevels = Math.Max(layerLevels >> 1, 1);
  430. }
  431. return (index, baseLevel);
  432. }
  433. else
  434. {
  435. return (index / _levels, index % _levels);
  436. }
  437. }
  438. /// <summary>
  439. /// Find the byte offset of a given texture relative to the storage.
  440. /// </summary>
  441. /// <param name="texture">The texture to locate</param>
  442. /// <returns>The offset of the texture in bytes</returns>
  443. public int FindOffset(Texture texture)
  444. {
  445. return _allOffsets[GetOffsetIndex(texture.FirstLayer, texture.FirstLevel)];
  446. }
  447. /// <summary>
  448. /// Find the offset index of a given layer and level.
  449. /// </summary>
  450. /// <param name="layer">The view layer</param>
  451. /// <param name="level">The view level</param>
  452. /// <returns>The offset index of the given layer and level</returns>
  453. public int GetOffsetIndex(int layer, int level)
  454. {
  455. if (_is3D)
  456. {
  457. return layer + Get3DLevelRange(level).Index;
  458. }
  459. else
  460. {
  461. return level + layer * _levels;
  462. }
  463. }
  464. /// <summary>
  465. /// The action to perform when a memory tracking handle is flipped to dirty.
  466. /// This notifies overlapping textures that the memory needs to be synchronized.
  467. /// </summary>
  468. /// <param name="groupHandle">The handle that a dirty flag was set on</param>
  469. private void DirtyAction(TextureGroupHandle groupHandle)
  470. {
  471. // Notify all textures that belong to this handle.
  472. Storage.SignalGroupDirty();
  473. lock (groupHandle.Overlaps)
  474. {
  475. foreach (Texture overlap in groupHandle.Overlaps)
  476. {
  477. overlap.SignalGroupDirty();
  478. }
  479. }
  480. }
  481. /// <summary>
  482. /// Generate a CpuRegionHandle for a given address and size range in CPU VA.
  483. /// </summary>
  484. /// <param name="address">The start address of the tracked region</param>
  485. /// <param name="size">The size of the tracked region</param>
  486. /// <returns>A CpuRegionHandle covering the given range</returns>
  487. private CpuRegionHandle GenerateHandle(ulong address, ulong size)
  488. {
  489. return _context.PhysicalMemory.BeginTracking(address, size);
  490. }
  491. /// <summary>
  492. /// Generate a TextureGroupHandle covering a specified range of views.
  493. /// </summary>
  494. /// <param name="viewStart">The start view of the handle</param>
  495. /// <param name="views">The number of views to cover</param>
  496. /// <returns>A TextureGroupHandle covering the given views</returns>
  497. private TextureGroupHandle GenerateHandles(int viewStart, int views)
  498. {
  499. int offset = _allOffsets[viewStart];
  500. int endOffset = (viewStart + views == _allOffsets.Length) ? (int)Storage.Size : _allOffsets[viewStart + views];
  501. int size = endOffset - offset;
  502. var result = new List<CpuRegionHandle>();
  503. for (int i = 0; i < TextureRange.Count; i++)
  504. {
  505. MemoryRange item = TextureRange.GetSubRange(i);
  506. int subRangeSize = (int)item.Size;
  507. int sliceStart = Math.Clamp(offset, 0, subRangeSize);
  508. int sliceEnd = Math.Clamp(endOffset, 0, subRangeSize);
  509. if (sliceStart != sliceEnd)
  510. {
  511. result.Add(GenerateHandle(item.Address + (ulong)sliceStart, (ulong)(sliceEnd - sliceStart)));
  512. }
  513. offset -= subRangeSize;
  514. endOffset -= subRangeSize;
  515. if (endOffset <= 0)
  516. {
  517. break;
  518. }
  519. }
  520. (int firstLayer, int firstLevel) = GetLayerLevelForView(viewStart);
  521. if (_hasLayerViews && _hasMipViews)
  522. {
  523. size = _sliceSizes[firstLevel];
  524. }
  525. var groupHandle = new TextureGroupHandle(this, _allOffsets[viewStart], (ulong)size, _views, firstLayer, firstLevel, result.ToArray());
  526. foreach (CpuRegionHandle handle in result)
  527. {
  528. handle.RegisterDirtyEvent(() => DirtyAction(groupHandle));
  529. }
  530. return groupHandle;
  531. }
  532. /// <summary>
  533. /// Update the views in this texture group, rebuilding the memory tracking if required.
  534. /// </summary>
  535. /// <param name="views">The views list of the storage texture</param>
  536. public void UpdateViews(List<Texture> views)
  537. {
  538. // This is saved to calculate overlapping views for each handle.
  539. _views = views;
  540. bool layerViews = _hasLayerViews;
  541. bool mipViews = _hasMipViews;
  542. bool regionsRebuilt = false;
  543. if (!(layerViews && mipViews))
  544. {
  545. foreach (Texture view in views)
  546. {
  547. if (view.Info.GetSlices() < _layers)
  548. {
  549. layerViews = true;
  550. }
  551. if (view.Info.Levels < _levels)
  552. {
  553. mipViews = true;
  554. }
  555. }
  556. (layerViews, mipViews) = PropagateGranularity(layerViews, mipViews);
  557. if (layerViews != _hasLayerViews || mipViews != _hasMipViews)
  558. {
  559. _hasLayerViews = layerViews;
  560. _hasMipViews = mipViews;
  561. RecalculateHandleRegions();
  562. regionsRebuilt = true;
  563. }
  564. }
  565. if (!regionsRebuilt)
  566. {
  567. // Must update the overlapping views on all handles, but only if they were not just recreated.
  568. foreach (TextureGroupHandle handle in _handles)
  569. {
  570. handle.RecalculateOverlaps(this, views);
  571. }
  572. }
  573. Storage.SignalGroupDirty();
  574. foreach (Texture texture in views)
  575. {
  576. texture.SignalGroupDirty();
  577. }
  578. }
  579. /// <summary>
  580. /// Inherit handle state from an old set of handles, such as modified and dirty flags.
  581. /// </summary>
  582. /// <param name="oldHandles">The set of handles to inherit state from</param>
  583. /// <param name="handles">The set of handles inheriting the state</param>
  584. private void InheritHandles(TextureGroupHandle[] oldHandles, TextureGroupHandle[] handles)
  585. {
  586. foreach (var group in handles)
  587. {
  588. foreach (var handle in group.Handles)
  589. {
  590. bool dirty = false;
  591. foreach (var oldGroup in oldHandles)
  592. {
  593. if (group.OverlapsWith(oldGroup.Offset, oldGroup.Size))
  594. {
  595. foreach (var oldHandle in oldGroup.Handles)
  596. {
  597. if (handle.OverlapsWith(oldHandle.Address, oldHandle.Size))
  598. {
  599. dirty |= oldHandle.Dirty;
  600. }
  601. }
  602. group.Inherit(oldGroup);
  603. }
  604. }
  605. if (dirty && !handle.Dirty)
  606. {
  607. handle.Reprotect(true);
  608. }
  609. if (group.Modified)
  610. {
  611. handle.RegisterAction((address, size) => FlushAction(group, address, size));
  612. }
  613. }
  614. }
  615. }
  616. /// <summary>
  617. /// Inherit state from another texture group.
  618. /// </summary>
  619. /// <param name="other">The texture group to inherit from</param>
  620. public void Inherit(TextureGroup other)
  621. {
  622. bool layerViews = _hasLayerViews || other._hasLayerViews;
  623. bool mipViews = _hasMipViews || other._hasMipViews;
  624. if (layerViews != _hasLayerViews || mipViews != _hasMipViews)
  625. {
  626. _hasLayerViews = layerViews;
  627. _hasMipViews = mipViews;
  628. RecalculateHandleRegions();
  629. }
  630. InheritHandles(other._handles, _handles);
  631. }
  632. /// <summary>
  633. /// Replace the current handles with the new handles. It is assumed that the new handles start dirty.
  634. /// The dirty flags from the previous handles will be kept.
  635. /// </summary>
  636. /// <param name="handles">The handles to replace the current handles with</param>
  637. private void ReplaceHandles(TextureGroupHandle[] handles)
  638. {
  639. if (_handles != null)
  640. {
  641. // When replacing handles, they should start as non-dirty.
  642. foreach (TextureGroupHandle groupHandle in handles)
  643. {
  644. foreach (CpuRegionHandle handle in groupHandle.Handles)
  645. {
  646. handle.Reprotect();
  647. }
  648. }
  649. InheritHandles(_handles, handles);
  650. foreach (var oldGroup in _handles)
  651. {
  652. foreach (var oldHandle in oldGroup.Handles)
  653. {
  654. oldHandle.Dispose();
  655. }
  656. }
  657. }
  658. _handles = handles;
  659. _loadNeeded = new bool[_handles.Length];
  660. }
  661. /// <summary>
  662. /// Recalculate handle regions for this texture group, and inherit existing state into the new handles.
  663. /// </summary>
  664. private void RecalculateHandleRegions()
  665. {
  666. TextureGroupHandle[] handles;
  667. if (!(_hasMipViews || _hasLayerViews))
  668. {
  669. // Single dirty region.
  670. var cpuRegionHandles = new CpuRegionHandle[TextureRange.Count];
  671. for (int i = 0; i < TextureRange.Count; i++)
  672. {
  673. var currentRange = TextureRange.GetSubRange(i);
  674. cpuRegionHandles[i] = GenerateHandle(currentRange.Address, currentRange.Size);
  675. }
  676. var groupHandle = new TextureGroupHandle(this, 0, Storage.Size, _views, 0, 0, cpuRegionHandles);
  677. foreach (CpuRegionHandle handle in cpuRegionHandles)
  678. {
  679. handle.RegisterDirtyEvent(() => DirtyAction(groupHandle));
  680. }
  681. handles = new TextureGroupHandle[] { groupHandle };
  682. }
  683. else
  684. {
  685. // Get views for the host texture.
  686. // It's worth noting that either the texture has layer views or mip views when getting to this point, which simplifies the logic a little.
  687. // Depending on if the texture is 3d, either the mip views imply that layer views are present (2d) or the other way around (3d).
  688. // This is enforced by the way the texture matched as a view, so we don't need to check.
  689. int layerHandles = _hasLayerViews ? _layers : 1;
  690. int levelHandles = _hasMipViews ? _levels : 1;
  691. int handleIndex = 0;
  692. if (_is3D)
  693. {
  694. var handlesList = new List<TextureGroupHandle>();
  695. for (int i = 0; i < levelHandles; i++)
  696. {
  697. for (int j = 0; j < layerHandles; j++)
  698. {
  699. (int viewStart, int views) = Get3DLevelRange(i);
  700. viewStart += j;
  701. views = _hasLayerViews ? 1 : views; // A layer view is also a mip view.
  702. handlesList.Add(GenerateHandles(viewStart, views));
  703. }
  704. layerHandles = Math.Max(1, layerHandles >> 1);
  705. }
  706. handles = handlesList.ToArray();
  707. }
  708. else
  709. {
  710. handles = new TextureGroupHandle[layerHandles * levelHandles];
  711. for (int i = 0; i < layerHandles; i++)
  712. {
  713. for (int j = 0; j < levelHandles; j++)
  714. {
  715. int viewStart = j + i * _levels;
  716. int views = _hasMipViews ? 1 : _levels; // A mip view is also a layer view.
  717. handles[handleIndex++] = GenerateHandles(viewStart, views);
  718. }
  719. }
  720. }
  721. }
  722. ReplaceHandles(handles);
  723. }
  724. /// <summary>
  725. /// Ensure that there is a handle for each potential texture view. Required for copy dependencies to work.
  726. /// </summary>
  727. private void EnsureFullSubdivision()
  728. {
  729. if (!(_hasLayerViews && _hasMipViews))
  730. {
  731. _hasLayerViews = true;
  732. _hasMipViews = true;
  733. RecalculateHandleRegions();
  734. }
  735. }
  736. /// <summary>
  737. /// Create a copy dependency between this texture group, and a texture at a given layer/level offset.
  738. /// </summary>
  739. /// <param name="other">The view compatible texture to create a dependency to</param>
  740. /// <param name="firstLayer">The base layer of the given texture relative to the storage</param>
  741. /// <param name="firstLevel">The base level of the given texture relative to the storage</param>
  742. /// <param name="copyTo">True if this texture is first copied to the given one, false for the opposite direction</param>
  743. public void CreateCopyDependency(Texture other, int firstLayer, int firstLevel, bool copyTo)
  744. {
  745. TextureGroup otherGroup = other.Group;
  746. EnsureFullSubdivision();
  747. otherGroup.EnsureFullSubdivision();
  748. // Get the location of each texture within its storage, so we can find the handles to apply the dependency to.
  749. // This can consist of multiple disjoint regions, for example if this is a mip slice of an array texture.
  750. var targetRange = new List<(int BaseHandle, int RegionCount)>();
  751. var otherRange = new List<(int BaseHandle, int RegionCount)>();
  752. EvaluateRelevantHandles(firstLayer, firstLevel, other.Info.GetSlices(), other.Info.Levels, (baseHandle, regionCount, split) => targetRange.Add((baseHandle, regionCount)));
  753. otherGroup.EvaluateRelevantHandles(other, (baseHandle, regionCount, split) => otherRange.Add((baseHandle, regionCount)));
  754. int targetIndex = 0;
  755. int otherIndex = 0;
  756. (int Handle, int RegionCount) targetRegion = (0, 0);
  757. (int Handle, int RegionCount) otherRegion = (0, 0);
  758. while (true)
  759. {
  760. if (targetRegion.RegionCount == 0)
  761. {
  762. if (targetIndex >= targetRange.Count)
  763. {
  764. break;
  765. }
  766. targetRegion = targetRange[targetIndex++];
  767. }
  768. if (otherRegion.RegionCount == 0)
  769. {
  770. if (otherIndex >= otherRange.Count)
  771. {
  772. break;
  773. }
  774. otherRegion = otherRange[otherIndex++];
  775. }
  776. TextureGroupHandle handle = _handles[targetRegion.Handle++];
  777. TextureGroupHandle otherHandle = other.Group._handles[otherRegion.Handle++];
  778. targetRegion.RegionCount--;
  779. otherRegion.RegionCount--;
  780. handle.CreateCopyDependency(otherHandle, copyTo);
  781. // If "copyTo" is true, this texture must copy to the other.
  782. // Otherwise, it must copy to this texture.
  783. if (copyTo)
  784. {
  785. otherHandle.Copy(handle);
  786. }
  787. else
  788. {
  789. handle.Copy(otherHandle);
  790. }
  791. }
  792. }
  793. /// <summary>
  794. /// A flush has been requested on a tracked region. Find an appropriate view to flush.
  795. /// </summary>
  796. /// <param name="handle">The handle this flush action is for</param>
  797. /// <param name="address">The address of the flushing memory access</param>
  798. /// <param name="size">The size of the flushing memory access</param>
  799. public void FlushAction(TextureGroupHandle handle, ulong address, ulong size)
  800. {
  801. Storage.ExternalFlush(address, size);
  802. lock (handle.Overlaps)
  803. {
  804. foreach (Texture overlap in handle.Overlaps)
  805. {
  806. overlap.ExternalFlush(address, size);
  807. }
  808. }
  809. handle.Modified = false;
  810. }
  811. /// <summary>
  812. /// Dispose this texture group, disposing all related memory tracking handles.
  813. /// </summary>
  814. public void Dispose()
  815. {
  816. foreach (TextureGroupHandle group in _handles)
  817. {
  818. group.Dispose();
  819. }
  820. }
  821. }
  822. }