// Copyright (c) 2023 Nico de Poel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.PostProcessing; using FidelityFX; namespace UnityEngine.Rendering.PostProcessing { [UnityEngine.Scripting.Preserve] [Serializable] public class SuperResolution { public static Func CallbacksFactory { get; set; } = (context) => new Callbacks(context.resources); [Tooltip("Standard scaling ratio presets.")] public Fsr2.QualityMode qualityMode = Fsr2.QualityMode.Quality; [Tooltip("Apply RCAS sharpening to the image after upscaling.")] public bool performSharpenPass = true; [Tooltip("Strength of the sharpening effect.")] [Range(0, 1)] public float sharpness = 0.8f; [Tooltip("Allow the use of half precision compute operations, potentially improving performance if the platform supports it.")] public bool enableFP16 = false; [Tooltip("Allow an exposure value to be computed internally. When set to false, either the provided exposure texture or a default exposure value will be used.")] public bool enableAutoExposure = true; [Tooltip("Value by which the input signal will be divided, to get back to the original signal produced by the game.")] public float preExposure = 1.0f; [Tooltip("Optional 1x1 texture containing the exposure value for the current frame.")] public Texture exposure = null; [Tooltip("Optional texture to control the influence of the current frame on the reconstructed output. If unset, either an auto-generated or a default cleared reactive mask will be used.")] public Texture reactiveMask = null; [Tooltip("Optional texture for marking areas of specialist rendering which should be accounted for during the upscaling process. If unset, a default cleared mask will be used.")] public Texture transparencyAndCompositionMask = null; [Tooltip("Automatically generate a reactive mask based on the difference between opaque-only render output and the final render output including alpha transparencies.")] public bool autoGenerateReactiveMask = true; [Tooltip("Parameters to control the process of auto-generating a reactive mask.")] public GenerateReactiveParameters generateReactiveParameters = new GenerateReactiveParameters(); [Serializable] public class GenerateReactiveParameters { [Range(0, 2)] public float scale = 0.5f; [Range(0, 1)] public float cutoffThreshold = 0.2f; [Range(0, 1)] public float binaryValue = 0.9f; public Fsr2.GenerateReactiveFlags flags = Fsr2.GenerateReactiveFlags.ApplyTonemap | Fsr2.GenerateReactiveFlags.ApplyThreshold | Fsr2.GenerateReactiveFlags.UseComponentsMax; } public Vector2 jitter { get; private set; } public Vector2Int renderSize => _renderSize; public Vector2Int displaySize => _displaySize; private Fsr2Context _fsrContext; private Vector2Int _renderSize; private Vector2Int _displaySize; private bool _reset; private IFsr2Callbacks _callbacks; private float _appliedBiasOffset; private readonly Fsr2.DispatchDescription _dispatchDescription = new Fsr2.DispatchDescription(); private readonly Fsr2.GenerateReactiveDescription _genReactiveDescription = new Fsr2.GenerateReactiveDescription(); private Fsr2.QualityMode _prevQualityMode; private Vector2Int _prevDisplaySize; private Rect _originalRect; public bool IsSupported() { return SystemInfo.supportsComputeShaders && SystemInfo.supportsMotionVectors; } public DepthTextureMode GetCameraFlags() { return DepthTextureMode.Depth | DepthTextureMode.MotionVectors; } public void Release() { DestroyFsrContext(); } public void ResetHistory() { _reset = true; } public void ConfigureJitteredProjectionMatrix(PostProcessRenderContext context) { ApplyJitter(context.camera); } public void ConfigureCameraViewport(PostProcessRenderContext context) { var camera = context.camera; _originalRect = camera.rect; _displaySize = new Vector2Int(camera.pixelWidth, camera.pixelHeight); // TODO: also support render texture targets properly Fsr2.GetRenderResolutionFromQualityMode(out int renderWidth, out int renderHeight, _displaySize.x, _displaySize.y, qualityMode); _renderSize = new Vector2Int(renderWidth, renderHeight); camera.aspect = (_displaySize.x * _originalRect.width) / (_displaySize.y * _originalRect.height); camera.rect = new Rect(0, 0, _originalRect.width * _renderSize.x / camera.pixelWidth, _originalRect.height * _renderSize.y / camera.pixelHeight); } public void ResetCameraViewport(PostProcessRenderContext context) { context.camera.rect = _originalRect; } public void Render(PostProcessRenderContext context) { var cmd = context.command; cmd.BeginSample("FSR2"); // Monitor for any resolution changes and recreate the FSR2 context if necessary // We can't create an FSR2 context without info from the post-processing context, so delay the initial setup until here if (_fsrContext == null || _displaySize.x != _prevDisplaySize.x || _displaySize.y != _prevDisplaySize.y || qualityMode != _prevQualityMode) { DestroyFsrContext(); CreateFsrContext(context); _prevQualityMode = qualityMode; } cmd.SetGlobalTexture(Fsr2ShaderIDs.SrvInputColor, context.source); cmd.SetGlobalTexture(Fsr2ShaderIDs.SrvInputDepth, BuiltinRenderTextureType.CameraTarget, RenderTextureSubElement.Depth); cmd.SetGlobalTexture(Fsr2ShaderIDs.SrvInputMotionVectors, BuiltinRenderTextureType.MotionVectors); SetupDispatchDescription(context); if (autoGenerateReactiveMask) { // TODO: auto-generate reactive mask } cmd.GetTemporaryRT(Fsr2ShaderIDs.UavUpscaledOutput, _displaySize.x, _displaySize.y, 0, default, context.sourceFormat, default, 1, true); _fsrContext.Dispatch(_dispatchDescription, cmd); cmd.BlitFullscreenTriangle(Fsr2ShaderIDs.UavUpscaledOutput, context.destination); cmd.ReleaseTemporaryRT(Fsr2ShaderIDs.UavUpscaledOutput); cmd.EndSample("FSR2"); _reset = false; } private void CreateFsrContext(PostProcessRenderContext context) { _prevDisplaySize = _displaySize; Fsr2.InitializationFlags flags = 0; if (context.camera.allowHDR) flags |= Fsr2.InitializationFlags.EnableHighDynamicRange; if (enableFP16) flags |= Fsr2.InitializationFlags.EnableFP16Usage; if (enableAutoExposure) flags |= Fsr2.InitializationFlags.EnableAutoExposure; _callbacks = CallbacksFactory(context); _fsrContext = Fsr2.CreateContext(_displaySize, _renderSize, _callbacks, flags); // Apply a mipmap bias so that textures retain their sharpness float biasOffset = Fsr2.GetMipmapBiasOffset(_renderSize.x, _displaySize.x); if (!float.IsNaN(biasOffset)) { _callbacks.ApplyMipmapBias(biasOffset); _appliedBiasOffset = biasOffset; } } private void DestroyFsrContext() { if (_fsrContext != null) { _fsrContext.Destroy(); _fsrContext = null; } if (!float.IsNaN(_appliedBiasOffset) && _appliedBiasOffset != 0f) { _callbacks.ApplyMipmapBias(-_appliedBiasOffset); _appliedBiasOffset = 0f; } } private void ApplyJitter(Camera camera) { // Perform custom jittering of the camera's projection matrix according to FSR2's recipe int jitterPhaseCount = Fsr2.GetJitterPhaseCount(_renderSize.x, _displaySize.x); Fsr2.GetJitterOffset(out float jitterX, out float jitterY, Time.frameCount, jitterPhaseCount); _dispatchDescription.JitterOffset = new Vector2(jitterX, jitterY); jitterX = 2.0f * jitterX / _renderSize.x; jitterY = 2.0f * jitterY / _renderSize.y; var jitterTranslationMatrix = Matrix4x4.Translate(new Vector3(jitterX, jitterY, 0)); camera.nonJitteredProjectionMatrix = camera.projectionMatrix; camera.projectionMatrix = jitterTranslationMatrix * camera.nonJitteredProjectionMatrix; camera.useJitteredProjectionMatrixForTransparentRendering = false; jitter = new Vector2(jitterX, jitterY); } private void SetupDispatchDescription(PostProcessRenderContext context) { var camera = context.camera; // Set up the main FSR2 dispatch parameters // The input and output textures are left blank here, as they are already being bound elsewhere in this source file _dispatchDescription.Color = null; _dispatchDescription.Depth = null; _dispatchDescription.MotionVectors = null; _dispatchDescription.Exposure = null; _dispatchDescription.Reactive = null; _dispatchDescription.TransparencyAndComposition = null; if (!enableAutoExposure && exposure != null) _dispatchDescription.Exposure = exposure; if (reactiveMask != null) _dispatchDescription.Reactive = reactiveMask; if (transparencyAndCompositionMask != null) _dispatchDescription.TransparencyAndComposition = transparencyAndCompositionMask; _dispatchDescription.Output = null; _dispatchDescription.PreExposure = preExposure; _dispatchDescription.EnableSharpening = performSharpenPass; _dispatchDescription.Sharpness = sharpness; _dispatchDescription.MotionVectorScale.x = -_renderSize.x; _dispatchDescription.MotionVectorScale.y = -_renderSize.y; _dispatchDescription.RenderSize = _renderSize; _dispatchDescription.InputResourceSize = new Vector2Int(context.width, context.height); _dispatchDescription.FrameTimeDelta = Time.unscaledDeltaTime; _dispatchDescription.CameraNear = camera.nearClipPlane; _dispatchDescription.CameraFar = camera.farClipPlane; _dispatchDescription.CameraFovAngleVertical = camera.fieldOfView * Mathf.Deg2Rad; _dispatchDescription.ViewSpaceToMetersFactor = 1.0f; // 1 unit is 1 meter in Unity _dispatchDescription.Reset = _reset; if (SystemInfo.usesReversedZBuffer) { // Swap the near and far clip plane distances as FSR2 expects this when using inverted depth (_dispatchDescription.CameraNear, _dispatchDescription.CameraFar) = (_dispatchDescription.CameraFar, _dispatchDescription.CameraNear); } } private class Callbacks : Fsr2CallbacksBase { private readonly PostProcessResources _resources; public Callbacks(PostProcessResources resources) { _resources = resources; } public override ComputeShader LoadComputeShader(string name) { return _resources.computeShaders.FindComputeShader(name); } public override void UnloadComputeShader(ComputeShader shader) { } } } }