TextureGroupHandle.cs 18 KB

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