R/Ryujinx.Graphics.Gpu/Image/AutoDeleteCache.cs

87 lines
2.8 KiB
C#
Raw Normal View History

2019-10-13 06:02:07 +00:00
using System.Collections;
using System.Collections.Generic;
namespace Ryujinx.Graphics.Gpu.Image
{
/// <summary>
/// A texture cache that automatically removes older textures that are not used for some time.
/// The cache works with a rotated list with a fixed size. When new textures are added, the
/// old ones at the bottom of the list are deleted.
/// </summary>
2019-10-13 06:02:07 +00:00
class AutoDeleteCache : IEnumerable<Texture>
{
private const int MaxCapacity = 2048;
private readonly LinkedList<Texture> _textures;
2019-10-13 06:02:07 +00:00
/// <summary>
/// Creates a new instance of the automatic deletion cache.
/// </summary>
2019-10-13 06:02:07 +00:00
public AutoDeleteCache()
{
_textures = new LinkedList<Texture>();
}
/// <summary>
/// Adds a new texture to the cache, even if the texture added is already on the cache.
2020-01-01 15:39:09 +00:00
/// </summary>
/// <remarks>
/// Using this method is only recommended if you know that the texture is not yet on the cache,
/// otherwise it would store the same texture more than once.
2020-01-01 15:39:09 +00:00
/// </remarks>
/// <param name="texture">The texture to be added to the cache</param>
2019-10-13 06:02:07 +00:00
public void Add(Texture texture)
{
texture.IncrementReferenceCount();
texture.CacheNode = _textures.AddLast(texture);
if (_textures.Count > MaxCapacity)
{
Texture oldestTexture = _textures.First.Value;
_textures.RemoveFirst();
oldestTexture.DecrementReferenceCount();
oldestTexture.CacheNode = null;
}
}
/// <summary>
/// Adds a new texture to the cache, or just moves it to the top of the list if the
2020-01-01 15:39:09 +00:00
/// texture is already on the cache.
/// </summary>
2020-01-01 15:39:09 +00:00
/// <remarks>
/// Moving the texture to the top of the list prevents it from being deleted,
/// as the textures on the bottom of the list are deleted when new ones are added.
/// </remarks>
/// <param name="texture">The texture to be added, or moved to the top</param>
2019-10-13 06:02:07 +00:00
public void Lift(Texture texture)
{
if (texture.CacheNode != null)
{
if (texture.CacheNode != _textures.Last)
{
_textures.Remove(texture.CacheNode);
texture.CacheNode = _textures.AddLast(texture);
}
}
else
{
Add(texture);
}
}
public IEnumerator<Texture> GetEnumerator()
{
return _textures.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _textures.GetEnumerator();
}
}
}