ААААААААААААААААААААААААААА БЛЕЯТЬААААААА

This commit is contained in:
Andron666
2022-03-23 01:34:38 +05:00
parent d631be4980
commit 905abc65ff
184 changed files with 10916 additions and 2 deletions
+103
View File
@@ -0,0 +1,103 @@
/*
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
using UnrealBuildTool;
public class DLSS : ModuleRules
{
public virtual string [] SupportedDynamicallyLoadedNGXRHIModules(ReadOnlyTargetRules Target)
{
if(Target.Platform == UnrealTargetPlatform.Win64 )
{
return new string[]
{
"NGXD3D11RHI",
"NGXD3D12RHI",
"NGXVulkanRHI"
};
}
return new string[] { "" };
}
public DLSS(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs;
PublicIncludePaths.AddRange(
new string[] {
// ... add public include paths required here ...
}
);
PrivateIncludePaths.AddRange(
new string[] {
EngineDirectory + "/Source/Runtime/Renderer/Private",
// ... add other private include paths required here ...
}
);
PublicDependencyModuleNames.AddRange(
new string[]
{
// ... add other public dependencies that you statically link with here ...
}
);
PrivateDependencyModuleNames.AddRange(
new string[]
{
"Core",
"CoreUObject",
"EngineSettings",
"Engine",
"RenderCore",
"Renderer",
"RHI",
"NGX",
"Projects",
"DeveloperSettings",
"DLSSUtility",
"NGXRHI",
// ... add private dependencies that you statically link with here ...
}
);
if (ReadOnlyBuildVersion.Current.MajorVersion == 5)
{
PrivateDependencyModuleNames.Add("RHICore");
}
DynamicallyLoadedModuleNames.AddRange(SupportedDynamicallyLoadedNGXRHIModules(Target));
// We can't quite check whether we have CL 16848904 (in UE5-Main) so we do this in a round about way
bool bSupportsPostProcessingScreenPercentage = (Target.Version.MajorVersion == 4) ||
((Target.Version.MajorVersion == 5) && (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess"))
;
PrivateDefinitions.Add(string.Format("SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE={0}", bSupportsPostProcessingScreenPercentage ? "1" : "0"));
// this is a public definition so the DLSSMoviePipelineSupport modules (if compiled against that branch) see it
bool bSupportsCustomStaticScreenpercentageSetupViewFamily = ((Target.Version.MajorVersion == 4) && (Target.Version.MinorVersion >= 27)) || ((Target.Version.MajorVersion == 5) && (Target.Version.BranchName != "++UE5+Release-5.0-EarlyAccess"));
PublicDefinitions.Add(string.Format("DLSS_ENGINE_SUPPORTS_CSSPD={0}", bSupportsCustomStaticScreenpercentageSetupViewFamily ? "1" : "0"));
// We can't quite check whether we have CL 16758229 so we do this in a round about way
bool bEngineHasAAM_TSR = (Target.Version.MajorVersion == 5) && (Target.Version.BranchName != "++UE5+Release-5.0-EarlyAccess");
PrivateDefinitions.Add(string.Format("DLSS_ENGINE_HAS_AAM_TSR={0}", bEngineHasAAM_TSR ? "1" : "0"));
// 4.x and early access 5.0 engines had GTemporalUpscaler interface
bool bEngineHasGTemporalUpscaler = (Target.Version.MajorVersion == 4) || (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess");
PrivateDefinitions.Add(string.Format("DLSS_ENGINE_HAS_GTEMPORALUPSCALER={0}", bEngineHasGTemporalUpscaler ? "1" : "0"));
// 4.x and early access 5.0 engines, ITemporalUpscaler::AddPasses returns values through pointers passed into the function
bool bEngineAddPassesReturnThroughParams = (Target.Version.MajorVersion == 4) || (Target.Version.BranchName == "++UE5+Release-5.0-EarlyAccess");
PublicDefinitions.Add(string.Format("DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS={0}", bEngineAddPassesReturnThroughParams ? "1" : "0"));
}
}
+527
View File
@@ -0,0 +1,527 @@
/*
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "DLSS.h"
#include "CoreMinimal.h"
#include "DLSSUpscalerPrivate.h"
#include "DLSSUpscaler.h"
#include "DLSSDenoiser.h"
#include "NGXRHI.h"
#include "Modules/ModuleManager.h"
#include "Interfaces/IPluginManager.h"
#include "GeneralProjectSettings.h"
#include "DLSSSettings.h"
#include "SceneViewExtension.h"
#include "SceneView.h"
#include "Misc/MessageDialog.h"
#define LOCTEXT_NAMESPACE "FDLSSModule"
DEFINE_LOG_CATEGORY(LogDLSS);
static TAutoConsoleVariable<int32> CVarNGXBinarySearchOrder(
TEXT("r.NGX.BinarySearchOrder"),
0,
TEXT("0: automatic: (default)\n")
TEXT(" use custom binaries from project and launch folder $(ProjectDir)/Binaries/ThirdParty/NVIDIA/NGX/$(Platform) if present\n")
TEXT(" fallback to generic binaries from plugin folder\n")
TEXT("1: force generic binaries from plugin folder, fail if not found\n")
TEXT("2: force custom binaries from project or launch folder, fail if not found\n")
TEXT("3: force generic development binaries from plugin folder, fail if not found. This is only supported in non-shipping build configurations\n"),
ECVF_ReadOnly);
static TAutoConsoleVariable<int32> CVarNGXEnable(
TEXT("r.NGX.Enable"), 1,
TEXT("Whether the NGX library should be loaded. This allow to have the DLSS plugin enabled but avoiding potential ")
TEXT("incompatibilities by skipping the driver side NGX parts of DLSS. Can also be set on the command line via -ngxenable and -ngxdisable"),
ECVF_Default);
static TAutoConsoleVariable<int32> CVarNGXDLSSMinimumWindowsBuildVersion(
TEXT("r.NGX.DLSS.MinimumWindowsBuildVersion"), 16299,
TEXT("Sets the minimum Windows 10 build version required to enable DLSS. (default: 16299 for v1709, Windows 10 Fall 2017 Creators Update 64-bit)"),
ECVF_Default
);
static TAutoConsoleVariable<int32> CVarNGXProjectIdentifier(
TEXT("r.NGX.ProjectIdentifier"),
0,
TEXT("0: automatic: (default)\n")
TEXT(" use NVIDIA NGX Application ID if non-zero, otherwise use UE Project ID)\n")
TEXT("1: force UE Project ID\n")
TEXT("2: force NVIDIA NGX Application ID (set via the Project Settings -> NVIDIA DLSS plugin)\n"),
ECVF_ReadOnly);
static TAutoConsoleVariable<bool> CVarNGXAutomationEnable(
TEXT("r.NGX.Automation.Enable"),
false,
TEXT("Enable automation for NGX DLSS image quality and performance evaluation. (default = 0)\n"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int> CVarNGXAutomationViewIndex(
TEXT("r.NGX.Automation.ViewIndex"),
0,
TEXT("Select which view to use with NGX DLSS image quality and performance automation. (default = 0). \n"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int> CVarNGXAutomationNonGameViews(
TEXT("r.NGX.Automation.NonGameViews"),
0,
TEXT("Enable NGX DLSS image quality and performance automation for non-game views. (default = 0). \n"),
ECVF_RenderThreadSafe);
class FNGXAutomationViewExtension final : public FSceneViewExtensionBase
{
public:
FNGXAutomationViewExtension(const FAutoRegister& AutoRegister): FSceneViewExtensionBase(AutoRegister)
{
FSceneViewExtensionIsActiveFunctor IsActiveFunctor;
IsActiveFunctor.IsActiveFunction = [](const ISceneViewExtension* SceneViewExtension, const FSceneViewExtensionContext& Context)
{
return CVarNGXAutomationEnable.GetValueOnAnyThread();
};
IsActiveThisFrameFunctions.Add(IsActiveFunctor);
}
virtual void SetupViewFamily(FSceneViewFamily& InViewFamily) {}
virtual void SetupView(FSceneViewFamily& InViewFamily, FSceneView& InView) {}
virtual void SetupViewPoint(APlayerController* Player, FMinimalViewInfo& InViewInfo) {}
virtual void BeginRenderViewFamily(FSceneViewFamily& InViewFamily) {}
virtual void PreRenderView_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneView& InView) final {}
virtual void PreRenderViewFamily_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneViewFamily& InViewFamily) final
{
int32 ViewIndex = CVarNGXAutomationViewIndex.GetValueOnRenderThread();
if (InViewFamily.Views.IsValidIndex(ViewIndex))
{
const FSceneView* View = InViewFamily.Views[ViewIndex];
if (View->bIsGameView || CVarNGXAutomationNonGameViews.GetValueOnRenderThread())
{
const FString AiAgentMarker = FString::Printf(TEXT("{\"camera\":{\"position\":{\"x\": %f, \"y\": %f, \"z\": %f},\"rotation\":{\"pitch\": %f, \"roll\": %f, \"yaw\": %f}}}"),
View->ViewLocation.X, View->ViewLocation.Y, View->ViewLocation.Z,
View->ViewRotation.Pitch, View->ViewRotation.Roll, View->ViewRotation.Yaw);
static FColor ColorMarker = FColor::FromHex("0xA1A5E87");
RHICmdList.PushEvent(*AiAgentMarker, ColorMarker);
RHICmdList.PopEvent();
}
}
}
};
static bool IsCompatibleEngineVersion(FString& OutPluginVersion, FString& OutEngineVersion)
{
// Binary incompatibility between 4.26.0 and 4.26.1, so check for the engine patch version at runtime here
// Engine loading code already checks for compatibility for major/minor/changelist
// Written so that no code change will be needed for future engine versions if compatibility isn't broken again
FEngineVersion Version = FEngineVersion::Current();
OutEngineVersion = FString::Printf(TEXT("%u.%u.%u"), Version.GetMajor(), Version.GetMinor(), Version.GetPatch());
OutPluginVersion = FString::Printf(TEXT("%u.%u.%u"), ENGINE_MAJOR_VERSION, ENGINE_MINOR_VERSION, ENGINE_PATCH_VERSION);
#if ENGINE_MAJOR_VERSION == 4
#if ENGINE_MINOR_VERSION == 26
#if ENGINE_PATCH_VERSION == 0
// 4.26.0
return Version.GetPatch() == 0;
#else
// 4.26.x, x > 0
return Version.GetPatch() >= 1;
#endif
#else
// 4.x._, x > 26
return true;
#endif
#elif ENGINE_MAJOR_VERSION == 5
return true;
#else
#error "ENGINE_MAJOR_VERSION must be either 4 or 5"
#endif
}
void FDLSSModule::StartupModule()
{
// This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
// Get the base directory of this plugin
const FString PluginBaseDir = IPluginManager::Get().FindPlugin(TEXT("DLSS"))->GetBaseDir();
const FString NGXBinariesDir = FPaths::Combine(*PluginBaseDir, TEXT("Binaries/ThirdParty/Win64/"));
const FString RHIName = GDynamicRHI->GetName();
UE_LOG(LogDLSS, Log, TEXT("PluginBaseDir %s"), *PluginBaseDir);
UE_LOG(LogDLSS, Log, TEXT("NGXBinariesDir %s"), *NGXBinariesDir);
UE_LOG(LogDLSS, Log, TEXT("GDynamicRHIName %s %s"), RHIVendorIdToString(), *RHIName );
bool bLoadLibraries = CVarNGXEnable.GetValueOnAnyThread() != 0;
if (FParse::Param(FCommandLine::Get(), TEXT("ngxenable")))
{
bLoadLibraries = true;
}
else if (FParse::Param(FCommandLine::Get(), TEXT("ngxdisable")))
{
bLoadLibraries = false;
}
const int32 NGXDLSSMinimumWindowsBuildVersion = CVarNGXDLSSMinimumWindowsBuildVersion.GetValueOnAnyThread();
FString PluginVersion;
FString EngineVersion;
if (!IsCompatibleEngineVersion(PluginVersion, EngineVersion))
{
FEngineVersion Version = FEngineVersion::Current();
UE_LOG(LogDLSS, Error,
TEXT("This prebuilt binary distribution version %s of the NVIDIA DLSS plugin is not compatible with the current engine version %s"),
*PluginVersion, *EngineVersion);
UE_LOG(LogDLSS, Error, TEXT("Build the DLSS plugin from source (e.g. via the Editor -> Plugins -> NVIDIA DLSS -> Package)"));
DLSSSupport = EDLSSSupport::NotSupported;
// we don't want this ever show up in packaged builds
#if WITH_EDITOR
const bool IsUnattended = FApp::IsUnattended() || IsRunningCommandlet() || GIsRunningUnattendedScript;
if (!IsUnattended )
{
const FText DialogTitle(LOCTEXT("DLSSIncompatibleEngineVersionTitle", "Error - DLSS plugin incompatible with engine"));
const FTextFormat Format(LOCTEXT("DLSSIncompatibleEngineVersion",
"The binary version {0} of this DLSS Unreal Engine Plugin is not compatible with the binary version {1} of this Unreal Engine installation. \n\n"
"Please build the DLSS plugin from source (e.g. via the Editor -> Plugins -> NVIDIA DLSS -> Package)"));
const FText WarningMessage = FText::Format(Format, FText::FromString(PluginVersion), FText::FromString(EngineVersion));
FMessageDialog::Open(EAppMsgType::Ok,WarningMessage, &DialogTitle);
}
#endif //WITH_EDITOR
}
else if (!IsRHIDeviceNVIDIA())
{
UE_LOG(LogDLSS, Log, TEXT("NVIDIA NGX DLSS requires an NVIDIA RTX series graphics card"));
DLSSSupport = EDLSSSupport::NotSupportedIncompatibleHardware;
}
#if PLATFORM_WINDOWS
else if (NGXDLSSMinimumWindowsBuildVersion > 0 && !FPlatformMisc::VerifyWindowsVersion(10, 0
#if PLATFORM_DESKTOP
, NGXDLSSMinimumWindowsBuildVersion
#endif
))
{
// From https://docs.microsoft.com/en-us/windows/release-information/
UE_LOG(LogDLSS, Log, TEXT("NVIDIA NGX DLSS requires at least Windows 10, build %u "), NGXDLSSMinimumWindowsBuildVersion);
DLSSSupport = EDLSSSupport::NotSupportedOperatingSystemOutOfDate;
}
#endif
else if (!bLoadLibraries)
{
UE_LOG(LogDLSS, Log, TEXT("NVIDIA NGX library loading has been disabled with r.NGX.Enable=0"));
DLSSSupport = EDLSSSupport::NotSupported;
}
else
{
const bool bIsDX12 = (RHIName == TEXT("D3D12")) && GetDefault<UDLSSSettings>()->bEnableDLSSD3D12;
const bool bIsDX11 = (RHIName == TEXT("D3D11")) && GetDefault<UDLSSSettings>()->bEnableDLSSD3D11;
const bool bIsVulkan = (RHIName == TEXT("Vulkan")) && GetDefault<UDLSSSettings>()->bEnableDLSSVulkan;
const TCHAR* NGXRHIModuleName = nullptr;
DLSSSupport = (bIsDX11 || bIsDX12 || bIsVulkan) ? EDLSSSupport::Supported : EDLSSSupport::NotSupported;
if (DLSSSupport == EDLSSSupport::Supported)
{
if (bIsDX11)
{
NGXRHIModuleName = TEXT("NGXD3D11RHI");
}
else if (bIsDX12)
{
NGXRHIModuleName = TEXT("NGXD3D12RHI");
}
else if (bIsVulkan)
{
// TODO Vulkan (which might need a second, pre RHI init module to route the required vulkan extensions to the VulkanRHI, similar to the HMD stuff
NGXRHIModuleName = TEXT("NGXVulkanRHI");
}
uint32 NGXAppID = GetDefault<UDLSSSettings>()->NVIDIANGXApplicationId;
UE_LOG(LogDLSS, Log, TEXT("Plugin settings: NGXAppId = %u"), NGXAppID);
if (NGXAppID != 0)
{
UE_LOG(LogDLSS, Warning, TEXT("NGX Application ID is specified, overriding the Project ID. Please refer to https://developer.nvidia.com/dlss."));
}
else
{
UE_LOG(LogDLSS, Warning, TEXT("NGX Application ID not specified, using the Project ID by default."));
}
FNGXRHICreateArguments Arguments;
Arguments.PluginBaseDir = PluginBaseDir;
Arguments.DynamicRHI = GDynamicRHI;
Arguments.NGXBinariesSearchOrder = ENGXBinariesSearchOrder(FMath::Clamp(CVarNGXBinarySearchOrder.GetValueOnAnyThread(), int32(ENGXBinariesSearchOrder::MinValue), int32(ENGXBinariesSearchOrder::MaxValue)));
Arguments.ProjectIdentifier = ENGXProjectIdentifier(FMath::Clamp(CVarNGXProjectIdentifier.GetValueOnAnyThread(), int32(ENGXProjectIdentifier::MinValue), int32(ENGXProjectIdentifier::MaxValue)));
Arguments.NGXAppId = NGXAppID;
Arguments.UnrealEngineVersion = FString::Printf(TEXT("%u.%u"), FEngineVersion::Current().GetMajor(), FEngineVersion::Current().GetMinor());
Arguments.UnrealProjectID = GetDefault<UGeneralProjectSettings>()->ProjectID.ToString();
INGXRHIModule* NGXRHIModule = &FModuleManager::LoadModuleChecked<INGXRHIModule>(NGXRHIModuleName);
NGXRHIExtensions = NGXRHIModule->CreateNGXRHI(Arguments);
const bool bRenderDocPluginFound = FModuleManager::Get().ModuleExists(TEXT("RenderDocPlugin"));
const bool bDLSSUnavailable = (!NGXRHIExtensions || !NGXRHIExtensions->IsDLSSAvailable());
const bool bIncompatibleAPICaptureToolActive = (bRenderDocPluginFound || NGXRHI::IsIncompatibleAPICaptureToolActive());
if (bDLSSUnavailable && bIncompatibleAPICaptureToolActive)
{
if (bRenderDocPluginFound)
{
UE_LOG(LogDLSS, Warning, TEXT("DLSS is not compatible with the RenderDoc plugin. To enable DLSS please disable the RenderDoc plugin."));
}
if (NGXRHI::IsIncompatibleAPICaptureToolActive())
{
UE_LOG(LogDLSS, Warning, TEXT("DLSS is not compatible with some API capture tools, such as RenderDoc. To enable DLSS please use an API capture tool such as NVIDIA NSIGHT graphics, which support the APIs required by DLSS."));
}
// we don't want this ever show up in packaged builds
#if WITH_EDITOR
const bool IsUnattended = FApp::IsUnattended() || IsRunningCommandlet() || GIsRunningUnattendedScript;
auto LocalSettings = GetMutableDefault<UDLSSOverrideSettings>();
if (!IsUnattended && LocalSettings->bShowDLSSIncompatiblePluginsToolsWarnings)
{
const FText DialogTitle(LOCTEXT("DLSSIncompatibleWithCaptureToolTitle", "Warning -- DLSS incompatible with plugins and/or API capture tools"));
const FText WarningMessage(LOCTEXT("DLSSIncompatibleWithCaptureTool",
"To enable DLSS, please disable the RenderDoc plugin and/or use an API capture tool such as NVIDIA NSIGHT graphics, which supports the APIs required by DLSS.\n\n"
"Would you like to continue to see this message for this project? It can also be disabled in the NVIDIA DLSS Overrides (Local) plugin settings."));
EAppReturnType::Type YesNoCancelReply = FMessageDialog::Open(EAppMsgType::YesNoCancel, EAppReturnType::Yes, WarningMessage, &DialogTitle);
if(YesNoCancelReply == EAppReturnType::No)
{
LocalSettings->bShowDLSSIncompatiblePluginsToolsWarnings = false;
}
else if (YesNoCancelReply == EAppReturnType::Cancel)
{
FPlatformMisc::RequestExit(true);
}
}
#endif //WITH_EDITOR
}
if (NGXRHIExtensions)
{
if (NGXRHIExtensions->IsDLSSAvailable())
{
check(NVSDK_NGX_SUCCEED(NGXRHIExtensions->GetDLSSInitResult()));
DLSSSupport = EDLSSSupport::Supported;
}
else
{
// map some of the NGX error codes to something that the UI/gameplay could suggest the end user to do something about
if (bIncompatibleAPICaptureToolActive)
{
DLSSSupport = EDLSSSupport::NotSupportedIncompatibleAPICaptureToolActive;
}
else if (NVSDK_NGX_Result_FAIL_OutOfDate == NGXRHIExtensions->GetDLSSInitResult())
{
DLSSSupport = EDLSSSupport::NotSupportedDriverOutOfDate;
}
else if (NVSDK_NGX_Result_FAIL_FeatureNotSupported == NGXRHIExtensions->GetDLSSInitResult())
{
DLSSSupport = EDLSSSupport::NotSupportedIncompatibleHardware;
}
else
{
DLSSSupport = EDLSSSupport::NotSupported;
}
}
const FNGXDriverRequirements DriverRequirements = NGXRHIExtensions->GetDLSSDriverRequirements();
if (DriverRequirements.DriverUpdateRequired)
{
if (DLSSSupport == EDLSSSupport::Supported)
{
UE_LOG(LogDLSS, Log, TEXT("NVIDIA NGX DLSS could be loaded properly. However it is recommended to update the version to at least: %u.%u"), DriverRequirements.MinDriverVersionMajor, DriverRequirements.MinDriverVersionMinor);
}
else
{
UE_LOG(LogDLSS, Log, TEXT("NVIDIA NGX DLSS cannot be loaded properly. Please verify that at least this driver version is installed: %u.%u"), DriverRequirements.MinDriverVersionMajor, DriverRequirements.MinDriverVersionMinor);
DLSSSupport = EDLSSSupport::NotSupportedDriverOutOfDate;
MinDriverVersionMajor = DriverRequirements.MinDriverVersionMajor;
MinDriverVersionMinor = DriverRequirements.MinDriverVersionMinor;
}
}
}
else
{
UE_LOG(LogDLSS, Log, TEXT("Could not load %s module"), NGXRHIModuleName);
DLSSSupport = EDLSSSupport::NotSupported;
}
if (DLSSSupport != EDLSSSupport::Supported)
{
UE_LOG(LogDLSS, Log, TEXT("DLSS not supported by the %s %s RHI in the %s module at runtime"), RHIVendorIdToString(), *RHIName, NGXRHIModuleName);
}
}
else
{
UE_LOG(LogDLSS, Log, TEXT("DLSS not implemented for the %s RHI, or disabled in the project settings"), *RHIName);
DLSSSupport = EDLSSSupport::NotSupported;
}
}
if (DLSSSupport == EDLSSSupport::Supported)
{
// set the upscaler
{
DLSSUpscaler.Reset(new FDLSSUpscaler(NGXRHIExtensions.Get()));
check(DLSSUpscaler);
if (DLSSUpscaler->GetNumRuntimeQualityModes() == 0)
{
UE_LOG(LogDLSS, Log, TEXT("DLSS not available due to not supporting any quality modes at runtime"));
DLSSSupport = EDLSSSupport::NotSupported;
DLSSUpscaler.Reset();
NGXRHIExtensions.Reset();
}
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
else
{
checkf(GTemporalUpscaler == ITemporalUpscaler::GetDefaultTemporalUpscaler(), TEXT("GTemporalUpscaler is not set to the default upscaler. Please check that only one upscaling plugin is active."));
GTemporalUpscaler = DLSSUpscaler.Get();
}
#endif
}
}
UE_LOG(LogDLSS, Log, TEXT("NVIDIA NGX DLSS supported %u"), QueryDLSSSupport() == EDLSSSupport::Supported);
// and the other related interfaces
if (DLSSSupport == EDLSSSupport::Supported)
{
// set the denoiser
{
static const auto CVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.Reflections.Denoiser"));
if (CVar && (CVar->GetInt() != 2))
{
UE_LOG(LogDLSS, Warning, TEXT("For optimal results NVIDIA NGX DLSS requires the use of a custom denoiser plugin, which currently is disabled. To enable, set r.Reflections.Denoiser=2"));
}
DLSSDenoiser.Reset(new FDLSSDenoiser(GScreenSpaceDenoiser, DLSSUpscaler.Get()));
GScreenSpaceDenoiser = DLSSDenoiser.Get();
UE_LOG(LogDLSS, Log, TEXT("%s wrapping %s"), DLSSDenoiser->GetDebugName(), DLSSDenoiser->GetWrappedDenoiser()->GetDebugName());
}
// set the screen percentage driver for game views
{
checkf(GCustomStaticScreenPercentage == nullptr, TEXT("GCustomStaticScreenPercentage is already in use. Please check that only one upscaling plugin is active."));
GCustomStaticScreenPercentage = DLSSUpscaler.Get();
}
// set the resource pool
{
checkf(GCustomResourcePool == nullptr, TEXT("GCustomResourcePool is already in use. Please check that only one upscaling plugin is active."));
GCustomResourcePool = DLSSUpscaler.Get();
}
}
// setup DLSS image quality and performance automation hooks
{
NGXAutomationViewExtension = FSceneViewExtensions::NewExtension<FNGXAutomationViewExtension>();
}
UE_LOG(LogDLSS, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
void FDLSSModule::ShutdownModule()
{
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
// reset DLSS image quality and performance automation hooks
{
NGXAutomationViewExtension = nullptr;
}
if (QueryDLSSSupport() == EDLSSSupport::Supported)
{
// reset the resource pool
{
GCustomResourcePool = nullptr;
}
// reset the screen percentage driver for game views
{
GCustomStaticScreenPercentage = nullptr;
}
// reset the denoiser
{
UE_LOG(LogDLSS, Log, TEXT("%s unwrapping %s"), DLSSDenoiser->GetDebugName(), DLSSDenoiser->GetWrappedDenoiser()->GetDebugName());
GScreenSpaceDenoiser = DLSSDenoiser->GetWrappedDenoiser();
DLSSDenoiser.Reset();
}
// reset the upscaler
{
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
GTemporalUpscaler = ITemporalUpscaler::GetDefaultTemporalUpscaler();
#endif
FDLSSUpscaler::ReleaseStaticResources();
DLSSUpscaler.Reset();
}
NGXRHIExtensions.Reset();
}
UE_LOG(LogDLSS, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
EDLSSSupport FDLSSModule::QueryDLSSSupport() const
{
return DLSSSupport;
}
void FDLSSModule::GetDLSSMinDriverVersion(int32& OutMajorVersion, int32& OutMinorVersion) const
{
OutMajorVersion = MinDriverVersionMajor;
OutMinorVersion = MinDriverVersionMinor;
}
float FDLSSModule::GetResolutionFractionForQuality(int32 Quality) const
{
checkf(QueryDLSSSupport() == EDLSSSupport::Supported,TEXT("GetResolutionFractionForQuality should only be called when DLSS is supported"));
checkf(Quality >= int32(EDLSSQualityMode::MinValue) && Quality <= int32(EDLSSQualityMode::MaxValue),TEXT("The Quality %d argument of GetResolutionFractionForQuality is out of range and/or an unsupported DLSS quality mode"), Quality);
return DLSSUpscaler->GetOptimalResolutionFractionForQuality(EDLSSQualityMode(Quality));
}
FDLSSUpscaler* FDLSSModule::GetDLSSUpscaler() const
{
return DLSSUpscaler.Get();
}
#undef LOCTEXT_NAMESPACE
IMPLEMENT_MODULE(FDLSSModule, DLSS)
@@ -0,0 +1,201 @@
/*
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "DLSSDenoiser.h"
#include "DLSSUpscaler.h"
#include "PostProcess/TemporalAA.h"
#include "SceneTextureParameters.h"
#include "ScenePrivate.h"
static TAutoConsoleVariable<int32> CVarNGXDLSSReflectionsTemporalAA(
TEXT("r.NGX.DLSS.Reflections.TemporalAA"),
1,
TEXT("Apply a temporal AA pass on the denoised reflections"),
ECVF_RenderThreadSafe
);
static TAutoConsoleVariable<int32> CVarNGXDLSSWaterReflectionsTemporalAA(
TEXT("r.NGX.DLSS.WaterReflections.TemporalAA"),
1,
TEXT("Apply a temporal AA pass on the denoised water reflections"),
ECVF_RenderThreadSafe
);
// defined in Buid.cs since it depends on the branch and engine version
#if !DLSS_ENGINE_HAS_AAM_TSR
/** Returns whether the anti-aliasing method use a temporal accumulation */
static inline bool IsTemporalAccumulationBasedMethod(EAntiAliasingMethod AntiAliasingMethod)
{
return AntiAliasingMethod == AAM_TemporalAA;
}
#endif
FDLSSDenoiser::FDLSSDenoiser(const IScreenSpaceDenoiser* InWrappedDenoiser, const FDLSSUpscaler* InUpscaler)
: WrappedDenoiser(InWrappedDenoiser)
, Upscaler(InUpscaler)
{
check(Upscaler);
check(WrappedDenoiser);
}
const TCHAR* FDLSSDenoiser::GetDebugName() const
{
if (Upscaler->IsDLSSActive())
{
// we don't have the View here to check whether we have a valid GetTemporalUpscalerInterface, which we'll do when we actually get called to denoise/add TAA
// and this is only for profilegpu anyways so OK if it's not 100% accurate
if (Upscaler->IsAutoQualityMode())
{
return TEXT("FDLSSDenoiserWrapper(Auto)");
}
else
{
return TEXT("FDLSSDenoiserWrapper(Active)");
}
}
else
{
return TEXT("FDLSSDenoiserWrapper(Inactive)");
}
}
IScreenSpaceDenoiser::EShadowRequirements FDLSSDenoiser::GetShadowRequirements(const FViewInfo& View, const FLightSceneInfo& LightSceneInfo, const FShadowRayTracingConfig& RayTracingConfig) const
{
return WrappedDenoiser->GetShadowRequirements(View, LightSceneInfo, RayTracingConfig);
}
void FDLSSDenoiser::DenoiseShadowVisibilityMasks(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const TStaticArray<FShadowVisibilityParameters, IScreenSpaceDenoiser::kMaxBatchSize>& InputParameters, const int32 InputParameterCount, TStaticArray<FShadowVisibilityOutputs, IScreenSpaceDenoiser::kMaxBatchSize>& Outputs) const
{
WrappedDenoiser->DenoiseShadowVisibilityMasks(GraphBuilder, View, PreviousViewInfos, SceneTextures, InputParameters, InputParameterCount, Outputs);
}
IScreenSpaceDenoiser::FPolychromaticPenumbraOutputs FDLSSDenoiser::DenoisePolychromaticPenumbraHarmonics(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FPolychromaticPenumbraHarmonics& Inputs) const
{
return WrappedDenoiser->DenoisePolychromaticPenumbraHarmonics(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs);
}
IScreenSpaceDenoiser::FReflectionsOutputs FDLSSDenoiser::DenoiseReflections(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FReflectionsInputs& Inputs, const FReflectionsRayTracingConfig Config) const
{
FReflectionsOutputs Outputs = WrappedDenoiser->DenoiseReflections(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
const bool bIsDLSSActive = Upscaler->IsDLSSActive() && View.Family && Upscaler->IsValidUpscalerInstance(View.Family->GetTemporalUpscalerInterface());
const bool bApplyTemporalAA = bIsDLSSActive && CVarNGXDLSSReflectionsTemporalAA.GetValueOnRenderThread() && View.ViewState && IsTemporalAccumulationBasedMethod(View.AntiAliasingMethod);
if(bApplyTemporalAA)
{
check(View.ViewState);
FTAAPassParameters TAASettings(View);
TAASettings.Pass = ETAAPassConfig::ScreenSpaceReflections;
TAASettings.SceneDepthTexture = SceneTextures.SceneDepthTexture;
TAASettings.SceneVelocityTexture = SceneTextures.GBufferVelocityTexture;
TAASettings.SceneColorInput = Outputs.Color;
TAASettings.bOutputRenderTargetable = true;
FTAAOutputs TAAOutputs = AddTemporalAAPass(
GraphBuilder,
View,
TAASettings,
View.PrevViewInfo.SSRHistory,
&View.ViewState->PrevFrameViewInfo.SSRHistory);
Outputs.Color = TAAOutputs.SceneColor;
}
return Outputs;
}
IScreenSpaceDenoiser::FReflectionsOutputs FDLSSDenoiser::DenoiseWaterReflections(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FReflectionsInputs& Inputs, const FReflectionsRayTracingConfig Config) const
{
FReflectionsOutputs Outputs = WrappedDenoiser->DenoiseWaterReflections(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
const bool bIsDLSSActive = Upscaler->IsDLSSActive() && View.Family && Upscaler->IsValidUpscalerInstance(View.Family->GetTemporalUpscalerInterface());
const bool bApplyTemporalAA = bIsDLSSActive && Upscaler->IsDLSSActive() && CVarNGXDLSSWaterReflectionsTemporalAA.GetValueOnRenderThread() && View.ViewState && IsTemporalAccumulationBasedMethod(View.AntiAliasingMethod);
if (bApplyTemporalAA)
{
check(View.ViewState);
FTAAPassParameters TAASettings(View);
TAASettings.Pass = ETAAPassConfig::ScreenSpaceReflections;
TAASettings.SceneDepthTexture = SceneTextures.SceneDepthTexture;
TAASettings.SceneVelocityTexture = SceneTextures.GBufferVelocityTexture;
TAASettings.SceneColorInput = Outputs.Color;
TAASettings.bOutputRenderTargetable = true;
FTAAOutputs TAAOutputs = AddTemporalAAPass(
GraphBuilder,
View,
TAASettings,
View.PrevViewInfo.WaterSSRHistory,
&View.ViewState->PrevFrameViewInfo.WaterSSRHistory);
Outputs.Color = TAAOutputs.SceneColor;
}
return Outputs;
}
IScreenSpaceDenoiser::FAmbientOcclusionOutputs FDLSSDenoiser::DenoiseAmbientOcclusion(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FAmbientOcclusionInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseAmbientOcclusion(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
#if ENGINE_MAJOR_VERSION == 4
IScreenSpaceDenoiser::FDiffuseIndirectOutputs FDLSSDenoiser::DenoiseDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseDiffuseIndirect(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
IScreenSpaceDenoiser::FDiffuseIndirectOutputs FDLSSDenoiser::DenoiseScreenSpaceDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseScreenSpaceDiffuseIndirect(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
IScreenSpaceDenoiser::FDiffuseIndirectHarmonic FDLSSDenoiser::DenoiseDiffuseIndirectHarmonic(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectHarmonic& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseDiffuseIndirectHarmonic(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
#elif ENGINE_MAJOR_VERSION == 5
FSSDSignalTextures FDLSSDenoiser::DenoiseDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseDiffuseIndirect(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
FSSDSignalTextures FDLSSDenoiser::DenoiseScreenSpaceDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseScreenSpaceDiffuseIndirect(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
FSSDSignalTextures FDLSSDenoiser::DenoiseDiffuseIndirectHarmonic(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectHarmonic& Inputs, const HybridIndirectLighting::FCommonParameters& CommonDiffuseParameters) const
{
return WrappedDenoiser->DenoiseDiffuseIndirectHarmonic(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, CommonDiffuseParameters);
}
#else
#error "ENGINE_MAJOR_VERSION must be either 4 or 5"
#endif
IScreenSpaceDenoiser::FDiffuseIndirectOutputs FDLSSDenoiser::DenoiseSkyLight(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseSkyLight(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
IScreenSpaceDenoiser::FDiffuseIndirectOutputs FDLSSDenoiser::DenoiseReflectedSkyLight(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const
{
return WrappedDenoiser->DenoiseReflectedSkyLight(GraphBuilder, View, PreviousViewInfos, SceneTextures, Inputs, Config);
}
bool FDLSSDenoiser::SupportsScreenSpaceDiffuseIndirectDenoiser(EShaderPlatform Platform) const
{
return WrappedDenoiser->SupportsScreenSpaceDiffuseIndirectDenoiser(Platform);
}
const IScreenSpaceDenoiser* FDLSSDenoiser::GetWrappedDenoiser() const
{
return WrappedDenoiser;
}
@@ -0,0 +1,65 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#pragma once
#include "CoreMinimal.h"
#include "ScreenSpaceDenoise.h"
// for ENGINE_MAJOR_VERSION
#include "Launch/Resources/Version.h"
class FDLSSUpscaler;
// wrapper for the default denoiser to add TAA after some passes
class DLSS_API FDLSSDenoiser final : public IScreenSpaceDenoiser
{
public:
FDLSSDenoiser(const IScreenSpaceDenoiser* InWrappedDenoiser, const FDLSSUpscaler* InUpscaler);
// Inherited via IScreenSpaceDenoiser
virtual const TCHAR* GetDebugName() const final;
virtual EShadowRequirements GetShadowRequirements(const FViewInfo& View, const FLightSceneInfo& LightSceneInfo, const FShadowRayTracingConfig& RayTracingConfig) const final;
virtual void DenoiseShadowVisibilityMasks(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const TStaticArray<FShadowVisibilityParameters, IScreenSpaceDenoiser::kMaxBatchSize>& InputParameters, const int32 InputParameterCount, TStaticArray<FShadowVisibilityOutputs, IScreenSpaceDenoiser::kMaxBatchSize>& Outputs) const final;
virtual FPolychromaticPenumbraOutputs DenoisePolychromaticPenumbraHarmonics(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FPolychromaticPenumbraHarmonics& Inputs) const final;
virtual FReflectionsOutputs DenoiseReflections(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FReflectionsInputs& Inputs, const FReflectionsRayTracingConfig Config) const final;
virtual FReflectionsOutputs DenoiseWaterReflections(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FReflectionsInputs& Inputs, const FReflectionsRayTracingConfig Config) const override;
virtual FAmbientOcclusionOutputs DenoiseAmbientOcclusion(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FAmbientOcclusionInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
#if ENGINE_MAJOR_VERSION == 4
virtual FDiffuseIndirectOutputs DenoiseDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FDiffuseIndirectHarmonic DenoiseDiffuseIndirectHarmonic(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectHarmonic& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FDiffuseIndirectOutputs DenoiseScreenSpaceDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
#elif ENGINE_MAJOR_VERSION == 5
virtual FSSDSignalTextures DenoiseDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FSSDSignalTextures DenoiseScreenSpaceDiffuseIndirect(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FSSDSignalTextures DenoiseDiffuseIndirectHarmonic(FRDGBuilder& GraphBuilder,const FViewInfo& View,FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectHarmonic& Inputs, const HybridIndirectLighting::FCommonParameters& CommonDiffuseParameters) const final;
#else
#error "ENGINE_MAJOR_VERSION must be either 4 or 5"
#endif
virtual FDiffuseIndirectOutputs DenoiseSkyLight(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual FDiffuseIndirectOutputs DenoiseReflectedSkyLight(FRDGBuilder& GraphBuilder, const FViewInfo& View, FPreviousViewInfo* PreviousViewInfos, const FSceneTextureParameters& SceneTextures, const FDiffuseIndirectInputs& Inputs, const FAmbientOcclusionRayTracingConfig Config) const final;
virtual bool SupportsScreenSpaceDiffuseIndirectDenoiser(EShaderPlatform Platform) const final;
const IScreenSpaceDenoiser* GetWrappedDenoiser() const;
private:
const IScreenSpaceDenoiser* WrappedDenoiser;
const FDLSSUpscaler* Upscaler;
};
@@ -0,0 +1,22 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include "DLSSSettings.h"
#define LOCTEXT_NAMESPACE "FDLSSModule"
@@ -0,0 +1,790 @@
/*
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#include "DLSSUpscaler.h"
#include "DLSSUpscalerPrivate.h"
#include "DLSSUpscalerHistory.h"
#include "DLSSSettings.h"
#include "VelocityCombinePass.h"
#include "PostProcess/SceneRenderTargets.h"
#include "PostProcess/PostProcessing.h"
#include "SceneTextureParameters.h"
#include "ScreenPass.h"
#include "RayTracing/RaytracingOptions.h"
#include "LegacyScreenPercentageDriver.h"
#define LOCTEXT_NAMESPACE "FDLSSModule"
#ifndef SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE
#define SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE 1
#endif
static TAutoConsoleVariable<int32> CVarNGXDLSSEnable(
TEXT("r.NGX.DLSS.Enable"), 1,
TEXT("Enable/Disable DLSS entirely."),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<bool> CVarNGXDLAAEnable(
TEXT("r.NGX.DLAA.Enable"), false,
TEXT("Enable/Disable DLAA"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarNGXDLSSAutomationTesting(
TEXT("r.NGX.DLSS.AutomationTesting"), 0,
TEXT("Whether the NGX library should be loaded when GIsAutomationTesting is true.(default is false)\n")
TEXT("Must be set to true before startup. This can be enabled for cases where running automation testing with DLSS desired"),
ECVF_ReadOnly);
static TAutoConsoleVariable<int32> CVarNGXDLSSPerfQualitySetting(
TEXT("r.NGX.DLSS.Quality"),
-1,
TEXT("DLSS Performance/Quality setting. Not all modes might be supported at runtime, in this case Balanced mode is used as a fallback\n")
TEXT(" -2: Ultra Performance\n")
TEXT(" -1: Performance (default)\n")
TEXT(" 0: Balanced\n")
TEXT(" 1: Quality\n")
TEXT(" 2: Ultra Quality\n"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<bool> CVarNGXDLSSAutoQualitySetting(
TEXT("r.NGX.DLSS.Quality.Auto"), 0,
TEXT("Enable/Disable DLSS automatically selecting the DLSS quality mode based on the render resolution"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<float> CVarNGXDLSSSharpness(
TEXT("r.NGX.DLSS.Sharpness"),
0.0f,
TEXT("-1.0 to 1.0: Softening/sharpening to apply to the DLSS pass. Negative values soften the image, positive values sharpen. (default: 0.0f)"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarNGXDLSSDilateMotionVectors(
TEXT("r.NGX.DLSS.DilateMotionVectors"),
1,
TEXT(" 0: pass low resolution motion vectors into DLSS\n")
TEXT(" 1: pass dilated high resolution motion vectors into DLSS. This can help with improving image quality of thin details. (default)"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarNGXDLSSAutoExposure(
TEXT("r.NGX.DLSS.AutoExposure"), 1,
TEXT("0: Use the engine-computed exposure value for input images to DLSS - in some cases this may reduce artifacts\n")
TEXT("1: Enable DLSS internal auto-exposure instead of the application provided one (default)\n"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarNGXDLSSReleaseMemoryOnDelete(
TEXT("r.NGX.DLSS.ReleaseMemoryOnDelete"),
1,
TEXT("Enabling/disable releasing DLSS related memory on the NGX side when DLSS features get released.(default=1)"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarNGXDLSSFeatureCreationNode(
TEXT("r.NGX.DLSS.FeatureCreationNode"), -1,
TEXT("Determines which GPU the DLSS feature is getting created on\n")
TEXT("-1: Create on the GPU the command list is getting executed on (default)\n")
TEXT(" 0: Create on GPU node 0 \n")
TEXT(" 1: Create on GPU node 1 \n"),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarNGXDLSSFeatureVisibilityMask(
TEXT("r.NGX.DLSS.FeatureVisibilityMask"), -1,
TEXT("Determines which GPU the DLSS feature is visible to\n")
TEXT("-1: Visible to the GPU the command list is getting executed on (default)\n")
TEXT(" 1: visible to GPU node 0 \n")
TEXT(" 2: visible to GPU node 1 \n")
TEXT(" 3: visible to GPU node 0 and GPU node 1\n"),
ECVF_RenderThreadSafe);
DECLARE_GPU_STAT(DLSS)
BEGIN_SHADER_PARAMETER_STRUCT(FDLSSShaderParameters, )
// Input images
SHADER_PARAMETER_RDG_TEXTURE(Texture2D, SceneColorInput)
SHADER_PARAMETER_RDG_TEXTURE(Texture2D, SceneDepthInput)
SHADER_PARAMETER_RDG_TEXTURE(Texture2D, EyeAdaptation)
SHADER_PARAMETER_RDG_TEXTURE(Texture2D, SceneVelocityInput)
// Output images
RDG_TEXTURE_ACCESS(SceneColorOutput, ERHIAccess::UAVCompute)
END_SHADER_PARAMETER_STRUCT()
FIntPoint FDLSSPassParameters::GetOutputExtent() const
{
check(Validate());
check(SceneColorInput);
FIntPoint InputExtent = SceneColorInput->Desc.Extent;
FIntPoint QuantizedPrimaryUpscaleViewSize;
QuantizeSceneBufferSize(OutputViewRect.Size(), QuantizedPrimaryUpscaleViewSize);
return FIntPoint(
FMath::Max(InputExtent.X, QuantizedPrimaryUpscaleViewSize.X),
FMath::Max(InputExtent.Y, QuantizedPrimaryUpscaleViewSize.Y));
}
bool FDLSSPassParameters::Validate() const
{
checkf(OutputViewRect.Min == FIntPoint::ZeroValue,TEXT("The DLSS OutputViewRect %dx%d must be non-zero"), OutputViewRect.Min.X, OutputViewRect.Min.Y);
return true;
}
const TCHAR* FDLSSUpscaler::GetDebugName() const
{
return TEXT("FDLSSUpscaler");
}
static NVSDK_NGX_PerfQuality_Value ToNGXQuality(EDLSSQualityMode Quality)
{
static_assert(int32(EDLSSQualityMode::NumValues) == 5, "dear DLSS plugin NVIDIA developer, please update this code to handle the new EDLSSQualityMode enum values");
switch (Quality)
{
case EDLSSQualityMode::UltraPerformance:
return NVSDK_NGX_PerfQuality_Value_UltraPerformance;
default:
checkf(false, TEXT("ToNGXQuality should not be called with an out of range EDLSSQualityMode from the higher level code"));
case EDLSSQualityMode::Performance:
return NVSDK_NGX_PerfQuality_Value_MaxPerf;
case EDLSSQualityMode::Balanced:
return NVSDK_NGX_PerfQuality_Value_Balanced;
case EDLSSQualityMode::Quality:
return NVSDK_NGX_PerfQuality_Value_MaxQuality;
case EDLSSQualityMode::UltraQuality:
return NVSDK_NGX_PerfQuality_Value_UltraQuality;
}
}
NGXRHI* FDLSSUpscaler::NGXRHIExtensions;
TStaticArray <TSharedPtr<FDLSSUpscaler>, uint32(EDLSSQualityMode::NumValues)> FDLSSUpscaler::DLSSUpscalerInstancesPerViewFamily;
float FDLSSUpscaler::MinResolutionFraction = TNumericLimits <float>::Max();
float FDLSSUpscaler::MaxResolutionFraction = TNumericLimits <float>::Min();
uint32 FDLSSUpscaler::NumRuntimeQualityModes = 0;
TArray<FDLSSOptimalSettings> FDLSSUpscaler::ResolutionSettings;
FDLSSUpscaler* FDLSSUpscaler::GetUpscalerInstanceForViewFamily(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InQualityMode)
{
uint32 ArrayIndex = (int32)ToNGXQuality(InQualityMode);
if (!DLSSUpscalerInstancesPerViewFamily[ArrayIndex])
{
DLSSUpscalerInstancesPerViewFamily[ArrayIndex] = MakeShared<FDLSSUpscaler>(InUpscaler, InQualityMode);
}
return DLSSUpscalerInstancesPerViewFamily[ArrayIndex].Get();
}
bool FDLSSUpscaler::IsValidUpscalerInstance(const ITemporalUpscaler* InUpscaler)
{
// DLSSUpscalerInstancesPerViewFamily gets lazily initialized, but we don't want to accidentally treat nullptr as a valid
// upscaler instance, when we want to check (e.g. in the denoiser) whether DLSS is actually active for the viewfamily
if (InUpscaler == nullptr)
{
return false;
}
for (auto UpscalerInstance : DLSSUpscalerInstancesPerViewFamily)
{
if (UpscalerInstance.Get() == InUpscaler)
{
return true;
}
}
return false;
}
bool FDLSSUpscaler::IsAutoQualityMode()
{
return CVarNGXDLSSAutoQualitySetting.GetValueOnAnyThread();
}
bool FDLSSUpscaler::IsDLAAMode()
{
return CVarNGXDLAAEnable.GetValueOnAnyThread();
}
void FDLSSUpscaler::SetAutoQualityMode(bool bAutoQualityMode)
{
check(IsInGameThread());
CVarNGXDLSSAutoQualitySetting->Set(bAutoQualityMode, ECVF_SetByCommandline);
}
// make copy & assign quality mode
FDLSSUpscaler::FDLSSUpscaler(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InQualityMode)
: FDLSSUpscaler(*InUpscaler)
{
DLSSQualityMode = InQualityMode;
check(NGXRHIExtensions);
}
FDLSSUpscaler::FDLSSUpscaler(NGXRHI* InNGXRHIExtensions)
{
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
checkf(!NGXRHIExtensions, TEXT("static member NGXRHIExtensions should only be assigned once by this ctor when called during module startup") );
NGXRHIExtensions = InNGXRHIExtensions;
ResolutionSettings.Init(FDLSSOptimalSettings(), int32(EDLSSQualityMode::NumValues));
static_assert(int32(EDLSSQualityMode::NumValues) == 5, "dear DLSS plugin NVIDIA developer, please update this code to handle the new EDLSSQualityMode enum values");
for (auto QualityMode : { EDLSSQualityMode::UltraPerformance, EDLSSQualityMode::Performance , EDLSSQualityMode::Balanced, EDLSSQualityMode::Quality, EDLSSQualityMode::UltraQuality })
{
check(ToNGXQuality(QualityMode) < ResolutionSettings.Num());
check(ToNGXQuality(QualityMode) >= 0);
FDLSSOptimalSettings OptimalSettings = NGXRHIExtensions->GetDLSSOptimalSettings(ToNGXQuality(QualityMode));
ResolutionSettings[ToNGXQuality(QualityMode)] = OptimalSettings;
// we only consider non-fixed resolutions for the overall min / max resolution fraction
if (OptimalSettings.bIsSupported && !OptimalSettings.IsFixedResolution())
{
// We use OptimalSettings.OptimalResolutionFraction to avoid getting to "floating point close" to OptimalSettings.{MinMax}ResolutionFraction)
MinResolutionFraction = FMath::Min(MinResolutionFraction, OptimalSettings.OptimalResolutionFraction);
MaxResolutionFraction = FMath::Max(MaxResolutionFraction, OptimalSettings.OptimalResolutionFraction);
++NumRuntimeQualityModes;
}
UE_LOG(LogDLSS, Log, TEXT("QualityMode %d: bSupported = %u, ResolutionFraction = %.4f. MinResolutionFraction=%.4f, MaxResolutionFraction %.4f"),
QualityMode, OptimalSettings.bIsSupported, OptimalSettings.OptimalResolutionFraction, OptimalSettings.MinResolutionFraction, OptimalSettings.MaxResolutionFraction);
}
// the DLSS module will report DLSS as not supported if there are no supported quality modes at runtime
UE_LOG(LogDLSS, Log, TEXT("NumRuntimeQualityModes=%u, MinResolutionFraction=%.4f, MaxResolutionFraction=%.4f"), NumRuntimeQualityModes, MinResolutionFraction, MaxResolutionFraction);
// Higher levels of the code (e.g. UI) should check whether each mode is actually supported
// But for now verify early that the DLSS 2.0 modes are supported. Those checks could be removed in the future
check(IsQualityModeSupported(EDLSSQualityMode::Performance));
check(IsQualityModeSupported(EDLSSQualityMode::Balanced));
check(IsQualityModeSupported(EDLSSQualityMode::Quality));
UE_LOG(LogDLSS, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
FDLSSUpscaler::~FDLSSUpscaler()
{
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
UE_LOG(LogDLSS, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
// this gets explicitly called during module shutdown
void FDLSSUpscaler::ReleaseStaticResources()
{
UE_LOG(LogDLSS, Log, TEXT("%s Enter"), ANSI_TO_TCHAR(__FUNCTION__));
ResolutionSettings.Empty();
for (auto& UpscalerInstance : DLSSUpscalerInstancesPerViewFamily)
{
UpscalerInstance.Reset();
}
UE_LOG(LogDLSS, Log, TEXT("%s Leave"), ANSI_TO_TCHAR(__FUNCTION__));
}
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
void FDLSSUpscaler::AddPasses(
#else
ITemporalUpscaler::FOutputs FDLSSUpscaler::AddPasses(
#endif
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FPassInputs& PassInputs
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
, FRDGTextureRef* OutSceneColorTexture
, FIntRect* OutSceneColorViewRect
, FRDGTextureRef* OutSceneColorHalfResTexture
, FIntRect* OutSceneColorHalfResViewRect
#endif
) const
{
#if ENGINE_MAJOR_VERSION < 5
// For TAAU, this can happen with screen percentages larger than 100%, so not something that DLSS viewports are setup with
checkf(!PassInputs.bAllowDownsampleSceneColor,TEXT("The DLSS plugin does not support downsampling the scenecolor. Please set r.TemporalAA.AllowDownsampling=0"));
#endif
checkf(View.PrimaryScreenPercentageMethod == EPrimaryScreenPercentageMethod::TemporalUpscale, TEXT("DLSS requires TemporalUpscale. If you hit this assert, please set r.TemporalAA.Upscale=1"));
const FTemporalAAHistory& InputHistory = View.PrevViewInfo.TemporalAAHistory;
const TRefCountPtr<ICustomTemporalAAHistory> InputCustomHistory = View.PrevViewInfo.CustomTemporalAAHistory;
FTemporalAAHistory* OutputHistory = View.ViewState ? &(View.ViewState->PrevFrameViewInfo.TemporalAAHistory) : nullptr;
TRefCountPtr < ICustomTemporalAAHistory >* OutputCustomHistory = View.ViewState ? &(View.ViewState->PrevFrameViewInfo.CustomTemporalAAHistory) : nullptr;
FDLSSPassParameters DLSSParameters(View);
const FIntRect SecondaryViewRect = DLSSParameters.OutputViewRect;
#if !DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
ITemporalUpscaler::FOutputs Outputs;
#endif
{
RDG_GPU_STAT_SCOPE(GraphBuilder, DLSS);
RDG_EVENT_SCOPE(GraphBuilder, "DLSS");
const bool bDilateMotionVectors = CVarNGXDLSSDilateMotionVectors.GetValueOnRenderThread() != 0;
FRDGTextureRef CombinedVelocityTexture = AddVelocityCombinePass(GraphBuilder, View, PassInputs.SceneDepthTexture, PassInputs.SceneVelocityTexture, bDilateMotionVectors);
DLSSParameters.SceneColorInput = PassInputs.SceneColorTexture;
DLSSParameters.SceneVelocityInput = CombinedVelocityTexture;
DLSSParameters.SceneDepthInput = PassInputs.SceneDepthTexture;
DLSSParameters.bHighResolutionMotionVectors = bDilateMotionVectors;
const FDLSSOutputs DLSSOutputs = AddDLSSPass(
GraphBuilder,
View,
DLSSParameters,
InputHistory,
OutputHistory,
InputCustomHistory,
OutputCustomHistory
);
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
FRDGTextureRef SceneColorTexture = DLSSOutputs.SceneColor;
*OutSceneColorTexture = SceneColorTexture;
*OutSceneColorViewRect = SecondaryViewRect;
*OutSceneColorHalfResTexture = nullptr;
*OutSceneColorHalfResViewRect = FIntRect(FIntPoint::ZeroValue, FIntPoint::ZeroValue);
#else
Outputs.FullRes.Texture = DLSSOutputs.SceneColor;
Outputs.FullRes.ViewRect = SecondaryViewRect;
#endif
}
#if !DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
return Outputs;
#endif
}
FDLSSOutputs FDLSSUpscaler::AddDLSSPass(
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FDLSSPassParameters& Inputs,
const FTemporalAAHistory& InputHistory,
FTemporalAAHistory* OutputHistory,
const TRefCountPtr<ICustomTemporalAAHistory> InputCustomHistoryInterface,
TRefCountPtr<ICustomTemporalAAHistory>* OutputCustomHistoryInterface
) const
{
check(IsValidUpscalerInstance(this));
check(IsDLSSActive());
const FDLSSUpscalerHistory* InputCustomHistory = static_cast<const FDLSSUpscalerHistory*>(InputCustomHistoryInterface.GetReference());
const bool bCameraCut = !InputHistory.IsValid() || View.bCameraCut || !OutputHistory;
const FIntPoint OutputExtent = Inputs.GetOutputExtent();
const FIntRect SrcRect = Inputs.InputViewRect;
const FIntRect DestRect = Inputs.OutputViewRect;
const float ScaleX = float(SrcRect.Width()) / float(DestRect.Width());
const float ScaleY = float(SrcRect.Height()) / float(DestRect.Height());
// FDLSSUpscaler::SetupMainGameViewFamily or FDLSSUpscalerEditor::SetupEditorViewFamily
// set DLSSQualityMode by setting an FDLSSUpscaler on the ViewFamily (from the pool in DLSSUpscalerInstancesPerViewFamily)
checkf(DLSSQualityMode != EDLSSQualityMode::NumValues, TEXT("Invalid Quality mode, not initialized"));
checkf(IsQualityModeSupported(DLSSQualityMode), TEXT("%u is not a valid Quality mode"), DLSSQualityMode);
// This assert can accidentally hit with small viewrect dimensions (e.g. when resizing an editor view) due to floating point rounding & quantization issues
// e.g. with 33% screen percentage at 1000 DestRect dimension we get 333/1000 = 0.33 but at 10 DestRect dimension we get 3/10 0.3, thus the assert hits
checkf(DestRect.Width() < 100 || GetMinResolutionFractionForQuality(DLSSQualityMode) - 0.01f <= ScaleX && ScaleX <= GetMaxResolutionFractionForQuality(DLSSQualityMode) + 0.01f, TEXT("The current resolution fraction %f is out of the supported DLSS range [%f ... %f] for quality mode %d."), ScaleX, GetMinResolutionFractionForQuality(DLSSQualityMode), GetMaxResolutionFractionForQuality(DLSSQualityMode), DLSSQualityMode);
checkf(DestRect.Height() < 100 || GetMinResolutionFractionForQuality(DLSSQualityMode) - 0.01f <= ScaleY && ScaleY <= GetMaxResolutionFractionForQuality(DLSSQualityMode) + 0.01f, TEXT("The current resolution fraction %f is out of the supported DLSS range [%f ... %f] for quality mode %d."), ScaleY, GetMinResolutionFractionForQuality(DLSSQualityMode), GetMaxResolutionFractionForQuality(DLSSQualityMode), DLSSQualityMode);
const TCHAR* PassName = TEXT("MainUpsampling");
// Create outputs
FDLSSOutputs Outputs;
{
FRDGTextureDesc SceneColorDesc = FRDGTextureDesc::Create2D(
OutputExtent,
PF_FloatRGBA,
FClearValueBinding::Black,
TexCreate_ShaderResource | TexCreate_UAV);
const TCHAR* OutputName = TEXT("DLSSOutputSceneColor");
Outputs.SceneColor = GraphBuilder.CreateTexture(
SceneColorDesc,
OutputName);
}
FDLSSStateRef DLSSState = (InputCustomHistory && InputCustomHistory->DLSSState) ? InputCustomHistory->DLSSState : MakeShared<FDLSSState, ESPMode::ThreadSafe>();
{
FDLSSShaderParameters* PassParameters = GraphBuilder.AllocParameters<FDLSSShaderParameters>();
// Set up common shader parameters
const FIntPoint InputExtent = Inputs.SceneColorInput->Desc.Extent;
const FIntRect InputViewRect = Inputs.InputViewRect;
const FIntRect OutputViewRect = Inputs.OutputViewRect;
// Input buffer shader parameters
{
PassParameters->SceneColorInput = Inputs.SceneColorInput;
PassParameters->SceneDepthInput = Inputs.SceneDepthInput;
PassParameters->SceneVelocityInput = Inputs.SceneVelocityInput;
PassParameters->EyeAdaptation = GetEyeAdaptationTexture(GraphBuilder, View);
}
// Outputs
{
PassParameters->SceneColorOutput = Outputs.SceneColor;
}
const FVector2D JitterOffset = View.TemporalJitterPixels;
#if ENGINE_MAJOR_VERSION < 5
const float DeltaWorldTime = View.Family->DeltaWorldTime;
#else
const float DeltaWorldTime = View.Family->Time.GetDeltaWorldTimeSeconds();
#endif
const float PreExposure = View.PreExposure;
const bool bUseAutoExposure = CVarNGXDLSSAutoExposure.GetValueOnRenderThread() != 0;
const bool bReleaseMemoryOnDelete = CVarNGXDLSSReleaseMemoryOnDelete.GetValueOnRenderThread() != 0;
const float Sharpness = FMath::Clamp(CVarNGXDLSSSharpness.GetValueOnRenderThread(), -1.0f, 1.0f);
NGXRHI* LocalNGXRHIExtensions = this->NGXRHIExtensions;
const int32 NGXPerfQuality = ToNGXQuality(DLSSQualityMode);
GraphBuilder.AddPass(
RDG_EVENT_NAME("DLSS %s%s %dx%d -> %dx%d",
PassName,
Sharpness != 0.0f ? TEXT(" Sharpen") : TEXT(""),
SrcRect.Width(), SrcRect.Height(),
DestRect.Width(), DestRect.Height()),
PassParameters,
ERDGPassFlags::Compute | ERDGPassFlags::Raster | ERDGPassFlags::SkipRenderPass,
[LocalNGXRHIExtensions, PassParameters, Inputs, bCameraCut, JitterOffset, DeltaWorldTime, PreExposure, Sharpness, NGXPerfQuality, DLSSState, bUseAutoExposure, bReleaseMemoryOnDelete](FRHICommandListImmediate& RHICmdList)
{
FRHIDLSSArguments DLSSArguments;
FMemory::Memzero(&DLSSArguments, sizeof(DLSSArguments));
// input parameters
DLSSArguments.SrcRect = Inputs.InputViewRect;
DLSSArguments.DestRect = Inputs.OutputViewRect;
DLSSArguments.Sharpness = Sharpness;
DLSSArguments.bReset = bCameraCut;
#if ENGINE_MAJOR_VERSION < 5
DLSSArguments.JitterOffset = JitterOffset;
DLSSArguments.MotionVectorScale = FVector2D(1.0f, 1.0f);
#else
DLSSArguments.JitterOffset = FVector2f(JitterOffset); // LWC_TODO: Precision loss
DLSSArguments.MotionVectorScale = FVector2f::UnitVector;
#endif ENGINE_MAJOR_VERSION
DLSSArguments.bHighResolutionMotionVectors = Inputs.bHighResolutionMotionVectors;
DLSSArguments.DeltaTime = DeltaWorldTime;
DLSSArguments.bReleaseMemoryOnDelete = bReleaseMemoryOnDelete;
DLSSArguments.PerfQuality = NGXPerfQuality;
check(PassParameters->SceneColorInput);
PassParameters->SceneColorInput->MarkResourceAsUsed();
DLSSArguments.InputColor = PassParameters->SceneColorInput->GetRHI();
check(PassParameters->SceneVelocityInput);
PassParameters->SceneVelocityInput->MarkResourceAsUsed();
DLSSArguments.InputMotionVectors = PassParameters->SceneVelocityInput->GetRHI();
check(PassParameters->SceneDepthInput);
PassParameters->SceneDepthInput->MarkResourceAsUsed();
DLSSArguments.InputDepth = PassParameters->SceneDepthInput->GetRHI();
check(PassParameters->EyeAdaptation);
PassParameters->EyeAdaptation->MarkResourceAsUsed();
DLSSArguments.InputExposure = PassParameters->EyeAdaptation->GetRHI();
DLSSArguments.PreExposure = PreExposure;
DLSSArguments.bUseAutoExposure = bUseAutoExposure;
// output images
check(PassParameters->SceneColorOutput);
PassParameters->SceneColorOutput->MarkResourceAsUsed();
DLSSArguments.OutputColor = PassParameters->SceneColorOutput->GetRHI();
RHICmdList.TransitionResource(ERHIAccess::UAVMask, DLSSArguments.OutputColor);
RHICmdList.EnqueueLambda(
[LocalNGXRHIExtensions, DLSSArguments, DLSSState](FRHICommandListImmediate& Cmd) mutable
{
const uint32 FeatureCreationNode = CVarNGXDLSSFeatureCreationNode.GetValueOnRenderThread();
const uint32 FeatureVisibilityMask = CVarNGXDLSSFeatureVisibilityMask.GetValueOnRenderThread();
DLSSArguments.GPUNode = FeatureCreationNode == -1 ? Cmd.GetGPUMask().ToIndex() : FMath::Clamp(FeatureCreationNode, 0u, GNumExplicitGPUsForRendering - 1);
DLSSArguments.GPUVisibility = FeatureVisibilityMask == -1 ? Cmd.GetGPUMask().GetNative() : (Cmd.GetGPUMask().All().GetNative() & FeatureVisibilityMask) ;
LocalNGXRHIExtensions->ExecuteDLSS(Cmd, DLSSArguments, DLSSState);
});
});
}
if (!View.bStatePrevViewInfoIsReadOnly && OutputHistory)
{
OutputHistory->SafeRelease();
GraphBuilder.QueueTextureExtraction(Outputs.SceneColor, &OutputHistory->RT[0]);
OutputHistory->ViewportRect = DestRect;
OutputHistory->ReferenceBufferSize = OutputExtent;
}
if (!View.bStatePrevViewInfoIsReadOnly && OutputCustomHistoryInterface)
{
if (!OutputCustomHistoryInterface->GetReference())
{
(*OutputCustomHistoryInterface) = new FDLSSUpscalerHistory(DLSSState);
}
}
return Outputs;
}
void FDLSSUpscaler::Tick(FRHICommandListImmediate& RHICmdList)
{
check(NGXRHIExtensions);
check(IsInRenderingThread());
// Pass it over to the RHI thread which handles the lifetime of the NGX DLSS resources
RHICmdList.EnqueueLambda(
[this](FRHICommandListImmediate& Cmd)
{
NGXRHIExtensions->TickPoolElements();
});
}
bool FDLSSUpscaler::IsQualityModeSupported(EDLSSQualityMode InQualityMode) const
{
return ResolutionSettings[ToNGXQuality(InQualityMode)].bIsSupported;
}
bool FDLSSUpscaler::IsDLSSActive() const
{
static const auto CVarTemporalAAUpscaler = IConsoleManager::Get().FindConsoleVariable(TEXT("r.TemporalAA.Upscaler"));
const bool bDLSSActive =
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
((GTemporalUpscaler == this) || IsValidUpscalerInstance(this)) &&
#else
((GCustomStaticScreenPercentage == this) || IsValidUpscalerInstance(this)) &&
#endif
CVarTemporalAAUpscaler && (CVarTemporalAAUpscaler->GetInt() != 0) &&
((CVarNGXDLSSEnable.GetValueOnAnyThread() != 0) || CVarNGXDLAAEnable.GetValueOnAnyThread());
return bDLSSActive;
}
void FDLSSUpscaler::SetupMainGameViewFamily(FSceneViewFamily& ViewFamily)
{
const bool bDLSSActiveWithAutomation = !GIsAutomationTesting || (GIsAutomationTesting && (CVarNGXDLSSAutomationTesting.GetValueOnAnyThread() != 0));
if (IsDLSSActive() && bDLSSActiveWithAutomation)
{
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
checkf(GTemporalUpscaler == this, TEXT("GTemporalUpscaler is not set to a DLSS upscaler . Please check that only one upscaling plugin is active."));
#endif
checkf(GCustomStaticScreenPercentage == this, TEXT("GCustomStaticScreenPercentage is not set to a DLSS upscaler. Please check that only one upscaling plugin is active."));
if (!GIsEditor || (GIsEditor && GIsPlayInEditorWorld && EnableDLSSInPlayInEditorViewports()))
{
bool bIsDLAAMode = IsDLAAMode();
EDLSSQualityMode DLSSQuality;
if (bIsDLAAMode)
{
DLSSQuality = EDLSSQualityMode::Quality;
}
else if (IsAutoQualityMode())
{
TOptional<EDLSSQualityMode> MaybeDLSSQuality = GetAutoQualityModeFromViewFamily(ViewFamily);
if (!MaybeDLSSQuality.IsSet())
{
return;
}
else
{
DLSSQuality = MaybeDLSSQuality.GetValue();
}
}
else
{
DLSSQuality = GetSupportedQualityModeFromCVarValue(CVarNGXDLSSPerfQualitySetting.GetValueOnGameThread());
}
ViewFamily.SetTemporalUpscalerInterface(GetUpscalerInstanceForViewFamily(this, DLSSQuality));
if (ViewFamily.EngineShowFlags.ScreenPercentage && !ViewFamily.GetScreenPercentageInterface())
{
// DLSS uses recommended resolution fraction, DLAA forces a 1.0 scale
float ResolutionFraction = 1.0f;
if (!bIsDLAAMode)
{
ResolutionFraction = GetOptimalResolutionFractionForQuality(DLSSQuality);
}
ViewFamily.SetScreenPercentageInterface(new FLegacyScreenPercentageDriver(
ViewFamily, ResolutionFraction
#if SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE
/* AllowPostProcessSettingsScreenPercentage = */ , false
#endif
));
}
}
}
}
#if DLSS_ENGINE_SUPPORTS_CSSPD
void FDLSSUpscaler::SetupViewFamily(FSceneViewFamily& ViewFamily, TSharedPtr<ICustomStaticScreenPercentageData> InScreenPercentageDataInterface)
{
check(InScreenPercentageDataInterface.IsValid());
TSharedPtr<FDLSSViewportQualitySetting> ScreenPercentageData = StaticCastSharedPtr<FDLSSViewportQualitySetting>(InScreenPercentageDataInterface);
EDLSSQualityMode Quality = static_cast<EDLSSQualityMode>(ScreenPercentageData->QualitySetting);
const bool bIsDLAAMode = ScreenPercentageData->bDLAAEnabled;
if (bIsDLAAMode)
{
Quality = EDLSSQualityMode::Quality;
}
if (!IsQualityModeSupported(Quality))
{
UE_LOG(LogDLSS, Warning, TEXT("DLSS Quality mode is not supported %d"), Quality);
return;
}
const bool bDLSSActiveWithAutomation = !GIsAutomationTesting || (GIsAutomationTesting && (CVarNGXDLSSAutomationTesting.GetValueOnAnyThread() != 0));
if (IsDLSSActive() && bDLSSActiveWithAutomation)
{
#if DLSS_ENGINE_HAS_GTEMPORALUPSCALER
checkf(GTemporalUpscaler == this, TEXT("GTemporalUpscaler is not set to a DLSS upscaler . Please check that only one upscaling plugin is active."));
#endif
checkf(GCustomStaticScreenPercentage == this, TEXT("GCustomStaticScreenPercentage is not set to a DLSS upscaler. Please check that only one upscaling plugin is active."));
ViewFamily.SetTemporalUpscalerInterface(GetUpscalerInstanceForViewFamily(this, Quality));
if (ViewFamily.EngineShowFlags.ScreenPercentage && !ViewFamily.GetScreenPercentageInterface())
{
const float ResolutionFraction = bIsDLAAMode ? 1.0f : GetOptimalResolutionFractionForQuality(Quality);
ViewFamily.SetScreenPercentageInterface(new FLegacyScreenPercentageDriver(
ViewFamily, ResolutionFraction
#if SUPPORTS_POSTPROCESSING_SCREEN_PERCENTAGE
/* AllowPostProcessSettingsScreenPercentage = */ , false
#endif
));
}
}
}
#endif
TOptional<EDLSSQualityMode> FDLSSUpscaler::GetAutoQualityModeFromViewFamily(const FSceneViewFamily& ViewFamily) const
{
if (ensure(ViewFamily.RenderTarget != nullptr))
{
FIntPoint ViewSize = ViewFamily.RenderTarget->GetSizeXY();
int32 Pixels = ViewSize.X * ViewSize.Y;
return GetAutoQualityModeFromPixels(Pixels);
}
return TOptional<EDLSSQualityMode> {};
}
TOptional<EDLSSQualityMode> FDLSSUpscaler::GetAutoQualityModeFromPixels(int PixelCount) const
{
if (PixelCount >= 8'300'000 && IsQualityModeSupported(EDLSSQualityMode::UltraPerformance))
{
return EDLSSQualityMode::UltraPerformance;
}
else if (PixelCount >= 3'690'000 && IsQualityModeSupported(EDLSSQualityMode::Performance))
{
return EDLSSQualityMode::Performance;
}
else if (PixelCount >= 2'030'000 && IsQualityModeSupported(EDLSSQualityMode::Quality))
{
return EDLSSQualityMode::Quality;
}
return TOptional<EDLSSQualityMode> {};
}
bool FDLSSUpscaler::EnableDLSSInPlayInEditorViewports() const
{
if (GetDefault<UDLSSOverrideSettings>()->EnableDLSSInPlayInEditorViewportsOverride == EDLSSSettingOverride::UseProjectSettings)
{
return GetDefault<UDLSSSettings>()->bEnableDLSSInPlayInEditorViewports;
}
else
{
return GetDefault<UDLSSOverrideSettings>()->EnableDLSSInPlayInEditorViewportsOverride == EDLSSSettingOverride::Enabled;
}
}
float FDLSSUpscaler::GetMinUpsampleResolutionFraction() const
{
return MinResolutionFraction;
}
float FDLSSUpscaler::GetMaxUpsampleResolutionFraction() const
{
return MaxResolutionFraction;
}
float FDLSSUpscaler::GetOptimalResolutionFractionForQuality(EDLSSQualityMode Quality) const
{
checkf(IsQualityModeSupported(Quality),TEXT("%u is not a valid Quality mode"), Quality);
return ResolutionSettings[ToNGXQuality(Quality)].OptimalResolutionFraction;
}
float FDLSSUpscaler::GetOptimalSharpnessForQuality(EDLSSQualityMode Quality) const
{
checkf(IsQualityModeSupported(Quality), TEXT("%u is not a valid Quality mode"), Quality);
return ResolutionSettings[ToNGXQuality(Quality)].Sharpness;
}
float FDLSSUpscaler::GetMinResolutionFractionForQuality(EDLSSQualityMode Quality) const
{
checkf(IsQualityModeSupported(Quality), TEXT("%u is not a valid Quality mode"), Quality);
return ResolutionSettings[ToNGXQuality(Quality)].MinResolutionFraction;
}
float FDLSSUpscaler::GetMaxResolutionFractionForQuality(EDLSSQualityMode Quality) const
{
checkf(IsQualityModeSupported(Quality), TEXT("%u is not a valid Quality mode"), Quality);
return ResolutionSettings[ToNGXQuality(Quality)].MaxResolutionFraction;
}
bool FDLSSUpscaler::IsFixedResolutionFraction(EDLSSQualityMode Quality) const
{
checkf(IsQualityModeSupported(Quality), TEXT("%u is not a valid Quality mode"), Quality);
return ResolutionSettings[ToNGXQuality(Quality)].IsFixedResolution();
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,189 @@
/*
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
#include "CoreMinimal.h"
#include "RendererInterface.h"
#include "PostProcess/TemporalAA.h"
#include "ScreenPass.h"
#include "NGXRHI.h"
#include "DLSSSettings.h"
#include "CustomStaticScreenPercentage.h"
#include "CustomResourcePool.h"
class FSceneTextureParameters;
struct FTemporalAAHistory;
class FRHITexture;
class NGXRHI;
struct FDLSSOptimalSettings;
struct FDLSSPassParameters
{
FIntRect InputViewRect;
FIntRect OutputViewRect;
bool bHighResolutionMotionVectors = false;
FRDGTexture* SceneColorInput = nullptr;
FRDGTexture* SceneVelocityInput = nullptr;
FRDGTexture* SceneDepthInput = nullptr;
FDLSSPassParameters(const FViewInfo& View)
: InputViewRect(View.ViewRect)
, OutputViewRect(FIntPoint::ZeroValue, View.GetSecondaryViewRectSize())
{
}
/** Returns the texture resolution that will be output. */
FIntPoint GetOutputExtent() const;
/** Validate the settings of TAA, to make sure there is no issue. */
bool Validate() const;
};
struct FDLSSOutputs
{
FRDGTexture* SceneColor = nullptr;
};
enum class EDLSSQualityMode
{
MinValue = -2,
UltraPerformance = -2,
Performance = -1,
Balanced = 0,
Quality = 1,
UltraQuality = 2,
MaxValue = UltraQuality,
NumValues = 5
};
class DLSS_API FDLSSUpscaler final : public ITemporalUpscaler, public ICustomStaticScreenPercentage, public ICustomResourcePool
{
friend class FDLSSModule;
public:
FDLSSUpscaler(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InQualityMode);
virtual ~FDLSSUpscaler();
// Inherited via ITemporalUpscaler
virtual const TCHAR* GetDebugName() const final;
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
virtual void AddPasses(
#else
virtual ITemporalUpscaler::FOutputs AddPasses(
#endif
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FPassInputs& PassInputs
#if DLSS_ENGINE_ADDPASSES_RETURN_THROUGH_PARAMS
, FRDGTextureRef* OutSceneColorTexture
, FIntRect* OutSceneColorViewRect
, FRDGTextureRef* OutSceneColorHalfResTexture
, FIntRect* OutSceneColorHalfResViewRect
#endif
) const final;
// Inherited via ICustomStaticScreenPercentage
virtual void SetupMainGameViewFamily(FSceneViewFamily& ViewFamily) final;
#if DLSS_ENGINE_SUPPORTS_CSSPD
/** Allows to setup View Family directly. To be used by modules that are aware of DLSS Plugin. */
virtual void SetupViewFamily(FSceneViewFamily& ViewFamily, TSharedPtr<ICustomStaticScreenPercentageData> InScreenPercentageDataInterface) final;
#endif
virtual float GetMinUpsampleResolutionFraction() const final;
virtual float GetMaxUpsampleResolutionFraction() const final;
float GetOptimalResolutionFractionForQuality(EDLSSQualityMode Quality) const;
float GetOptimalSharpnessForQuality(EDLSSQualityMode Quality) const;
float GetMinResolutionFractionForQuality(EDLSSQualityMode Quality) const;
float GetMaxResolutionFractionForQuality(EDLSSQualityMode Quality) const;
bool IsFixedResolutionFraction(EDLSSQualityMode Quality) const;
const NGXRHI* GetNGXRHI() const
{
return NGXRHIExtensions;
}
// Inherited via ICustomResourcePool
virtual void Tick(FRHICommandListImmediate& RHICmdList) override;
bool IsQualityModeSupported(EDLSSQualityMode InQualityMode) const;
uint32 GetNumRuntimeQualityModes() const
{
return NumRuntimeQualityModes;
}
bool IsDLSSActive() const;
static FDLSSUpscaler* GetUpscalerInstanceForViewFamily(const FDLSSUpscaler* InUpscaler, EDLSSQualityMode InQualityMode);
static bool IsValidUpscalerInstance(const ITemporalUpscaler* InUpscaler);
static bool IsDLAAMode();
static bool IsAutoQualityMode();
static void SetAutoQualityMode(bool bAutoQualityMode);
// Give the suggested EDLSSQualityMode if one is appropriate for the given pixel count, or nothing if DLSS should be disabled
TOptional<EDLSSQualityMode> GetAutoQualityModeFromPixels(int PixelCount) const;
static void ReleaseStaticResources();
private:
FDLSSUpscaler(NGXRHI* InNGXRHIExtensions);
FDLSSUpscaler(const FDLSSUpscaler&) = default;
EDLSSQualityMode GetSupportedQualityModeFromCVarValue(int32 InCVarValue) const
{
checkf(NumRuntimeQualityModes, TEXT("This should only be called from the higher level code when DLSS is supported") );
static_assert(int32(EDLSSQualityMode::NumValues) == 5, "dear DLSS plugin NVIDIA developer, please update this code to handle the new EDLSSQualityMode enum values");
for (auto QualityMode : { EDLSSQualityMode::UltraPerformance, EDLSSQualityMode::Performance , EDLSSQualityMode::Balanced, EDLSSQualityMode::Quality, EDLSSQualityMode::UltraQuality })
{
if (InCVarValue == static_cast<int32>(QualityMode) && IsQualityModeSupported(QualityMode))
{
return QualityMode;
}
}
return EDLSSQualityMode::Balanced;
}
TOptional<EDLSSQualityMode> GetAutoQualityModeFromViewFamily(const FSceneViewFamily& ViewFamily) const;
bool EnableDLSSInPlayInEditorViewports() const;
FDLSSOutputs AddDLSSPass(
FRDGBuilder& GraphBuilder,
const FViewInfo& View,
const FDLSSPassParameters& Inputs,
const FTemporalAAHistory& InputHistory,
FTemporalAAHistory* OutputHistory,
const TRefCountPtr<ICustomTemporalAAHistory> InputCustomHistoryInterface,
TRefCountPtr<ICustomTemporalAAHistory>* OutputCustomHistoryInterface
) const;
EDLSSQualityMode DLSSQualityMode = EDLSSQualityMode::NumValues;
// The FDLSSUpscaler(NGXRHI*) will update those once
static NGXRHI* NGXRHIExtensions;
static float MinResolutionFraction;
static float MaxResolutionFraction;
static uint32 NumRuntimeQualityModes;
static TArray<FDLSSOptimalSettings> ResolutionSettings;
static TStaticArray <TSharedPtr<FDLSSUpscaler>, uint32(EDLSSQualityMode::NumValues)> DLSSUpscalerInstancesPerViewFamily;
};
@@ -0,0 +1,44 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include "DLSSUpscalerHistory.h"
#include "DLSSUpscalerPrivate.h"
#include "NGXRHI.h"
#include "PostProcess/SceneRenderTargets.h"
#include "PostProcess/PostProcessing.h"
#define LOCTEXT_NAMESPACE "FDLSSModule"
FDLSSUpscalerHistory::FDLSSUpscalerHistory(FDLSSStateRef InDLSSState)
: DLSSState(InDLSSState)
{
}
FDLSSUpscalerHistory::~FDLSSUpscalerHistory()
{
}
#undef LOCTEXT_NAMESPACE
@@ -0,0 +1,53 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#pragma once
#include "CoreMinimal.h"
#include "SceneRendering.h"
#include "NGXRHI.h"
class DLSS_API FDLSSUpscalerHistory final : public ICustomTemporalAAHistory, public FRefCountBase
{
friend class FDLSSUpscaler;
FDLSSStateRef DLSSState;
virtual uint32 AddRef() const final
{
return FRefCountBase::AddRef();
}
virtual uint32 Release() const final
{
return FRefCountBase::Release();
}
virtual uint32 GetRefCount() const final
{
return FRefCountBase::GetRefCount();
}
FDLSSUpscalerHistory(FDLSSStateRef InDLSSState);
~FDLSSUpscalerHistory();
};
@@ -0,0 +1,26 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#pragma once
#include "CoreMinimal.h"
DECLARE_LOG_CATEGORY_EXTERN(LogDLSS, Verbose, All);
+74
View File
@@ -0,0 +1,74 @@
/*
* Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#pragma once
#include "Modules/ModuleManager.h"
class FDLSSUpscaler;
class FDLSSDenoiser;
class FNGXAutomationViewExtension;
class NGXRHI;
enum class EDLSSSupport : uint8
{
Supported,
NotSupported,
NotSupportedIncompatibleHardware,
NotSupportedDriverOutOfDate,
NotSupportedOperatingSystemOutOfDate,
NotSupportedIncompatibleAPICaptureToolActive,
};
class IDLSSModuleInterface : public IModuleInterface
{
public:
virtual EDLSSSupport QueryDLSSSupport() const = 0;
virtual void GetDLSSMinDriverVersion(int32& MajorVersion, int32& MinorVersion) const = 0;
virtual float GetResolutionFractionForQuality(int32 Quality) const = 0;
virtual FDLSSUpscaler* GetDLSSUpscaler() const = 0;
};
class FDLSSModule final: public IDLSSModuleInterface
{
public:
/** IModuleInterface implementation */
virtual void StartupModule();
virtual void ShutdownModule();
// Inherited via IDLSSModuleInterface
virtual EDLSSSupport QueryDLSSSupport() const;
virtual void GetDLSSMinDriverVersion(int32& MajorVersion, int32& MinorVersion) const;
virtual float GetResolutionFractionForQuality(int32 Quality) const;
virtual FDLSSUpscaler* GetDLSSUpscaler() const ;
private:
TUniquePtr<FDLSSUpscaler> DLSSUpscaler;
TUniquePtr<FDLSSDenoiser> DLSSDenoiser;
TUniquePtr<NGXRHI> NGXRHIExtensions;
TSharedPtr< FNGXAutomationViewExtension, ESPMode::ThreadSafe> NGXAutomationViewExtension;
EDLSSSupport DLSSSupport = EDLSSSupport::NotSupported;
int32 MinDriverVersionMinor;
int32 MinDriverVersionMajor;
};
@@ -0,0 +1,121 @@
/*
* Copyright (c) 2020 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
*
* NVIDIA CORPORATION, its affiliates and licensors retain all intellectual
* property and proprietary rights in and to this material, related
* documentation and any modifications thereto. Any use, reproduction,
* disclosure or distribution of this material and related documentation
* without an express license agreement from NVIDIA CORPORATION or
* its affiliates is strictly prohibited.
*/
#pragma once
#include "UObject/ObjectMacros.h"
#include "UObject/Object.h"
#include "Engine/DeveloperSettings.h"
#include "CustomStaticScreenPercentage.h"
#include "Runtime/Launch/Resources/Version.h"
#include "DLSSSettings.generated.h"
UENUM()
enum class EDLSSSettingOverride : uint8
{
Enabled UMETA(DisplayName = "True"),
Disabled UMETA(DisplayName = "False"),
UseProjectSettings UMETA(DisplayName = "Use project settings"),
};
UCLASS(Config = Engine, ProjectUserConfig)
class DLSS_API UDLSSOverrideSettings : public UObject
{
public:
GENERATED_BODY()
/** This enables DLSS in editor viewports. Saved to local user config only.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport (Local)", DisplayName = "Enable DLSS to be turned on in Editor viewports")
EDLSSSettingOverride EnableDLSSInEditorViewportsOverride = EDLSSSettingOverride::UseProjectSettings;
/** This setting enables adjusting the screenpercentage directly in the editor, outside of the optimized DLSS quality modes. Saved to local user config only.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport (Local)", DisplayName = "Enable Screenpercentage Manipulation in DLSS Editor Viewports")
EDLSSSettingOverride EnableScreenpercentageManipulationInDLSSEditorViewportsOverride = EDLSSSettingOverride::UseProjectSettings;
/** This enables DLSS in play in editor viewports. Saved to local user config only. */
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport (Local)", DisplayName = "Enable DLSS in Play In Editor viewports")
EDLSSSettingOverride EnableDLSSInPlayInEditorViewportsOverride = EDLSSSettingOverride::UseProjectSettings;
/** This enables warnings about plugins & tools that are incompatible with DLSS in the editor. Saved to local user config only. */
UPROPERTY(Config, EditAnywhere, Category = "Editor (Local)", DisplayName = "Warn about incompatible plugins and tools")
bool bShowDLSSIncompatiblePluginsToolsWarnings = true;
/** This enables on screen warnings and errors about DLSS */
UPROPERTY(Config, EditAnywhere, Category = "Editor (Local)", DisplayName = "Show various DLSS on screen debug messages")
EDLSSSettingOverride ShowDLSSSDebugOnScreenMessages = EDLSSSettingOverride::UseProjectSettings;
};
UCLASS(Config = Engine, DefaultConfig, DisplayName="NVIDIA DLSS")
class DLSS_API UDLSSSettings: public UObject
{
GENERATED_BODY()
private:
public:
/** Enable DLSS for D3D12, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS for the D3D12RHI")
bool bEnableDLSSD3D12 = PLATFORM_WINDOWS;
/** Enable DLSS for D3D11, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS for the D3D11RHI")
bool bEnableDLSSD3D11 = PLATFORM_WINDOWS;
/** Enable DLSS for Vulkan, if the driver supports it at runtime */
UPROPERTY(Config, EditAnywhere, Category = "Platforms", DisplayName = "Enable DLSS for the VulkanRHI")
bool bEnableDLSSVulkan = PLATFORM_WINDOWS;
/** This enables DLSS in editor viewports. This project wide setting can be locally overridden in the NVIDIA DLSS (Local) settings.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Enable DLSS to be turned on in Editor viewports")
bool bEnableDLSSInEditorViewports = true;
/** This setting enables adjusting the screenpercentage directly in the editor, outside of the optimized DLSS quality modes. This project wide setting can be locally overridden in the NVIDIA DLSS (Local) settings.*/
UPROPERTY(Config = Editor, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Enable Screenpercentage Manipulation in DLSS Editor Viewports")
bool bEnableScreenpercentageManipulationInDLSSEditorViewports = false;
/** This enables DLSS in play in editor viewports. This project wide setting can be locally overridden in in the NVIDIA DLSS (Local) settings.*/
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Enable DLSS in Play In Editor viewports")
bool bEnableDLSSInPlayInEditorViewports = true;
/** This enables on screen warnings and errors about DLSS. This project wide setting can be locally overridden in the NVIDIA DLSS (Local) settings. */
UPROPERTY(Config, EditAnywhere, Category = "Level Editor - Viewport", DisplayName = "Show various DLSS on screen debug messages")
bool bShowDLSSSDebugOnScreenMessages = true;
/** This is part of the DLSS plugin and used by most projects*/
UPROPERTY(VisibleAnywhere, Config, Category = "General Settings", DisplayName = "Generic DLSS Binary Path")
FString GenericDLSSBinaryPath;
UPROPERTY(VisibleAnywhere, Config, Category = "General Settings", DisplayName = "Exists")
bool bGenericDLSSBinaryExists;
/** By default the DLSS plugin uses the UE Project ID to initalize DLSS. In some cases NVIDIA might provide a separate NVIDIA Application ID, which should be put here. Please refer to https://developer.nvidia.com/dlss for details*/
UPROPERTY(Config, EditAnywhere, Category = "General Settings", DisplayName = "NVIDIA NGX Application ID", AdvancedDisplay)
uint32 NVIDIANGXApplicationId;
/** In some cases NVIDIA might provide a project specific DLSS binary for your project. Please refer to https://developer.nvidia.com/dlss for details*/
UPROPERTY(VisibleAnywhere, Config, Category = "General Settings", DisplayName = "Custom DLSS Binary Path", AdvancedDisplay)
FString CustomDLSSBinaryPath;
UPROPERTY(VisibleAnywhere, Config, Category = "General Settings", DisplayName = "Exists", AdvancedDisplay)
bool bCustomDLSSBinaryExists;
};
// This is publically defined in the .Build.cs so it can key off branch names, which is not feasible to do with the preprocessor
#if DLSS_ENGINE_SUPPORTS_CSSPD
class FDLSSViewportQualitySetting final : public ICustomStaticScreenPercentageData
{
public:
int32 QualitySetting = 0;
bool bDLAAEnabled = false;
};
#endif