Texture.cs 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655
  1. using Ryujinx.Common.Logging;
  2. using Ryujinx.Common.Memory;
  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;
  8. using Ryujinx.Memory.Range;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Diagnostics;
  12. using System.Linq;
  13. using System.Numerics;
  14. namespace Ryujinx.Graphics.Gpu.Image
  15. {
  16. /// <summary>
  17. /// Represents a cached GPU texture.
  18. /// </summary>
  19. class Texture : IMultiRangeItem, IDisposable
  20. {
  21. // How many updates we need before switching to the byte-by-byte comparison
  22. // modification check method.
  23. // This method uses much more memory so we want to avoid it if possible.
  24. private const int ByteComparisonSwitchThreshold = 4;
  25. // Tuning for blacklisting textures from scaling when their data is updated from CPU.
  26. // Each write adds the weight, each GPU modification subtracts 1.
  27. // Exceeding the threshold blacklists the texture.
  28. private const int ScaledSetWeight = 10;
  29. private const int ScaledSetThreshold = 30;
  30. private const int MinLevelsForForceAnisotropy = 5;
  31. private struct TexturePoolOwner
  32. {
  33. public TexturePool Pool;
  34. public int ID;
  35. }
  36. private GpuContext _context;
  37. private PhysicalMemory _physicalMemory;
  38. private SizeInfo _sizeInfo;
  39. /// <summary>
  40. /// Texture format.
  41. /// </summary>
  42. public Format Format => Info.FormatInfo.Format;
  43. /// <summary>
  44. /// Texture target.
  45. /// </summary>
  46. public Target Target { get; private set; }
  47. /// <summary>
  48. /// Texture width.
  49. /// </summary>
  50. public int Width { get; private set; }
  51. /// <summary>
  52. /// Texture height.
  53. /// </summary>
  54. public int Height { get; private set; }
  55. /// <summary>
  56. /// Texture information.
  57. /// </summary>
  58. public TextureInfo Info { get; private set; }
  59. /// <summary>
  60. /// Set when anisotropic filtering can be forced on the given texture.
  61. /// </summary>
  62. public bool CanForceAnisotropy { get; private set; }
  63. /// <summary>
  64. /// Host scale factor.
  65. /// </summary>
  66. public float ScaleFactor { get; private set; }
  67. /// <summary>
  68. /// Upscaling mode. Informs if a texture is scaled, or is eligible for scaling.
  69. /// </summary>
  70. public TextureScaleMode ScaleMode { get; private set; }
  71. /// <summary>
  72. /// Group that this texture belongs to. Manages read/write memory tracking.
  73. /// </summary>
  74. public TextureGroup Group { get; private set; }
  75. /// <summary>
  76. /// Set when a texture's GPU VA has ever been partially or fully unmapped.
  77. /// This indicates that the range must be fully checked when matching the texture.
  78. /// </summary>
  79. public bool ChangedMapping { get; private set; }
  80. /// <summary>
  81. /// True if the data for this texture must always be flushed when an overlap appears.
  82. /// This is useful if SetData is called directly on this texture, but the data is meant for a future texture.
  83. /// </summary>
  84. public bool AlwaysFlushOnOverlap { get; private set; }
  85. /// <summary>
  86. /// Increments when the host texture is swapped, or when the texture is removed from all pools.
  87. /// </summary>
  88. public int InvalidatedSequence { get; private set; }
  89. private int _depth;
  90. private int _layers;
  91. public int FirstLayer { get; private set; }
  92. public int FirstLevel { get; private set; }
  93. private bool _hasData;
  94. private bool _dirty = true;
  95. private int _updateCount;
  96. private byte[] _currentData;
  97. private bool _modifiedStale = true;
  98. private ITexture _arrayViewTexture;
  99. private Target _arrayViewTarget;
  100. private ITexture _flushHostTexture;
  101. private ITexture _setHostTexture;
  102. private int _scaledSetScore;
  103. private Texture _viewStorage;
  104. private List<Texture> _views;
  105. /// <summary>
  106. /// Host texture.
  107. /// </summary>
  108. public ITexture HostTexture { get; private set; }
  109. /// <summary>
  110. /// Intrusive linked list node used on the auto deletion texture cache.
  111. /// </summary>
  112. public LinkedListNode<Texture> CacheNode { get; set; }
  113. /// <summary>
  114. /// Entry for this texture in the short duration cache, if present.
  115. /// </summary>
  116. public ShortTextureCacheEntry ShortCacheEntry { get; set; }
  117. /// Physical memory ranges where the texture data is located.
  118. /// </summary>
  119. public MultiRange Range { get; private set; }
  120. /// <summary>
  121. /// Layer size in bytes.
  122. /// </summary>
  123. public int LayerSize => _sizeInfo.LayerSize;
  124. /// <summary>
  125. /// Texture size in bytes.
  126. /// </summary>
  127. public ulong Size => (ulong)_sizeInfo.TotalSize;
  128. /// <summary>
  129. /// Whether or not the texture belongs is a view.
  130. /// </summary>
  131. public bool IsView => _viewStorage != this;
  132. private int _referenceCount;
  133. private List<TexturePoolOwner> _poolOwners;
  134. /// <summary>
  135. /// Constructs a new instance of the cached GPU texture.
  136. /// </summary>
  137. /// <param name="context">GPU context that the texture belongs to</param>
  138. /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
  139. /// <param name="info">Texture information</param>
  140. /// <param name="sizeInfo">Size information of the texture</param>
  141. /// <param name="range">Physical memory ranges where the texture data is located</param>
  142. /// <param name="firstLayer">The first layer of the texture, or 0 if the texture has no parent</param>
  143. /// <param name="firstLevel">The first mipmap level of the texture, or 0 if the texture has no parent</param>
  144. /// <param name="scaleFactor">The floating point scale factor to initialize with</param>
  145. /// <param name="scaleMode">The scale mode to initialize with</param>
  146. private Texture(
  147. GpuContext context,
  148. PhysicalMemory physicalMemory,
  149. TextureInfo info,
  150. SizeInfo sizeInfo,
  151. MultiRange range,
  152. int firstLayer,
  153. int firstLevel,
  154. float scaleFactor,
  155. TextureScaleMode scaleMode)
  156. {
  157. InitializeTexture(context, physicalMemory, info, sizeInfo, range);
  158. FirstLayer = firstLayer;
  159. FirstLevel = firstLevel;
  160. ScaleFactor = scaleFactor;
  161. ScaleMode = scaleMode;
  162. InitializeData(true);
  163. }
  164. /// <summary>
  165. /// Constructs a new instance of the cached GPU texture.
  166. /// </summary>
  167. /// <param name="context">GPU context that the texture belongs to</param>
  168. /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
  169. /// <param name="info">Texture information</param>
  170. /// <param name="sizeInfo">Size information of the texture</param>
  171. /// <param name="range">Physical memory ranges where the texture data is located</param>
  172. /// <param name="scaleMode">The scale mode to initialize with. If scaled, the texture's data is loaded immediately and scaled up</param>
  173. public Texture(
  174. GpuContext context,
  175. PhysicalMemory physicalMemory,
  176. TextureInfo info,
  177. SizeInfo sizeInfo,
  178. MultiRange range,
  179. TextureScaleMode scaleMode)
  180. {
  181. ScaleFactor = 1f; // Texture is first loaded at scale 1x.
  182. ScaleMode = scaleMode;
  183. InitializeTexture(context, physicalMemory, info, sizeInfo, range);
  184. }
  185. /// <summary>
  186. /// Common texture initialization method.
  187. /// This sets the context, info and sizeInfo fields.
  188. /// Other fields are initialized with their default values.
  189. /// </summary>
  190. /// <param name="context">GPU context that the texture belongs to</param>
  191. /// <param name="physicalMemory">Physical memory where the texture is mapped</param>
  192. /// <param name="info">Texture information</param>
  193. /// <param name="sizeInfo">Size information of the texture</param>
  194. /// <param name="range">Physical memory ranges where the texture data is located</param>
  195. private void InitializeTexture(
  196. GpuContext context,
  197. PhysicalMemory physicalMemory,
  198. TextureInfo info,
  199. SizeInfo sizeInfo,
  200. MultiRange range)
  201. {
  202. _context = context;
  203. _physicalMemory = physicalMemory;
  204. _sizeInfo = sizeInfo;
  205. Range = range;
  206. SetInfo(info);
  207. _viewStorage = this;
  208. _views = new List<Texture>();
  209. _poolOwners = new List<TexturePoolOwner>();
  210. }
  211. /// <summary>
  212. /// Initializes the data for a texture. Can optionally initialize the texture with or without data.
  213. /// If the texture is a view, it will initialize memory tracking to be non-dirty.
  214. /// </summary>
  215. /// <param name="isView">True if the texture is a view, false otherwise</param>
  216. /// <param name="withData">True if the texture is to be initialized with data</param>
  217. public void InitializeData(bool isView, bool withData = false)
  218. {
  219. withData |= Group != null && Group.FlushIncompatibleOverlapsIfNeeded();
  220. if (withData)
  221. {
  222. Debug.Assert(!isView);
  223. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
  224. HostTexture = _context.Renderer.CreateTexture(createInfo, ScaleFactor);
  225. SynchronizeMemory(); // Load the data.
  226. if (ScaleMode == TextureScaleMode.Scaled)
  227. {
  228. SetScale(GraphicsConfig.ResScale); // Scale the data up.
  229. }
  230. }
  231. else
  232. {
  233. _hasData = true;
  234. if (!isView)
  235. {
  236. // Don't update this texture the next time we synchronize.
  237. CheckModified(true);
  238. if (ScaleMode == TextureScaleMode.Scaled)
  239. {
  240. // Don't need to start at 1x as there is no data to scale, just go straight to the target scale.
  241. ScaleFactor = GraphicsConfig.ResScale;
  242. }
  243. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, ScaleFactor);
  244. HostTexture = _context.Renderer.CreateTexture(createInfo, ScaleFactor);
  245. }
  246. }
  247. }
  248. /// <summary>
  249. /// Initialize a new texture group with this texture as storage.
  250. /// </summary>
  251. /// <param name="hasLayerViews">True if the texture will have layer views</param>
  252. /// <param name="hasMipViews">True if the texture will have mip views</param>
  253. /// <param name="incompatibleOverlaps">Groups that overlap with this one but are incompatible</param>
  254. public void InitializeGroup(bool hasLayerViews, bool hasMipViews, List<TextureIncompatibleOverlap> incompatibleOverlaps)
  255. {
  256. Group = new TextureGroup(_context, _physicalMemory, this, incompatibleOverlaps);
  257. Group.Initialize(ref _sizeInfo, hasLayerViews, hasMipViews);
  258. }
  259. /// <summary>
  260. /// Create a texture view from this texture.
  261. /// A texture view is defined as a child texture, from a sub-range of their parent texture.
  262. /// For example, the initial layer and mipmap level of the view can be defined, so the texture
  263. /// will start at the given layer/level of the parent texture.
  264. /// </summary>
  265. /// <param name="info">Child texture information</param>
  266. /// <param name="sizeInfo">Child texture size information</param>
  267. /// <param name="range">Physical memory ranges where the texture data is located</param>
  268. /// <param name="firstLayer">Start layer of the child texture on the parent texture</param>
  269. /// <param name="firstLevel">Start mipmap level of the child texture on the parent texture</param>
  270. /// <returns>The child texture</returns>
  271. public Texture CreateView(TextureInfo info, SizeInfo sizeInfo, MultiRange range, int firstLayer, int firstLevel)
  272. {
  273. Texture texture = new Texture(
  274. _context,
  275. _physicalMemory,
  276. info,
  277. sizeInfo,
  278. range,
  279. FirstLayer + firstLayer,
  280. FirstLevel + firstLevel,
  281. ScaleFactor,
  282. ScaleMode);
  283. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(info, _context.Capabilities, ScaleFactor);
  284. texture.HostTexture = HostTexture.CreateView(createInfo, firstLayer, firstLevel);
  285. _viewStorage.AddView(texture);
  286. return texture;
  287. }
  288. /// <summary>
  289. /// Adds a child texture to this texture.
  290. /// </summary>
  291. /// <param name="texture">The child texture</param>
  292. private void AddView(Texture texture)
  293. {
  294. IncrementReferenceCount();
  295. _views.Add(texture);
  296. texture._viewStorage = this;
  297. Group.UpdateViews(_views);
  298. if (texture.Group != null && texture.Group != Group)
  299. {
  300. if (texture.Group.Storage == texture)
  301. {
  302. // This texture's group is no longer used.
  303. Group.Inherit(texture.Group);
  304. texture.Group.Dispose();
  305. }
  306. }
  307. texture.Group = Group;
  308. }
  309. /// <summary>
  310. /// Removes a child texture from this texture.
  311. /// </summary>
  312. /// <param name="texture">The child texture</param>
  313. private void RemoveView(Texture texture)
  314. {
  315. _views.Remove(texture);
  316. texture._viewStorage = texture;
  317. DecrementReferenceCount();
  318. }
  319. /// <summary>
  320. /// Create a copy dependency to a texture that is view compatible with this one.
  321. /// When either texture is modified, the texture data will be copied to the other to keep them in sync.
  322. /// This is essentially an emulated view, useful for handling multiple view parents or format incompatibility.
  323. /// This also forces a copy on creation, to or from the given texture to get them in sync immediately.
  324. /// </summary>
  325. /// <param name="contained">The view compatible texture to create a dependency to</param>
  326. /// <param name="layer">The base layer of the given texture relative to this one</param>
  327. /// <param name="level">The base level of the given texture relative to this one</param>
  328. /// <param name="copyTo">True if this texture is first copied to the given one, false for the opposite direction</param>
  329. public void CreateCopyDependency(Texture contained, int layer, int level, bool copyTo)
  330. {
  331. if (contained.Group == Group)
  332. {
  333. return;
  334. }
  335. Group.CreateCopyDependency(contained, FirstLayer + layer, FirstLevel + level, copyTo);
  336. }
  337. /// <summary>
  338. /// Registers when a texture has had its data set after being scaled, and
  339. /// determines if it should be blacklisted from scaling to improve performance.
  340. /// </summary>
  341. /// <returns>True if setting data for a scaled texture is allowed, false if the texture has been blacklisted</returns>
  342. private bool AllowScaledSetData()
  343. {
  344. _scaledSetScore += ScaledSetWeight;
  345. if (_scaledSetScore >= ScaledSetThreshold)
  346. {
  347. BlacklistScale();
  348. return false;
  349. }
  350. return true;
  351. }
  352. /// <summary>
  353. /// Blacklists this texture from being scaled. Resets its scale to 1 if needed.
  354. /// </summary>
  355. public void BlacklistScale()
  356. {
  357. ScaleMode = TextureScaleMode.Blacklisted;
  358. SetScale(1f);
  359. }
  360. /// <summary>
  361. /// Propagates the scale between this texture and another to ensure they have the same scale.
  362. /// If one texture is blacklisted from scaling, the other will become blacklisted too.
  363. /// </summary>
  364. /// <param name="other">The other texture</param>
  365. public void PropagateScale(Texture other)
  366. {
  367. if (other.ScaleMode == TextureScaleMode.Blacklisted || ScaleMode == TextureScaleMode.Blacklisted)
  368. {
  369. BlacklistScale();
  370. other.BlacklistScale();
  371. }
  372. else
  373. {
  374. // Prefer the configured scale if present. If not, prefer the max.
  375. float targetScale = GraphicsConfig.ResScale;
  376. float sharedScale = (ScaleFactor == targetScale || other.ScaleFactor == targetScale) ? targetScale : Math.Max(ScaleFactor, other.ScaleFactor);
  377. SetScale(sharedScale);
  378. other.SetScale(sharedScale);
  379. }
  380. }
  381. /// <summary>
  382. /// Copy the host texture to a scaled one. If a texture is not provided, create it with the given scale.
  383. /// </summary>
  384. /// <param name="scale">Scale factor</param>
  385. /// <param name="copy">True if the data should be copied to the texture, false otherwise</param>
  386. /// <param name="storage">Texture to use instead of creating one</param>
  387. /// <returns>A host texture containing a scaled version of this texture</returns>
  388. private ITexture GetScaledHostTexture(float scale, bool copy, ITexture storage = null)
  389. {
  390. if (storage == null)
  391. {
  392. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(Info, _context.Capabilities, scale);
  393. storage = _context.Renderer.CreateTexture(createInfo, scale);
  394. }
  395. if (copy)
  396. {
  397. HostTexture.CopyTo(storage, new Extents2D(0, 0, HostTexture.Width, HostTexture.Height), new Extents2D(0, 0, storage.Width, storage.Height), true);
  398. }
  399. return storage;
  400. }
  401. /// <summary>
  402. /// Sets the Scale Factor on this texture, and immediately recreates it at the correct size.
  403. /// When a texture is resized, a scaled copy is performed from the old texture to the new one, to ensure no data is lost.
  404. /// If scale is equivalent, this only propagates the blacklisted/scaled mode.
  405. /// If called on a view, its storage is resized instead.
  406. /// When resizing storage, all texture views are recreated.
  407. /// </summary>
  408. /// <param name="scale">The new scale factor for this texture</param>
  409. public void SetScale(float scale)
  410. {
  411. bool unscaled = ScaleMode == TextureScaleMode.Blacklisted || (ScaleMode == TextureScaleMode.Undesired && scale == 1);
  412. TextureScaleMode newScaleMode = unscaled ? ScaleMode : TextureScaleMode.Scaled;
  413. if (_viewStorage != this)
  414. {
  415. _viewStorage.ScaleMode = newScaleMode;
  416. _viewStorage.SetScale(scale);
  417. return;
  418. }
  419. if (ScaleFactor != scale)
  420. {
  421. Logger.Debug?.Print(LogClass.Gpu, $"Rescaling {Info.Width}x{Info.Height} {Info.FormatInfo.Format.ToString()} to ({ScaleFactor} to {scale}). ");
  422. ScaleFactor = scale;
  423. ITexture newStorage = GetScaledHostTexture(ScaleFactor, true);
  424. Logger.Debug?.Print(LogClass.Gpu, $" Copy performed: {HostTexture.Width}x{HostTexture.Height} to {newStorage.Width}x{newStorage.Height}");
  425. ReplaceStorage(newStorage);
  426. // All views must be recreated against the new storage.
  427. foreach (var view in _views)
  428. {
  429. Logger.Debug?.Print(LogClass.Gpu, $" Recreating view {Info.Width}x{Info.Height} {Info.FormatInfo.Format.ToString()}.");
  430. view.ScaleFactor = scale;
  431. TextureCreateInfo viewCreateInfo = TextureCache.GetCreateInfo(view.Info, _context.Capabilities, scale);
  432. ITexture newView = HostTexture.CreateView(viewCreateInfo, view.FirstLayer - FirstLayer, view.FirstLevel - FirstLevel);
  433. view.ReplaceStorage(newView);
  434. view.ScaleMode = newScaleMode;
  435. }
  436. }
  437. if (ScaleMode != newScaleMode)
  438. {
  439. ScaleMode = newScaleMode;
  440. foreach (var view in _views)
  441. {
  442. view.ScaleMode = newScaleMode;
  443. }
  444. }
  445. }
  446. /// <summary>
  447. /// Checks if the memory for this texture was modified, and returns true if it was.
  448. /// The modified flags are optionally consumed as a result.
  449. /// </summary>
  450. /// <param name="consume">True to consume the dirty flags and reprotect, false to leave them as is</param>
  451. /// <returns>True if the texture was modified, false otherwise.</returns>
  452. public bool CheckModified(bool consume)
  453. {
  454. return Group.CheckDirty(this, consume);
  455. }
  456. /// <summary>
  457. /// Synchronizes guest and host memory.
  458. /// This will overwrite the texture data with the texture data on the guest memory, if a CPU
  459. /// modification is detected.
  460. /// Be aware that this can cause texture data written by the GPU to be lost, this is just a
  461. /// one way copy (from CPU owned to GPU owned memory).
  462. /// </summary>
  463. public void SynchronizeMemory()
  464. {
  465. if (Target == Target.TextureBuffer)
  466. {
  467. return;
  468. }
  469. if (!_dirty)
  470. {
  471. return;
  472. }
  473. _dirty = false;
  474. if (_hasData)
  475. {
  476. Group.SynchronizeMemory(this);
  477. }
  478. else
  479. {
  480. Group.CheckDirty(this, true);
  481. SynchronizeFull();
  482. }
  483. }
  484. /// <summary>
  485. /// Signal that this texture is dirty, indicating that the texture group must be checked.
  486. /// </summary>
  487. public void SignalGroupDirty()
  488. {
  489. _dirty = true;
  490. }
  491. /// <summary>
  492. /// Signal that the modified state is dirty, indicating that the texture group should be notified when it changes.
  493. /// </summary>
  494. public void SignalModifiedDirty()
  495. {
  496. _modifiedStale = true;
  497. }
  498. /// <summary>
  499. /// Fully synchronizes guest and host memory.
  500. /// This will replace the entire texture with the data present in guest memory.
  501. /// </summary>
  502. public void SynchronizeFull()
  503. {
  504. ReadOnlySpan<byte> data = _physicalMemory.GetSpan(Range);
  505. // If the host does not support ASTC compression, we need to do the decompression.
  506. // The decompression is slow, so we want to avoid it as much as possible.
  507. // This does a byte-by-byte check and skips the update if the data is equal in this case.
  508. // This improves the speed on applications that overwrites ASTC data without changing anything.
  509. if (Info.FormatInfo.Format.IsAstc() && !_context.Capabilities.SupportsAstcCompression)
  510. {
  511. if (_updateCount < ByteComparisonSwitchThreshold)
  512. {
  513. _updateCount++;
  514. }
  515. else
  516. {
  517. bool dataMatches = _currentData != null && data.SequenceEqual(_currentData);
  518. if (dataMatches)
  519. {
  520. return;
  521. }
  522. _currentData = data.ToArray();
  523. }
  524. }
  525. SpanOrArray<byte> result = ConvertToHostCompatibleFormat(data);
  526. if (ScaleFactor != 1f && AllowScaledSetData())
  527. {
  528. // If needed, create a texture to load from 1x scale.
  529. ITexture texture = _setHostTexture = GetScaledHostTexture(1f, false, _setHostTexture);
  530. texture.SetData(result);
  531. texture.CopyTo(HostTexture, new Extents2D(0, 0, texture.Width, texture.Height), new Extents2D(0, 0, HostTexture.Width, HostTexture.Height), true);
  532. }
  533. else
  534. {
  535. HostTexture.SetData(result);
  536. }
  537. _hasData = true;
  538. }
  539. /// <summary>
  540. /// Uploads new texture data to the host GPU.
  541. /// </summary>
  542. /// <param name="data">New data</param>
  543. public void SetData(SpanOrArray<byte> data)
  544. {
  545. BlacklistScale();
  546. Group.CheckDirty(this, true);
  547. AlwaysFlushOnOverlap = true;
  548. HostTexture.SetData(data);
  549. _hasData = true;
  550. }
  551. /// <summary>
  552. /// Uploads new texture data to the host GPU for a specific layer/level.
  553. /// </summary>
  554. /// <param name="data">New data</param>
  555. /// <param name="layer">Target layer</param>
  556. /// <param name="level">Target level</param>
  557. public void SetData(SpanOrArray<byte> data, int layer, int level)
  558. {
  559. BlacklistScale();
  560. HostTexture.SetData(data, layer, level);
  561. _currentData = null;
  562. _hasData = true;
  563. }
  564. /// <summary>
  565. /// Uploads new texture data to the host GPU for a specific layer/level and 2D sub-region.
  566. /// </summary>
  567. /// <param name="data">New data</param>
  568. /// <param name="layer">Target layer</param>
  569. /// <param name="level">Target level</param>
  570. /// <param name="region">Target sub-region of the texture to update</param>
  571. public void SetData(ReadOnlySpan<byte> data, int layer, int level, Rectangle<int> region)
  572. {
  573. BlacklistScale();
  574. HostTexture.SetData(data, layer, level, region);
  575. _currentData = null;
  576. _hasData = true;
  577. }
  578. /// <summary>
  579. /// Converts texture data to a format and layout that is supported by the host GPU.
  580. /// </summary>
  581. /// <param name="data">Data to be converted</param>
  582. /// <param name="level">Mip level to convert</param>
  583. /// <param name="single">True to convert a single slice</param>
  584. /// <returns>Converted data</returns>
  585. public SpanOrArray<byte> ConvertToHostCompatibleFormat(ReadOnlySpan<byte> data, int level = 0, bool single = false)
  586. {
  587. int width = Info.Width;
  588. int height = Info.Height;
  589. int depth = _depth;
  590. int layers = single ? 1 : _layers;
  591. int levels = single ? 1 : (Info.Levels - level);
  592. width = Math.Max(width >> level, 1);
  593. height = Math.Max(height >> level, 1);
  594. depth = Math.Max(depth >> level, 1);
  595. SpanOrArray<byte> result;
  596. if (Info.IsLinear)
  597. {
  598. result = LayoutConverter.ConvertLinearStridedToLinear(
  599. width,
  600. height,
  601. Info.FormatInfo.BlockWidth,
  602. Info.FormatInfo.BlockHeight,
  603. Info.Stride,
  604. Info.Stride,
  605. Info.FormatInfo.BytesPerPixel,
  606. data);
  607. }
  608. else
  609. {
  610. result = LayoutConverter.ConvertBlockLinearToLinear(
  611. width,
  612. height,
  613. depth,
  614. single ? 1 : depth,
  615. levels,
  616. layers,
  617. Info.FormatInfo.BlockWidth,
  618. Info.FormatInfo.BlockHeight,
  619. Info.FormatInfo.BytesPerPixel,
  620. Info.GobBlocksInY,
  621. Info.GobBlocksInZ,
  622. Info.GobBlocksInTileX,
  623. _sizeInfo,
  624. data);
  625. }
  626. // Handle compressed cases not supported by the host:
  627. // - ASTC is usually not supported on desktop cards.
  628. // - BC4/BC5 is not supported on 3D textures.
  629. if (!_context.Capabilities.SupportsAstcCompression && Format.IsAstc())
  630. {
  631. if (!AstcDecoder.TryDecodeToRgba8P(
  632. result.ToArray(),
  633. Info.FormatInfo.BlockWidth,
  634. Info.FormatInfo.BlockHeight,
  635. width,
  636. height,
  637. depth,
  638. levels,
  639. layers,
  640. out byte[] decoded))
  641. {
  642. string texInfo = $"{Info.Target} {Info.FormatInfo.Format} {Info.Width}x{Info.Height}x{Info.DepthOrLayers} levels {Info.Levels}";
  643. Logger.Debug?.Print(LogClass.Gpu, $"Invalid ASTC texture at 0x{Info.GpuAddress:X} ({texInfo}).");
  644. }
  645. if (GraphicsConfig.EnableTextureRecompression)
  646. {
  647. decoded = BCnEncoder.EncodeBC7(decoded, width, height, depth, levels, layers);
  648. }
  649. result = decoded;
  650. }
  651. else if (!_context.Capabilities.SupportsEtc2Compression && Format.IsEtc2())
  652. {
  653. switch (Format)
  654. {
  655. case Format.Etc2RgbaSrgb:
  656. case Format.Etc2RgbaUnorm:
  657. result = ETC2Decoder.DecodeRgba(result, width, height, depth, levels, layers);
  658. break;
  659. case Format.Etc2RgbPtaSrgb:
  660. case Format.Etc2RgbPtaUnorm:
  661. result = ETC2Decoder.DecodePta(result, width, height, depth, levels, layers);
  662. break;
  663. case Format.Etc2RgbSrgb:
  664. case Format.Etc2RgbUnorm:
  665. result = ETC2Decoder.DecodeRgb(result, width, height, depth, levels, layers);
  666. break;
  667. }
  668. }
  669. else if (!TextureCompatibility.HostSupportsBcFormat(Format, Target, _context.Capabilities))
  670. {
  671. switch (Format)
  672. {
  673. case Format.Bc1RgbaSrgb:
  674. case Format.Bc1RgbaUnorm:
  675. result = BCnDecoder.DecodeBC1(result, width, height, depth, levels, layers);
  676. break;
  677. case Format.Bc2Srgb:
  678. case Format.Bc2Unorm:
  679. result = BCnDecoder.DecodeBC2(result, width, height, depth, levels, layers);
  680. break;
  681. case Format.Bc3Srgb:
  682. case Format.Bc3Unorm:
  683. result = BCnDecoder.DecodeBC3(result, width, height, depth, levels, layers);
  684. break;
  685. case Format.Bc4Snorm:
  686. case Format.Bc4Unorm:
  687. result = BCnDecoder.DecodeBC4(result, width, height, depth, levels, layers, Format == Format.Bc4Snorm);
  688. break;
  689. case Format.Bc5Snorm:
  690. case Format.Bc5Unorm:
  691. result = BCnDecoder.DecodeBC5(result, width, height, depth, levels, layers, Format == Format.Bc5Snorm);
  692. break;
  693. case Format.Bc6HSfloat:
  694. case Format.Bc6HUfloat:
  695. result = BCnDecoder.DecodeBC6(result, width, height, depth, levels, layers, Format == Format.Bc6HSfloat);
  696. break;
  697. case Format.Bc7Srgb:
  698. case Format.Bc7Unorm:
  699. result = BCnDecoder.DecodeBC7(result, width, height, depth, levels, layers);
  700. break;
  701. }
  702. }
  703. else if (!_context.Capabilities.SupportsR4G4Format && Format == Format.R4G4Unorm)
  704. {
  705. result = PixelConverter.ConvertR4G4ToR4G4B4A4(result, width);
  706. if (!_context.Capabilities.SupportsR4G4B4A4Format)
  707. {
  708. result = PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(result, width);
  709. }
  710. }
  711. else if (Format == Format.R4G4B4A4Unorm)
  712. {
  713. if (!_context.Capabilities.SupportsR4G4B4A4Format)
  714. {
  715. result = PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(result, width);
  716. }
  717. }
  718. else if (!_context.Capabilities.Supports5BitComponentFormat && Format.Is16BitPacked())
  719. {
  720. switch (Format)
  721. {
  722. case Format.B5G6R5Unorm:
  723. case Format.R5G6B5Unorm:
  724. result = PixelConverter.ConvertR5G6B5ToR8G8B8A8(result, width);
  725. break;
  726. case Format.B5G5R5A1Unorm:
  727. case Format.R5G5B5X1Unorm:
  728. case Format.R5G5B5A1Unorm:
  729. result = PixelConverter.ConvertR5G5B5ToR8G8B8A8(result, width, Format == Format.R5G5B5X1Unorm);
  730. break;
  731. case Format.A1B5G5R5Unorm:
  732. result = PixelConverter.ConvertA1B5G5R5ToR8G8B8A8(result, width);
  733. break;
  734. case Format.R4G4B4A4Unorm:
  735. result = PixelConverter.ConvertR4G4B4A4ToR8G8B8A8(result, width);
  736. break;
  737. }
  738. }
  739. return result;
  740. }
  741. /// <summary>
  742. /// Converts texture data from a format and layout that is supported by the host GPU, back into the intended format on the guest GPU.
  743. /// </summary>
  744. /// <param name="output">Optional output span to convert into</param>
  745. /// <param name="data">Data to be converted</param>
  746. /// <param name="level">Mip level to convert</param>
  747. /// <param name="single">True to convert a single slice</param>
  748. /// <returns>Converted data</returns>
  749. public ReadOnlySpan<byte> ConvertFromHostCompatibleFormat(Span<byte> output, ReadOnlySpan<byte> data, int level = 0, bool single = false)
  750. {
  751. if (Target != Target.TextureBuffer)
  752. {
  753. int width = Info.Width;
  754. int height = Info.Height;
  755. int depth = _depth;
  756. int layers = single ? 1 : _layers;
  757. int levels = single ? 1 : (Info.Levels - level);
  758. width = Math.Max(width >> level, 1);
  759. height = Math.Max(height >> level, 1);
  760. depth = Math.Max(depth >> level, 1);
  761. if (Info.IsLinear)
  762. {
  763. data = LayoutConverter.ConvertLinearToLinearStrided(
  764. output,
  765. Info.Width,
  766. Info.Height,
  767. Info.FormatInfo.BlockWidth,
  768. Info.FormatInfo.BlockHeight,
  769. Info.Stride,
  770. Info.FormatInfo.BytesPerPixel,
  771. data);
  772. }
  773. else
  774. {
  775. data = LayoutConverter.ConvertLinearToBlockLinear(
  776. output,
  777. width,
  778. height,
  779. depth,
  780. single ? 1 : depth,
  781. levels,
  782. layers,
  783. Info.FormatInfo.BlockWidth,
  784. Info.FormatInfo.BlockHeight,
  785. Info.FormatInfo.BytesPerPixel,
  786. Info.GobBlocksInY,
  787. Info.GobBlocksInZ,
  788. Info.GobBlocksInTileX,
  789. _sizeInfo,
  790. data);
  791. }
  792. }
  793. return data;
  794. }
  795. /// <summary>
  796. /// Flushes the texture data.
  797. /// This causes the texture data to be written back to guest memory.
  798. /// If the texture was written by the GPU, this includes all modification made by the GPU
  799. /// up to this point.
  800. /// Be aware that this is an expensive operation, avoid calling it unless strictly needed.
  801. /// This may cause data corruption if the memory is already being used for something else on the CPU side.
  802. /// </summary>
  803. /// <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>
  804. /// <returns>True if data was flushed, false otherwise</returns>
  805. public bool FlushModified(bool tracked = true)
  806. {
  807. return TextureCompatibility.CanTextureFlush(Info, _context.Capabilities) && Group.FlushModified(this, tracked);
  808. }
  809. /// <summary>
  810. /// Flushes the texture data.
  811. /// This causes the texture data to be written back to guest memory.
  812. /// If the texture was written by the GPU, this includes all modification made by the GPU
  813. /// up to this point.
  814. /// Be aware that this is an expensive operation, avoid calling it unless strictly needed.
  815. /// This may cause data corruption if the memory is already being used for something else on the CPU side.
  816. /// </summary>
  817. /// <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>
  818. public void Flush(bool tracked)
  819. {
  820. if (TextureCompatibility.CanTextureFlush(Info, _context.Capabilities))
  821. {
  822. FlushTextureDataToGuest(tracked);
  823. }
  824. }
  825. /// <summary>
  826. /// Gets a host texture to use for flushing the texture, at 1x resolution.
  827. /// If the HostTexture is already at 1x resolution, it is returned directly.
  828. /// </summary>
  829. /// <returns>The host texture to flush</returns>
  830. public ITexture GetFlushTexture()
  831. {
  832. ITexture texture = HostTexture;
  833. if (ScaleFactor != 1f)
  834. {
  835. // If needed, create a texture to flush back to host at 1x scale.
  836. texture = _flushHostTexture = GetScaledHostTexture(1f, true, _flushHostTexture);
  837. }
  838. return texture;
  839. }
  840. /// <summary>
  841. /// Gets data from the host GPU, and flushes it all to guest memory.
  842. /// </summary>
  843. /// <remarks>
  844. /// This method should be used to retrieve data that was modified by the host GPU.
  845. /// This is not cheap, avoid doing that unless strictly needed.
  846. /// When possible, the data is written directly into guest memory, rather than copied.
  847. /// </remarks>
  848. /// <param name="tracked">True if writing the texture data is tracked, false otherwise</param>
  849. /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
  850. public void FlushTextureDataToGuest(bool tracked, ITexture texture = null)
  851. {
  852. using WritableRegion region = _physicalMemory.GetWritableRegion(Range, tracked);
  853. GetTextureDataFromGpu(region.Memory.Span, tracked, texture);
  854. }
  855. /// <summary>
  856. /// Gets data from the host GPU.
  857. /// </summary>
  858. /// <remarks>
  859. /// This method should be used to retrieve data that was modified by the host GPU.
  860. /// This is not cheap, avoid doing that unless strictly needed.
  861. /// </remarks>
  862. /// <param name="output">An output span to place the texture data into. If empty, one is generated</param>
  863. /// <param name="blacklist">True if the texture should be blacklisted, false otherwise</param>
  864. /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
  865. /// <returns>The span containing the texture data</returns>
  866. private ReadOnlySpan<byte> GetTextureDataFromGpu(Span<byte> output, bool blacklist, ITexture texture = null)
  867. {
  868. ReadOnlySpan<byte> data;
  869. if (texture != null)
  870. {
  871. data = texture.GetData();
  872. }
  873. else
  874. {
  875. if (blacklist)
  876. {
  877. BlacklistScale();
  878. data = HostTexture.GetData();
  879. }
  880. else if (ScaleFactor != 1f)
  881. {
  882. float scale = ScaleFactor;
  883. SetScale(1f);
  884. data = HostTexture.GetData();
  885. SetScale(scale);
  886. }
  887. else
  888. {
  889. data = HostTexture.GetData();
  890. }
  891. }
  892. data = ConvertFromHostCompatibleFormat(output, data);
  893. return data;
  894. }
  895. /// <summary>
  896. /// Gets data from the host GPU for a single slice.
  897. /// </summary>
  898. /// <remarks>
  899. /// This method should be used to retrieve data that was modified by the host GPU.
  900. /// This is not cheap, avoid doing that unless strictly needed.
  901. /// </remarks>
  902. /// <param name="output">An output span to place the texture data into. If empty, one is generated</param>
  903. /// <param name="layer">The layer of the texture to flush</param>
  904. /// <param name="level">The level of the texture to flush</param>
  905. /// <param name="blacklist">True if the texture should be blacklisted, false otherwise</param>
  906. /// <param name="texture">The specific host texture to flush. Defaults to this texture</param>
  907. /// <returns>The span containing the texture data</returns>
  908. public ReadOnlySpan<byte> GetTextureDataSliceFromGpu(Span<byte> output, int layer, int level, bool blacklist, ITexture texture = null)
  909. {
  910. ReadOnlySpan<byte> data;
  911. if (texture != null)
  912. {
  913. data = texture.GetData(layer, level);
  914. }
  915. else
  916. {
  917. if (blacklist)
  918. {
  919. BlacklistScale();
  920. data = HostTexture.GetData(layer, level);
  921. }
  922. else if (ScaleFactor != 1f)
  923. {
  924. float scale = ScaleFactor;
  925. SetScale(1f);
  926. data = HostTexture.GetData(layer, level);
  927. SetScale(scale);
  928. }
  929. else
  930. {
  931. data = HostTexture.GetData(layer, level);
  932. }
  933. }
  934. data = ConvertFromHostCompatibleFormat(output, data, level, true);
  935. return data;
  936. }
  937. /// <summary>
  938. /// This performs a strict comparison, used to check if this texture is equal to the one supplied.
  939. /// </summary>
  940. /// <param name="info">Texture information to compare against</param>
  941. /// <param name="flags">Comparison flags</param>
  942. /// <returns>A value indicating how well this texture matches the given info</returns>
  943. public TextureMatchQuality IsExactMatch(TextureInfo info, TextureSearchFlags flags)
  944. {
  945. bool forSampler = (flags & TextureSearchFlags.ForSampler) != 0;
  946. TextureMatchQuality matchQuality = TextureCompatibility.FormatMatches(Info, info, forSampler, (flags & TextureSearchFlags.ForCopy) != 0);
  947. if (matchQuality == TextureMatchQuality.NoMatch)
  948. {
  949. return matchQuality;
  950. }
  951. if (!TextureCompatibility.LayoutMatches(Info, info))
  952. {
  953. return TextureMatchQuality.NoMatch;
  954. }
  955. if (!TextureCompatibility.SizeMatches(Info, info, forSampler))
  956. {
  957. return TextureMatchQuality.NoMatch;
  958. }
  959. if ((flags & TextureSearchFlags.ForSampler) != 0)
  960. {
  961. if (!TextureCompatibility.SamplerParamsMatches(Info, info))
  962. {
  963. return TextureMatchQuality.NoMatch;
  964. }
  965. }
  966. if ((flags & TextureSearchFlags.ForCopy) != 0)
  967. {
  968. bool msTargetCompatible = Info.Target == Target.Texture2DMultisample && info.Target == Target.Texture2D;
  969. if (!msTargetCompatible && !TextureCompatibility.TargetAndSamplesCompatible(Info, info))
  970. {
  971. return TextureMatchQuality.NoMatch;
  972. }
  973. }
  974. else if (!TextureCompatibility.TargetAndSamplesCompatible(Info, info))
  975. {
  976. return TextureMatchQuality.NoMatch;
  977. }
  978. return Info.Levels == info.Levels ? matchQuality : TextureMatchQuality.NoMatch;
  979. }
  980. /// <summary>
  981. /// Check if it's possible to create a view, with the given parameters, from this texture.
  982. /// </summary>
  983. /// <param name="info">Texture view information</param>
  984. /// <param name="range">Texture view physical memory ranges</param>
  985. /// <param name="exactSize">Indicates if the texture sizes must be exactly equal, or width is allowed to differ</param>
  986. /// <param name="layerSize">Layer size on the given texture</param>
  987. /// <param name="caps">Host GPU capabilities</param>
  988. /// <param name="firstLayer">Texture view initial layer on this texture</param>
  989. /// <param name="firstLevel">Texture view first mipmap level on this texture</param>
  990. /// <returns>The level of compatiblilty a view with the given parameters created from this texture has</returns>
  991. public TextureViewCompatibility IsViewCompatible(
  992. TextureInfo info,
  993. MultiRange range,
  994. bool exactSize,
  995. int layerSize,
  996. Capabilities caps,
  997. out int firstLayer,
  998. out int firstLevel)
  999. {
  1000. TextureViewCompatibility result = TextureViewCompatibility.Full;
  1001. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewFormatCompatible(Info, info, caps));
  1002. if (result != TextureViewCompatibility.Incompatible)
  1003. {
  1004. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewTargetCompatible(Info, info, ref caps));
  1005. bool bothMs = Info.Target.IsMultisample() && info.Target.IsMultisample();
  1006. if (bothMs && (Info.SamplesInX != info.SamplesInX || Info.SamplesInY != info.SamplesInY))
  1007. {
  1008. result = TextureViewCompatibility.Incompatible;
  1009. }
  1010. if (result == TextureViewCompatibility.Full && Info.FormatInfo.Format != info.FormatInfo.Format && !_context.Capabilities.SupportsMismatchingViewFormat)
  1011. {
  1012. // AMD and Intel have a bug where the view format is always ignored;
  1013. // they use the parent format instead.
  1014. // Create a copy dependency to avoid this issue.
  1015. result = TextureViewCompatibility.CopyOnly;
  1016. }
  1017. }
  1018. firstLayer = 0;
  1019. firstLevel = 0;
  1020. if (result == TextureViewCompatibility.Incompatible)
  1021. {
  1022. return TextureViewCompatibility.Incompatible;
  1023. }
  1024. int offset = Range.FindOffset(range);
  1025. if (offset < 0 || !_sizeInfo.FindView(offset, out firstLayer, out firstLevel))
  1026. {
  1027. return TextureViewCompatibility.LayoutIncompatible;
  1028. }
  1029. if (!TextureCompatibility.ViewLayoutCompatible(Info, info, firstLevel))
  1030. {
  1031. return TextureViewCompatibility.LayoutIncompatible;
  1032. }
  1033. if (info.GetSlices() > 1 && LayerSize != layerSize)
  1034. {
  1035. return TextureViewCompatibility.LayoutIncompatible;
  1036. }
  1037. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewSizeMatches(Info, info, exactSize, firstLevel));
  1038. result = TextureCompatibility.PropagateViewCompatibility(result, TextureCompatibility.ViewSubImagesInBounds(Info, info, firstLayer, firstLevel));
  1039. return result;
  1040. }
  1041. /// <summary>
  1042. /// Gets a texture of the specified target type from this texture.
  1043. /// This can be used to get an array texture from a non-array texture and vice-versa.
  1044. /// If this texture and the requested targets are equal, then this texture Host texture is returned directly.
  1045. /// </summary>
  1046. /// <param name="target">The desired target type</param>
  1047. /// <returns>A view of this texture with the requested target, or null if the target is invalid for this texture</returns>
  1048. public ITexture GetTargetTexture(Target target)
  1049. {
  1050. if (target == Target)
  1051. {
  1052. return HostTexture;
  1053. }
  1054. if (_arrayViewTexture == null && IsSameDimensionsTarget(target))
  1055. {
  1056. FormatInfo formatInfo = TextureCompatibility.ToHostCompatibleFormat(Info, _context.Capabilities);
  1057. TextureCreateInfo createInfo = new TextureCreateInfo(
  1058. Info.Width,
  1059. Info.Height,
  1060. target == Target.CubemapArray ? 6 : 1,
  1061. Info.Levels,
  1062. Info.Samples,
  1063. formatInfo.BlockWidth,
  1064. formatInfo.BlockHeight,
  1065. formatInfo.BytesPerPixel,
  1066. formatInfo.Format,
  1067. Info.DepthStencilMode,
  1068. target,
  1069. Info.SwizzleR,
  1070. Info.SwizzleG,
  1071. Info.SwizzleB,
  1072. Info.SwizzleA);
  1073. ITexture viewTexture = HostTexture.CreateView(createInfo, 0, 0);
  1074. _arrayViewTexture = viewTexture;
  1075. _arrayViewTarget = target;
  1076. return viewTexture;
  1077. }
  1078. else if (_arrayViewTarget == target)
  1079. {
  1080. return _arrayViewTexture;
  1081. }
  1082. return null;
  1083. }
  1084. /// <summary>
  1085. /// Determine if this texture can have anisotropic filtering forced.
  1086. /// Filtered textures that we might want to force anisotropy on should have a lot of mip levels.
  1087. /// </summary>
  1088. /// <returns>True if anisotropic filtering can be forced, false otherwise</returns>
  1089. private bool CanTextureForceAnisotropy()
  1090. {
  1091. if (!(Target == Target.Texture2D || Target == Target.Texture2DArray))
  1092. {
  1093. return false;
  1094. }
  1095. int maxSize = Math.Max(Info.Width, Info.Height);
  1096. int maxLevels = BitOperations.Log2((uint)maxSize) + 1;
  1097. return Info.Levels >= Math.Min(MinLevelsForForceAnisotropy, maxLevels);
  1098. }
  1099. /// <summary>
  1100. /// Check if this texture and the specified target have the same number of dimensions.
  1101. /// For the purposes of this comparison, 2D and 2D Multisample textures are not considered to have
  1102. /// the same number of dimensions. Same for Cubemap and 3D textures.
  1103. /// </summary>
  1104. /// <param name="target">The target to compare with</param>
  1105. /// <returns>True if both targets have the same number of dimensions, false otherwise</returns>
  1106. private bool IsSameDimensionsTarget(Target target)
  1107. {
  1108. switch (Info.Target)
  1109. {
  1110. case Target.Texture1D:
  1111. case Target.Texture1DArray:
  1112. return target == Target.Texture1D ||
  1113. target == Target.Texture1DArray;
  1114. case Target.Texture2D:
  1115. case Target.Texture2DArray:
  1116. return target == Target.Texture2D ||
  1117. target == Target.Texture2DArray;
  1118. case Target.Cubemap:
  1119. case Target.CubemapArray:
  1120. return target == Target.Cubemap ||
  1121. target == Target.CubemapArray;
  1122. case Target.Texture2DMultisample:
  1123. case Target.Texture2DMultisampleArray:
  1124. return target == Target.Texture2DMultisample ||
  1125. target == Target.Texture2DMultisampleArray;
  1126. case Target.Texture3D:
  1127. return target == Target.Texture3D;
  1128. }
  1129. return false;
  1130. }
  1131. /// <summary>
  1132. /// Replaces view texture information.
  1133. /// This should only be used for child textures with a parent.
  1134. /// </summary>
  1135. /// <param name="parent">The parent texture</param>
  1136. /// <param name="info">The new view texture information</param>
  1137. /// <param name="hostTexture">The new host texture</param>
  1138. /// <param name="firstLayer">The first layer of the view</param>
  1139. /// <param name="firstLevel">The first level of the view</param>
  1140. public void ReplaceView(Texture parent, TextureInfo info, ITexture hostTexture, int firstLayer, int firstLevel)
  1141. {
  1142. IncrementReferenceCount();
  1143. parent._viewStorage.SynchronizeMemory();
  1144. // If this texture has views, they must be given to the new parent.
  1145. if (_views.Count > 0)
  1146. {
  1147. Texture[] viewCopy = _views.ToArray();
  1148. foreach (Texture view in viewCopy)
  1149. {
  1150. TextureCreateInfo createInfo = TextureCache.GetCreateInfo(view.Info, _context.Capabilities, ScaleFactor);
  1151. ITexture newView = parent.HostTexture.CreateView(createInfo, view.FirstLayer + firstLayer, view.FirstLevel + firstLevel);
  1152. view.ReplaceView(parent, view.Info, newView, view.FirstLayer + firstLayer, view.FirstLevel + firstLevel);
  1153. }
  1154. }
  1155. ReplaceStorage(hostTexture);
  1156. if (_viewStorage != this)
  1157. {
  1158. _viewStorage.RemoveView(this);
  1159. }
  1160. FirstLayer = parent.FirstLayer + firstLayer;
  1161. FirstLevel = parent.FirstLevel + firstLevel;
  1162. parent._viewStorage.AddView(this);
  1163. SetInfo(info);
  1164. DecrementReferenceCount();
  1165. }
  1166. /// <summary>
  1167. /// Sets the internal texture information structure.
  1168. /// </summary>
  1169. /// <param name="info">The new texture information</param>
  1170. private void SetInfo(TextureInfo info)
  1171. {
  1172. Info = info;
  1173. Target = info.Target;
  1174. Width = info.Width;
  1175. Height = info.Height;
  1176. CanForceAnisotropy = CanTextureForceAnisotropy();
  1177. _depth = info.GetDepth();
  1178. _layers = info.GetLayers();
  1179. }
  1180. /// <summary>
  1181. /// Signals that the texture has been modified.
  1182. /// </summary>
  1183. public void SignalModified()
  1184. {
  1185. _scaledSetScore = Math.Max(0, _scaledSetScore - 1);
  1186. if (_modifiedStale || Group.HasCopyDependencies)
  1187. {
  1188. _modifiedStale = false;
  1189. Group.SignalModified(this);
  1190. }
  1191. _physicalMemory.TextureCache.Lift(this);
  1192. }
  1193. /// <summary>
  1194. /// Signals that a texture has been bound, or has been unbound.
  1195. /// During this time, lazy copies will not clear the dirty flag.
  1196. /// </summary>
  1197. /// <param name="bound">True if the texture has been bound, false if it has been unbound</param>
  1198. public void SignalModifying(bool bound)
  1199. {
  1200. if (bound)
  1201. {
  1202. _scaledSetScore = Math.Max(0, _scaledSetScore - 1);
  1203. }
  1204. if (_modifiedStale || Group.HasCopyDependencies)
  1205. {
  1206. _modifiedStale = false;
  1207. Group.SignalModifying(this, bound);
  1208. }
  1209. _physicalMemory.TextureCache.Lift(this);
  1210. if (bound)
  1211. {
  1212. IncrementReferenceCount();
  1213. }
  1214. else
  1215. {
  1216. DecrementReferenceCount();
  1217. }
  1218. }
  1219. /// <summary>
  1220. /// Replaces the host texture, while disposing of the old one if needed.
  1221. /// </summary>
  1222. /// <param name="hostTexture">The new host texture</param>
  1223. private void ReplaceStorage(ITexture hostTexture)
  1224. {
  1225. DisposeTextures();
  1226. HostTexture = hostTexture;
  1227. }
  1228. /// <summary>
  1229. /// Determine if any of this texture's data overlaps with another.
  1230. /// </summary>
  1231. /// <param name="texture">The texture to check against</param>
  1232. /// <param name="compatibility">The view compatibility of the two textures</param>
  1233. /// <returns>True if any slice of the textures overlap, false otherwise</returns>
  1234. public bool DataOverlaps(Texture texture, TextureViewCompatibility compatibility)
  1235. {
  1236. if (compatibility == TextureViewCompatibility.LayoutIncompatible && Info.GobBlocksInZ > 1 && Info.GobBlocksInZ == texture.Info.GobBlocksInZ)
  1237. {
  1238. // Allow overlapping slices of layout compatible 3D textures with matching GobBlocksInZ, as they are interleaved.
  1239. return false;
  1240. }
  1241. if (texture._sizeInfo.AllOffsets.Length == 1 && _sizeInfo.AllOffsets.Length == 1)
  1242. {
  1243. return Range.OverlapsWith(texture.Range);
  1244. }
  1245. MultiRange otherRange = texture.Range;
  1246. IEnumerable<MultiRange> regions = _sizeInfo.AllRegions().Select((region) => Range.GetSlice((ulong)region.Offset, (ulong)region.Size));
  1247. IEnumerable<MultiRange> otherRegions = texture._sizeInfo.AllRegions().Select((region) => otherRange.GetSlice((ulong)region.Offset, (ulong)region.Size));
  1248. foreach (MultiRange region in regions)
  1249. {
  1250. foreach (MultiRange otherRegion in otherRegions)
  1251. {
  1252. if (region.OverlapsWith(otherRegion))
  1253. {
  1254. return true;
  1255. }
  1256. }
  1257. }
  1258. return false;
  1259. }
  1260. /// <summary>
  1261. /// Increments the texture reference count.
  1262. /// </summary>
  1263. public void IncrementReferenceCount()
  1264. {
  1265. _referenceCount++;
  1266. }
  1267. /// <summary>
  1268. /// Increments the reference count and records the given texture pool and ID as a pool owner.
  1269. /// </summary>
  1270. /// <param name="pool">The texture pool this texture has been added to</param>
  1271. /// <param name="id">The ID of the reference to this texture in the pool</param>
  1272. public void IncrementReferenceCount(TexturePool pool, int id)
  1273. {
  1274. lock (_poolOwners)
  1275. {
  1276. _poolOwners.Add(new TexturePoolOwner { Pool = pool, ID = id });
  1277. }
  1278. _referenceCount++;
  1279. if (ShortCacheEntry != null)
  1280. {
  1281. _physicalMemory.TextureCache.RemoveShortCache(this);
  1282. }
  1283. }
  1284. /// <summary>
  1285. /// Indicates that the texture has one reference left, and will delete on reference decrement.
  1286. /// </summary>
  1287. /// <returns>True if there is one reference remaining, false otherwise</returns>
  1288. public bool HasOneReference()
  1289. {
  1290. return _referenceCount == 1;
  1291. }
  1292. /// <summary>
  1293. /// Decrements the texture reference count.
  1294. /// When the reference count hits zero, the texture may be deleted and can't be used anymore.
  1295. /// </summary>
  1296. /// <returns>True if the texture is now referenceless, false otherwise</returns>
  1297. public bool DecrementReferenceCount()
  1298. {
  1299. int newRefCount = --_referenceCount;
  1300. if (newRefCount == 0)
  1301. {
  1302. if (_viewStorage != this)
  1303. {
  1304. _viewStorage.RemoveView(this);
  1305. }
  1306. _physicalMemory.TextureCache.RemoveTextureFromCache(this);
  1307. }
  1308. Debug.Assert(newRefCount >= 0);
  1309. DeleteIfNotUsed();
  1310. return newRefCount <= 0;
  1311. }
  1312. /// <summary>
  1313. /// Decrements the texture reference count, also removing an associated pool owner reference.
  1314. /// When the reference count hits zero, the texture may be deleted and can't be used anymore.
  1315. /// </summary>
  1316. /// <param name="pool">The texture pool this texture is being removed from</param>
  1317. /// <param name="id">The ID of the reference to this texture in the pool</param>
  1318. /// <returns>True if the texture is now referenceless, false otherwise</returns>
  1319. public bool DecrementReferenceCount(TexturePool pool, int id = -1)
  1320. {
  1321. lock (_poolOwners)
  1322. {
  1323. int references = _poolOwners.RemoveAll(entry => entry.Pool == pool && entry.ID == id || id == -1);
  1324. if (references == 0)
  1325. {
  1326. // This reference has already been removed.
  1327. return _referenceCount <= 0;
  1328. }
  1329. Debug.Assert(references == 1);
  1330. }
  1331. return DecrementReferenceCount();
  1332. }
  1333. /// <summary>
  1334. /// Forcibly remove this texture from all pools that reference it.
  1335. /// </summary>
  1336. /// <param name="deferred">Indicates if the removal is being done from another thread.</param>
  1337. public void RemoveFromPools(bool deferred)
  1338. {
  1339. lock (_poolOwners)
  1340. {
  1341. foreach (var owner in _poolOwners)
  1342. {
  1343. owner.Pool.ForceRemove(this, owner.ID, deferred);
  1344. }
  1345. _poolOwners.Clear();
  1346. }
  1347. if (ShortCacheEntry != null && _context.IsGpuThread())
  1348. {
  1349. // If this is called from another thread (unmapped), the short cache will
  1350. // have to remove this texture on a future tick.
  1351. _physicalMemory.TextureCache.RemoveShortCache(this);
  1352. }
  1353. InvalidatedSequence++;
  1354. }
  1355. /// <summary>
  1356. /// Delete the texture if it is not used anymore.
  1357. /// The texture is considered unused when the reference count is zero,
  1358. /// and it has no child views.
  1359. /// </summary>
  1360. private void DeleteIfNotUsed()
  1361. {
  1362. // We can delete the texture as long it is not being used
  1363. // in any cache (the reference count is 0 in this case), and
  1364. // also all views that may be created from this texture were
  1365. // already deleted (views count is 0).
  1366. if (_referenceCount == 0 && _views.Count == 0)
  1367. {
  1368. Dispose();
  1369. }
  1370. }
  1371. /// <summary>
  1372. /// Performs texture disposal, deleting the texture.
  1373. /// </summary>
  1374. private void DisposeTextures()
  1375. {
  1376. InvalidatedSequence++;
  1377. _currentData = null;
  1378. HostTexture.Release();
  1379. _arrayViewTexture?.Release();
  1380. _arrayViewTexture = null;
  1381. _flushHostTexture?.Release();
  1382. _flushHostTexture = null;
  1383. _setHostTexture?.Release();
  1384. _setHostTexture = null;
  1385. }
  1386. /// <summary>
  1387. /// Called when the memory for this texture has been unmapped.
  1388. /// Calls are from non-gpu threads.
  1389. /// </summary>
  1390. /// <param name="unmapRange">The range of memory being unmapped</param>
  1391. public void Unmapped(MultiRange unmapRange)
  1392. {
  1393. ChangedMapping = true;
  1394. if (Group.Storage == this)
  1395. {
  1396. Group.ClearModified(unmapRange);
  1397. }
  1398. RemoveFromPools(true);
  1399. }
  1400. /// <summary>
  1401. /// Performs texture disposal, deleting the texture.
  1402. /// </summary>
  1403. public void Dispose()
  1404. {
  1405. DisposeTextures();
  1406. if (Group.Storage == this)
  1407. {
  1408. Group.Dispose();
  1409. }
  1410. }
  1411. }
  1412. }