TextureGroup.cs 36 KB

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