using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CalamityMod.Utilities.Daybreak.Buffers;
///
/// Manages the scope of a render target to be rendered to, swapping out the
/// currently-used targets of a device on creation and replacing it with the
/// given target. Switches back to the old targets upon disposal.
///
public readonly struct RenderTargetScope : IDisposable
{
private readonly GraphicsDevice graphicsDevice;
private readonly RenderTargetBinding[] previous;
///
/// Creates a new scope, saving the current device targets and starts
/// rendering to the new one instead.
///
/// The target to render to.
///
/// Whether to ensure swapped targets preserve their contents.
///
///
/// If not null, clears the target to the given color.
///
public RenderTargetScope(
RenderTarget2D target,
bool preserveContents = true,
Color? clearColor = null
)
{
ArgumentNullException.ThrowIfNull(target);
graphicsDevice = target.GraphicsDevice;
previous = graphicsDevice.GetRenderTargets();
if (preserveContents)
{
RenderTargetPreserver.PreserveBindings(previous);
}
graphicsDevice.SetRenderTarget(target);
if (clearColor.HasValue)
{
graphicsDevice.Clear(clearColor.Value);
}
}
///
/// Sets the device to use the targets that were in use before this
/// scope was instantiated.
///
public void Dispose()
{
graphicsDevice.SetRenderTargets(previous);
}
}
///
/// Extensions supporting .
///
public static class RenderTargetScopeExtensions
{
///
/// Creates a new scope, saving the current device targets and starts
/// rendering to the new one instead.
///
/// The target to render to.
///
/// Whether to ensure swapped targets preserve their contents.
///
///
/// If not null, clears the target to the given color.
///
public static RenderTargetScope Scope(
this RenderTarget2D target,
bool preserveContents = true,
Color? clearColor = null
)
{
return new RenderTargetScope(
target,
preserveContents,
clearColor
);
}
///
/// Creates a new scope, saving the current device targets and starts
/// rendering to the new one instead.
///
/// The target to render to.
///
/// Whether to ensure swapped targets preserve their contents.
///
///
/// If not null, clears the target to the given color.
///
public static RenderTargetScope Scope(
this RenderTargetLease target,
bool preserveContents = true,
Color? clearColor = null
)
{
return new RenderTargetScope(
target.Target,
preserveContents,
clearColor
);
}
}