using System;
using System.Buffers;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
namespace CalamityMod.Utilities.Daybreak.Buffers;
///
/// Describes the creation parameters of a render target.
///
///
///
///
///
///
public readonly record struct RenderTargetDescriptor(
SurfaceFormat Format,
DepthFormat Depth,
int MultiSampleCount,
RenderTargetUsage Usage,
bool GenerateMipmaps
)
{
///
/// Default creation parameters.
///
public static RenderTargetDescriptor Default { get; } = new(
SurfaceFormat.Color,
DepthFormat.None,
0,
RenderTargetUsage.DiscardContents,
false
);
///
/// with usage set to
/// .
///
public static RenderTargetDescriptor DefaultPreserveContents { get; } = new(
SurfaceFormat.Color,
DepthFormat.None,
0,
RenderTargetUsage.PreserveContents,
false
);
///
///
///
public int MultiSampleCount { get; } = Math.Max(0, MultiSampleCount);
///
/// Creates a new 2D render target from the descriptor.
///
/// The device to create the target from.
/// The width of the target.
/// The height of the target.
public RenderTarget2D Create(GraphicsDevice device, int width, int height)
{
return new RenderTarget2D(device, width, height, GenerateMipmaps, Format, Depth, MultiSampleCount, Usage);
}
///
/// Constructs a descriptor from an existing target.
///
public static RenderTargetDescriptor From(RenderTarget2D target)
{
return new RenderTargetDescriptor(
target.Format,
target.DepthStencilFormat,
target.MultiSampleCount,
RenderTargetUsage.DiscardContents,
target.LevelCount > 1
);
}
}
///
/// A leased target from a pool, to be returned back.
///
/// The pool leasing the target.
/// The target being leased.
public sealed class RenderTargetLease(
RenderTarget2D target,
RenderTargetPool pool
) : IDisposable
{
///
/// The target being leased.
///
public RenderTarget2D Target { get; set; } = target;
///
/// Returns the target back to the pool.
///
public void Dispose()
{
pool.Return(this);
}
}
///
/// Provides a resource pool that enables reusing instances of render
/// targets.
///
///
/// Renting and returning buffers with a can
/// increase performance in situations where targets are created and
/// destroyed frequently, resulting in excessive use of VRAM.
///
/// This class is not thread-safe, and all methods and their implementations
/// are expected to be invoked solely on the Main Thread unless explicitly
/// specified otherwise.
///
public abstract class RenderTargetPool : IDisposable
{
// Store as field of derived shared type so the JIT can de-virtualize calls
// to it when the Shared property gets inlined.
private static readonly SharedRenderTargetPool shared = new();
///
/// Retrieves a shared instance.
///
///
/// The shared pool provides a default implementation of
/// that's intended for general
/// applicability. It assumes targets should not be manually cleared
/// and always returns a target of the exact request descriptor and
/// dimensions.
///
/// Disposed on unload.
///
public static RenderTargetPool Shared => shared;
///
/// Retrieves a buffer that is of the exact specified dimensions
/// and with the
/// given render target .
///
/// The device to initialize with.
/// The width of the target.
/// The height of the target.
/// The initialization parameters.
///
/// A leased target which should be disposed upon use, automatically
/// returning the target to the pool.
///
///
/// This buffer is loaned to the caller and should be returned to the
/// same pool via, so that it may be reused in
/// subsequent usage of . It is not a fatal error to
/// not return a rented buffer, but failure to do so may lead to
/// decreased application performance, as the pool may need to create a
/// new buffer to replace the one lost. The default
/// implementation returns a leased
/// target that will automatically return the pool on disposal, but
/// different implementations or configurations are not required to do
/// so.
///
public abstract RenderTargetLease Rent(
GraphicsDevice device,
int width,
int height,
RenderTargetDescriptor descriptor
);
///
/// Returns to the pool a render target that was previously obtained via
/// on the same .
///
///
/// The lease previously obtained from to return to
/// the pool.
///
///
/// This is automatically called by
/// and generally should not be
/// called manually without being explicitly told to do so.
///
/// Once a buffer has been returned to the pool, the caller gives up all
/// ownership of the buffer and must not use it. The reference returned
/// from a given call to must only be returned via
/// once. The default
/// may hold onto the returned buffer in
/// order to rent it again, or it my release the returned buffer if it's
/// determined that the pool already has enough buffers stored.
///
public abstract void Return(RenderTargetLease lease);
///
/// Disposes of the pool and releases any owned render targets,
/// including ones still potentially leased.
///
/// Generally, disposal should only be performed when either the
/// consumer has ownership over the pool and knows when all buffers have
/// been returned, or at the very end of execution and disposal must
/// occur (such as during mod unloading).
///
public abstract void Dispose();
private static readonly List leases_to_clear = [];
///
/// Queues a lease to be disposed of on the next render frame for cases
/// where ownership of the lease is given up for rendering during a
/// frame.
///
///
/// The lease to dispose of at the start of the next frame.
///
///
/// This API should generally be avoided when possible. It's a
/// last-resort option for when you cannot guarantee ownership over a
/// target.
///
public static void ReturnNextFrame(RenderTargetLease lease)
{
leases_to_clear.Add(lease);
}
///
/// Clears any pending leases that were queued via
/// .
///
internal static void ClearPendingLeases()
{
foreach (var lease in leases_to_clear)
{
lease.Dispose();
}
leases_to_clear.Clear();
}
}
///
/// Extension methods for that operate
/// agnostically on any implementation.
///
internal static class RenderTargetPoolExtensions
{
// TODO: Vector2 scale extensions and individual float width/height
// extensions.
/// The pool to rent from.
extension(RenderTargetPool pool)
{
///
/// See .
///
public RenderTargetLease Rent(
GraphicsDevice device,
int width,
int height
)
{
return pool.Rent(
device,
width,
height,
RenderTargetDescriptor.Default
);
}
///
/// Retrieves a buffer of size scaled by
/// rounded up to the nearest integer
/// value.
///
/// The device to initialize with.
/// The base (unscaled) size of the target.
/// The scale factor of the target.
///
/// A leased target which should be disposed upon use, automatically
/// returning the target to the pool.
///
public RenderTargetLease RentScaled(
GraphicsDevice device,
Point baseSize,
float scale
)
{
return pool.RentScaled(
device,
baseSize,
scale,
RenderTargetDescriptor.Default
);
}
///
/// Retrieves a buffer of size scaled by
/// rounded up to the nearest integer value and
/// with the given render target .
///
/// The device to initialize with.
/// The base (unscaled) size of the target.
/// The scale factor of the target.
/// The initialization parameters.
///
/// A leased target which should be disposed upon use, automatically
/// returning the target to the pool.
///
public RenderTargetLease RentScaled(
GraphicsDevice device,
Point baseSize,
float scale,
RenderTargetDescriptor descriptor
)
{
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(scale, 0f);
var width = Math.Max(1, (int)MathF.Ceiling(baseSize.X * scale));
var height = Math.Max(1, (int)MathF.Ceiling(baseSize.Y * scale));
return pool.Rent(device, width, height, descriptor);
}
}
}
// TODO: Account for different graphics devices?
internal sealed class SharedRenderTargetPool : RenderTargetPool
{
private readonly record struct Key(
int Width,
int Height,
RenderTargetDescriptor Descriptor
)
{
public static Key From(RenderTarget2D target)
{
return new Key(target.Width, target.Height, RenderTargetDescriptor.From(target));
}
}
private sealed class Entry
{
public Stack Targets { get; } = [];
public DateTime LastUsed { get; set; } = DateTime.UtcNow;
}
// TODO: We can tweak these later for performance?
private const int max_per_key = 4; // Max identical targets.
private const int max_total_targets = 128; // Max targets stored.
private static readonly TimeSpan max_idle_time = TimeSpan.FromSeconds(5);
private static readonly TimeSpan minimum_trim_time = TimeSpan.FromSeconds(1);
private readonly Dictionary cache = [];
private DateTime lastTrimmed = DateTime.UtcNow;
private int totalCached;
private bool disposed;
public override RenderTargetLease Rent(GraphicsDevice device, int width, int height, RenderTargetDescriptor descriptor)
{
ArgumentNullException.ThrowIfNull(device);
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(width, 0);
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(height, 0);
ObjectDisposedException.ThrowIf(disposed, this);
try
{
var key = new Key(width, height, descriptor);
if (!cache.TryGetValue(key, out var entry))
{
cache[key] = entry = new Entry();
}
else
{
entry.LastUsed = DateTime.UtcNow;
}
RenderTarget2D target;
if (entry.Targets.Count > 0)
{
target = entry.Targets.Pop();
totalCached--;
}
else
{
target = descriptor.Create(device, width, height);
}
return new RenderTargetLease(target, this);
}
finally
{
TrimAged();
}
}
public override void Return(RenderTargetLease lease)
{
ArgumentNullException.ThrowIfNull(lease);
ObjectDisposedException.ThrowIf(disposed, this);
var key = Key.From(lease.Target);
if (!cache.TryGetValue(key, out var entry))
{
cache[key] = entry = new Entry();
}
else
{
// Mark it as used on return because that's realistically where the
// countdown should begin.
entry.LastUsed = DateTime.UtcNow;
}
if (entry.Targets.Count < max_per_key)
{
if (totalCached >= max_total_targets)
{
lease.Target.Dispose();
return;
}
entry.Targets.Push(lease.Target);
totalCached++;
}
else
{
lease.Target.Dispose();
}
}
public override void Dispose()
{
if (disposed)
{
return;
}
Trim();
disposed = true;
}
private void Trim()
{
foreach (var entry in cache.Values)
{
while (entry.Targets.Count > 0)
{
entry.Targets.Pop().Dispose();
totalCached--;
}
}
cache.Clear();
}
private void TrimAged()
{
var now = DateTime.UtcNow;
if (now - lastTrimmed < minimum_trim_time)
{
return;
}
lastTrimmed = now;
foreach (var (key, entry) in cache)
{
if (now - entry.LastUsed <= max_idle_time)
{
continue;
}
while (entry.Targets.Count > 0)
{
entry.Targets.Pop().Dispose();
totalCached--;
}
cache.Remove(key);
}
}
}