TextureGroupHandle.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. using Ryujinx.Cpu.Tracking;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading;
  6. namespace Ryujinx.Graphics.Gpu.Image
  7. {
  8. /// <summary>
  9. /// A tracking handle for a texture group, which represents a range of views in a storage texture.
  10. /// Retains a list of overlapping texture views, a modified flag, and tracking for each
  11. /// CPU VA range that the views cover.
  12. /// Also tracks copy dependencies for the handle - references to other handles that must be kept
  13. /// in sync with this one before use.
  14. /// </summary>
  15. class TextureGroupHandle : IDisposable
  16. {
  17. private TextureGroup _group;
  18. private int _bindCount;
  19. private int _firstLevel;
  20. private int _firstLayer;
  21. // Sync state for texture flush.
  22. /// <summary>
  23. /// The sync number last registered.
  24. /// </summary>
  25. private ulong _registeredSync;
  26. /// <summary>
  27. /// The sync number when the texture was last modified by GPU.
  28. /// </summary>
  29. private ulong _modifiedSync;
  30. /// <summary>
  31. /// Whether a tracking action is currently registered or not. (0/1)
  32. /// </summary>
  33. private int _actionRegistered;
  34. /// <summary>
  35. /// Whether a sync action is currently registered or not.
  36. /// </summary>
  37. private bool _syncActionRegistered;
  38. /// <summary>
  39. /// The byte offset from the start of the storage of this handle.
  40. /// </summary>
  41. public int Offset { get; }
  42. /// <summary>
  43. /// The size in bytes covered by this handle.
  44. /// </summary>
  45. public int Size { get; }
  46. /// <summary>
  47. /// The base slice index for this handle.
  48. /// </summary>
  49. public int BaseSlice { get; }
  50. /// <summary>
  51. /// The number of slices covered by this handle.
  52. /// </summary>
  53. public int SliceCount { get; }
  54. /// <summary>
  55. /// The textures which this handle overlaps with.
  56. /// </summary>
  57. public List<Texture> Overlaps { get; }
  58. /// <summary>
  59. /// The CPU memory tracking handles that cover this handle.
  60. /// </summary>
  61. public CpuRegionHandle[] Handles { get; }
  62. /// <summary>
  63. /// True if a texture overlapping this handle has been modified. Is set false when the flush action is called.
  64. /// </summary>
  65. public bool Modified { get; set; }
  66. /// <summary>
  67. /// Dependencies to handles from other texture groups.
  68. /// </summary>
  69. public List<TextureDependency> Dependencies { get; }
  70. /// <summary>
  71. /// A flag indicating that a copy is required from one of the dependencies.
  72. /// </summary>
  73. public bool NeedsCopy => DeferredCopy != null;
  74. /// <summary>
  75. /// A data copy that must be acknowledged the next time this handle is used.
  76. /// </summary>
  77. public TextureGroupHandle DeferredCopy { get; set; }
  78. /// <summary>
  79. /// Create a new texture group handle, representing a range of views in a storage texture.
  80. /// </summary>
  81. /// <param name="group">The TextureGroup that the handle belongs to</param>
  82. /// <param name="offset">The byte offset from the start of the storage of the handle</param>
  83. /// <param name="size">The size in bytes covered by the handle</param>
  84. /// <param name="views">All views of the storage texture, used to calculate overlaps</param>
  85. /// <param name="firstLayer">The first layer of this handle in the storage texture</param>
  86. /// <param name="firstLevel">The first level of this handle in the storage texture</param>
  87. /// <param name="baseSlice">The base slice index of this handle</param>
  88. /// <param name="sliceCount">The number of slices this handle covers</param>
  89. /// <param name="handles">The memory tracking handles that cover this handle</param>
  90. public TextureGroupHandle(TextureGroup group,
  91. int offset,
  92. ulong size,
  93. List<Texture> views,
  94. int firstLayer,
  95. int firstLevel,
  96. int baseSlice,
  97. int sliceCount,
  98. CpuRegionHandle[] handles)
  99. {
  100. _group = group;
  101. _firstLayer = firstLayer;
  102. _firstLevel = firstLevel;
  103. Offset = offset;
  104. Size = (int)size;
  105. Overlaps = new List<Texture>();
  106. Dependencies = new List<TextureDependency>();
  107. BaseSlice = baseSlice;
  108. SliceCount = sliceCount;
  109. if (views != null)
  110. {
  111. RecalculateOverlaps(group, views);
  112. }
  113. Handles = handles;
  114. }
  115. /// <summary>
  116. /// Calculate a list of which views overlap this handle.
  117. /// </summary>
  118. /// <param name="group">The parent texture group, used to find a view's base CPU VA offset</param>
  119. /// <param name="views">The list of views to search for overlaps</param>
  120. public void RecalculateOverlaps(TextureGroup group, List<Texture> views)
  121. {
  122. // Overlaps can be accessed from the memory tracking signal handler, so access must be atomic.
  123. lock (Overlaps)
  124. {
  125. int endOffset = Offset + Size;
  126. Overlaps.Clear();
  127. foreach (Texture view in views)
  128. {
  129. int viewOffset = group.FindOffset(view);
  130. if (viewOffset < endOffset && Offset < viewOffset + (int)view.Size)
  131. {
  132. Overlaps.Add(view);
  133. }
  134. }
  135. }
  136. }
  137. /// <summary>
  138. /// Registers a sync action to happen for this handle, and an interim flush action on the tracking handle.
  139. /// </summary>
  140. /// <param name="context">The GPU context to register a sync action on</param>
  141. private void RegisterSync(GpuContext context)
  142. {
  143. if (!_syncActionRegistered)
  144. {
  145. _modifiedSync = context.SyncNumber;
  146. context.RegisterSyncAction(SyncAction, true);
  147. _syncActionRegistered = true;
  148. }
  149. if (Interlocked.Exchange(ref _actionRegistered, 1) == 0)
  150. {
  151. _group.RegisterAction(this);
  152. }
  153. }
  154. /// <summary>
  155. /// Signal that this handle has been modified to any existing dependencies, and set the modified flag.
  156. /// </summary>
  157. /// <param name="context">The GPU context to register a sync action on</param>
  158. public void SignalModified(GpuContext context)
  159. {
  160. Modified = true;
  161. // If this handle has any copy dependencies, notify the other handle that a copy needs to be performed.
  162. foreach (TextureDependency dependency in Dependencies)
  163. {
  164. dependency.SignalModified();
  165. }
  166. RegisterSync(context);
  167. }
  168. /// <summary>
  169. /// Signal that this handle has either started or ended being modified.
  170. /// </summary>
  171. /// <param name="bound">True if this handle is being bound, false if unbound</param>
  172. /// <param name="context">The GPU context to register a sync action on</param>
  173. public void SignalModifying(bool bound, GpuContext context)
  174. {
  175. SignalModified(context);
  176. // Note: Bind count currently resets to 0 on inherit for safety, as the handle <-> view relationship can change.
  177. _bindCount = Math.Max(0, _bindCount + (bound ? 1 : -1));
  178. }
  179. /// <summary>
  180. /// Synchronize dependent textures, if any of them have deferred a copy from this texture.
  181. /// </summary>
  182. public void SynchronizeDependents()
  183. {
  184. foreach (TextureDependency dependency in Dependencies)
  185. {
  186. TextureGroupHandle otherHandle = dependency.Other.Handle;
  187. if (otherHandle.DeferredCopy == this)
  188. {
  189. otherHandle._group.Storage.SynchronizeMemory();
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// Wait for the latest sync number that the texture handle was written to,
  195. /// removing the modified flag if it was reached, or leaving it set if it has not yet been created.
  196. /// </summary>
  197. /// <param name="context">The GPU context used to wait for sync</param>
  198. public void Sync(GpuContext context)
  199. {
  200. ulong registeredSync = _registeredSync;
  201. long diff = (long)(context.SyncNumber - registeredSync);
  202. if (diff > 0)
  203. {
  204. context.Renderer.WaitSync(registeredSync);
  205. if ((long)(_modifiedSync - registeredSync) > 0)
  206. {
  207. // Flush the data in a previous state. Do not remove the modified flag - it will be removed to ignore following writes.
  208. return;
  209. }
  210. Modified = false;
  211. }
  212. // If the difference is <= 0, no data is not ready yet. Flush any data we can without waiting or removing modified flag.
  213. }
  214. /// <summary>
  215. /// Clears the action registered variable, indicating that the tracking action should be
  216. /// re-registered on the next modification.
  217. /// </summary>
  218. public void ClearActionRegistered()
  219. {
  220. Interlocked.Exchange(ref _actionRegistered, 0);
  221. }
  222. /// <summary>
  223. /// Action to perform when a sync number is registered after modification.
  224. /// This action will register a read tracking action on the memory tracking handle so that a flush from CPU can happen.
  225. /// </summary>
  226. private void SyncAction()
  227. {
  228. // The storage will need to signal modified again to update the sync number in future.
  229. _group.Storage.SignalModifiedDirty();
  230. lock (Overlaps)
  231. {
  232. foreach (Texture texture in Overlaps)
  233. {
  234. texture.SignalModifiedDirty();
  235. }
  236. }
  237. // Register region tracking for CPU? (again)
  238. _registeredSync = _modifiedSync;
  239. _syncActionRegistered = false;
  240. if (Interlocked.Exchange(ref _actionRegistered, 1) == 0)
  241. {
  242. _group.RegisterAction(this);
  243. }
  244. }
  245. /// <summary>
  246. /// Signal that a copy dependent texture has been modified, and must have its data copied to this one.
  247. /// </summary>
  248. /// <param name="copyFrom">The texture handle that must defer a copy to this one</param>
  249. public void DeferCopy(TextureGroupHandle copyFrom)
  250. {
  251. Modified = false;
  252. DeferredCopy = copyFrom;
  253. _group.Storage.SignalGroupDirty();
  254. foreach (Texture overlap in Overlaps)
  255. {
  256. overlap.SignalGroupDirty();
  257. }
  258. }
  259. /// <summary>
  260. /// Create a copy dependency between this handle, and another.
  261. /// </summary>
  262. /// <param name="other">The handle to create a copy dependency to</param>
  263. /// <param name="copyToOther">True if a copy should be deferred to all of the other handle's dependencies</param>
  264. public void CreateCopyDependency(TextureGroupHandle other, bool copyToOther = false)
  265. {
  266. // Does this dependency already exist?
  267. foreach (TextureDependency existing in Dependencies)
  268. {
  269. if (existing.Other.Handle == other)
  270. {
  271. // Do not need to create it again. May need to set the dirty flag.
  272. return;
  273. }
  274. }
  275. _group.HasCopyDependencies = true;
  276. other._group.HasCopyDependencies = true;
  277. TextureDependency dependency = new TextureDependency(this);
  278. TextureDependency otherDependency = new TextureDependency(other);
  279. dependency.Other = otherDependency;
  280. otherDependency.Other = dependency;
  281. Dependencies.Add(dependency);
  282. other.Dependencies.Add(otherDependency);
  283. // Recursively create dependency:
  284. // All of this handle's dependencies must depend on the other.
  285. foreach (TextureDependency existing in Dependencies.ToArray())
  286. {
  287. if (existing != dependency && existing.Other.Handle != other)
  288. {
  289. existing.Other.Handle.CreateCopyDependency(other);
  290. }
  291. }
  292. // All of the other handle's dependencies must depend on this.
  293. foreach (TextureDependency existing in other.Dependencies.ToArray())
  294. {
  295. if (existing != otherDependency && existing.Other.Handle != this)
  296. {
  297. existing.Other.Handle.CreateCopyDependency(this);
  298. if (copyToOther)
  299. {
  300. existing.Other.Handle.DeferCopy(this);
  301. }
  302. }
  303. }
  304. }
  305. /// <summary>
  306. /// Remove a dependency from this handle's dependency list.
  307. /// </summary>
  308. /// <param name="dependency">The dependency to remove</param>
  309. public void RemoveDependency(TextureDependency dependency)
  310. {
  311. Dependencies.Remove(dependency);
  312. }
  313. /// <summary>
  314. /// Check if any of this handle's memory tracking handles are dirty.
  315. /// </summary>
  316. /// <returns>True if at least one of the handles is dirty</returns>
  317. private bool CheckDirty()
  318. {
  319. return Handles.Any(handle => handle.Dirty);
  320. }
  321. /// <summary>
  322. /// Perform a copy from the provided handle to this one, or perform a deferred copy if none is provided.
  323. /// </summary>
  324. /// <param name="context">GPU context to register sync for modified handles</param>
  325. /// <param name="fromHandle">The handle to copy from. If not provided, this method will copy from and clear the deferred copy instead</param>
  326. /// <returns>True if the copy was performed, false otherwise</returns>
  327. public bool Copy(GpuContext context, TextureGroupHandle fromHandle = null)
  328. {
  329. bool result = false;
  330. bool shouldCopy = false;
  331. if (fromHandle == null)
  332. {
  333. fromHandle = DeferredCopy;
  334. if (fromHandle != null)
  335. {
  336. // Only copy if the copy texture is still modified.
  337. // It will be set as unmodified if new data is written from CPU, as the data previously in the texture will flush.
  338. // It will also set as unmodified if a copy is deferred to it.
  339. shouldCopy = fromHandle.Modified;
  340. if (fromHandle._bindCount == 0)
  341. {
  342. // Repeat the copy in future if the bind count is greater than 0.
  343. DeferredCopy = null;
  344. }
  345. }
  346. }
  347. else
  348. {
  349. // Copies happen directly when initializing a copy dependency.
  350. // If dirty, do not copy. Its data no longer matters, and this handle should also be dirty.
  351. // Also, only direct copy if the data in this handle is not already modified (can be set by copies from modified handles).
  352. shouldCopy = !fromHandle.CheckDirty() && (fromHandle.Modified || !Modified);
  353. }
  354. if (shouldCopy)
  355. {
  356. Texture from = fromHandle._group.Storage;
  357. Texture to = _group.Storage;
  358. if (from.ScaleFactor != to.ScaleFactor)
  359. {
  360. to.PropagateScale(from);
  361. }
  362. from.HostTexture.CopyTo(
  363. to.HostTexture,
  364. fromHandle._firstLayer,
  365. _firstLayer,
  366. fromHandle._firstLevel,
  367. _firstLevel);
  368. if (fromHandle.Modified)
  369. {
  370. Modified = true;
  371. RegisterSync(context);
  372. }
  373. result = true;
  374. }
  375. return result;
  376. }
  377. /// <summary>
  378. /// Check if this handle has a dependency to a given texture group.
  379. /// </summary>
  380. /// <param name="group">The texture group to check for</param>
  381. /// <returns>True if there is a dependency, false otherwise</returns>
  382. public bool HasDependencyTo(TextureGroup group)
  383. {
  384. foreach (TextureDependency dep in Dependencies)
  385. {
  386. if (dep.Other.Handle._group == group)
  387. {
  388. return true;
  389. }
  390. }
  391. return false;
  392. }
  393. /// <summary>
  394. /// Inherit modified flags and dependencies from another texture handle.
  395. /// </summary>
  396. /// <param name="old">The texture handle to inherit from</param>
  397. /// <param name="withCopies">Whether the handle should inherit copy dependencies or not</param>
  398. public void Inherit(TextureGroupHandle old, bool withCopies)
  399. {
  400. Modified |= old.Modified;
  401. if (withCopies)
  402. {
  403. foreach (TextureDependency dependency in old.Dependencies.ToArray())
  404. {
  405. CreateCopyDependency(dependency.Other.Handle);
  406. if (dependency.Other.Handle.DeferredCopy == old)
  407. {
  408. dependency.Other.Handle.DeferredCopy = this;
  409. }
  410. }
  411. DeferredCopy = old.DeferredCopy;
  412. }
  413. }
  414. /// <summary>
  415. /// Check if this region overlaps with another.
  416. /// </summary>
  417. /// <param name="address">Base address</param>
  418. /// <param name="size">Size of the region</param>
  419. /// <returns>True if overlapping, false otherwise</returns>
  420. public bool OverlapsWith(int offset, int size)
  421. {
  422. return Offset < offset + size && offset < Offset + Size;
  423. }
  424. /// <summary>
  425. /// Dispose this texture group handle, removing all its dependencies and disposing its memory tracking handles.
  426. /// </summary>
  427. public void Dispose()
  428. {
  429. foreach (CpuRegionHandle handle in Handles)
  430. {
  431. handle.Dispose();
  432. }
  433. foreach (TextureDependency dependency in Dependencies.ToArray())
  434. {
  435. dependency.Other.Handle.RemoveDependency(dependency.Other);
  436. }
  437. }
  438. }
  439. }