TextureGroupHandle.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. bool needsSync = !context.IsGpuThread();
  201. if (needsSync)
  202. {
  203. ulong registeredSync = _registeredSync;
  204. long diff = (long)(context.SyncNumber - registeredSync);
  205. if (diff > 0)
  206. {
  207. context.Renderer.WaitSync(registeredSync);
  208. if ((long)(_modifiedSync - registeredSync) > 0)
  209. {
  210. // Flush the data in a previous state. Do not remove the modified flag - it will be removed to ignore following writes.
  211. return;
  212. }
  213. Modified = false;
  214. }
  215. // If the difference is <= 0, no data is not ready yet. Flush any data we can without waiting or removing modified flag.
  216. }
  217. else
  218. {
  219. Modified = false;
  220. }
  221. }
  222. /// <summary>
  223. /// Clears the action registered variable, indicating that the tracking action should be
  224. /// re-registered on the next modification.
  225. /// </summary>
  226. public void ClearActionRegistered()
  227. {
  228. Interlocked.Exchange(ref _actionRegistered, 0);
  229. }
  230. /// <summary>
  231. /// Action to perform when a sync number is registered after modification.
  232. /// This action will register a read tracking action on the memory tracking handle so that a flush from CPU can happen.
  233. /// </summary>
  234. private void SyncAction()
  235. {
  236. // The storage will need to signal modified again to update the sync number in future.
  237. _group.Storage.SignalModifiedDirty();
  238. lock (Overlaps)
  239. {
  240. foreach (Texture texture in Overlaps)
  241. {
  242. texture.SignalModifiedDirty();
  243. }
  244. }
  245. // Register region tracking for CPU? (again)
  246. _registeredSync = _modifiedSync;
  247. _syncActionRegistered = false;
  248. if (Interlocked.Exchange(ref _actionRegistered, 1) == 0)
  249. {
  250. _group.RegisterAction(this);
  251. }
  252. }
  253. /// <summary>
  254. /// Signal that a copy dependent texture has been modified, and must have its data copied to this one.
  255. /// </summary>
  256. /// <param name="copyFrom">The texture handle that must defer a copy to this one</param>
  257. public void DeferCopy(TextureGroupHandle copyFrom)
  258. {
  259. Modified = false;
  260. DeferredCopy = copyFrom;
  261. _group.Storage.SignalGroupDirty();
  262. foreach (Texture overlap in Overlaps)
  263. {
  264. overlap.SignalGroupDirty();
  265. }
  266. }
  267. /// <summary>
  268. /// Create a copy dependency between this handle, and another.
  269. /// </summary>
  270. /// <param name="other">The handle to create a copy dependency to</param>
  271. /// <param name="copyToOther">True if a copy should be deferred to all of the other handle's dependencies</param>
  272. public void CreateCopyDependency(TextureGroupHandle other, bool copyToOther = false)
  273. {
  274. // Does this dependency already exist?
  275. foreach (TextureDependency existing in Dependencies)
  276. {
  277. if (existing.Other.Handle == other)
  278. {
  279. // Do not need to create it again. May need to set the dirty flag.
  280. return;
  281. }
  282. }
  283. _group.HasCopyDependencies = true;
  284. other._group.HasCopyDependencies = true;
  285. TextureDependency dependency = new TextureDependency(this);
  286. TextureDependency otherDependency = new TextureDependency(other);
  287. dependency.Other = otherDependency;
  288. otherDependency.Other = dependency;
  289. Dependencies.Add(dependency);
  290. other.Dependencies.Add(otherDependency);
  291. // Recursively create dependency:
  292. // All of this handle's dependencies must depend on the other.
  293. foreach (TextureDependency existing in Dependencies.ToArray())
  294. {
  295. if (existing != dependency && existing.Other.Handle != other)
  296. {
  297. existing.Other.Handle.CreateCopyDependency(other);
  298. }
  299. }
  300. // All of the other handle's dependencies must depend on this.
  301. foreach (TextureDependency existing in other.Dependencies.ToArray())
  302. {
  303. if (existing != otherDependency && existing.Other.Handle != this)
  304. {
  305. existing.Other.Handle.CreateCopyDependency(this);
  306. if (copyToOther)
  307. {
  308. existing.Other.Handle.DeferCopy(this);
  309. }
  310. }
  311. }
  312. }
  313. /// <summary>
  314. /// Remove a dependency from this handle's dependency list.
  315. /// </summary>
  316. /// <param name="dependency">The dependency to remove</param>
  317. public void RemoveDependency(TextureDependency dependency)
  318. {
  319. Dependencies.Remove(dependency);
  320. }
  321. /// <summary>
  322. /// Check if any of this handle's memory tracking handles are dirty.
  323. /// </summary>
  324. /// <returns>True if at least one of the handles is dirty</returns>
  325. private bool CheckDirty()
  326. {
  327. return Handles.Any(handle => handle.Dirty);
  328. }
  329. /// <summary>
  330. /// Perform a copy from the provided handle to this one, or perform a deferred copy if none is provided.
  331. /// </summary>
  332. /// <param name="context">GPU context to register sync for modified handles</param>
  333. /// <param name="fromHandle">The handle to copy from. If not provided, this method will copy from and clear the deferred copy instead</param>
  334. /// <returns>True if the copy was performed, false otherwise</returns>
  335. public bool Copy(GpuContext context, TextureGroupHandle fromHandle = null)
  336. {
  337. bool result = false;
  338. bool shouldCopy = false;
  339. if (fromHandle == null)
  340. {
  341. fromHandle = DeferredCopy;
  342. if (fromHandle != null)
  343. {
  344. // Only copy if the copy texture is still modified.
  345. // It will be set as unmodified if new data is written from CPU, as the data previously in the texture will flush.
  346. // It will also set as unmodified if a copy is deferred to it.
  347. shouldCopy = fromHandle.Modified;
  348. if (fromHandle._bindCount == 0)
  349. {
  350. // Repeat the copy in future if the bind count is greater than 0.
  351. DeferredCopy = null;
  352. }
  353. }
  354. }
  355. else
  356. {
  357. // Copies happen directly when initializing a copy dependency.
  358. // If dirty, do not copy. Its data no longer matters, and this handle should also be dirty.
  359. // Also, only direct copy if the data in this handle is not already modified (can be set by copies from modified handles).
  360. shouldCopy = !fromHandle.CheckDirty() && (fromHandle.Modified || !Modified);
  361. }
  362. if (shouldCopy)
  363. {
  364. Texture from = fromHandle._group.Storage;
  365. Texture to = _group.Storage;
  366. if (from.ScaleFactor != to.ScaleFactor)
  367. {
  368. to.PropagateScale(from);
  369. }
  370. from.HostTexture.CopyTo(
  371. to.HostTexture,
  372. fromHandle._firstLayer,
  373. _firstLayer,
  374. fromHandle._firstLevel,
  375. _firstLevel);
  376. if (fromHandle.Modified)
  377. {
  378. Modified = true;
  379. RegisterSync(context);
  380. }
  381. result = true;
  382. }
  383. return result;
  384. }
  385. /// <summary>
  386. /// Check if this handle has a dependency to a given texture group.
  387. /// </summary>
  388. /// <param name="group">The texture group to check for</param>
  389. /// <returns>True if there is a dependency, false otherwise</returns>
  390. public bool HasDependencyTo(TextureGroup group)
  391. {
  392. foreach (TextureDependency dep in Dependencies)
  393. {
  394. if (dep.Other.Handle._group == group)
  395. {
  396. return true;
  397. }
  398. }
  399. return false;
  400. }
  401. /// <summary>
  402. /// Inherit modified flags and dependencies from another texture handle.
  403. /// </summary>
  404. /// <param name="old">The texture handle to inherit from</param>
  405. /// <param name="withCopies">Whether the handle should inherit copy dependencies or not</param>
  406. public void Inherit(TextureGroupHandle old, bool withCopies)
  407. {
  408. Modified |= old.Modified;
  409. if (withCopies)
  410. {
  411. foreach (TextureDependency dependency in old.Dependencies.ToArray())
  412. {
  413. CreateCopyDependency(dependency.Other.Handle);
  414. if (dependency.Other.Handle.DeferredCopy == old)
  415. {
  416. dependency.Other.Handle.DeferredCopy = this;
  417. }
  418. }
  419. DeferredCopy = old.DeferredCopy;
  420. }
  421. }
  422. /// <summary>
  423. /// Check if this region overlaps with another.
  424. /// </summary>
  425. /// <param name="address">Base address</param>
  426. /// <param name="size">Size of the region</param>
  427. /// <returns>True if overlapping, false otherwise</returns>
  428. public bool OverlapsWith(int offset, int size)
  429. {
  430. return Offset < offset + size && offset < Offset + Size;
  431. }
  432. /// <summary>
  433. /// Dispose this texture group handle, removing all its dependencies and disposing its memory tracking handles.
  434. /// </summary>
  435. public void Dispose()
  436. {
  437. foreach (CpuRegionHandle handle in Handles)
  438. {
  439. handle.Dispose();
  440. }
  441. foreach (TextureDependency dependency in Dependencies.ToArray())
  442. {
  443. dependency.Other.Handle.RemoveDependency(dependency.Other);
  444. }
  445. }
  446. }
  447. }