TextureGroup.cs 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. using Ryujinx.Common.Memory;
  2. using Ryujinx.Cpu.Tracking;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu.Memory;
  5. using Ryujinx.Graphics.Texture;
  6. using Ryujinx.Memory;
  7. using Ryujinx.Memory.Range;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Runtime.CompilerServices;
  11. namespace Ryujinx.Graphics.Gpu.Image
  12. {
  13. /// <summary>
  14. /// An overlapping texture group with a given view compatibility.
  15. /// </summary>
  16. readonly struct TextureIncompatibleOverlap
  17. {
  18. public readonly TextureGroup Group;
  19. public readonly TextureViewCompatibility Compatibility;
  20. /// <summary>
  21. /// Create a new texture incompatible overlap.
  22. /// </summary>
  23. /// <param name="group">The group that is incompatible</param>
  24. /// <param name="compatibility">The view compatibility for the group</param>
  25. public TextureIncompatibleOverlap(TextureGroup group, TextureViewCompatibility compatibility)
  26. {
  27. Group = group;
  28. Compatibility = compatibility;
  29. }
  30. }
  31. /// <summary>
  32. /// A texture group represents a group of textures that belong to the same storage.
  33. /// When views are created, this class will track memory accesses for them separately.
  34. /// The group iteratively adds more granular tracking as views of different kinds are added.
  35. /// Note that a texture group can be absorbed into another when it becomes a view parent.
  36. /// </summary>
  37. class TextureGroup : IDisposable
  38. {
  39. private delegate void HandlesCallbackDelegate(int baseHandle, int regionCount, bool split = false);
  40. /// <summary>
  41. /// The storage texture associated with this group.
  42. /// </summary>
  43. public Texture Storage { get; }
  44. /// <summary>
  45. /// Indicates if the texture has copy dependencies. If true, then all modifications
  46. /// must be signalled to the group, rather than skipping ones still to be flushed.
  47. /// </summary>
  48. public bool HasCopyDependencies { get; set; }
  49. /// <summary>
  50. /// Indicates if this texture has any incompatible overlaps alive.
  51. /// </summary>
  52. public bool HasIncompatibleOverlaps => _incompatibleOverlaps.Count > 0;
  53. private readonly GpuContext _context;
  54. private readonly PhysicalMemory _physicalMemory;
  55. private int[] _allOffsets;
  56. private int[] _sliceSizes;
  57. private bool _is3D;
  58. private bool _hasMipViews;
  59. private bool _hasLayerViews;
  60. private int _layers;
  61. private int _levels;
  62. private MultiRange TextureRange => Storage.Range;
  63. /// <summary>
  64. /// The views list from the storage texture.
  65. /// </summary>
  66. private List<Texture> _views;
  67. private TextureGroupHandle[] _handles;
  68. private bool[] _loadNeeded;
  69. /// <summary>
  70. /// Other texture groups that have incompatible overlaps with this one.
  71. /// </summary>
  72. private List<TextureIncompatibleOverlap> _incompatibleOverlaps;
  73. private bool _incompatibleOverlapsDirty = true;
  74. private bool _flushIncompatibleOverlaps;
  75. /// <summary>
  76. /// Create a new texture group.
  77. /// </summary>
  78. /// <param name="context">GPU context that the texture group belongs to</param>
  79. /// <param name="physicalMemory">Physical memory where the <paramref name="storage"/> texture is mapped</param>
  80. /// <param name="storage">The storage texture for this group</param>
  81. /// <param name="incompatibleOverlaps">Groups that overlap with this one but are incompatible</param>
  82. public TextureGroup(GpuContext context, PhysicalMemory physicalMemory, Texture storage, List<TextureIncompatibleOverlap> incompatibleOverlaps)
  83. {
  84. Storage = storage;
  85. _context = context;
  86. _physicalMemory = physicalMemory;
  87. _is3D = storage.Info.Target == Target.Texture3D;
  88. _layers = storage.Info.GetSlices();
  89. _levels = storage.Info.Levels;
  90. _incompatibleOverlaps = incompatibleOverlaps;
  91. _flushIncompatibleOverlaps = TextureCompatibility.IsFormatHostIncompatible(storage.Info, context.Capabilities);
  92. }
  93. /// <summary>
  94. /// Initialize a new texture group's dirty regions and offsets.
  95. /// </summary>
  96. /// <param name="size">Size info for the storage texture</param>
  97. /// <param name="hasLayerViews">True if the storage will have layer views</param>
  98. /// <param name="hasMipViews">True if the storage will have mip views</param>
  99. public void Initialize(ref SizeInfo size, bool hasLayerViews, bool hasMipViews)
  100. {
  101. _allOffsets = size.AllOffsets;
  102. _sliceSizes = size.SliceSizes;
  103. (_hasLayerViews, _hasMipViews) = PropagateGranularity(hasLayerViews, hasMipViews);
  104. RecalculateHandleRegions();
  105. }
  106. /// <summary>
  107. /// Initialize all incompatible overlaps in the list, registering them with the other texture groups
  108. /// and creating copy dependencies when partially compatible.
  109. /// </summary>
  110. public void InitializeOverlaps()
  111. {
  112. foreach (TextureIncompatibleOverlap overlap in _incompatibleOverlaps)
  113. {
  114. if (overlap.Compatibility == TextureViewCompatibility.LayoutIncompatible)
  115. {
  116. CreateCopyDependency(overlap.Group, false);
  117. }
  118. overlap.Group._incompatibleOverlaps.Add(new TextureIncompatibleOverlap(this, overlap.Compatibility));
  119. overlap.Group._incompatibleOverlapsDirty = true;
  120. }
  121. if (_incompatibleOverlaps.Count > 0)
  122. {
  123. SignalIncompatibleOverlapModified();
  124. }
  125. }
  126. /// <summary>
  127. /// Signal that the group is dirty to all views and the storage.
  128. /// </summary>
  129. private void SignalAllDirty()
  130. {
  131. Storage.SignalGroupDirty();
  132. if (_views != null)
  133. {
  134. foreach (Texture texture in _views)
  135. {
  136. texture.SignalGroupDirty();
  137. }
  138. }
  139. }
  140. /// <summary>
  141. /// Signal that an incompatible overlap has been modified.
  142. /// If this group must flush incompatible overlaps, the group is signalled as dirty too.
  143. /// </summary>
  144. private void SignalIncompatibleOverlapModified()
  145. {
  146. _incompatibleOverlapsDirty = true;
  147. if (_flushIncompatibleOverlaps)
  148. {
  149. SignalAllDirty();
  150. }
  151. }
  152. /// <summary>
  153. /// Flushes incompatible overlaps if the storage format requires it, and they have been modified.
  154. /// This allows unsupported host formats to accept data written to format aliased textures.
  155. /// </summary>
  156. /// <returns>True if data was flushed, false otherwise</returns>
  157. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  158. public bool FlushIncompatibleOverlapsIfNeeded()
  159. {
  160. if (_flushIncompatibleOverlaps && _incompatibleOverlapsDirty)
  161. {
  162. bool flushed = false;
  163. foreach (var overlap in _incompatibleOverlaps)
  164. {
  165. flushed |= overlap.Group.Storage.FlushModified(true);
  166. }
  167. _incompatibleOverlapsDirty = false;
  168. return flushed;
  169. }
  170. else
  171. {
  172. return false;
  173. }
  174. }
  175. /// <summary>
  176. /// Check and optionally consume the dirty flags for a given texture.
  177. /// The state is shared between views of the same layers and levels.
  178. /// </summary>
  179. /// <param name="texture">The texture being used</param>
  180. /// <param name="consume">True to consume the dirty flags and reprotect, false to leave them as is</param>
  181. /// <returns>True if a flag was dirty, false otherwise</returns>
  182. public bool CheckDirty(Texture texture, bool consume)
  183. {
  184. bool dirty = false;
  185. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  186. {
  187. for (int i = 0; i < regionCount; i++)
  188. {
  189. TextureGroupHandle group = _handles[baseHandle + i];
  190. foreach (CpuRegionHandle handle in group.Handles)
  191. {
  192. if (handle.Dirty)
  193. {
  194. if (consume)
  195. {
  196. handle.Reprotect();
  197. }
  198. dirty = true;
  199. }
  200. }
  201. }
  202. });
  203. return dirty;
  204. }
  205. /// <summary>
  206. /// Synchronize memory for a given texture.
  207. /// If overlapping tracking handles are dirty, fully or partially synchronize the texture data.
  208. /// </summary>
  209. /// <param name="texture">The texture being used</param>
  210. public void SynchronizeMemory(Texture texture)
  211. {
  212. FlushIncompatibleOverlapsIfNeeded();
  213. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  214. {
  215. bool dirty = false;
  216. bool anyModified = false;
  217. bool anyUnmapped = false;
  218. for (int i = 0; i < regionCount; i++)
  219. {
  220. TextureGroupHandle group = _handles[baseHandle + i];
  221. bool modified = group.Modified;
  222. bool handleDirty = false;
  223. bool handleUnmapped = false;
  224. foreach (CpuRegionHandle handle in group.Handles)
  225. {
  226. if (handle.Dirty)
  227. {
  228. handle.Reprotect();
  229. handleDirty = true;
  230. }
  231. else
  232. {
  233. handleUnmapped |= handle.Unmapped;
  234. }
  235. }
  236. // If the modified flag is still present, prefer the data written from gpu.
  237. // A write from CPU will do a flush before writing its data, which should unset this.
  238. if (modified)
  239. {
  240. handleDirty = false;
  241. }
  242. // Evaluate if any copy dependencies need to be fulfilled. A few rules:
  243. // If the copy handle needs to be synchronized, prefer our own state.
  244. // If we need to be synchronized and there is a copy present, prefer the copy.
  245. if (group.NeedsCopy && group.Copy(_context))
  246. {
  247. anyModified |= true; // The copy target has been modified.
  248. handleDirty = false;
  249. }
  250. else
  251. {
  252. anyModified |= modified;
  253. dirty |= handleDirty;
  254. }
  255. anyUnmapped |= handleUnmapped;
  256. if (group.NeedsCopy)
  257. {
  258. // The texture we copied from is still being written to. Copy from it again the next time this texture is used.
  259. texture.SignalGroupDirty();
  260. }
  261. _loadNeeded[baseHandle + i] = handleDirty && !handleUnmapped;
  262. }
  263. if (dirty)
  264. {
  265. if (anyUnmapped || (_handles.Length > 1 && (anyModified || split)))
  266. {
  267. // Partial texture invalidation. Only update the layers/levels with dirty flags of the storage.
  268. SynchronizePartial(baseHandle, regionCount);
  269. }
  270. else
  271. {
  272. // Full texture invalidation.
  273. texture.SynchronizeFull();
  274. }
  275. }
  276. });
  277. }
  278. /// <summary>
  279. /// Synchronize part of the storage texture, represented by a given range of handles.
  280. /// Only handles marked by the _loadNeeded array will be synchronized.
  281. /// </summary>
  282. /// <param name="baseHandle">The base index of the range of handles</param>
  283. /// <param name="regionCount">The number of handles to synchronize</param>
  284. private void SynchronizePartial(int baseHandle, int regionCount)
  285. {
  286. for (int i = 0; i < regionCount; i++)
  287. {
  288. if (_loadNeeded[baseHandle + i])
  289. {
  290. var info = GetHandleInformation(baseHandle + i);
  291. // Only one of these will be greater than 1, as partial sync is only called when there are sub-image views.
  292. for (int layer = 0; layer < info.Layers; layer++)
  293. {
  294. for (int level = 0; level < info.Levels; level++)
  295. {
  296. int offsetIndex = GetOffsetIndex(info.BaseLayer + layer, info.BaseLevel + level);
  297. int offset = _allOffsets[offsetIndex];
  298. int endOffset = Math.Min(offset + _sliceSizes[info.BaseLevel + level], (int)Storage.Size);
  299. int size = endOffset - offset;
  300. ReadOnlySpan<byte> data = _physicalMemory.GetSpan(Storage.Range.GetSlice((ulong)offset, (ulong)size));
  301. SpanOrArray<byte> result = Storage.ConvertToHostCompatibleFormat(data, info.BaseLevel + level, true);
  302. Storage.SetData(result, info.BaseLayer + layer, info.BaseLevel + level);
  303. }
  304. }
  305. }
  306. }
  307. }
  308. /// <summary>
  309. /// Synchronize dependent textures, if any of them have deferred a copy from the given texture.
  310. /// </summary>
  311. /// <param name="texture">The texture to synchronize dependents of</param>
  312. public void SynchronizeDependents(Texture texture)
  313. {
  314. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  315. {
  316. for (int i = 0; i < regionCount; i++)
  317. {
  318. TextureGroupHandle group = _handles[baseHandle + i];
  319. group.SynchronizeDependents();
  320. }
  321. });
  322. }
  323. /// <summary>
  324. /// Determines whether flushes in this texture group should be tracked.
  325. /// Incompatible overlaps may need data from this texture to flush tracked for it to be visible to them.
  326. /// </summary>
  327. /// <returns>True if flushes should be tracked, false otherwise</returns>
  328. private bool ShouldFlushTriggerTracking()
  329. {
  330. foreach (var overlap in _incompatibleOverlaps)
  331. {
  332. if (overlap.Group._flushIncompatibleOverlaps)
  333. {
  334. return true;
  335. }
  336. }
  337. return false;
  338. }
  339. /// <summary>
  340. /// Gets data from the host GPU, and flushes a slice to guest memory.
  341. /// </summary>
  342. /// <remarks>
  343. /// This method should be used to retrieve data that was modified by the host GPU.
  344. /// This is not cheap, avoid doing that unless strictly needed.
  345. /// When possible, the data is written directly into guest memory, rather than copied.
  346. /// </remarks>
  347. /// <param name="tracked">True if writing the texture data is tracked, false otherwise</param>
  348. /// <param name="sliceIndex">The index of the slice to flush</param>
  349. /// <param name="texture">The specific host texture to flush. Defaults to the storage texture</param>
  350. private void FlushTextureDataSliceToGuest(bool tracked, int sliceIndex, ITexture texture = null)
  351. {
  352. (int layer, int level) = GetLayerLevelForView(sliceIndex);
  353. int offset = _allOffsets[sliceIndex];
  354. int endOffset = Math.Min(offset + _sliceSizes[level], (int)Storage.Size);
  355. int size = endOffset - offset;
  356. using WritableRegion region = _physicalMemory.GetWritableRegion(Storage.Range.GetSlice((ulong)offset, (ulong)size), tracked);
  357. Storage.GetTextureDataSliceFromGpu(region.Memory.Span, layer, level, tracked, texture);
  358. }
  359. /// <summary>
  360. /// Gets and flushes a number of slices of the storage texture to guest memory.
  361. /// </summary>
  362. /// <param name="tracked">True if writing the texture data is tracked, false otherwise</param>
  363. /// <param name="sliceStart">The first slice to flush</param>
  364. /// <param name="sliceEnd">The slice to finish flushing on (exclusive)</param>
  365. /// <param name="texture">The specific host texture to flush. Defaults to the storage texture</param>
  366. private void FlushSliceRange(bool tracked, int sliceStart, int sliceEnd, ITexture texture = null)
  367. {
  368. for (int i = sliceStart; i < sliceEnd; i++)
  369. {
  370. FlushTextureDataSliceToGuest(tracked, i, texture);
  371. }
  372. }
  373. /// <summary>
  374. /// Flush modified ranges for a given texture.
  375. /// </summary>
  376. /// <param name="texture">The texture being used</param>
  377. /// <param name="tracked">True if the flush writes should be tracked, false otherwise</param>
  378. /// <returns>True if data was flushed, false otherwise</returns>
  379. public bool FlushModified(Texture texture, bool tracked)
  380. {
  381. tracked = tracked || ShouldFlushTriggerTracking();
  382. bool flushed = false;
  383. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  384. {
  385. int startSlice = 0;
  386. int endSlice = 0;
  387. bool allModified = true;
  388. for (int i = 0; i < regionCount; i++)
  389. {
  390. TextureGroupHandle group = _handles[baseHandle + i];
  391. if (group.Modified)
  392. {
  393. if (endSlice < group.BaseSlice)
  394. {
  395. if (endSlice > startSlice)
  396. {
  397. FlushSliceRange(tracked, startSlice, endSlice);
  398. flushed = true;
  399. }
  400. startSlice = group.BaseSlice;
  401. }
  402. endSlice = group.BaseSlice + group.SliceCount;
  403. if (tracked)
  404. {
  405. group.Modified = false;
  406. foreach (Texture texture in group.Overlaps)
  407. {
  408. texture.SignalModifiedDirty();
  409. }
  410. }
  411. }
  412. else
  413. {
  414. allModified = false;
  415. }
  416. }
  417. if (endSlice > startSlice)
  418. {
  419. if (allModified && !split)
  420. {
  421. texture.Flush(tracked);
  422. }
  423. else
  424. {
  425. FlushSliceRange(tracked, startSlice, endSlice);
  426. }
  427. flushed = true;
  428. }
  429. });
  430. Storage.SignalModifiedDirty();
  431. return flushed;
  432. }
  433. /// <summary>
  434. /// Clears competing modified flags for all incompatible ranges, if they have possibly been modified.
  435. /// </summary>
  436. /// <param name="texture">The texture that has been modified</param>
  437. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  438. private void ClearIncompatibleOverlaps(Texture texture)
  439. {
  440. if (_incompatibleOverlapsDirty)
  441. {
  442. foreach (TextureIncompatibleOverlap incompatible in _incompatibleOverlaps)
  443. {
  444. incompatible.Group.ClearModified(texture.Range, this);
  445. incompatible.Group.SignalIncompatibleOverlapModified();
  446. }
  447. _incompatibleOverlapsDirty = false;
  448. }
  449. }
  450. /// <summary>
  451. /// Signal that a texture in the group has been modified by the GPU.
  452. /// </summary>
  453. /// <param name="texture">The texture that has been modified</param>
  454. public void SignalModified(Texture texture)
  455. {
  456. ClearIncompatibleOverlaps(texture);
  457. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  458. {
  459. for (int i = 0; i < regionCount; i++)
  460. {
  461. TextureGroupHandle group = _handles[baseHandle + i];
  462. group.SignalModified(_context);
  463. }
  464. });
  465. }
  466. /// <summary>
  467. /// Signal that a texture in the group is actively bound, or has been unbound by the GPU.
  468. /// </summary>
  469. /// <param name="texture">The texture that has been modified</param>
  470. /// <param name="bound">True if this texture is being bound, false if unbound</param>
  471. public void SignalModifying(Texture texture, bool bound)
  472. {
  473. ClearIncompatibleOverlaps(texture);
  474. EvaluateRelevantHandles(texture, (baseHandle, regionCount, split) =>
  475. {
  476. for (int i = 0; i < regionCount; i++)
  477. {
  478. TextureGroupHandle group = _handles[baseHandle + i];
  479. group.SignalModifying(bound, _context);
  480. }
  481. });
  482. }
  483. /// <summary>
  484. /// Register a read/write action to flush for a texture group.
  485. /// </summary>
  486. /// <param name="group">The group to register an action for</param>
  487. public void RegisterAction(TextureGroupHandle group)
  488. {
  489. foreach (CpuRegionHandle handle in group.Handles)
  490. {
  491. handle.RegisterAction((address, size) => FlushAction(group, address, size));
  492. }
  493. }
  494. /// <summary>
  495. /// Propagates the mip/layer view flags depending on the texture type.
  496. /// When the most granular type of subresource has views, the other type of subresource must be segmented granularly too.
  497. /// </summary>
  498. /// <param name="hasLayerViews">True if the storage has layer views</param>
  499. /// <param name="hasMipViews">True if the storage has mip views</param>
  500. /// <returns>The input values after propagation</returns>
  501. private (bool HasLayerViews, bool HasMipViews) PropagateGranularity(bool hasLayerViews, bool hasMipViews)
  502. {
  503. if (_is3D)
  504. {
  505. hasMipViews |= hasLayerViews;
  506. }
  507. else
  508. {
  509. hasLayerViews |= hasMipViews;
  510. }
  511. return (hasLayerViews, hasMipViews);
  512. }
  513. /// <summary>
  514. /// Evaluate the range of tracking handles which a view texture overlaps with.
  515. /// </summary>
  516. /// <param name="texture">The texture to get handles for</param>
  517. /// <param name="callback">
  518. /// 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.
  519. /// This can be called for multiple disjoint ranges, if required.
  520. /// </param>
  521. private void EvaluateRelevantHandles(Texture texture, HandlesCallbackDelegate callback)
  522. {
  523. if (texture == Storage || !(_hasMipViews || _hasLayerViews))
  524. {
  525. callback(0, _handles.Length);
  526. return;
  527. }
  528. EvaluateRelevantHandles(texture.FirstLayer, texture.FirstLevel, texture.Info.GetSlices(), texture.Info.Levels, callback);
  529. }
  530. /// <summary>
  531. /// Evaluate the range of tracking handles which a view texture overlaps with,
  532. /// using the view's position and slice/level counts.
  533. /// </summary>
  534. /// <param name="firstLayer">The first layer of the texture</param>
  535. /// <param name="firstLevel">The first level of the texture</param>
  536. /// <param name="slices">The slice count of the texture</param>
  537. /// <param name="levels">The level count of the texture</param>
  538. /// <param name="callback">
  539. /// 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.
  540. /// This can be called for multiple disjoint ranges, if required.
  541. /// </param>
  542. private void EvaluateRelevantHandles(int firstLayer, int firstLevel, int slices, int levels, HandlesCallbackDelegate callback)
  543. {
  544. int targetLayerHandles = _hasLayerViews ? slices : 1;
  545. int targetLevelHandles = _hasMipViews ? levels : 1;
  546. if (_is3D)
  547. {
  548. // Future mip levels come after all layers of the last mip level. Each mipmap has less layers (depth) than the last.
  549. if (!_hasLayerViews)
  550. {
  551. // When there are no layer views, the mips are at a consistent offset.
  552. callback(firstLevel, targetLevelHandles);
  553. }
  554. else
  555. {
  556. (int levelIndex, int layerCount) = Get3DLevelRange(firstLevel);
  557. if (levels > 1 && slices < _layers)
  558. {
  559. // The given texture only covers some of the depth of multiple mips. (a "depth slice")
  560. // Callback with each mip's range separately.
  561. // Can assume that the group is fully subdivided (both slices and levels > 1 for storage)
  562. while (levels-- > 1)
  563. {
  564. callback(firstLayer + levelIndex, slices);
  565. levelIndex += layerCount;
  566. layerCount = Math.Max(layerCount >> 1, 1);
  567. slices = Math.Max(layerCount >> 1, 1);
  568. }
  569. }
  570. else
  571. {
  572. int totalSize = Math.Min(layerCount, slices);
  573. while (levels-- > 1)
  574. {
  575. layerCount = Math.Max(layerCount >> 1, 1);
  576. totalSize += layerCount;
  577. }
  578. callback(firstLayer + levelIndex, totalSize);
  579. }
  580. }
  581. }
  582. else
  583. {
  584. // Future layers come after all mipmaps of the last.
  585. int levelHandles = _hasMipViews ? _levels : 1;
  586. if (slices > 1 && levels < _levels)
  587. {
  588. // The given texture only covers some of the mipmaps of multiple slices. (a "mip slice")
  589. // Callback with each layer's range separately.
  590. // Can assume that the group is fully subdivided (both slices and levels > 1 for storage)
  591. for (int i = 0; i < slices; i++)
  592. {
  593. callback(firstLevel + (firstLayer + i) * levelHandles, targetLevelHandles, true);
  594. }
  595. }
  596. else
  597. {
  598. callback(firstLevel + firstLayer * levelHandles, targetLevelHandles + (targetLayerHandles - 1) * levelHandles);
  599. }
  600. }
  601. }
  602. /// <summary>
  603. /// Get the range of offsets for a given mip level of a 3D texture.
  604. /// </summary>
  605. /// <param name="level">The level to return</param>
  606. /// <returns>Start index and count of offsets for the given level</returns>
  607. private (int Index, int Count) Get3DLevelRange(int level)
  608. {
  609. int index = 0;
  610. int count = _layers; // Depth. Halves with each mip level.
  611. while (level-- > 0)
  612. {
  613. index += count;
  614. count = Math.Max(count >> 1, 1);
  615. }
  616. return (index, count);
  617. }
  618. /// <summary>
  619. /// Get view information for a single tracking handle.
  620. /// </summary>
  621. /// <param name="handleIndex">The index of the handle</param>
  622. /// <returns>The layers and levels that the handle covers, and its index in the offsets array</returns>
  623. private (int BaseLayer, int BaseLevel, int Levels, int Layers, int Index) GetHandleInformation(int handleIndex)
  624. {
  625. int baseLayer;
  626. int baseLevel;
  627. int levels = _hasMipViews ? 1 : _levels;
  628. int layers = _hasLayerViews ? 1 : _layers;
  629. int index;
  630. if (_is3D)
  631. {
  632. if (_hasLayerViews)
  633. {
  634. // NOTE: Will also have mip views, or only one level in storage.
  635. index = handleIndex;
  636. baseLevel = 0;
  637. int levelLayers = _layers;
  638. while (handleIndex >= levelLayers)
  639. {
  640. handleIndex -= levelLayers;
  641. baseLevel++;
  642. levelLayers = Math.Max(levelLayers >> 1, 1);
  643. }
  644. baseLayer = handleIndex;
  645. }
  646. else
  647. {
  648. baseLayer = 0;
  649. baseLevel = handleIndex;
  650. (index, _) = Get3DLevelRange(baseLevel);
  651. }
  652. }
  653. else
  654. {
  655. baseLevel = _hasMipViews ? handleIndex % _levels : 0;
  656. baseLayer = _hasMipViews ? handleIndex / _levels : handleIndex;
  657. index = baseLevel + baseLayer * _levels;
  658. }
  659. return (baseLayer, baseLevel, levels, layers, index);
  660. }
  661. /// <summary>
  662. /// Gets the layer and level for a given view.
  663. /// </summary>
  664. /// <param name="index">The index of the view</param>
  665. /// <returns>The layer and level of the specified view</returns>
  666. private (int BaseLayer, int BaseLevel) GetLayerLevelForView(int index)
  667. {
  668. if (_is3D)
  669. {
  670. int baseLevel = 0;
  671. int levelLayers = _layers;
  672. while (index >= levelLayers)
  673. {
  674. index -= levelLayers;
  675. baseLevel++;
  676. levelLayers = Math.Max(levelLayers >> 1, 1);
  677. }
  678. return (index, baseLevel);
  679. }
  680. else
  681. {
  682. return (index / _levels, index % _levels);
  683. }
  684. }
  685. /// <summary>
  686. /// Find the byte offset of a given texture relative to the storage.
  687. /// </summary>
  688. /// <param name="texture">The texture to locate</param>
  689. /// <returns>The offset of the texture in bytes</returns>
  690. public int FindOffset(Texture texture)
  691. {
  692. return _allOffsets[GetOffsetIndex(texture.FirstLayer, texture.FirstLevel)];
  693. }
  694. /// <summary>
  695. /// Find the offset index of a given layer and level.
  696. /// </summary>
  697. /// <param name="layer">The view layer</param>
  698. /// <param name="level">The view level</param>
  699. /// <returns>The offset index of the given layer and level</returns>
  700. public int GetOffsetIndex(int layer, int level)
  701. {
  702. if (_is3D)
  703. {
  704. return layer + Get3DLevelRange(level).Index;
  705. }
  706. else
  707. {
  708. return level + layer * _levels;
  709. }
  710. }
  711. /// <summary>
  712. /// The action to perform when a memory tracking handle is flipped to dirty.
  713. /// This notifies overlapping textures that the memory needs to be synchronized.
  714. /// </summary>
  715. /// <param name="groupHandle">The handle that a dirty flag was set on</param>
  716. private void DirtyAction(TextureGroupHandle groupHandle)
  717. {
  718. // Notify all textures that belong to this handle.
  719. Storage.SignalGroupDirty();
  720. lock (groupHandle.Overlaps)
  721. {
  722. foreach (Texture overlap in groupHandle.Overlaps)
  723. {
  724. overlap.SignalGroupDirty();
  725. }
  726. }
  727. }
  728. /// <summary>
  729. /// Generate a CpuRegionHandle for a given address and size range in CPU VA.
  730. /// </summary>
  731. /// <param name="address">The start address of the tracked region</param>
  732. /// <param name="size">The size of the tracked region</param>
  733. /// <returns>A CpuRegionHandle covering the given range</returns>
  734. private CpuRegionHandle GenerateHandle(ulong address, ulong size)
  735. {
  736. return _physicalMemory.BeginTracking(address, size, ResourceKind.Texture);
  737. }
  738. /// <summary>
  739. /// Generate a TextureGroupHandle covering a specified range of views.
  740. /// </summary>
  741. /// <param name="viewStart">The start view of the handle</param>
  742. /// <param name="views">The number of views to cover</param>
  743. /// <returns>A TextureGroupHandle covering the given views</returns>
  744. private TextureGroupHandle GenerateHandles(int viewStart, int views)
  745. {
  746. int offset = _allOffsets[viewStart];
  747. int endOffset = (viewStart + views == _allOffsets.Length) ? (int)Storage.Size : _allOffsets[viewStart + views];
  748. int size = endOffset - offset;
  749. var result = new List<CpuRegionHandle>();
  750. for (int i = 0; i < TextureRange.Count; i++)
  751. {
  752. MemoryRange item = TextureRange.GetSubRange(i);
  753. int subRangeSize = (int)item.Size;
  754. int sliceStart = Math.Clamp(offset, 0, subRangeSize);
  755. int sliceEnd = Math.Clamp(endOffset, 0, subRangeSize);
  756. if (sliceStart != sliceEnd && item.Address != MemoryManager.PteUnmapped)
  757. {
  758. result.Add(GenerateHandle(item.Address + (ulong)sliceStart, (ulong)(sliceEnd - sliceStart)));
  759. }
  760. offset -= subRangeSize;
  761. endOffset -= subRangeSize;
  762. if (endOffset <= 0)
  763. {
  764. break;
  765. }
  766. }
  767. (int firstLayer, int firstLevel) = GetLayerLevelForView(viewStart);
  768. if (_hasLayerViews && _hasMipViews)
  769. {
  770. size = _sliceSizes[firstLevel];
  771. }
  772. offset = _allOffsets[viewStart];
  773. ulong maxSize = Storage.Size - (ulong)offset;
  774. var groupHandle = new TextureGroupHandle(
  775. this,
  776. offset,
  777. Math.Min(maxSize, (ulong)size),
  778. _views,
  779. firstLayer,
  780. firstLevel,
  781. viewStart,
  782. views,
  783. result.ToArray());
  784. foreach (CpuRegionHandle handle in result)
  785. {
  786. handle.RegisterDirtyEvent(() => DirtyAction(groupHandle));
  787. }
  788. return groupHandle;
  789. }
  790. /// <summary>
  791. /// Update the views in this texture group, rebuilding the memory tracking if required.
  792. /// </summary>
  793. /// <param name="views">The views list of the storage texture</param>
  794. public void UpdateViews(List<Texture> views)
  795. {
  796. // This is saved to calculate overlapping views for each handle.
  797. _views = views;
  798. bool layerViews = _hasLayerViews;
  799. bool mipViews = _hasMipViews;
  800. bool regionsRebuilt = false;
  801. if (!(layerViews && mipViews))
  802. {
  803. foreach (Texture view in views)
  804. {
  805. if (view.Info.GetSlices() < _layers)
  806. {
  807. layerViews = true;
  808. }
  809. if (view.Info.Levels < _levels)
  810. {
  811. mipViews = true;
  812. }
  813. }
  814. (layerViews, mipViews) = PropagateGranularity(layerViews, mipViews);
  815. if (layerViews != _hasLayerViews || mipViews != _hasMipViews)
  816. {
  817. _hasLayerViews = layerViews;
  818. _hasMipViews = mipViews;
  819. RecalculateHandleRegions();
  820. regionsRebuilt = true;
  821. }
  822. }
  823. if (!regionsRebuilt)
  824. {
  825. // Must update the overlapping views on all handles, but only if they were not just recreated.
  826. foreach (TextureGroupHandle handle in _handles)
  827. {
  828. handle.RecalculateOverlaps(this, views);
  829. }
  830. }
  831. SignalAllDirty();
  832. }
  833. /// <summary>
  834. /// Inherit handle state from an old set of handles, such as modified and dirty flags.
  835. /// </summary>
  836. /// <param name="oldHandles">The set of handles to inherit state from</param>
  837. /// <param name="handles">The set of handles inheriting the state</param>
  838. /// <param name="relativeOffset">The offset of the old handles in relation to the new ones</param>
  839. private void InheritHandles(TextureGroupHandle[] oldHandles, TextureGroupHandle[] handles, int relativeOffset)
  840. {
  841. foreach (var group in handles)
  842. {
  843. foreach (var handle in group.Handles)
  844. {
  845. bool dirty = false;
  846. foreach (var oldGroup in oldHandles)
  847. {
  848. if (group.OverlapsWith(oldGroup.Offset + relativeOffset, oldGroup.Size))
  849. {
  850. foreach (var oldHandle in oldGroup.Handles)
  851. {
  852. if (handle.OverlapsWith(oldHandle.Address, oldHandle.Size))
  853. {
  854. dirty |= oldHandle.Dirty;
  855. }
  856. }
  857. group.Inherit(oldGroup, group.Offset == oldGroup.Offset + relativeOffset);
  858. }
  859. }
  860. if (dirty && !handle.Dirty)
  861. {
  862. handle.Reprotect(true);
  863. }
  864. if (group.Modified)
  865. {
  866. handle.RegisterAction((address, size) => FlushAction(group, address, size));
  867. }
  868. }
  869. }
  870. foreach (var oldGroup in oldHandles)
  871. {
  872. oldGroup.Modified = false;
  873. }
  874. }
  875. /// <summary>
  876. /// Inherit state from another texture group.
  877. /// </summary>
  878. /// <param name="other">The texture group to inherit from</param>
  879. public void Inherit(TextureGroup other)
  880. {
  881. bool layerViews = _hasLayerViews || other._hasLayerViews;
  882. bool mipViews = _hasMipViews || other._hasMipViews;
  883. if (layerViews != _hasLayerViews || mipViews != _hasMipViews)
  884. {
  885. _hasLayerViews = layerViews;
  886. _hasMipViews = mipViews;
  887. RecalculateHandleRegions();
  888. }
  889. foreach (TextureIncompatibleOverlap incompatible in other._incompatibleOverlaps)
  890. {
  891. RegisterIncompatibleOverlap(incompatible, false);
  892. incompatible.Group._incompatibleOverlaps.RemoveAll(overlap => overlap.Group == other);
  893. }
  894. int relativeOffset = Storage.Range.FindOffset(other.Storage.Range);
  895. InheritHandles(other._handles, _handles, relativeOffset);
  896. }
  897. /// <summary>
  898. /// Replace the current handles with the new handles. It is assumed that the new handles start dirty.
  899. /// The dirty flags from the previous handles will be kept.
  900. /// </summary>
  901. /// <param name="handles">The handles to replace the current handles with</param>
  902. private void ReplaceHandles(TextureGroupHandle[] handles)
  903. {
  904. if (_handles != null)
  905. {
  906. // When replacing handles, they should start as non-dirty.
  907. foreach (TextureGroupHandle groupHandle in handles)
  908. {
  909. foreach (CpuRegionHandle handle in groupHandle.Handles)
  910. {
  911. handle.Reprotect();
  912. }
  913. }
  914. InheritHandles(_handles, handles, 0);
  915. foreach (var oldGroup in _handles)
  916. {
  917. foreach (var oldHandle in oldGroup.Handles)
  918. {
  919. oldHandle.Dispose();
  920. }
  921. }
  922. }
  923. _handles = handles;
  924. _loadNeeded = new bool[_handles.Length];
  925. }
  926. /// <summary>
  927. /// Recalculate handle regions for this texture group, and inherit existing state into the new handles.
  928. /// </summary>
  929. private void RecalculateHandleRegions()
  930. {
  931. TextureGroupHandle[] handles;
  932. if (!(_hasMipViews || _hasLayerViews))
  933. {
  934. // Single dirty region.
  935. var cpuRegionHandles = new CpuRegionHandle[TextureRange.Count];
  936. int count = 0;
  937. for (int i = 0; i < TextureRange.Count; i++)
  938. {
  939. var currentRange = TextureRange.GetSubRange(i);
  940. if (currentRange.Address != MemoryManager.PteUnmapped)
  941. {
  942. cpuRegionHandles[count++] = GenerateHandle(currentRange.Address, currentRange.Size);
  943. }
  944. }
  945. if (count != TextureRange.Count)
  946. {
  947. Array.Resize(ref cpuRegionHandles, count);
  948. }
  949. var groupHandle = new TextureGroupHandle(this, 0, Storage.Size, _views, 0, 0, 0, _allOffsets.Length, cpuRegionHandles);
  950. foreach (CpuRegionHandle handle in cpuRegionHandles)
  951. {
  952. handle.RegisterDirtyEvent(() => DirtyAction(groupHandle));
  953. }
  954. handles = new TextureGroupHandle[] { groupHandle };
  955. }
  956. else
  957. {
  958. // Get views for the host texture.
  959. // 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.
  960. // Depending on if the texture is 3d, either the mip views imply that layer views are present (2d) or the other way around (3d).
  961. // This is enforced by the way the texture matched as a view, so we don't need to check.
  962. int layerHandles = _hasLayerViews ? _layers : 1;
  963. int levelHandles = _hasMipViews ? _levels : 1;
  964. int handleIndex = 0;
  965. if (_is3D)
  966. {
  967. var handlesList = new List<TextureGroupHandle>();
  968. for (int i = 0; i < levelHandles; i++)
  969. {
  970. for (int j = 0; j < layerHandles; j++)
  971. {
  972. (int viewStart, int views) = Get3DLevelRange(i);
  973. viewStart += j;
  974. views = _hasLayerViews ? 1 : views; // A layer view is also a mip view.
  975. handlesList.Add(GenerateHandles(viewStart, views));
  976. }
  977. layerHandles = Math.Max(1, layerHandles >> 1);
  978. }
  979. handles = handlesList.ToArray();
  980. }
  981. else
  982. {
  983. handles = new TextureGroupHandle[layerHandles * levelHandles];
  984. for (int i = 0; i < layerHandles; i++)
  985. {
  986. for (int j = 0; j < levelHandles; j++)
  987. {
  988. int viewStart = j + i * _levels;
  989. int views = _hasMipViews ? 1 : _levels; // A mip view is also a layer view.
  990. handles[handleIndex++] = GenerateHandles(viewStart, views);
  991. }
  992. }
  993. }
  994. }
  995. ReplaceHandles(handles);
  996. }
  997. /// <summary>
  998. /// Ensure that there is a handle for each potential texture view. Required for copy dependencies to work.
  999. /// </summary>
  1000. private void EnsureFullSubdivision()
  1001. {
  1002. if (!(_hasLayerViews && _hasMipViews))
  1003. {
  1004. _hasLayerViews = true;
  1005. _hasMipViews = true;
  1006. RecalculateHandleRegions();
  1007. }
  1008. }
  1009. /// <summary>
  1010. /// Create a copy dependency between this texture group, and a texture at a given layer/level offset.
  1011. /// </summary>
  1012. /// <param name="other">The view compatible texture to create a dependency to</param>
  1013. /// <param name="firstLayer">The base layer of the given texture relative to the storage</param>
  1014. /// <param name="firstLevel">The base level of the given texture relative to the storage</param>
  1015. /// <param name="copyTo">True if this texture is first copied to the given one, false for the opposite direction</param>
  1016. public void CreateCopyDependency(Texture other, int firstLayer, int firstLevel, bool copyTo)
  1017. {
  1018. TextureGroup otherGroup = other.Group;
  1019. EnsureFullSubdivision();
  1020. otherGroup.EnsureFullSubdivision();
  1021. // Get the location of each texture within its storage, so we can find the handles to apply the dependency to.
  1022. // This can consist of multiple disjoint regions, for example if this is a mip slice of an array texture.
  1023. var targetRange = new List<(int BaseHandle, int RegionCount)>();
  1024. var otherRange = new List<(int BaseHandle, int RegionCount)>();
  1025. EvaluateRelevantHandles(firstLayer, firstLevel, other.Info.GetSlices(), other.Info.Levels, (baseHandle, regionCount, split) => targetRange.Add((baseHandle, regionCount)));
  1026. otherGroup.EvaluateRelevantHandles(other, (baseHandle, regionCount, split) => otherRange.Add((baseHandle, regionCount)));
  1027. int targetIndex = 0;
  1028. int otherIndex = 0;
  1029. (int Handle, int RegionCount) targetRegion = (0, 0);
  1030. (int Handle, int RegionCount) otherRegion = (0, 0);
  1031. while (true)
  1032. {
  1033. if (targetRegion.RegionCount == 0)
  1034. {
  1035. if (targetIndex >= targetRange.Count)
  1036. {
  1037. break;
  1038. }
  1039. targetRegion = targetRange[targetIndex++];
  1040. }
  1041. if (otherRegion.RegionCount == 0)
  1042. {
  1043. if (otherIndex >= otherRange.Count)
  1044. {
  1045. break;
  1046. }
  1047. otherRegion = otherRange[otherIndex++];
  1048. }
  1049. TextureGroupHandle handle = _handles[targetRegion.Handle++];
  1050. TextureGroupHandle otherHandle = other.Group._handles[otherRegion.Handle++];
  1051. targetRegion.RegionCount--;
  1052. otherRegion.RegionCount--;
  1053. handle.CreateCopyDependency(otherHandle, copyTo);
  1054. // If "copyTo" is true, this texture must copy to the other.
  1055. // Otherwise, it must copy to this texture.
  1056. if (copyTo)
  1057. {
  1058. otherHandle.Copy(_context, handle);
  1059. }
  1060. else
  1061. {
  1062. handle.Copy(_context, otherHandle);
  1063. }
  1064. }
  1065. }
  1066. /// <summary>
  1067. /// Creates a copy dependency to another texture group, where handles overlap.
  1068. /// Scans through all handles to find compatible patches in the other group.
  1069. /// </summary>
  1070. /// <param name="other">The texture group that overlaps this one</param>
  1071. /// <param name="copyTo">True if this texture is first copied to the given one, false for the opposite direction</param>
  1072. public void CreateCopyDependency(TextureGroup other, bool copyTo)
  1073. {
  1074. for (int i = 0; i < _allOffsets.Length; i++)
  1075. {
  1076. (int layer, int level) = GetLayerLevelForView(i);
  1077. MultiRange handleRange = Storage.Range.GetSlice((ulong)_allOffsets[i], 1);
  1078. ulong handleBase = handleRange.GetSubRange(0).Address;
  1079. for (int j = 0; j < other._handles.Length; j++)
  1080. {
  1081. (int otherLayer, int otherLevel) = other.GetLayerLevelForView(j);
  1082. MultiRange otherHandleRange = other.Storage.Range.GetSlice((ulong)other._allOffsets[j], 1);
  1083. ulong otherHandleBase = otherHandleRange.GetSubRange(0).Address;
  1084. if (handleBase == otherHandleBase)
  1085. {
  1086. // Check if the two sizes are compatible.
  1087. TextureInfo info = Storage.Info;
  1088. TextureInfo otherInfo = other.Storage.Info;
  1089. if (TextureCompatibility.ViewLayoutCompatible(info, otherInfo, level, otherLevel) &&
  1090. TextureCompatibility.CopySizeMatches(info, otherInfo, level, otherLevel))
  1091. {
  1092. // These textures are copy compatible. Create the dependency.
  1093. EnsureFullSubdivision();
  1094. other.EnsureFullSubdivision();
  1095. TextureGroupHandle handle = _handles[i];
  1096. TextureGroupHandle otherHandle = other._handles[j];
  1097. handle.CreateCopyDependency(otherHandle, copyTo);
  1098. // If "copyTo" is true, this texture must copy to the other.
  1099. // Otherwise, it must copy to this texture.
  1100. if (copyTo)
  1101. {
  1102. otherHandle.Copy(_context, handle);
  1103. }
  1104. else
  1105. {
  1106. handle.Copy(_context, otherHandle);
  1107. }
  1108. }
  1109. }
  1110. }
  1111. }
  1112. }
  1113. /// <summary>
  1114. /// Registers another texture group as an incompatible overlap, if not already registered.
  1115. /// </summary>
  1116. /// <param name="other">The texture group to add to the incompatible overlaps list</param>
  1117. /// <param name="copy">True if the overlap should register copy dependencies</param>
  1118. public void RegisterIncompatibleOverlap(TextureIncompatibleOverlap other, bool copy)
  1119. {
  1120. if (!_incompatibleOverlaps.Exists(overlap => overlap.Group == other.Group))
  1121. {
  1122. if (copy && other.Compatibility == TextureViewCompatibility.LayoutIncompatible)
  1123. {
  1124. // Any of the group's views may share compatibility, even if the parents do not fully.
  1125. CreateCopyDependency(other.Group, false);
  1126. }
  1127. _incompatibleOverlaps.Add(other);
  1128. other.Group._incompatibleOverlaps.Add(new TextureIncompatibleOverlap(this, other.Compatibility));
  1129. }
  1130. other.Group.SignalIncompatibleOverlapModified();
  1131. SignalIncompatibleOverlapModified();
  1132. }
  1133. /// <summary>
  1134. /// Clear modified flags in the given range.
  1135. /// This will stop any GPU written data from flushing or copying to dependent textures.
  1136. /// </summary>
  1137. /// <param name="range">The range to clear modified flags in</param>
  1138. /// <param name="ignore">Ignore handles that have a copy dependency to the specified group</param>
  1139. public void ClearModified(MultiRange range, TextureGroup ignore = null)
  1140. {
  1141. TextureGroupHandle[] handles = _handles;
  1142. foreach (TextureGroupHandle handle in handles)
  1143. {
  1144. // Handles list is not modified by another thread, only replaced, so this is thread safe.
  1145. // Remove modified flags from all overlapping handles, so that the textures don't flush to unmapped/remapped GPU memory.
  1146. MultiRange subRange = Storage.Range.GetSlice((ulong)handle.Offset, (ulong)handle.Size);
  1147. if (range.OverlapsWith(subRange))
  1148. {
  1149. if ((ignore == null || !handle.HasDependencyTo(ignore)) && handle.Modified)
  1150. {
  1151. handle.Modified = false;
  1152. Storage.SignalModifiedDirty();
  1153. lock (handle.Overlaps)
  1154. {
  1155. foreach (Texture texture in handle.Overlaps)
  1156. {
  1157. texture.SignalModifiedDirty();
  1158. }
  1159. }
  1160. }
  1161. }
  1162. }
  1163. Storage.SignalModifiedDirty();
  1164. if (_views != null)
  1165. {
  1166. foreach (Texture texture in _views)
  1167. {
  1168. texture.SignalModifiedDirty();
  1169. }
  1170. }
  1171. }
  1172. /// <summary>
  1173. /// A flush has been requested on a tracked region. Flush texture data for the given handle.
  1174. /// </summary>
  1175. /// <param name="handle">The handle this flush action is for</param>
  1176. /// <param name="address">The address of the flushing memory access</param>
  1177. /// <param name="size">The size of the flushing memory access</param>
  1178. public void FlushAction(TextureGroupHandle handle, ulong address, ulong size)
  1179. {
  1180. // If the page size is larger than 4KB, we will have a lot of false positives for flushing.
  1181. // Let's avoid flushing textures that are unlikely to be read from CPU to improve performance
  1182. // on those platforms.
  1183. if (!_physicalMemory.Supports4KBPages && !Storage.Info.IsLinear && !_context.IsGpuThread())
  1184. {
  1185. return;
  1186. }
  1187. // There is a small gap here where the action is removed but _actionRegistered is still 1.
  1188. // In this case it will skip registering the action, but here we are already handling it,
  1189. // so there shouldn't be any issue as it's the same handler for all actions.
  1190. handle.ClearActionRegistered();
  1191. if (!handle.Modified)
  1192. {
  1193. return;
  1194. }
  1195. bool isGpuThread = _context.IsGpuThread();
  1196. if (isGpuThread)
  1197. {
  1198. // No need to wait if we're on the GPU thread, we can just clear the modified flag immediately.
  1199. handle.Modified = false;
  1200. }
  1201. _context.Renderer.BackgroundContextAction(() =>
  1202. {
  1203. if (!isGpuThread)
  1204. {
  1205. handle.Sync(_context);
  1206. }
  1207. Storage.SignalModifiedDirty();
  1208. lock (handle.Overlaps)
  1209. {
  1210. foreach (Texture texture in handle.Overlaps)
  1211. {
  1212. texture.SignalModifiedDirty();
  1213. }
  1214. }
  1215. if (TextureCompatibility.CanTextureFlush(Storage.Info, _context.Capabilities))
  1216. {
  1217. FlushSliceRange(false, handle.BaseSlice, handle.BaseSlice + handle.SliceCount, Storage.GetFlushTexture());
  1218. }
  1219. });
  1220. }
  1221. /// <summary>
  1222. /// Dispose this texture group, disposing all related memory tracking handles.
  1223. /// </summary>
  1224. public void Dispose()
  1225. {
  1226. foreach (TextureGroupHandle group in _handles)
  1227. {
  1228. group.Dispose();
  1229. }
  1230. foreach (TextureIncompatibleOverlap incompatible in _incompatibleOverlaps)
  1231. {
  1232. incompatible.Group._incompatibleOverlaps.RemoveAll(overlap => overlap.Group == this);
  1233. }
  1234. }
  1235. }
  1236. }