Texture.cs 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Gpu.Memory;
  5. using Ryujinx.Graphics.Texture;
  6. using Ryujinx.Graphics.Texture.Astc;
  7. using Ryujinx.Memory.Range;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Diagnostics;
  11. namespace Ryujinx.Graphics.Gpu.Image
  12. {
  13. /// <summary>
  14. /// Represents a cached GPU texture.
  15. /// </summary>
  16. class Texture : IMultiRangeItem, IDisposable
  17. {
  18. // How many updates we need before switching to the byte-by-byte comparison
  19. // modification check method.
  20. // This method uses much more memory so we want to avoid it if possible.
  21. private const int ByteComparisonSwitchThreshold = 4;
  22. private GpuContext _context;
  23. private SizeInfo _sizeInfo;
  24. /// <summary>
  25. /// Texture format.
  26. /// </summary>
  27. public Format Format => Info.FormatInfo.Format;
  28. /// <summary>
  29. /// Texture target.
  30. /// </summary>
  31. public Target Target { get; private set; }
  32. /// <summary>
  33. /// Texture information.
  34. /// </summary>
  35. public TextureInfo Info { get; private set; }
  36. /// <summary>
  37. /// Host scale factor.
  38. /// </summary>
  39. public float ScaleFactor { get; private set; }
  40. /// <summary>
  41. /// Upscaling mode. Informs if a texture is scaled, or is eligible for scaling.
  42. /// </summary>
  43. public TextureScaleMode ScaleMode { get; private set; }
  44. /// <summary>
  45. /// Set when a texture has been modified by the Host GPU since it was last flushed.
  46. /// </summary>
  47. public bool IsModified { get; internal set; }
  48. /// <summary>
  49. /// Set when a texture has been changed size. This indicates that it may need to be
  50. /// changed again when obtained as a sampler.
  51. /// </summary>
  52. public bool ChangedSize { get; internal set; }
  53. private int _depth;
  54. private int _layers;
  55. private int _firstLayer;
  56. private int _firstLevel;
  57. private bool _hasData;
  58. private int _updateCount;
  59. private byte[] _currentData;
  60. private ITexture _arrayViewTexture;
  61. private Target _arrayViewTarget;
  62. private ITexture _flushHostTexture;
  63. private Texture _viewStorage;
  64. private List<Texture> _views;
  65. /// <summary>
  66. /// Host texture.
  67. /// </summary>
  68. public ITexture HostTexture { get; private set; }
  69. /// <summary>
  70. /// Intrusive linked list node used on the auto deletion texture cache.
  71. /// </summary>
  72. public LinkedListNode<Texture> CacheNode { get; set; }
  73. /// <summary>
  74. /// Event to fire when texture data is disposed.
  75. /// </summary>
  76. public event Action<Texture> Disposed;
  77. /// <summary>
  78. /// Physical memory ranges where the texture data is located.
  79. /// </summary>
  80. public MultiRange Range { get; private set; }
  81. /// <summary>
  82. /// Texture size in bytes.
  83. /// </summary>
  84. public ulong Size => (ulong)_sizeInfo.TotalSize;
  85. private GpuRegionHandle _memoryTracking;
  86. private int _referenceCount;
  87. /// <summary>
  88. /// Constructs a new instance of the cached GPU texture.
  89. /// </summary>
  90. /// <param name="context">GPU context that the texture belongs to</param>
  91. /// <param name="info">Texture information</param>
  92. /// <param name="sizeInfo">Size information of the texture</param>
  93. /// <param name="range">Physical memory ranges where the texture data is located</param>
  94. /// <param name="firstLayer">The first layer of the texture, or 0 if the texture has no parent</param>
  95. /// <param name="firstLevel">The first mipmap level of the texture, or 0 if the texture has no parent</param>
  96. /// <param name="scaleFactor">The floating point scale factor to initialize with</param>
  97. /// <param name="scaleMode">The scale mode to initialize with</param>
  98. private Texture(
  99. GpuContext context,
  100. TextureInfo info,
  101. SizeInfo sizeInfo,
  102. MultiRange range,
  103. int firstLayer,
  104. int firstLevel,
  105. float scaleFactor,
  106. TextureScaleMode scaleMode)
  107. {
  108. InitializeTexture(context, info, sizeInfo, range);
  109. _firstLayer = firstLayer;
  110. _firstLevel = firstLevel;
  111. ScaleFactor = scaleFactor;
  112. ScaleMode = scaleMode;
  113. InitializeData(true);
  114. }
  115. /// <summary>
  116. /// Constructs a new instance of the cached GPU texture.
  117. /// </summary>
  118. /// <param name="context">GPU context that the texture belongs to</param>
  119. /// <param name="info">Texture information</param>
  120. /// <param name="sizeInfo">Size information of the texture</param>
  121. /// <param name="range">Physical memory ranges where the texture data is located</param>
  122. /// <param name="scaleMode">The scale mode to initialize with. If scaled, the texture's data is loaded immediately and scaled up</param>
  123. public Texture(GpuContext context, TextureInfo info, SizeInfo sizeInfo, MultiRange range, TextureScaleMode scaleMode)
  124. {
  125. ScaleFactor = 1f; // Texture is first loaded at scale 1x.
  126. ScaleMode = scaleMode;
  127. InitializeTexture(context, info, sizeInfo, range);
  128. }
  129. /// <summary>
  130. /// Common texture initialization method.
  131. /// This sets the context, info and sizeInfo fields.
  132. /// Other fields are initialized with their default values.
  133. /// </summary>
  134. /// <param name="context">GPU context that the texture belongs to</param>
  135. /// <param name="info">Texture information</param>
  136. /// <param name="sizeInfo">Size information of the texture</param>
  137. /// <param name="range">Physical memory ranges where the texture data is located</param>
  138. private void InitializeTexture(GpuContext context, TextureInfo info, SizeInfo sizeInfo, MultiRange range)
  139. {
  140. _context = context;
  141. _sizeInfo = sizeInfo;
  142. Range = range;
  143. SetInfo(info);
  144. _viewStorage = this;
  145. _views = new List<Texture>();
  146. }
  147. /// <summary>
  148. /// Initializes the data for a texture. Can optionally initialize the texture with or without data.
  149. /// If the texture is a view, it will initialize memory tracking to be non-dirty.
  150. /// </summary>
  151. /// <param name="isView">True if the texture is a view, false otherwise</param>
  152. /// <param name="withData">True if the texture is to be initialized with data</param>
  153. public void InitializeData(bool isView, bool withData = false)
  154. {
  155. _memoryTracking = _context.PhysicalMemory.BeginTracking(Range);
  156. if (withData)
  157. {
  158. Debug.Assert(!isView);
  159. TextureCreateInfo createInfo = TextureManager.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
  160. HostTexture = _context.Renderer.CreateTexture(createInfo, ScaleFactor);
  161. SynchronizeMemory(); // Load the data.
  162. if (ScaleMode == TextureScaleMode.Scaled)
  163. {
  164. SetScale(GraphicsConfig.ResScale); // Scale the data up.
  165. }
  166. }
  167. else
  168. {
  169. // Don't update this texture the next time we synchronize.
  170. ConsumeModified();
  171. _hasData = true;
  172. if (!isView)
  173. {
  174. if (ScaleMode == TextureScaleMode.Scaled)
  175. {
  176. // Don't need to start at 1x as there is no data to scale, just go straight to the target scale.
  177. ScaleFactor = GraphicsConfig.ResScale;
  178. }
  179. TextureCreateInfo createInfo = TextureManager.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
  180. HostTexture = _context.Renderer.CreateTexture(createInfo, ScaleFactor);
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// Create a texture view from this texture.
  186. /// A texture view is defined as a child texture, from a sub-range of their parent texture.
  187. /// For example, the initial layer and mipmap level of the view can be defined, so the texture
  188. /// will start at the given layer/level of the parent texture.
  189. /// </summary>
  190. /// <param name="info">Child texture information</param>
  191. /// <param name="sizeInfo">Child texture size information</param>
  192. /// <param name="range">Physical memory ranges where the texture data is located</param>
  193. /// <param name="firstLayer">Start layer of the child texture on the parent texture</param>
  194. /// <param name="firstLevel">Start mipmap level of the child texture on the parent texture</param>
  195. /// <returns>The child texture</returns>
  196. public Texture CreateView(TextureInfo info, SizeInfo sizeInfo, MultiRange range, int firstLayer, int firstLevel)
  197. {
  198. Texture texture = new Texture(
  199. _context,
  200. info,
  201. sizeInfo,
  202. range,
  203. _firstLayer + firstLayer,
  204. _firstLevel + firstLevel,
  205. ScaleFactor,
  206. ScaleMode);
  207. TextureCreateInfo createInfo = TextureManager.GetCreateInfo(info, _context.Capabilities, ScaleFactor);
  208. texture.HostTexture = HostTexture.CreateView(createInfo, firstLayer, firstLevel);
  209. _viewStorage.AddView(texture);
  210. return texture;
  211. }
  212. /// <summary>
  213. /// Adds a child texture to this texture.
  214. /// </summary>
  215. /// <param name="texture">The child texture</param>
  216. private void AddView(Texture texture)
  217. {
  218. DisableMemoryTracking();
  219. _views.Add(texture);
  220. texture._viewStorage = this;
  221. }
  222. /// <summary>
  223. /// Removes a child texture from this texture.
  224. /// </summary>
  225. /// <param name="texture">The child texture</param>
  226. private void RemoveView(Texture texture)
  227. {
  228. _views.Remove(texture);
  229. texture._viewStorage = texture;
  230. DeleteIfNotUsed();
  231. }
  232. /// <summary>
  233. /// Changes the texture size.
  234. /// </summary>
  235. /// <remarks>
  236. /// This operation may also change the size of all mipmap levels, including from the parent
  237. /// and other possible child textures, to ensure that all sizes are consistent.
  238. /// </remarks>
  239. /// <param name="width">The new texture width</param>
  240. /// <param name="height">The new texture height</param>
  241. /// <param name="depthOrLayers">The new texture depth (for 3D textures) or layers (for layered textures)</param>
  242. public void ChangeSize(int width, int height, int depthOrLayers)
  243. {
  244. int blockWidth = Info.FormatInfo.BlockWidth;
  245. int blockHeight = Info.FormatInfo.BlockHeight;
  246. width <<= _firstLevel;
  247. height <<= _firstLevel;
  248. if (Target == Target.Texture3D)
  249. {
  250. depthOrLayers <<= _firstLevel;
  251. }
  252. else
  253. {
  254. depthOrLayers = _viewStorage.Info.DepthOrLayers;
  255. }
  256. _viewStorage.RecreateStorageOrView(width, height, blockWidth, blockHeight, depthOrLayers);
  257. foreach (Texture view in _viewStorage._views)
  258. {
  259. int viewWidth = Math.Max(1, width >> view._firstLevel);
  260. int viewHeight = Math.Max(1, height >> view._firstLevel);
  261. int viewDepthOrLayers;
  262. if (view.Info.Target == Target.Texture3D)
  263. {
  264. viewDepthOrLayers = Math.Max(1, depthOrLayers >> view._firstLevel);
  265. }
  266. else
  267. {
  268. viewDepthOrLayers = view.Info.DepthOrLayers;
  269. }
  270. view.RecreateStorageOrView(viewWidth, viewHeight, blockWidth, blockHeight, viewDepthOrLayers);
  271. }
  272. }
  273. /// <summary>
  274. /// Disables memory tracking on this texture. Currently used for view containers, as we assume their views are covering all memory regions.
  275. /// Textures with disabled memory tracking also cannot flush in most circumstances.
  276. /// </summary>
  277. public void DisableMemoryTracking()
  278. {
  279. _memoryTracking?.Dispose();
  280. _memoryTracking = null;
  281. }
  282. /// <summary>
  283. /// Recreates the texture storage (or view, in the case of child textures) of this texture.
  284. /// This allows recreating the texture with a new size.
  285. /// A copy is automatically performed from the old to the new texture.
  286. /// </summary>
  287. /// <param name="width">The new texture width</param>
  288. /// <param name="height">The new texture height</param>
  289. /// <param name="width">The block width related to the given width</param>
  290. /// <param name="height">The block height related to the given height</param>
  291. /// <param name="depthOrLayers">The new texture depth (for 3D textures) or layers (for layered textures)</param>
  292. private void RecreateStorageOrView(int width, int height, int blockWidth, int blockHeight, int depthOrLayers)
  293. {
  294. RecreateStorageOrView(
  295. BitUtils.DivRoundUp(width * Info.FormatInfo.BlockWidth, blockWidth),
  296. BitUtils.DivRoundUp(height * Info.FormatInfo.BlockHeight, blockHeight),
  297. depthOrLayers);
  298. }
  299. /// <summary>
  300. /// Recreates the texture storage (or view, in the case of child textures) of this texture.
  301. /// This allows recreating the texture with a new size.
  302. /// A copy is automatically performed from the old to the new texture.
  303. /// </summary>
  304. /// <param name="width">The new texture width</param>
  305. /// <param name="height">The new texture height</param>
  306. /// <param name="depthOrLayers">The new texture depth (for 3D textures) or layers (for layered textures)</param>
  307. private void RecreateStorageOrView(int width, int height, int depthOrLayers)
  308. {
  309. ChangedSize = true;
  310. SetInfo(new TextureInfo(
  311. Info.GpuAddress,
  312. width,
  313. height,
  314. depthOrLayers,
  315. Info.Levels,
  316. Info.SamplesInX,
  317. Info.SamplesInY,
  318. Info.Stride,
  319. Info.IsLinear,
  320. Info.GobBlocksInY,
  321. Info.GobBlocksInZ,
  322. Info.GobBlocksInTileX,
  323. Info.Target,
  324. Info.FormatInfo,
  325. Info.DepthStencilMode,
  326. Info.SwizzleR,
  327. Info.SwizzleG,
  328. Info.SwizzleB,
  329. Info.SwizzleA));
  330. TextureCreateInfo createInfo = TextureManager.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
  331. if (_viewStorage != this)
  332. {
  333. ReplaceStorage(_viewStorage.HostTexture.CreateView(createInfo, _firstLayer, _firstLevel));
  334. }
  335. else
  336. {
  337. ITexture newStorage = _context.Renderer.CreateTexture(createInfo, ScaleFactor);
  338. HostTexture.CopyTo(newStorage, 0, 0);
  339. ReplaceStorage(newStorage);
  340. }
  341. }
  342. /// <summary>
  343. /// Blacklists this texture from being scaled. Resets its scale to 1 if needed.
  344. /// </summary>
  345. public void BlacklistScale()
  346. {
  347. ScaleMode = TextureScaleMode.Blacklisted;
  348. SetScale(1f);
  349. }
  350. /// <summary>
  351. /// Propagates the scale between this texture and another to ensure they have the same scale.
  352. /// If one texture is blacklisted from scaling, the other will become blacklisted too.
  353. /// </summary>
  354. /// <param name="other">The other texture</param>
  355. public void PropagateScale(Texture other)
  356. {
  357. if (other.ScaleMode == TextureScaleMode.Blacklisted || ScaleMode == TextureScaleMode.Blacklisted)
  358. {
  359. BlacklistScale();
  360. other.BlacklistScale();
  361. }
  362. else
  363. {
  364. // Prefer the configured scale if present. If not, prefer the max.
  365. float targetScale = GraphicsConfig.ResScale;
  366. float sharedScale = (ScaleFactor == targetScale || other.ScaleFactor == targetScale) ? targetScale : Math.Max(ScaleFactor, other.ScaleFactor);
  367. SetScale(sharedScale);
  368. other.SetScale(sharedScale);
  369. }
  370. }
  371. /// <summary>
  372. /// Copy the host texture to a scaled one. If a texture is not provided, create it with the given scale.
  373. /// </summary>
  374. /// <param name="scale">Scale factor</param>
  375. /// <param name="storage">Texture to use instead of creating one</param>
  376. /// <returns>A host texture containing a scaled version of this texture</returns>
  377. private ITexture GetScaledHostTexture(float scale, ITexture storage = null)
  378. {
  379. if (storage == null)
  380. {
  381. TextureCreateInfo createInfo = TextureManager.GetCreateInfo(Info, _context.Capabilities, scale);
  382. storage = _context.Renderer.CreateTexture(createInfo, scale);
  383. }
  384. HostTexture.CopyTo(storage, new Extents2D(0, 0, HostTexture.Width, HostTexture.Height), new Extents2D(0, 0, storage.Width, storage.Height), true);
  385. return storage;
  386. }
  387. /// <summary>
  388. /// Sets the Scale Factor on this texture, and immediately recreates it at the correct size.
  389. /// When a texture is resized, a scaled copy is performed from the old texture to the new one, to ensure no data is lost.
  390. /// If scale is equivalent, this only propagates the blacklisted/scaled mode.
  391. /// If called on a view, its storage is resized instead.
  392. /// When resizing storage, all texture views are recreated.
  393. /// </summary>
  394. /// <param name="scale">The new scale factor for this texture</param>
  395. public void SetScale(float scale)
  396. {
  397. TextureScaleMode newScaleMode = ScaleMode == TextureScaleMode.Blacklisted ? ScaleMode : TextureScaleMode.Scaled;
  398. if (_viewStorage != this)
  399. {
  400. _viewStorage.ScaleMode = newScaleMode;
  401. _viewStorage.SetScale(scale);
  402. return;
  403. }
  404. if (ScaleFactor != scale)
  405. {
  406. Logger.Debug?.Print(LogClass.Gpu, $"Rescaling {Info.Width}x{Info.Height} {Info.FormatInfo.Format.ToString()} to ({ScaleFactor} to {scale}). ");
  407. ScaleFactor = scale;
  408. ITexture newStorage = GetScaledHostTexture(ScaleFactor);
  409. Logger.Debug?.Print(LogClass.Gpu, $" Copy performed: {HostTexture.Width}x{HostTexture.Height} to {newStorage.Width}x{newStorage.Height}");
  410. ReplaceStorage(newStorage);
  411. // All views must be recreated against the new storage.
  412. foreach (var view in _views)
  413. {
  414. Logger.Debug?.Print(LogClass.Gpu, $" Recreating view {Info.Width}x{Info.Height} {Info.FormatInfo.Format.ToString()}.");
  415. view.ScaleFactor = scale;
  416. TextureCreateInfo viewCreateInfo = TextureManager.GetCreateInfo(view.Info, _context.Capabilities, scale);
  417. ITexture newView = HostTexture.CreateView(viewCreateInfo, view._firstLayer - _firstLayer, view._firstLevel - _firstLevel);
  418. view.ReplaceStorage(newView);
  419. view.ScaleMode = newScaleMode;
  420. }
  421. }
  422. if (ScaleMode != newScaleMode)
  423. {
  424. ScaleMode = newScaleMode;
  425. foreach (var view in _views)
  426. {
  427. view.ScaleMode = newScaleMode;
  428. }
  429. }
  430. }
  431. /// <summary>
  432. /// Checks if the memory for this texture was modified, and returns true if it was.
  433. /// The modified flags are consumed as a result.
  434. /// </summary>
  435. /// <remarks>
  436. /// If there is no memory tracking for this texture, it will always report as modified.
  437. /// </remarks>
  438. /// <returns>True if the texture was modified, false otherwise.</returns>
  439. public bool ConsumeModified()
  440. {
  441. bool wasDirty = _memoryTracking?.Dirty ?? true;
  442. _memoryTracking?.Reprotect();
  443. return wasDirty;
  444. }
  445. /// <summary>
  446. /// Synchronizes guest and host memory.
  447. /// This will overwrite the texture data with the texture data on the guest memory, if a CPU
  448. /// modification is detected.
  449. /// Be aware that this can cause texture data written by the GPU to be lost, this is just a
  450. /// one way copy (from CPU owned to GPU owned memory).
  451. /// </summary>
  452. public void SynchronizeMemory()
  453. {
  454. if (Target == Target.TextureBuffer)
  455. {
  456. return;
  457. }
  458. if (_hasData)
  459. {
  460. if (_memoryTracking?.Dirty != true)
  461. {
  462. return;
  463. }
  464. BlacklistScale();
  465. }
  466. _memoryTracking?.Reprotect();
  467. ReadOnlySpan<byte> data = _context.PhysicalMemory.GetSpan(Range);
  468. IsModified = false;
  469. // If the host does not support ASTC compression, we need to do the decompression.
  470. // The decompression is slow, so we want to avoid it as much as possible.
  471. // This does a byte-by-byte check and skips the update if the data is equal in this case.
  472. // This improves the speed on applications that overwrites ASTC data without changing anything.
  473. if (Info.FormatInfo.Format.IsAstc() && !_context.Capabilities.SupportsAstcCompression)
  474. {
  475. if (_updateCount < ByteComparisonSwitchThreshold)
  476. {
  477. _updateCount++;
  478. }
  479. else
  480. {
  481. bool dataMatches = _currentData != null && data.SequenceEqual(_currentData);
  482. _currentData = data.ToArray();
  483. if (dataMatches)
  484. {
  485. return;
  486. }
  487. }
  488. }
  489. data = ConvertToHostCompatibleFormat(data);
  490. HostTexture.SetData(data);
  491. _hasData = true;
  492. }
  493. /// <summary>
  494. /// Uploads new texture data to the host GPU.
  495. /// </summary>
  496. /// <param name="data">New data</param>
  497. public void SetData(ReadOnlySpan<byte> data)
  498. {
  499. BlacklistScale();
  500. _memoryTracking?.Reprotect();
  501. IsModified = false;
  502. HostTexture.SetData(data);
  503. _hasData = true;
  504. }
  505. /// <summary>
  506. /// Converts texture data to a format and layout that is supported by the host GPU.
  507. /// </summary>
  508. /// <param name="data">Data to be converted</param>
  509. /// <returns>Converted data</returns>
  510. private ReadOnlySpan<byte> ConvertToHostCompatibleFormat(ReadOnlySpan<byte> data)
  511. {
  512. if (Info.IsLinear)
  513. {
  514. data = LayoutConverter.ConvertLinearStridedToLinear(
  515. Info.Width,
  516. Info.Height,
  517. Info.FormatInfo.BlockWidth,
  518. Info.FormatInfo.BlockHeight,
  519. Info.Stride,
  520. Info.FormatInfo.BytesPerPixel,
  521. data);
  522. }
  523. else
  524. {
  525. data = LayoutConverter.ConvertBlockLinearToLinear(
  526. Info.Width,
  527. Info.Height,
  528. _depth,
  529. Info.Levels,
  530. _layers,
  531. Info.FormatInfo.BlockWidth,
  532. Info.FormatInfo.BlockHeight,
  533. Info.FormatInfo.BytesPerPixel,
  534. Info.GobBlocksInY,
  535. Info.GobBlocksInZ,
  536. Info.GobBlocksInTileX,
  537. _sizeInfo,
  538. data);
  539. }
  540. // Handle compressed cases not supported by the host:
  541. // - ASTC is usually not supported on desktop cards.
  542. // - BC4/BC5 is not supported on 3D textures.
  543. if (!_context.Capabilities.SupportsAstcCompression && Info.FormatInfo.Format.IsAstc())
  544. {
  545. if (!AstcDecoder.TryDecodeToRgba8P(
  546. data.ToArray(),
  547. Info.FormatInfo.BlockWidth,
  548. Info.FormatInfo.BlockHeight,
  549. Info.Width,
  550. Info.Height,
  551. _depth,
  552. Info.Levels,
  553. _layers,
  554. out Span<byte> decoded))
  555. {
  556. string texInfo = $"{Info.Target} {Info.FormatInfo.Format} {Info.Width}x{Info.Height}x{Info.DepthOrLayers} levels {Info.Levels}";
  557. Logger.Debug?.Print(LogClass.Gpu, $"Invalid ASTC texture at 0x{Info.GpuAddress:X} ({texInfo}).");
  558. }
  559. data = decoded;
  560. }
  561. else if (Target == Target.Texture3D && Info.FormatInfo.Format.IsBc4())
  562. {
  563. data = BCnDecoder.DecodeBC4(data, Info.Width, Info.Height, _depth, Info.Levels, _layers, Info.FormatInfo.Format == Format.Bc4Snorm);
  564. }
  565. else if (Target == Target.Texture3D && Info.FormatInfo.Format.IsBc5())
  566. {
  567. data = BCnDecoder.DecodeBC5(data, Info.Width, Info.Height, _depth, Info.Levels, _layers, Info.FormatInfo.Format == Format.Bc5Snorm);
  568. }
  569. return data;
  570. }
  571. /// <summary>
  572. /// Flushes the texture data.
  573. /// This causes the texture data to be written back to guest memory.
  574. /// If the texture was written by the GPU, this includes all modification made by the GPU
  575. /// up to this point.
  576. /// Be aware that this is an expensive operation, avoid calling it unless strictly needed.
  577. /// This may cause data corruption if the memory is already being used for something else on the CPU side.
  578. /// </summary>
  579. /// <param name="tracked">Whether or not the flush triggers write tracking. If it doesn't, the texture will not be blacklisted for scaling either.</param>
  580. public void Flush(bool tracked = true)
  581. {
  582. IsModified = false;
  583. if (TextureCompatibility.IsFormatHostIncompatible(Info, _context.Capabilities))
  584. {
  585. return; // Flushing this format is not supported, as it may have been converted to another host format.
  586. }
  587. if (tracked)
  588. {
  589. _context.PhysicalMemory.Write(Range, GetTextureDataFromGpu(tracked));
  590. }
  591. else
  592. {
  593. _context.PhysicalMemory.WriteUntracked(Range, GetTextureDataFromGpu(tracked));
  594. }
  595. }
  596. /// <summary>
  597. /// Flushes the texture data, to be called from an external thread.
  598. /// The host backend must ensure that we have shared access to the resource from this thread.
  599. /// This is used when flushing from memory access handlers.
  600. /// </summary>
  601. public void ExternalFlush(ulong address, ulong size)
  602. {
  603. if (!IsModified || _memoryTracking == null)
  604. {
  605. return;
  606. }
  607. _context.Renderer.BackgroundContextAction(() =>
  608. {
  609. IsModified = false;
  610. if (TextureCompatibility.IsFormatHostIncompatible(Info, _context.Capabilities))
  611. {
  612. return; // Flushing this format is not supported, as it may have been converted to another host format.
  613. }
  614. ITexture texture = HostTexture;
  615. if (ScaleFactor != 1f)
  616. {
  617. // If needed, create a texture to flush back to host at 1x scale.
  618. texture = _flushHostTexture = GetScaledHostTexture(1f, _flushHostTexture);
  619. }
  620. _context.PhysicalMemory.WriteUntracked(Range, GetTextureDataFromGpu(false, texture));
  621. });
  622. }
  623. /// <summary>
  624. /// Gets data from the host GPU.
  625. /// </summary>
  626. /// <remarks>
  627. /// This method should be used to retrieve data that was modified by the host GPU.
  628. /// This is not cheap, avoid doing that unless strictly needed.
  629. /// </remarks>
  630. /// <returns>Host texture data</returns>
  631. private Span<byte> GetTextureDataFromGpu(bool blacklist, ITexture texture = null)
  632. {
  633. Span<byte> data;
  634. if (texture != null)
  635. {
  636. data = texture.GetData();
  637. }
  638. else
  639. {
  640. if (blacklist)
  641. {
  642. BlacklistScale();
  643. data = HostTexture.GetData();
  644. }
  645. else if (ScaleFactor != 1f)
  646. {
  647. float scale = ScaleFactor;
  648. SetScale(1f);
  649. data = HostTexture.GetData();
  650. SetScale(scale);
  651. }
  652. else
  653. {
  654. data = HostTexture.GetData();
  655. }
  656. }
  657. if (Target != Target.TextureBuffer)
  658. {
  659. if (Info.IsLinear)
  660. {
  661. data = LayoutConverter.ConvertLinearToLinearStrided(
  662. Info.Width,
  663. Info.Height,
  664. Info.FormatInfo.BlockWidth,
  665. Info.FormatInfo.BlockHeight,
  666. Info.Stride,
  667. Info.FormatInfo.BytesPerPixel,
  668. data);
  669. }
  670. else
  671. {
  672. data = LayoutConverter.ConvertLinearToBlockLinear(
  673. Info.Width,
  674. Info.Height,
  675. _depth,
  676. Info.Levels,
  677. _layers,
  678. Info.FormatInfo.BlockWidth,
  679. Info.FormatInfo.BlockHeight,
  680. Info.FormatInfo.BytesPerPixel,
  681. Info.GobBlocksInY,
  682. Info.GobBlocksInZ,
  683. Info.GobBlocksInTileX,
  684. _sizeInfo,
  685. data);
  686. }
  687. }
  688. return data;
  689. }
  690. /// <summary>
  691. /// This performs a strict comparison, used to check if this texture is equal to the one supplied.
  692. /// </summary>
  693. /// <param name="info">Texture information to compare against</param>
  694. /// <param name="flags">Comparison flags</param>
  695. /// <returns>A value indicating how well this texture matches the given info</returns>
  696. public TextureMatchQuality IsExactMatch(TextureInfo info, TextureSearchFlags flags)
  697. {
  698. TextureMatchQuality matchQuality = TextureCompatibility.FormatMatches(Info, info, (flags & TextureSearchFlags.ForSampler) != 0, (flags & TextureSearchFlags.ForCopy) != 0);
  699. if (matchQuality == TextureMatchQuality.NoMatch)
  700. {
  701. return matchQuality;
  702. }
  703. if (!TextureCompatibility.LayoutMatches(Info, info))
  704. {
  705. return TextureMatchQuality.NoMatch;
  706. }
  707. if (!TextureCompatibility.SizeMatches(Info, info, (flags & TextureSearchFlags.Strict) == 0))
  708. {
  709. return TextureMatchQuality.NoMatch;
  710. }
  711. if ((flags & TextureSearchFlags.ForSampler) != 0 || (flags & TextureSearchFlags.Strict) != 0)
  712. {
  713. if (!TextureCompatibility.SamplerParamsMatches(Info, info))
  714. {
  715. return TextureMatchQuality.NoMatch;
  716. }
  717. }
  718. if ((flags & TextureSearchFlags.ForCopy) != 0)
  719. {
  720. bool msTargetCompatible = Info.Target == Target.Texture2DMultisample && info.Target == Target.Texture2D;
  721. if (!msTargetCompatible && !TextureCompatibility.TargetAndSamplesCompatible(Info, info))
  722. {
  723. return TextureMatchQuality.NoMatch;
  724. }
  725. }
  726. else if (!TextureCompatibility.TargetAndSamplesCompatible(Info, info))
  727. {
  728. return TextureMatchQuality.NoMatch;
  729. }
  730. return Info.Levels == info.Levels ? matchQuality : TextureMatchQuality.NoMatch;
  731. }
  732. /// <summary>
  733. /// Check if it's possible to create a view, with the given parameters, from this texture.
  734. /// </summary>
  735. /// <param name="info">Texture view information</param>
  736. /// <param name="range">Texture view physical memory ranges</param>
  737. /// <param name="firstLayer">Texture view initial layer on this texture</param>
  738. /// <param name="firstLevel">Texture view first mipmap level on this texture</param>
  739. /// <returns>The level of compatiblilty a view with the given parameters created from this texture has</returns>
  740. public TextureViewCompatibility IsViewCompatible(TextureInfo info, MultiRange range, out int firstLayer, out int firstLevel)
  741. {
  742. int offset = Range.FindOffset(range);
  743. // Out of range.
  744. if (offset < 0)
  745. {
  746. firstLayer = 0;
  747. firstLevel = 0;
  748. return TextureViewCompatibility.Incompatible;
  749. }
  750. if (!_sizeInfo.FindView(offset, out firstLayer, out firstLevel))
  751. {
  752. return TextureViewCompatibility.Incompatible;
  753. }
  754. if (!TextureCompatibility.ViewLayoutCompatible(Info, info, firstLevel))
  755. {
  756. return TextureViewCompatibility.Incompatible;
  757. }
  758. if (!TextureCompatibility.ViewFormatCompatible(Info, info))
  759. {
  760. return TextureViewCompatibility.Incompatible;
  761. }
  762. TextureViewCompatibility result = TextureViewCompatibility.Full;
  763. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewSizeMatches(Info, info, firstLevel));
  764. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewTargetCompatible(Info, info));
  765. return (Info.SamplesInX == info.SamplesInX &&
  766. Info.SamplesInY == info.SamplesInY) ? result : TextureViewCompatibility.Incompatible;
  767. }
  768. /// <summary>
  769. /// Gets a texture of the specified target type from this texture.
  770. /// This can be used to get an array texture from a non-array texture and vice-versa.
  771. /// If this texture and the requested targets are equal, then this texture Host texture is returned directly.
  772. /// </summary>
  773. /// <param name="target">The desired target type</param>
  774. /// <returns>A view of this texture with the requested target, or null if the target is invalid for this texture</returns>
  775. public ITexture GetTargetTexture(Target target)
  776. {
  777. if (target == Target)
  778. {
  779. return HostTexture;
  780. }
  781. if (_arrayViewTexture == null && IsSameDimensionsTarget(target))
  782. {
  783. TextureCreateInfo createInfo = new TextureCreateInfo(
  784. Info.Width,
  785. Info.Height,
  786. target == Target.CubemapArray ? 6 : 1,
  787. Info.Levels,
  788. Info.Samples,
  789. Info.FormatInfo.BlockWidth,
  790. Info.FormatInfo.BlockHeight,
  791. Info.FormatInfo.BytesPerPixel,
  792. Info.FormatInfo.Format,
  793. Info.DepthStencilMode,
  794. target,
  795. Info.SwizzleR,
  796. Info.SwizzleG,
  797. Info.SwizzleB,
  798. Info.SwizzleA);
  799. ITexture viewTexture = HostTexture.CreateView(createInfo, 0, 0);
  800. _arrayViewTexture = viewTexture;
  801. _arrayViewTarget = target;
  802. return viewTexture;
  803. }
  804. else if (_arrayViewTarget == target)
  805. {
  806. return _arrayViewTexture;
  807. }
  808. return null;
  809. }
  810. /// <summary>
  811. /// Check if this texture and the specified target have the same number of dimensions.
  812. /// For the purposes of this comparison, 2D and 2D Multisample textures are not considered to have
  813. /// the same number of dimensions. Same for Cubemap and 3D textures.
  814. /// </summary>
  815. /// <param name="target">The target to compare with</param>
  816. /// <returns>True if both targets have the same number of dimensions, false otherwise</returns>
  817. private bool IsSameDimensionsTarget(Target target)
  818. {
  819. switch (Info.Target)
  820. {
  821. case Target.Texture1D:
  822. case Target.Texture1DArray:
  823. return target == Target.Texture1D ||
  824. target == Target.Texture1DArray;
  825. case Target.Texture2D:
  826. case Target.Texture2DArray:
  827. return target == Target.Texture2D ||
  828. target == Target.Texture2DArray;
  829. case Target.Cubemap:
  830. case Target.CubemapArray:
  831. return target == Target.Cubemap ||
  832. target == Target.CubemapArray;
  833. case Target.Texture2DMultisample:
  834. case Target.Texture2DMultisampleArray:
  835. return target == Target.Texture2DMultisample ||
  836. target == Target.Texture2DMultisampleArray;
  837. case Target.Texture3D:
  838. return target == Target.Texture3D;
  839. }
  840. return false;
  841. }
  842. /// <summary>
  843. /// Replaces view texture information.
  844. /// This should only be used for child textures with a parent.
  845. /// </summary>
  846. /// <param name="parent">The parent texture</param>
  847. /// <param name="info">The new view texture information</param>
  848. /// <param name="hostTexture">The new host texture</param>
  849. /// <param name="firstLayer">The first layer of the view</param>
  850. /// <param name="firstLevel">The first level of the view</param>
  851. public void ReplaceView(Texture parent, TextureInfo info, ITexture hostTexture, int firstLayer, int firstLevel)
  852. {
  853. parent._viewStorage.SynchronizeMemory();
  854. ReplaceStorage(hostTexture);
  855. _firstLayer = parent._firstLayer + firstLayer;
  856. _firstLevel = parent._firstLevel + firstLevel;
  857. parent._viewStorage.AddView(this);
  858. SetInfo(info);
  859. }
  860. /// <summary>
  861. /// Sets the internal texture information structure.
  862. /// </summary>
  863. /// <param name="info">The new texture information</param>
  864. private void SetInfo(TextureInfo info)
  865. {
  866. Info = info;
  867. Target = info.Target;
  868. _depth = info.GetDepth();
  869. _layers = info.GetLayers();
  870. }
  871. /// <summary>
  872. /// Signals that the texture has been modified.
  873. /// </summary>
  874. public void SignalModified()
  875. {
  876. IsModified = true;
  877. if (_viewStorage != this)
  878. {
  879. _viewStorage.SignalModified();
  880. }
  881. _memoryTracking?.RegisterAction(ExternalFlush);
  882. }
  883. /// <summary>
  884. /// Replaces the host texture, while disposing of the old one if needed.
  885. /// </summary>
  886. /// <param name="hostTexture">The new host texture</param>
  887. private void ReplaceStorage(ITexture hostTexture)
  888. {
  889. DisposeTextures();
  890. HostTexture = hostTexture;
  891. }
  892. /// <summary>
  893. /// Determine if any of our child textures are compaible as views of the given texture.
  894. /// </summary>
  895. /// <param name="texture">The texture to check against</param>
  896. /// <returns>True if any child is view compatible, false otherwise</returns>
  897. public bool HasViewCompatibleChild(Texture texture)
  898. {
  899. if (_viewStorage != this || _views.Count == 0)
  900. {
  901. return false;
  902. }
  903. foreach (Texture view in _views)
  904. {
  905. if (texture.IsViewCompatible(view.Info, view.Range, out _, out _) != TextureViewCompatibility.Incompatible)
  906. {
  907. return true;
  908. }
  909. }
  910. return false;
  911. }
  912. /// <summary>
  913. /// Increments the texture reference count.
  914. /// </summary>
  915. public void IncrementReferenceCount()
  916. {
  917. _referenceCount++;
  918. }
  919. /// <summary>
  920. /// Decrements the texture reference count.
  921. /// When the reference count hits zero, the texture may be deleted and can't be used anymore.
  922. /// </summary>
  923. /// <returns>True if the texture is now referenceless, false otherwise</returns>
  924. public bool DecrementReferenceCount()
  925. {
  926. int newRefCount = --_referenceCount;
  927. if (newRefCount == 0)
  928. {
  929. if (_viewStorage != this)
  930. {
  931. _viewStorage.RemoveView(this);
  932. }
  933. _context.Methods.TextureManager.RemoveTextureFromCache(this);
  934. }
  935. Debug.Assert(newRefCount >= 0);
  936. DeleteIfNotUsed();
  937. return newRefCount <= 0;
  938. }
  939. /// <summary>
  940. /// Delete the texture if it is not used anymore.
  941. /// The texture is considered unused when the reference count is zero,
  942. /// and it has no child views.
  943. /// </summary>
  944. private void DeleteIfNotUsed()
  945. {
  946. // We can delete the texture as long it is not being used
  947. // in any cache (the reference count is 0 in this case), and
  948. // also all views that may be created from this texture were
  949. // already deleted (views count is 0).
  950. if (_referenceCount == 0 && _views.Count == 0)
  951. {
  952. Dispose();
  953. }
  954. }
  955. /// <summary>
  956. /// Performs texture disposal, deleting the texture.
  957. /// </summary>
  958. private void DisposeTextures()
  959. {
  960. _currentData = null;
  961. HostTexture.Release();
  962. _arrayViewTexture?.Release();
  963. _arrayViewTexture = null;
  964. _flushHostTexture?.Release();
  965. _flushHostTexture = null;
  966. }
  967. /// <summary>
  968. /// Called when the memory for this texture has been unmapped.
  969. /// Calls are from non-gpu threads.
  970. /// </summary>
  971. public void Unmapped()
  972. {
  973. IsModified = false; // We shouldn't flush this texture, as its memory is no longer mapped.
  974. var tracking = _memoryTracking;
  975. tracking?.Reprotect();
  976. tracking?.RegisterAction(null);
  977. }
  978. /// <summary>
  979. /// Performs texture disposal, deleting the texture.
  980. /// </summary>
  981. public void Dispose()
  982. {
  983. DisposeTextures();
  984. Disposed?.Invoke(this);
  985. _memoryTracking?.Dispose();
  986. }
  987. }
  988. }