This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,363 @@
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
using UnityEngine.NVIDIA;
#endif
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
static class RegisterDLSS
{
static RegisterDLSS() => UpscalerRegistry.Register<DLSSIUpscaler, DLSSOptions>(DLSSIUpscaler.upscalerName);
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void InitRuntime() => UpscalerRegistry.Register<DLSSIUpscaler, DLSSOptions>(DLSSIUpscaler.upscalerName);
}
/// <summary>
/// Per-camera context for DLSS upscaling. Wraps the native NVIDIA DLSSContext
/// and tracks the settings it was created with for validation.
/// Native context creation is deferred until first use (requires CommandBuffer).
/// </summary>
public class DLSSUpscalerContext : PluginUpscalerContext<DLSSContext, DLSSOptions>
{
public DLSSQuality createdWithQuality { get; }
public DLSSPreset createdWithPresetQuality { get; }
public DLSSPreset createdWithPresetBalanced { get; }
public DLSSPreset createdWithPresetPerformance { get; }
public DLSSPreset createdWithPresetUltraPerformance { get; }
public DLSSPreset createdWithPresetDLAA { get; }
/// <summary>
/// Creates a new DLSS context wrapper. Native context creation is deferred.
/// Stores context-creation settings (quality, presets) for init and validation.
/// Per-frame settings should be read from io.options in RecordRenderGraph.
/// </summary>
public DLSSUpscalerContext(DLSSOptions options, Vector2Int displayResolution)
: base(displayResolution)
{
createdWithQuality = options.dlssQualityMode;
createdWithPresetQuality = options.dlssRenderPresetQuality;
createdWithPresetBalanced = options.dlssRenderPresetBalanced;
createdWithPresetPerformance = options.dlssRenderPresetPerformance;
createdWithPresetUltraPerformance = options.dlssRenderPresetUltraPerformance;
createdWithPresetDLAA = options.dlssRenderPresetDLAA;
}
/// <summary>
/// Gets the native DLSS context, creating it if necessary.
/// </summary>
/// <param name="cmd">Command buffer to record creation commands.</param>
/// <param name="settings">Initialization settings for the native context.</param>
/// <returns>The native DLSS context.</returns>
public DLSSContext GetOrCreateNativeContext(CommandBuffer cmd, DLSSCommandInitializationData settings)
{
m_NativeContext ??= GraphicsDevice.device.CreateFeature(cmd, settings);
return m_NativeContext;
}
/// <inheritdoc/>
protected override void DestroyNativeContext(CommandBuffer cmd, DLSSContext context)
=> GraphicsDevice.device.DestroyFeature(cmd, context);
/// <inheritdoc/>
protected override bool ValidateOptions(DLSSOptions options)
{
// Quality mode and preset changes require context recreation
return options.dlssQualityMode == createdWithQuality &&
options.dlssRenderPresetQuality == createdWithPresetQuality &&
options.dlssRenderPresetBalanced == createdWithPresetBalanced &&
options.dlssRenderPresetPerformance == createdWithPresetPerformance &&
options.dlssRenderPresetUltraPerformance == createdWithPresetUltraPerformance &&
options.dlssRenderPresetDLAA == createdWithPresetDLAA;
}
}
public class DLSSIUpscaler : AbstractUpscaler
{
public static readonly string upscalerName = "Deep Learning Super Sampling 4";
#region DLSS_UTILITIES
static bool CheckDLSSFeatureAvailable()
{
// check plugin availability
if (!UnityEngine.NVIDIA.NVUnityPlugin.IsLoaded())
{
Debug.LogWarning("NVUnityPlugin not loaded.");
return false;
}
// check GPU vendor
if (!SystemInfo.graphicsDeviceVendor.ToLowerInvariant().Contains("nvidia"))
{
Debug.LogWarning("DLSS not available on non-NVIDIA graphics cards.");
return false;
}
// check device
UnityEngine.NVIDIA.GraphicsDevice device = UnityEngine.NVIDIA.GraphicsDevice.CreateGraphicsDevice();
if (device == null)
{
Debug.LogWarning("NVUnityPlugin failed to create device.");
return false;
}
// check DLSS feature
if(!device.IsFeatureAvailable(UnityEngine.NVIDIA.GraphicsDeviceFeature.DLSS))
{
Debug.LogWarning("DLSS not available on the current NVIDIA graphics card.");
return false;
}
return true;
}
#endregion // DLSS_UTILITIES
#region RENDERGRAPH_INTERFACE_DATA
class DLSSGraphData
{
public DLSSUpscalerContext upscalerContext;
public bool needsInitSettings; // True when native context doesn't exist yet
public DLSSCommandInitializationData initSettings;
public DLSSCommandExecutionData execData;
public TextureHandle colorInput;
public TextureHandle depth;
public TextureHandle motionVectors;
public TextureHandle colorOutput;
};
#endregion
#region IUPSCALER_INTERFACE
public DLSSIUpscaler()
{
m_DLSSReady = CheckDLSSFeatureAvailable();
}
public override string name => upscalerName;
public override bool isTemporal => true;
public override bool supportsSharpening => false;
public override bool hasQualityMode => true;
public override IUpscalerContext CreateContext(UpscalerOptions options, Vector2Int displayResolution)
{
if (!m_DLSSReady || options is not DLSSOptions dlssOptions)
return null;
return new DLSSUpscalerContext(dlssOptions, displayResolution);
}
public override void CalculateJitter(int frameIndex, float upscaleRatio, out Vector2 jitter, out bool allowScaling)
{
int numPhases = CalculateJitterPhaseCount(upscaleRatio);
int haltonIndex = (frameIndex % numPhases) + 1;
float x = HaltonSequence.Get(haltonIndex, 2) - 0.5f;
float y = HaltonSequence.Get(haltonIndex, 3) - 0.5f;
jitter = new Vector2(x, y);
allowScaling = false;
}
public override UpscalerResolutionInfo GetResolutionInfo(Vector2Int displayResolution, UpscalerOptions options)
{
var dlssOptions = options as DLSSOptions;
if (!m_DLSSReady || dlssOptions == null)
return UpscalerResolutionInfo.Fixed(displayResolution);
// Query the DLSS SDK for the optimal render resolution and the supported [min,max] range for this quality mode.
if (GraphicsDevice.device.GetOptimalSettings(
(uint)displayResolution.x,
(uint)displayResolution.y,
dlssOptions.dlssQualityMode,
out OptimalDLSSSettingsData optimalSettings))
{
var optimal = new Vector2Int((int)optimalSettings.outRenderWidth, (int)optimalSettings.outRenderHeight);
var min = new Vector2Int((int)optimalSettings.minWidth, (int)optimalSettings.minHeight);
var max = new Vector2Int((int)optimalSettings.maxWidth, (int)optimalSettings.maxHeight);
// The render resolution must always stay within [min,max] or DLSS Evaluate fails, so even CustomScaling
// reports the range as a clamp (the pipeline drives within it). When the quality mode has no range
// (min == max — e.g. UltraPerformance, or an older DLSS library) only the optimal is valid, so pin to it.
switch (dlssOptions.resolutionMode)
{
case UpscalerResolutionMode.CustomScaling:
return (min != max)
? UpscalerResolutionInfo.Range(min, max)
: UpscalerResolutionInfo.Fixed(optimal);
default: // QualityMode
return UpscalerResolutionInfo.Fixed(optimal);
}
}
// Fallback if GetOptimalSettings fails
return UpscalerResolutionInfo.Fixed(displayResolution);
}
public override float CalculateMipBias(Vector2Int preUpscaleResolution, Vector2Int postUpscaleResolution)
{
// NVUnityPlugin should provide this value.
float xBias = Mathf.Log((float)preUpscaleResolution.x / postUpscaleResolution.x, 2f);
float yBias = Mathf.Log((float)preUpscaleResolution.y / postUpscaleResolution.y, 2f);
return Mathf.Min(xBias, yBias) - 1.0f;
}
static int CalculateJitterPhaseCount(float upscaleRatio)
{
const float k_BasePhaseCount = 8.0f;
// Round half up, don't truncate: upscaleRatio is reconstructed as display/round(renderSize), so a clean preset
// (e.g. 1.5x) arrives slightly low (~1.497) and 8*1.497^2 = 17.93 would truncate to 17 instead of 18.
return Mathf.FloorToInt(k_BasePhaseCount * upscaleRatio * upscaleRatio + 0.5f);
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
if(!m_DLSSReady)
return;
Debug.Assert(GraphicsDevice.device != null);
UpscalingIO io = frameData.Get<UpscalingIO>();
var upscalerContext = io.context as DLSSUpscalerContext;
if (upscalerContext == null)
{
Debug.LogWarning("DLSSIUpscaler: No valid context provided via io.context. Skipping upscaling.");
return;
}
// describe output texture
TextureHandle outputColor;
{
TextureDesc inputDesc = io.cameraColor.GetDescriptor(renderGraph);
TextureDesc outputDesc = inputDesc;
outputDesc.width = io.postUpscaleResolution.x;
outputDesc.height = io.postUpscaleResolution.y;
outputDesc.format = inputDesc.format;
outputDesc.msaaSamples = MSAASamples.None;
outputDesc.useMipMap = false;
outputDesc.autoGenerateMips = false;
outputDesc.useDynamicScale = false;
outputDesc.anisoLevel = 0;
outputDesc.discardBuffer = false;
outputDesc.enableRandomWrite = true; // compute shader resource
outputDesc.name = "_DLSSOutputTarget";
outputDesc.clearBuffer = false;
outputDesc.filterMode = FilterMode.Bilinear;
outputColor = renderGraph.CreateTexture(outputDesc);
}
using (var builder = renderGraph.AddUnsafePass<DLSSGraphData>("Deep Learning Super Sampling", out DLSSGraphData passData, new ProfilingSampler("DLSS")))
{
float motionVectorSign = io.motionVectorDirection == UpscalingIO.MotionVectorDirection.PreviousFrameToCurrentFrame ? -1.0f : 1.0f;
float motionVectorScaleX = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC ? io.motionVectorTextureSize.x : 1.0f;
float motionVectorScaleY = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC ? io.motionVectorTextureSize.y : 1.0f;
// Setup pass data
passData.upscalerContext = upscalerContext;
passData.needsInitSettings = !upscalerContext.hasNativeContext;
// Only build initialization settings when native context needs to be created
if (passData.needsInitSettings)
{
bool mvLowResolution = io.motionVectorTextureSize.x <= io.preUpscaleResolution.x ||
io.motionVectorTextureSize.y <= io.preUpscaleResolution.y;
passData.initSettings = new DLSSCommandInitializationData();
passData.initSettings.SetFlag(DLSSFeatureFlags.IsHDR, io.hdrInput);
passData.initSettings.SetFlag(DLSSFeatureFlags.MVLowRes, mvLowResolution);
passData.initSettings.SetFlag(DLSSFeatureFlags.DepthInverted, io.invertedDepth);
passData.initSettings.SetFlag(DLSSFeatureFlags.MVJittered, io.jitteredMotionVectors);
// The DLSS SDK requires the feature to be created at the quality mode's optimal render size (not the max,
// display, or current size) regardless of resolution mode. The per-frame subrect (execData below) is the
// actual render size; it may vary but must stay within the quality mode's [min,max] or Evaluate fails.
// The pipeline allocates the input color buffer at the max so the subrect always fits.
Vector2Int optimalRenderSize = io.preUpscaleResolution; // fallback if the SDK query fails
if (GraphicsDevice.device.GetOptimalSettings(
(uint)io.postUpscaleResolution.x, (uint)io.postUpscaleResolution.y,
upscalerContext.createdWithQuality, out OptimalDLSSSettingsData optimalSettings))
{
optimalRenderSize = new Vector2Int((int)optimalSettings.outRenderWidth, (int)optimalSettings.outRenderHeight);
}
passData.initSettings.inputRTWidth = (uint)optimalRenderSize.x;
passData.initSettings.inputRTHeight = (uint)optimalRenderSize.y;
passData.initSettings.outputRTWidth = (uint)io.postUpscaleResolution.x;
passData.initSettings.outputRTHeight = (uint)io.postUpscaleResolution.y;
passData.initSettings.quality = upscalerContext.createdWithQuality;
passData.initSettings.presetQualityMode = upscalerContext.createdWithPresetQuality;
passData.initSettings.presetBalancedMode = upscalerContext.createdWithPresetBalanced;
passData.initSettings.presetPerformanceMode = upscalerContext.createdWithPresetPerformance;
passData.initSettings.presetUltraPerformanceMode = upscalerContext.createdWithPresetUltraPerformance;
passData.initSettings.presetDlaaMode = upscalerContext.createdWithPresetDLAA;
}
// Per-frame execution data
passData.execData.mvScaleX = motionVectorSign * motionVectorScaleX;
passData.execData.mvScaleY = motionVectorSign * motionVectorScaleY;
passData.execData.subrectOffsetX = 0;
passData.execData.subrectOffsetY = 0;
passData.execData.subrectWidth = (uint)io.preUpscaleResolution.x;
passData.execData.subrectHeight = (uint)io.preUpscaleResolution.y;
passData.execData.jitterOffsetX = io.subpixelJitter.x;
passData.execData.jitterOffsetY = io.subpixelJitter.y;
passData.execData.preExposure = Mathf.Clamp(io.preExposureValue, 0.20f, 2.0f); // clamp to a reasonable value to prevent ghosting
passData.execData.invertYAxis = io.flippedY ? 1u : 0u;
passData.execData.invertXAxis = io.flippedX ? 1u : 0u;
passData.execData.reset = io.resetHistory ? 1 : 0;
// Texture handles
builder.UseTexture(io.cameraColor);
builder.UseTexture(io.cameraDepth);
builder.UseTexture(io.motionVectorColor);
builder.UseTexture(outputColor, AccessFlags.Write);
passData.colorInput = io.cameraColor;
passData.depth = io.cameraDepth;
passData.motionVectors = io.motionVectorColor;
passData.colorOutput = outputColor;
// set render function
builder.SetRenderFunc((DLSSGraphData data, UnsafeGraphContext ctx) =>
{
CommandBuffer cmd = CommandBufferHelpers.GetNativeCommandBuffer(ctx.cmd);
// Verify init settings were populated if native context needs to be created
Debug.Assert(!data.needsInitSettings || data.initSettings.outputRTWidth > 0,
"DLSS init settings must be populated when native context doesn't exist");
// Get the native context, creating it if necessary (uses pre-built init settings)
DLSSContext nativeContext = data.upscalerContext.GetOrCreateNativeContext(cmd, data.initSettings);
Debug.Assert(nativeContext != null);
nativeContext.executeData = data.execData;
DLSSTextureTable textureTable = new()
{
colorInput = data.colorInput,
depth = data.depth,
motionVectors = data.motionVectors,
colorOutput = data.colorOutput,
};
GraphicsDevice.device.ExecuteDLSS(cmd, nativeContext, textureTable);
});
}
io.cameraColor = outputColor;
}
#endregion
#region DATA
private bool m_DLSSReady = false;
#endregion
}
#endif // ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ac8be94ed6c6df548a43cbac716f5147
@@ -0,0 +1,131 @@
using UnityEngine;
using UnityEngine.Rendering;
#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
using UnityEngine.NVIDIA;
#endif
using System;
#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
[Serializable]
public class DLSSOptions : UpscalerOptions
{
#region BACKING_FIELDS
[SerializeField]
[Tooltip("Selects a performance quality setting for NVIDIA Deep Learning Super Sampling (DLSS).")]
private DLSSQuality m_DLSSQualityMode = DLSSQuality.MaximumQuality;
[Header("Render Presets")]
[SerializeField]
[Tooltip("DLSS will use the specified render preset for the Quality mode.")]
private DLSSPreset m_DLSSRenderPresetQuality;
[SerializeField]
[Tooltip("DLSS will use the specified render preset for the Balanced mode.")]
private DLSSPreset m_DLSSRenderPresetBalanced;
[SerializeField]
[Tooltip("DLSS will use the specified render preset for the Performance mode.")]
private DLSSPreset m_DLSSRenderPresetPerformance;
[SerializeField]
[Tooltip("DLSS will use the specified render preset for the Ultra Performance mode.")]
private DLSSPreset m_DLSSRenderPresetUltraPerformance;
[SerializeField]
[Tooltip("DLSS will use the specified render preset for the DLAA mode.")]
private DLSSPreset m_DLSSRenderPresetDLAA;
#endregion
#region PROPERTIES
/// <summary>
/// Gets or sets the performance quality setting for NVIDIA DLSS.
/// </summary>
public DLSSQuality dlssQualityMode
{
get { return m_DLSSQualityMode; }
set { m_DLSSQualityMode = value; }
}
/// <summary>
/// The specific render preset to use when DLSS is in Quality mode.
/// </summary>
public DLSSPreset dlssRenderPresetQuality
{
get { return m_DLSSRenderPresetQuality; }
set { m_DLSSRenderPresetQuality = value; }
}
/// <summary>
/// The specific render preset to use when DLSS is in Balanced mode.
/// </summary>
public DLSSPreset dlssRenderPresetBalanced
{
get { return m_DLSSRenderPresetBalanced; }
set { m_DLSSRenderPresetBalanced = value; }
}
/// <summary>
/// The specific render preset to use when DLSS is in Performance mode.
/// </summary>
public DLSSPreset dlssRenderPresetPerformance
{
get { return m_DLSSRenderPresetPerformance; }
set { m_DLSSRenderPresetPerformance = value; }
}
/// <summary>
/// The specific render preset to use when DLSS is in Ultra Performance mode.
/// </summary>
public DLSSPreset dlssRenderPresetUltraPerformance
{
get { return m_DLSSRenderPresetUltraPerformance; }
set { m_DLSSRenderPresetUltraPerformance = value; }
}
/// <summary>
/// The specific render preset to use when DLSS is in DLAA mode.
/// </summary>
public DLSSPreset dlssRenderPresetDLAA
{
get { return m_DLSSRenderPresetDLAA; }
set { m_DLSSRenderPresetDLAA = value; }
}
#endregion
/// <summary>
/// Checks if the settings of this object match another instance.
/// </summary>
public bool IsSame(DLSSOptions other)
{
if (other == null)
return false;
return resolutionMode == other.resolutionMode &&
m_DLSSQualityMode == other.m_DLSSQualityMode &&
m_DLSSRenderPresetQuality == other.m_DLSSRenderPresetQuality &&
m_DLSSRenderPresetBalanced == other.m_DLSSRenderPresetBalanced &&
m_DLSSRenderPresetPerformance == other.m_DLSSRenderPresetPerformance &&
m_DLSSRenderPresetUltraPerformance == other.m_DLSSRenderPresetUltraPerformance &&
m_DLSSRenderPresetDLAA == other.m_DLSSRenderPresetDLAA;
}
/// <summary>
/// Shallow copies values from another DLSSOptions instance into this one.
/// </summary>
public void CopyFrom(DLSSOptions other)
{
if (other == null)
return;
resolutionMode = other.resolutionMode;
m_DLSSQualityMode = other.m_DLSSQualityMode;
m_DLSSRenderPresetQuality = other.m_DLSSRenderPresetQuality;
m_DLSSRenderPresetBalanced = other.m_DLSSRenderPresetBalanced;
m_DLSSRenderPresetPerformance = other.m_DLSSRenderPresetPerformance;
m_DLSSRenderPresetUltraPerformance = other.m_DLSSRenderPresetUltraPerformance;
m_DLSSRenderPresetDLAA = other.m_DLSSRenderPresetDLAA;
}
}
#endif // ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: dffd75c6cf5e26843be8893fada27a36
@@ -0,0 +1,408 @@
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
using UnityEngine.AMD;
#endif
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
static class RegisterFSR2
{
static RegisterFSR2() => UpscalerRegistry.Register<FSR2IUpscaler, FSR2Options>(FSR2IUpscaler.upscalerName);
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void InitRuntime() => UpscalerRegistry.Register<FSR2IUpscaler, FSR2Options>(FSR2IUpscaler.upscalerName);
}
/// <summary>
/// Per-camera context for FSR2 upscaling. Wraps the native AMD FSR2Context
/// and tracks the settings it was created with for validation.
/// Native context creation is deferred until first use (requires CommandBuffer).
/// </summary>
public class FSR2UpscalerContext : PluginUpscalerContext<FSR2Context, FSR2Options>
{
public FSR2Quality createdWithQuality { get; }
/// <summary>
/// The max render size (= io.maxPreUpscaleResolution) the native context was created for. The native context sizes
/// its internal buffers to this and rejects a per-frame renderSize above it (FFX_ERROR_OUT_OF_RANGE), so it must be
/// recreated when this changes. It is stable under hardware DRS (the full allocation; only the per-frame subrect
/// varies) but changes when the render allocation does — switching resolution mode or changing Render Scale.
/// </summary>
public Vector2Int createdWithMaxRenderSize { get; private set; }
/// <summary>
/// The initialization flags the native context was baked with. They follow per-frame inputs (HDR format, DRS state)
/// that can change without changing the display resolution or options, so a flag change must recreate the native
/// context. (The init display size needs no tracking — a resolution change already recreates the whole context via
/// <see cref="IUpscalerContext.createdForDisplayResolution"/>.)
/// </summary>
public FfxFsr2InitializationFlags createdWithFlags { get; private set; }
/// <summary>
/// Creates a new FSR2 context wrapper. Native context creation is deferred.
/// Stores context-creation settings (quality). Per-frame settings (sharpness)
/// should be read from io.options in RecordRenderGraph.
/// </summary>
public FSR2UpscalerContext(FSR2Options options, Vector2Int displayResolution)
: base(displayResolution)
{
createdWithQuality = options.fsr2QualityMode;
}
/// <summary>
/// Returns the native FSR2 context, creating it on first use and recreating it when the max render size or
/// initialization flags in <paramref name="settings"/> differ from those the current context was created with.
/// </summary>
/// <param name="cmd">Command buffer to record any creation/destruction commands.</param>
/// <param name="settings">Initialization settings for the native context (carries the requested max render size and flags).</param>
/// <returns>The native FSR2 context, valid for the requested max render size and flags.</returns>
public FSR2Context EnsureNativeContext(CommandBuffer cmd, FSR2CommandInitializationData settings)
{
var requestedMaxRenderSize = new Vector2Int((int)settings.maxRenderSizeWidth, (int)settings.maxRenderSizeHeight);
bool recreate = createdWithMaxRenderSize != requestedMaxRenderSize || createdWithFlags != settings.ffxFsrFlags;
if (m_NativeContext != null && recreate)
{
DestroyNativeContext(cmd, m_NativeContext);
m_NativeContext = null;
}
if (m_NativeContext == null)
{
m_NativeContext = GraphicsDevice.device.CreateFeature(cmd, settings);
createdWithMaxRenderSize = requestedMaxRenderSize;
createdWithFlags = settings.ffxFsrFlags;
}
return m_NativeContext;
}
/// <inheritdoc/>
protected override void DestroyNativeContext(CommandBuffer cmd, FSR2Context context)
=> GraphicsDevice.device.DestroyFeature(cmd, context);
/// <inheritdoc/>
protected override bool ValidateOptions(FSR2Options options)
{
// Quality mode changes require context recreation
// Sharpness changes do NOT require recreation (just parameters)
return options.fsr2QualityMode == createdWithQuality;
}
}
public class FSR2IUpscaler : AbstractUpscaler
{
public static readonly string upscalerName = "FidelityFX Super Resolution 2";
#region FSR2_UTILITIES
static bool CheckFSR2FeatureAvailable()
{
// check plugin availability
if (!UnityEngine.AMD.AMDUnityPlugin.IsLoaded())
{
Debug.LogWarning("AMDUnityPlugin not loaded.");
return false;
}
// check device
UnityEngine.AMD.GraphicsDevice device = UnityEngine.AMD.GraphicsDevice.CreateGraphicsDevice();
if (device == null)
{
Debug.LogWarning("AMDUnityPlugin failed to create device.");
return false;
}
return true;
}
#endregion // FSR2_UTILITIES
#region RENDERGRAPH_INTERFACE_DATA
class FSR2GraphData
{
public FSR2UpscalerContext upscalerContext;
public FSR2CommandInitializationData initSettings;
public FSR2CommandExecutionData execData;
public TextureHandle colorInput;
public TextureHandle depth;
public TextureHandle motionVectors;
public TextureHandle colorOutput;
};
#endregion
#region IUPSCALER_INTERFACE
public FSR2IUpscaler()
{
m_FSR2Ready = CheckFSR2FeatureAvailable();
}
public override string name => upscalerName;
public override bool isTemporal => true;
public override bool supportsSharpening => true;
public override bool hasQualityMode => true;
public override IUpscalerContext CreateContext(UpscalerOptions options, Vector2Int displayResolution)
{
if (!m_FSR2Ready || options is not FSR2Options fsr2Options)
return null;
return new FSR2UpscalerContext(fsr2Options, displayResolution);
}
public override void CalculateJitter(int frameIndex, float upscaleRatio, out Vector2 jitter, out bool allowScaling)
{
int numPhases = CalculateJitterPhaseCount(upscaleRatio);
int haltonIndex = (frameIndex % numPhases) + 1;
float x = HaltonSequence.Get(haltonIndex, 2) - 0.5f;
float y = HaltonSequence.Get(haltonIndex, 3) - 0.5f;
jitter = new Vector2(x, y);
allowScaling = false;
}
static int CalculateJitterPhaseCount(float upscaleRatio)
{
const float basePhaseCount = 8.0f;
// Round half up, don't truncate: upscaleRatio is reconstructed as display/round(renderSize), so a clean preset
// (e.g. 1.5x) arrives slightly low (~1.497) and 8*1.497^2 = 17.93 would truncate to 17 instead of 18.
return Mathf.FloorToInt(basePhaseCount * upscaleRatio * upscaleRatio + 0.5f);
}
public override UpscalerResolutionInfo GetResolutionInfo(Vector2Int displayResolution, UpscalerOptions options)
{
var fsr2Options = options as FSR2Options;
if (!m_FSR2Ready || fsr2Options == null)
return UpscalerResolutionInfo.Fixed(displayResolution);
UpscalerResolutionInfo info;
if (fsr2Options.resolutionMode == UpscalerResolutionMode.CustomScaling)
{
// Custom scaling: the user drives the render resolution (Render Scale / DRS); FSR2 has no opinion on it and
// no hard per-quality min/max range (unlike DLSS/XeSS) — it supports DRS globally instead.
info = base.GetResolutionInfo(displayResolution, options);
}
else // Quality mode: the preset defines a single optimal render resolution (no range).
{
// Fall through (don't early-return on failure) so recommendedMinScale is still reported below.
info = GraphicsDevice.device.GetRenderResolutionFromQualityMode(fsr2Options.fsr2QualityMode,
(uint)displayResolution.x, (uint)displayResolution.y,
out uint renderWidth, out uint renderHeight)
? UpscalerResolutionInfo.Fixed(new Vector2Int((int)renderWidth, (int)renderHeight))
: UpscalerResolutionInfo.Fixed(displayResolution); // SDK/device not ready
}
// Resolution- and mode-independent, so report it on both resolution-mode branches.
info.recommendedMinScale = GetRecommendedMinScale();
return info;
}
// FSR2's recommended minimum render scale: below it FSR2 still runs but quality degrades — advisory only, never clamped.
// Two bounds, because the recommended max upscale is tighter under dynamic resolution (~1.5x → ~0.667) than for static
// scaling (~3x → ~0.33). Each is cached on first success to avoid a per-frame P/Invoke; not cached on failure so a
// device-not-ready result can be retried.
float m_CachedRecommendedMinScale = -1f; // static scaling; < 0 = not yet queried
float m_CachedRecommendedMinScaleDynamic = -1f; // dynamic resolution; < 0 = not yet queried
// Static-scaling floor: FSR2's largest upscale ratio (UltraPerformance).
float GetRecommendedMinScale() => RecommendedMinScaleFor(FSR2Quality.UltraPerformance, ref m_CachedRecommendedMinScale);
// Dynamic-resolution floor: FSR2's recommended ~1.5x max upscale (the Quality preset's ratio). See GPUOpen GDC 2022 presentation.
float GetRecommendedMinScaleForDynamicResolution() => RecommendedMinScaleFor(FSR2Quality.Quality, ref m_CachedRecommendedMinScaleDynamic);
float RecommendedMinScaleFor(FSR2Quality qualityMode, ref float cache)
{
if (cache >= 0f)
return cache;
if (!m_FSR2Ready || GraphicsDevice.device == null)
return 0f; // not cached; retry once ready
float upscaleRatio = GraphicsDevice.device.GetUpscaleRatioFromQualityMode(qualityMode);
if (upscaleRatio <= 0f)
return 0f; // not cached; allow retry
return cache = 1f / upscaleRatio;
}
// Last render scale (rounded to 2 decimals) we logged a notice for; NaN means none. Tracked so a sustained or
// jittering below-recommended scale logs once per distinct value instead of every frame.
float m_LastNotifiedBelowScale = float.NaN;
// FSR2 keeps working below its recommended render scale but image quality degrades, so log an informational notice
// (never clamp the user's chosen scale). INFO severity matches the editor's HelpBox for this soft floor; hard
// [min,max] clamps warn instead. preUpscaleResolution reflects both Render Scale and hardware DRS
// (ScalableBufferManager), so this covers both.
void NotifyIfBelowRecommendedRenderScale(UpscalingIO io)
{
bool dynamicResolution = io.dynamicResolution.HasValue;
float recommendedMinScale = dynamicResolution ? GetRecommendedMinScaleForDynamicResolution() : GetRecommendedMinScale();
if (recommendedMinScale <= 0f)
return; // device gave no ratio
if (io.postUpscaleResolution.x <= 0)
return; // guard against a degenerate display size (early init / resize) before dividing
float scale = (float)io.preUpscaleResolution.x / io.postUpscaleResolution.x;
if (scale >= recommendedMinScale)
{
m_LastNotifiedBelowScale = float.NaN; // at/above the recommendation: clear it so dropping below notifies again
return;
}
float roundedScale = Mathf.Floor(scale * 100f + 0.5f) / 100f;
if (Mathf.Approximately(m_LastNotifiedBelowScale, roundedScale))
return;
m_LastNotifiedBelowScale = roundedScale;
string mode = dynamicResolution ? "with dynamic resolution" : "at a fixed Render Scale";
Debug.Log(
$"FSR2 is rendering at Render Scale {scale:0.00} {mode}, below its recommended minimum of " +
$"{recommendedMinScale:0.00} (beyond FSR2's recommended maximum upscale ratio for this mode). FSR2 still " +
"runs, but image quality degrades at this scale. Raise Render Scale / dynamic resolution to stay at or " +
"above the recommended minimum.");
}
public override float CalculateMipBias(Vector2Int preUpscaleResolution, Vector2Int postUpscaleResolution)
{
// AMDUnityPlugin should provide this value.
float xBias = Mathf.Log((float)preUpscaleResolution.x / postUpscaleResolution.x, 2f);
float yBias = Mathf.Log((float)preUpscaleResolution.y / postUpscaleResolution.y, 2f);
return Mathf.Min(xBias, yBias) - 1.0f;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
if(!m_FSR2Ready)
return;
Debug.Assert(GraphicsDevice.device != null);
UpscalingIO io = frameData.Get<UpscalingIO>();
// Get the per-camera context from UpscalingIO (set by the pipeline)
var upscalerContext = io.context as FSR2UpscalerContext;
if (upscalerContext == null)
{
Debug.LogWarning("FSR2IUpscaler: No valid context provided via io.context. Skipping upscaling.");
return;
}
if (Debug.isDebugBuild)
NotifyIfBelowRecommendedRenderScale(io);
// describe output texture
TextureHandle outputColor;
{
TextureDesc inputDesc = io.cameraColor.GetDescriptor(renderGraph);
TextureDesc outputDesc = inputDesc;
outputDesc.width = io.postUpscaleResolution.x;
outputDesc.height = io.postUpscaleResolution.y;
outputDesc.format = GraphicsFormatUtility.GetLinearFormat(inputDesc.format);
outputDesc.msaaSamples = MSAASamples.None;
outputDesc.useMipMap = false;
outputDesc.autoGenerateMips = false;
outputDesc.useDynamicScale = false;
outputDesc.anisoLevel = 0;
outputDesc.discardBuffer = false;
outputDesc.enableRandomWrite = true; // compute shader resource
outputDesc.name = "_FSR2OutputTarget";
outputDesc.clearBuffer = false;
outputDesc.filterMode = FilterMode.Bilinear;
outputColor = renderGraph.CreateTexture(outputDesc);
}
using (var builder = renderGraph.AddUnsafePass<FSR2GraphData>("FidelityFX Super Resolution 2", out FSR2GraphData passData, new ProfilingSampler("FSR2")))
{
float motionVectorSign = io.motionVectorDirection == UpscalingIO.MotionVectorDirection.PreviousFrameToCurrentFrame ? -1.0f : 1.0f;
float motionVectorScaleX = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC ? io.motionVectorTextureSize.x : 1.0f;
float motionVectorScaleY = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC ? io.motionVectorTextureSize.y : 1.0f;
// Filled every frame (cheap), but EnsureNativeContext only (re)creates the native context when the max render
// size or init flags actually change (see those fields) — both rare, so this is not a per-frame reallocation.
passData.upscalerContext = upscalerContext;
{
bool displayResolutionMotionVectors = io.motionVectorTextureSize.x == io.postUpscaleResolution.x &&
io.motionVectorTextureSize.y == io.postUpscaleResolution.y;
passData.initSettings = new FSR2CommandInitializationData();
passData.initSettings.SetFlag(FfxFsr2InitializationFlags.EnableHighDynamicRange, io.hdrInput);
passData.initSettings.SetFlag(FfxFsr2InitializationFlags.EnableDisplayResolutionMotionVectors, displayResolutionMotionVectors);
passData.initSettings.SetFlag(FfxFsr2InitializationFlags.DepthInverted, io.invertedDepth);
passData.initSettings.SetFlag(FfxFsr2InitializationFlags.EnableMotionVectorsJitterCancellation, io.jitteredMotionVectors);
passData.initSettings.SetFlag(FfxFsr2InitializationFlags.EnableDynamicResolution, io.dynamicResolution.HasValue);
// Allocate at the max render size; the per-frame renderSize (execData below) is the actually-rendered
// sub-region, so dynamic resolution never reallocates. With DRS off the max equals the render size.
passData.initSettings.maxRenderSizeWidth = (uint)io.maxPreUpscaleResolution.x;
passData.initSettings.maxRenderSizeHeight = (uint)io.maxPreUpscaleResolution.y;
passData.initSettings.displaySizeWidth = (uint)io.postUpscaleResolution.x;
passData.initSettings.displaySizeHeight = (uint)io.postUpscaleResolution.y;
}
// Per-frame execution data read from io.options, so live changes (e.g. sharpness) apply without recreating
// the context. Null-guarded only defensively; FSR2 always has framework-resolved options.
var currentOptions = io.options as FSR2Options;
passData.execData.enableSharpening = (currentOptions != null && currentOptions.enableSharpening) ? 1 : 0;
passData.execData.sharpness = currentOptions != null ? currentOptions.sharpness : 0f;
passData.execData.MVScaleX = motionVectorSign * motionVectorScaleX;
passData.execData.MVScaleY = motionVectorSign * motionVectorScaleY;
passData.execData.renderSizeWidth = (uint)io.preUpscaleResolution.x;
passData.execData.renderSizeHeight = (uint)io.preUpscaleResolution.y;
passData.execData.jitterOffsetX = io.subpixelJitter.x;
passData.execData.jitterOffsetY = io.subpixelJitter.y;
passData.execData.cameraNear = io.nearClipPlane;
passData.execData.cameraFar = io.farClipPlane;
passData.execData.cameraFovAngleVertical = 2.0f * (float)Math.PI * (1 / 360.0f) * io.fieldOfViewDegrees; // radians
passData.execData.preExposure = 1.0f; // Mathf.Clamp(io.preExposureValue, 0.20f, 2.0f); // clamp to a reasonable value to prevent ghosting
passData.execData.frameTimeDelta = io.deltaTime * 1000.0f; // in milliseconds
passData.execData.reset = io.resetHistory ? 1 : 0;
// Texture handles
builder.UseTexture(io.cameraColor);
builder.UseTexture(io.cameraDepth);
builder.UseTexture(io.motionVectorColor);
builder.UseTexture(outputColor, AccessFlags.Write);
passData.colorInput = io.cameraColor;
passData.depth = io.cameraDepth;
passData.motionVectors = io.motionVectorColor;
passData.colorOutput = outputColor;
// set render function
builder.SetRenderFunc((FSR2GraphData data, UnsafeGraphContext ctx) =>
{
CommandBuffer cmd = CommandBufferHelpers.GetNativeCommandBuffer(ctx.cmd);
Debug.Assert(data.initSettings.displaySizeWidth > 0, "FSR2 init settings must be populated");
// Get the native context, (re)creating it only if the max render size or init flags changed (the context decides).
FSR2Context nativeContext = data.upscalerContext.EnsureNativeContext(cmd, data.initSettings);
Debug.Assert(nativeContext != null);
nativeContext.executeData = data.execData;
FSR2TextureTable textureTable = new()
{
colorInput = data.colorInput,
depth = data.depth,
motionVectors = data.motionVectors,
colorOutput = data.colorOutput,
};
GraphicsDevice.device.ExecuteFSR2(cmd, nativeContext, textureTable);
});
}
io.cameraColor = outputColor;
}
#endregion
#region DATA
private bool m_FSR2Ready = false;
#endregion
}
#endif // ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: be41240ee7c09d949b3575ef8d2ad8c9
@@ -0,0 +1,79 @@
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
using UnityEngine.AMD;
#endif
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
[Serializable]
public class FSR2Options : UpscalerOptions
{
#region BACKING_FIELDS
[SerializeField]
[Tooltip("Selects a performance quality setting for AMD FidelityFX 2.0 Super Resolution (FSR2).")]
private FSR2Quality m_FSR2QualityMode = FSR2Quality.Quality;
[SerializeField]
[Tooltip("Enable an additional sharpening pass on FidelityFX 2.0 Super Resolution (FSR2).")]
private bool m_EnableSharpening = false;
[SerializeField]
[Tooltip("The sharpness value between 0 and 1, where 0 is no additional sharpness and 1 is maximum additional sharpness.")]
[Range(0.0f, 1.0f)]
private float m_Sharpness = 0.92f;
#endregion
#region PROPERTIES
/// <summary>
/// Gets or sets the performance quality setting for AMD FSR2.
/// </summary>
public FSR2Quality fsr2QualityMode
{
get { return m_FSR2QualityMode; }
set { m_FSR2QualityMode = value; }
}
/// <summary>
/// Enables or disables the additional sharpening pass within FSR2.
/// </summary>
public bool enableSharpening
{
get { return m_EnableSharpening; }
set { m_EnableSharpening = value; }
}
/// <summary>
/// Controls the intensity of the sharpening filter (0.0 to 1.0).
/// </summary>
public float sharpness
{
get { return m_Sharpness; }
set { m_Sharpness = value; }
}
#endregion
/// <summary>
/// Shallow copies values from another FSR2Options instance into this one.
/// </summary>
public void CopyFrom(FSR2Options other)
{
if (other == null)
return;
resolutionMode = other.resolutionMode;
m_FSR2QualityMode = other.m_FSR2QualityMode;
m_EnableSharpening = other.m_EnableSharpening;
m_Sharpness = other.m_Sharpness;
}
}
#endif // ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1b516656c1bb6634192a33e967e54491
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 80c8d7b6f99b7a34eba11304141760a1
@@ -0,0 +1,208 @@
#if ENABLE_UPSCALER_FRAMEWORK
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine.Scripting;
using static UnityEngine.Rendering.DynamicResolutionHandler;
namespace UnityEngine.Rendering
{
#nullable enable
/// <summary>
/// Base ScriptableObject for holding configuration data for a specific upscaler.
/// Concrete implementations (e.g., DLSSOptions, FSR2Options) should inherit from this.
/// </summary>
[Serializable]
public class UpscalerOptions : ScriptableObject
{
/// <summary>
/// The unique identifier or display name of the upscaler associated with these options.
/// </summary>
public string upscalerName
{
get => m_UpscalerName;
set => m_UpscalerName = value;
}
/// <summary>
/// Determines at which stage in the render pipeline the upscaling pass is injected.
/// </summary>
public UpsamplerScheduleType injectionPoint
{
get => m_InjectionPoint;
set => m_InjectionPoint = value;
}
/// <summary>
/// Selects how the render resolution is determined for this upscaler. Only meaningful for upscalers that
/// expose a quality mode (<see cref="IUpscaler.hasQualityMode"/>); for the others it is dormant and the
/// upscaler always behaves as <see cref="UpscalerResolutionMode.CustomScaling"/>.
/// </summary>
public UpscalerResolutionMode resolutionMode
{
get => m_ResolutionMode;
set => m_ResolutionMode = value;
}
[SerializeField, HideInInspector]
private string m_UpscalerName = "";
[SerializeField, HideInInspector] // hide in inspector for URP, HDRP manually renders it
private UpsamplerScheduleType m_InjectionPoint = UpsamplerScheduleType.BeforePost;
[SerializeField]
[Tooltip("Determines how the render resolution is selected: from the upscaler's quality preset (Quality " +
"Mode), or driven by the pipeline's own render scaling / dynamic resolution (Custom Scaling). " +
"Ignored by upscalers without a quality mode.")]
private UpscalerResolutionMode m_ResolutionMode = UpscalerResolutionMode.QualityMode;
#if UNITY_EDITOR
/// <summary>
/// Validates and auto-populates the upscaler options list within a Render Pipeline Asset.
/// It ensures that for every registered upscaler, a corresponding Options sub-asset exists.
/// </summary>
/// <param name="parentRPAsset">The Render Pipeline Asset that will contain these options as sub-assets.</param>
/// <param name="optionsListProp">The SerializedProperty representing the list/array of UpscalerOptions.</param>
/// <returns>True if the property was modified (cleaned up or populated), false otherwise.</returns>
public static bool ValidateSerializedUpscalerOptionReferencesWithinRPAsset(ScriptableObject parentRPAsset, SerializedProperty optionsListProp)
{
if (parentRPAsset == null)
{
Debug.LogError("[Auto-Populate] Parent asset is null.");
return false;
}
if (optionsListProp == null || !optionsListProp.isArray)
{
Debug.LogError($"[Auto-Populate] Provided SerializedProperty '{optionsListProp?.name ?? "null"}' is not a valid list for upscaler options.");
return false;
}
bool propertyModified = false;
// Track valid objects to identify orphans later
HashSet<Object> validReferencedObjects = new HashSet<Object>();
HashSet<Type> typesInList = new HashSet<Type>();
// =================================================================================
// PASS 1: Clean up the Serialized List (Nulls & Duplicate Types)
// =================================================================================
for (int i = optionsListProp.arraySize - 1; i >= 0; i--)
{
SerializedProperty elementProp = optionsListProp.GetArrayElementAtIndex(i);
Object objRef = elementProp.objectReferenceValue;
// 1. Remove Nulls
if (objRef == null)
{
// TODO: find a way to properly remove abandoned upscaler options.
// there's no good way to remove null options from the RPAsset with Delete/Destroy calls.
// one alternative is to copy non-null entries into memory and rewrite the RPAsset.
//
// optionsListProp.DeleteArrayElementAtIndex(i);
// propertyModified = true;
// Debug.LogWarning($"[RP Asset] Removed null upscaler option from active list in '{parentRPAsset.name}'.");
continue;
}
// 2. Check for Duplicate Types within the active list
// (e.g., The list somehow has two FSR2Options. We keep the first, remove the rest).
Type objType = objRef.GetType();
if (typesInList.Contains(objType))
{
optionsListProp.DeleteArrayElementAtIndex(i);
propertyModified = true;
Debug.LogWarning($"[RP Asset] Removed duplicate active reference of type {objType.Name} from list in '{parentRPAsset.name}'.");
// We do NOT add to validReferencedObjects, so it will be caught in Pass 2 and destroyed.
}
else
{
typesInList.Add(objType);
validReferencedObjects.Add(objRef);
}
}
// =================================================================================
// PASS 2: Ghost Hunting (Destroy orphaned Sub-Assets)
// =================================================================================
// Load ALL assets contained within the file
string assetPath = AssetDatabase.GetAssetPath(parentRPAsset);
Object[] allSubAssets = AssetDatabase.LoadAllAssetsAtPath(assetPath);
List<Object> assetsToDestroy = new List<Object>();
foreach (Object subAsset in allSubAssets)
{
// We only care about UpscalerOptions. Ignore the main RPAsset or other embedded data.
// We also check if it is HideInHierarchy/HideInInspector, which usually indicates a sub-asset.
if (subAsset is UpscalerOptions)
{
// If this asset exists in the file, but is NOT in our 'validReferencedObjects' set, it is an orphan.
if (!validReferencedObjects.Contains(subAsset))
{
assetsToDestroy.Add(subAsset);
}
}
}
if (assetsToDestroy.Count > 0)
{
Debug.Log($"[RP Asset] Found {assetsToDestroy.Count} orphaned/duplicate sub-assets in '{parentRPAsset.name}'. Cleaning up...");
foreach (Object orphan in assetsToDestroy)
{
Debug.Log($"[RP Asset] Destroying orphan: {orphan.name} ({orphan.GetType().Name})");
// Crucial: Object.DestroyImmediate with 'true' allows destroying assets in the Editor.
// This removes the YAML block entirely.
Object.DestroyImmediate(orphan, true);
}
propertyModified = true;
}
// =================================================================================
// PASS 3: Populate Missing Required Options
// =================================================================================
foreach (var kvp in UpscalerRegistry.s_RegisteredUpscalers)
{
Type upscalerType = kvp.Key;
Type? optionsType = kvp.Value.OptionsType;
if (optionsType == null)
continue;
string upscalerName = kvp.Value.ID;
// Check if we already have this type in our tracked types from Pass 1
bool foundExisting = typesInList.Contains(optionsType);
if (!foundExisting)
{
UpscalerOptions newOption = (UpscalerOptions)ScriptableObject.CreateInstance(optionsType);
newOption.hideFlags = HideFlags.HideInHierarchy; // Standard for embedded sub-assets
newOption.name = optionsType.Name; // Give it a clean name in the file
newOption.upscalerName = upscalerName;
// Add the physical object to the main asset file
AssetDatabase.AddObjectToAsset(newOption, parentRPAsset);
// Add the reference to the list
optionsListProp.arraySize++;
optionsListProp.GetArrayElementAtIndex(optionsListProp.arraySize - 1).objectReferenceValue = newOption;
propertyModified = true;
Debug.Log($"[RP Asset] Created missing upscaler option on asset '{parentRPAsset.name}': {optionsType.Name} for ID: {upscalerName}");
}
}
return propertyModified;
}
#endif
}
#nullable disable
}
#endif // ENABLE_UPSCALER_FRAMEWORK
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 588cd674e5de5f94c8cb1337010456a3
@@ -0,0 +1,452 @@
#if ENABLE_UPSCALER_FRAMEWORK
#nullable enable
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering
{
/// <summary>
/// Manages per-camera upscaler contexts. Handles context creation, caching, validation, and expiry.
/// </summary>
internal class UpscalerContextManager
{
private struct ContextKey : IEquatable<ContextKey>
{
public ulong cameraId;
public string upscalerName;
public ContextKey(ulong cameraId, string upscalerName)
{
this.cameraId = cameraId;
this.upscalerName = upscalerName;
}
public bool Equals(ContextKey other)
{
return cameraId == other.cameraId &&
upscalerName == other.upscalerName;
}
public override bool Equals(object? obj) => obj is ContextKey other && Equals(other);
public override int GetHashCode() => HashCode.Combine(cameraId, upscalerName);
}
// Contexts unused for this many frames are automatically cleaned up.
// 400 frames at 60 FPS ≈ 6.7 seconds. This threshold follows the pattern
// established in HDRP's existing context management.
private const int k_ContextExpiryFrames = 400;
private readonly Dictionary<ContextKey, IUpscalerContext> m_Contexts = new();
private readonly List<ContextKey> m_KeysToRemove = new(); // Reusable list for cleanup
private readonly List<IUpscalerContext> m_InvalidatedContexts = new(); // Contexts pending cleanup
/// <summary>
/// Acquires a context for the specified camera and upscaler.
/// Returns a cached context if valid, or creates a new one if missing or invalid.
/// Also updates the context's last-used frame for expiry tracking.
/// </summary>
/// <param name="cameraId">Unique ID for the camera. In XR scenarios, this must be unique per view (encode eye information into the ID).</param>
/// <param name="upscaler">The upscaler to acquire a context for.</param>
/// <param name="options">The current upscaler options.</param>
/// <param name="displayResolution">The target display resolution.</param>
/// <returns>The context, or null for spatial upscalers that don't need context.</returns>
public IUpscalerContext? AcquireContext(
ulong cameraId,
IUpscaler upscaler,
UpscalerOptions options,
Vector2Int displayResolution)
{
var key = new ContextKey(cameraId, upscaler.name);
// Note: Time.frameCount may not advance in Editor when Game view is inactive.
// This is acceptable because contexts are only acquired during active rendering,
// and lastUsedFrame is updated on every AcquireContext call. If a more robust
// solution is needed (e.g., for scene view upscaling), consider using
// Time.realtimeSinceStartup or a pipeline-provided render counter.
int currentFrame = Time.frameCount;
if (m_Contexts.TryGetValue(key, out var existingContext))
{
// Check if context is still valid
bool resolutionValid = existingContext.createdForDisplayResolution == displayResolution;
bool optionsValid = existingContext.IsValidForOptions(options);
if (resolutionValid && optionsValid)
{
existingContext.lastUsedFrame = currentFrame;
return existingContext;
}
// Context is invalid, queue it for cleanup and remove from cache
m_InvalidatedContexts.Add(existingContext);
m_Contexts.Remove(key);
}
// Create new context
var newContext = upscaler.CreateContext(options, displayResolution);
if (newContext != null)
{
newContext.lastUsedFrame = currentFrame;
m_Contexts[key] = newContext;
}
else if (upscaler.isTemporal)
{
// Temporal upscalers should always return a context. Null indicates
// a creation failure (e.g., plugin not loaded, GPU not supported).
Debug.LogWarning($"[UpscalerContextManager] Temporal upscaler '{upscaler.name}' returned null context. " +
"Upscaling may not function correctly.");
}
return newContext;
}
/// <summary>
/// Removes contexts that haven't been used for more than k_ContextExpiryFrames frames.
/// Also cleans up any contexts that were invalidated (due to resolution or option changes).
/// Should be called once per frame from the render pipeline.
/// </summary>
public void CleanupExpiredContexts(CommandBuffer cmd)
{
// Clean up invalidated contexts first
foreach (var context in m_InvalidatedContexts)
{
context.Cleanup(cmd);
}
m_InvalidatedContexts.Clear();
// Clean up expired contexts (see AcquireContext for Time.frameCount limitations)
int currentFrame = Time.frameCount;
m_KeysToRemove.Clear();
foreach (var kvp in m_Contexts)
{
var context = kvp.Value;
int framesSinceLastUse = currentFrame - context.lastUsedFrame;
if (framesSinceLastUse > k_ContextExpiryFrames)
{
context.Cleanup(cmd);
m_KeysToRemove.Add(kvp.Key);
}
}
foreach (var key in m_KeysToRemove)
{
m_Contexts.Remove(key);
}
}
/// <summary>
/// Cleans up all contexts. Called when the upscaling system is disposed.
/// </summary>
public void Dispose(CommandBuffer cmd)
{
// Clean up any pending invalidated contexts
foreach (var context in m_InvalidatedContexts)
{
context.Cleanup(cmd);
}
m_InvalidatedContexts.Clear();
// Clean up all active contexts
foreach (var kvp in m_Contexts)
{
kvp.Value.Cleanup(cmd);
}
m_Contexts.Clear();
}
}
public static class UpscalerRegistry
{
public static readonly Dictionary<Type, (Type? OptionsType, string ID)> s_RegisteredUpscalers = new();
/// <summary>
/// Registers an IUpscaler type without any custom options type.
/// </summary>
public static void Register<TUpscaler>(string id) where TUpscaler : IUpscaler, new()
{
s_RegisteredUpscalers[typeof(TUpscaler)] = (null, id);
}
/// <summary>
/// Registers an IUpscaler type with its custom options type.
/// </summary>
public static void Register<TUpscaler, TOptions>(string id)
where TUpscaler : IUpscaler
where TOptions : UpscalerOptions
{
s_RegisteredUpscalers[typeof(TUpscaler)] = (typeof(TOptions), id);
}
}
public class Upscaling
{
#region private
// The integration type is internally used by the SRP systems, which contain embedded upscaling passes in an uber-pass.
// The external upscaler integrations are assumed to be standalone render passes.
private enum UpscalerIntegrationType
{
StandalonePass, // The upscaler is executed as a standalone Render Graph pass.
EmbeddedPass // The upscaler is baked into a pipeline-specific uber-pass (e.g., URP's Post-process pass).
}
private struct UpscalerEntry
{
readonly public IUpscaler Instance { get; }
readonly public UpscalerIntegrationType IntegrationType { get; }
readonly public bool IsEmbedded { get { return IntegrationType == UpscalerIntegrationType.EmbeddedPass; } }
public UpscalerEntry(IUpscaler instance, UpscalerIntegrationType integrationType)
{
Instance = instance;
IntegrationType = integrationType;
}
}
private List<UpscalerEntry> m_Upscalers = new List<UpscalerEntry>();
private string[] m_UpscalerNamesCache;
private int m_ActiveUpscalerIndex = -1;
private readonly UpscalerContextManager m_ContextManager = new();
// Pipeline-wide ("global") options per upscaler, keyed by upscaler name; GetGlobalOptions() returns these.
// Absent for upscalers registered without an options type (spatial/embedded) — their options are null.
private readonly Dictionary<string, UpscalerOptions> m_GlobalOptions = new();
#endregion
/// <summary>
/// Returns the names of the upscalers registered to the upscaling system.
/// </summary>
public IReadOnlyList<string> upscalerNames => m_UpscalerNamesCache;
/// <summary>
/// Returns the active IUpscaler instance, null if none is selected.
/// </summary>
public IUpscaler? activeUpscaler => (m_ActiveUpscalerIndex >= 0) ? m_Upscalers[m_ActiveUpscalerIndex].Instance : null;
/// <summary>
/// Returns true if the active upscaler is embedded in an uber pass.
/// </summary>
public bool activeUpscalerIsEmbedded => (m_ActiveUpscalerIndex >= 0) && m_Upscalers[m_ActiveUpscalerIndex].IsEmbedded;
/// <summary>
/// Initializes the Upscaling system. with the given list of upscaler options per upscaler type.
/// </summary>
/// <param name="upscalerOptions">The list of options from the RP asset.</param>
/// <param name="embeddedTypes">A set of types that the pipeline handles internally (e.g., Bilinear, Point in URP).</param>
/// <param name="priorityOrder">
/// An ordered list of Types. Upscalers matching these types will appear first
/// in the list, in the order provided. All others appear after, alphabetically.
/// </param>
public Upscaling(
List<UpscalerOptions> upscalerOptions,
HashSet<Type>? embeddedTypes = null,
Type[]? priorityOrder = null
)
{
// 1. Instantiate the upscaler instances
foreach (var kvp in UpscalerRegistry.s_RegisteredUpscalers)
{
Type upscalerType = kvp.Key;
Type? optionsType = kvp.Value.OptionsType;
// find any serialized options, if any provided by the package implementor
int optionsIndex = upscalerOptions.FindIndex(o => o != null && o.GetType() == optionsType);
bool optionsNotFound = optionsIndex == -1;
UpscalerOptions? options = optionsNotFound ? null: upscalerOptions[optionsIndex];
// construct upscaler (always parameterless; options are owned by the framework, not the instance)
IUpscaler upscaler = (IUpscaler)Activator.CreateInstance(upscalerType);
// Create a fresh options object when the asset provided none, so a quality-mode upscaler always has one.
// Upscalers without an options type (spatial/embedded) keep no entry, leaving their options null.
if (options == null && optionsType != null)
{
options = (UpscalerOptions)ScriptableObject.CreateInstance(optionsType);
options.upscalerName = upscaler.name;
}
if (options != null && string.IsNullOrEmpty(options.upscalerName))
{
Debug.LogWarningFormat("[Upscaling] UpscalerOptions with empty upscalerName for {0}", upscaler.name);
options.upscalerName = upscaler.name;
}
if (options != null)
m_GlobalOptions[upscaler.name] = options;
bool isEmbedded = embeddedTypes != null && embeddedTypes.Contains(upscalerType);
m_Upscalers.Add(new UpscalerEntry(upscaler, isEmbedded ? UpscalerIntegrationType.EmbeddedPass : UpscalerIntegrationType.StandalonePass));
}
// 2. Type-based sorting based on priorty order
m_Upscalers.Sort((a, b) =>
{
Type typeA = a.Instance.GetType();
Type typeB = b.Instance.GetType();
int indexA = -1;
int indexB = -1;
if (priorityOrder != null)
{
indexA = Array.IndexOf(priorityOrder, typeA);
indexB = Array.IndexOf(priorityOrder, typeB);
}
// Priority Sort: If both are in the priority list, respect that order.
if (indexA != -1 && indexB != -1) return indexA.CompareTo(indexB);
// Mixed Sort: Priority items always come before non-priority items.
if (indexA != -1) return -1;
if (indexB != -1) return 1;
// Fallback Sort: If neither are in the list (external upscalers), sort Alphabetically.
return string.Compare(a.Instance.name, b.Instance.name, StringComparison.OrdinalIgnoreCase);
});
// 3. Populate name cache
m_UpscalerNamesCache = new string[m_Upscalers.Count];
for (int i = 0; i < m_Upscalers.Count; i++)
{
string name = m_Upscalers[i].Instance.name;
m_UpscalerNamesCache[i] = name;
}
}
/// <summary>
/// Sets the active upscaler by name, returns whether an upscaler with the given name was found.
/// </summary>
public bool SetActiveUpscaler(string name)
{
int index = Array.IndexOf(m_UpscalerNamesCache, name);
if (index == -1)
{
m_ActiveUpscalerIndex = -1;
return false;
}
m_ActiveUpscalerIndex = index;
// TODO (Apoorva): We need to allow the IUpscaler itself to decide whether it can run. E.g.
// DLSS might need a certain version of Windows, and a compatible GPU. We should add an
// overrideable function to IUpscaler so that the active IUpscaler can return a bool
// indicating support.
return true;
}
/// <summary>
/// Returns the index of the upscalerName. -1 is returned if upscalerName is not in the name cache.
/// </summary>
public int IndexOf(string upscalerName)
{
return Array.IndexOf(m_UpscalerNamesCache, upscalerName);
}
/// <summary>
/// Returns the registered IUpscaler instance with the given name, or null if none matches. Resolves the same
/// name as <see cref="SetActiveUpscaler"/> (the registered upscaler name).
/// </summary>
public IUpscaler? GetIUpscalerByName(string upscalerName)
{
int index = IndexOf(upscalerName);
return index >= 0 ? m_Upscalers[index].Instance : null;
}
/// <summary>
/// Returns null if no IUpscaler exists for given type
/// </summary>
public IUpscaler? GetIUpscalerOfType<T>() where T : IUpscaler
{
if(!UpscalerRegistry.s_RegisteredUpscalers.ContainsKey(typeof(T)))
return null;
foreach (UpscalerEntry entry in m_Upscalers)
if (entry.Instance.GetType() == typeof(T))
return entry.Instance;
Debug.LogErrorFormat($"Upscaler type {typeof(T)} not found");
return null;
}
/// <summary>
/// Returns null if no IUpscaler exists for given type
/// </summary>
public IUpscaler? GetIUpscalerOfType(Type T)
{
if (!UpscalerRegistry.s_RegisteredUpscalers.ContainsKey(T))
return null;
foreach (UpscalerEntry entry in m_Upscalers)
if (entry.Instance.GetType() == T)
return entry.Instance;
Debug.LogErrorFormat($"Upscaler type {T} not found");
return null;
}
#region Options
/// <summary>
/// Returns the pipeline-wide ("global") options for the given upscaler — the live, user-configured options
/// object the pipeline supplied (e.g. an RP-asset sub-asset), shared by all cameras — or <c>null</c> if the
/// upscaler was registered without an options type (e.g. spatial/embedded upscalers).
/// </summary>
/// <param name="upscaler">The upscaler whose global options to fetch.</param>
/// <returns>The pipeline-wide options, or null if the upscaler has no options type.</returns>
/// <remarks>
/// This is not a copy and not factory defaults: editing the returned object (inspector or C# API) is reflected
/// here, because it is the same serialized instance. Options are owned by the framework, not the
/// <see cref="IUpscaler"/> instance.
/// <para>
/// Per-camera options (future) layer on top of this: add an override-aware
/// <c>ResolveOptions(IUpscaler, UpscalerOptions perCameraOverride)</c> returning
/// <c>perCameraOverride ?? GetGlobalOptions(upscaler)</c>, and have the call sites pass the camera's serialized
/// override (read from the pipeline-specific camera component — core cannot see it). That is a non-breaking
/// addition and this method stays as the global fallback. Not added now because no per-camera override source
/// exists yet (it would be a no-op).
/// </para>
/// </remarks>
public UpscalerOptions? GetGlobalOptions(IUpscaler upscaler)
{
return upscaler != null && m_GlobalOptions.TryGetValue(upscaler.name, out var options) ? options : null;
}
#endregion
#region Context Management
/// <summary>
/// Acquires an upscaler context for the specified camera.
/// Returns a cached context if valid, or creates a new one if missing or invalid.
/// Also updates the context's last-used frame for expiry tracking.
/// </summary>
/// <param name="cameraId">Unique ID for the camera. In XR scenarios, this must be unique per view (encode eye information into the ID).</param>
/// <param name="upscaler">The upscaler to acquire a context for.</param>
/// <param name="options">The current upscaler options.</param>
/// <param name="displayResolution">The target display resolution.</param>
/// <returns>The context, or null for spatial upscalers that don't need context.</returns>
public IUpscalerContext? AcquireContext(
ulong cameraId,
IUpscaler upscaler,
UpscalerOptions options,
Vector2Int displayResolution)
{
return m_ContextManager.AcquireContext(cameraId, upscaler, options, displayResolution);
}
/// <summary>
/// Cleans up contexts that haven't been used for a while (400 frames).
/// Should be called once per frame from the render pipeline.
/// </summary>
/// <param name="cmd">The command buffer to record cleanup commands into.</param>
public void CleanupExpiredContexts(CommandBuffer cmd)
{
m_ContextManager.CleanupExpiredContexts(cmd);
}
/// <summary>
/// Cleans up all contexts. Call when the upscaling system is torn down (e.g. when the render
/// pipeline is disposed)
/// </summary>
/// <param name="cmd">The command buffer to record cleanup commands into.</param>
public void Dispose(CommandBuffer cmd)
{
m_ContextManager.Dispose(cmd);
}
#endregion
}
}
#endif
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 89581a153029901419c003d693ca36a6