Files
UnrealEngineUWP/Engine/Source/Runtime/RenderCore/Public/RenderResource.h
Ben Marsh 7c77078af1 Copying //UE4/Dev-Core to //UE4/Dev-Main (Source: //UE4/Dev-Core @ 3345728)
#lockdown Nick.Penwarden

==========================
MAJOR FEATURES + CHANGES
==========================

Change 3315219 on 2017/02/21 by Steve.Robb

	Fix for FObjectAndNameAsStringProxyArchive when serializing a TWeakObjectPtr.

Change 3315285 on 2017/02/21 by Steve.Robb

	Explicitly pass string builder into code generation functions.

Change 3315341 on 2017/02/21 by Ben.Marsh

	UAT: Clean up some formatting in StreamCopyDescription output - remove #fyi lines, exclude merge commits, and remove some blank lines.

Change 3315350 on 2017/02/21 by Ben.Marsh

	Fix shared resource files not being rebuilt if the version header changes.

Change 3315823 on 2017/02/21 by Ben.Marsh

	UAT: Use a class derived from AutomationException to return information specific to commandlets failing, rather than putting it in the base class.

Change 3315826 on 2017/02/21 by Ben.Marsh

	UAT: Move Distiller class from general use in UAT; FileFilter provides a much safer and fully featured implementation of the same concepts.

Change 3315857 on 2017/02/21 by Ben.Marsh

	UBT: Remove the StripBaseDirectory() and MakeRerootedFilePath() utility functions from UBT. These operations can now be done more safely with FileReference objects.

Change 3315942 on 2017/02/21 by Ben.Marsh

	UBT: Convert FileFilter to use FileReference and DirectoryReference arguments everywhere.

Change 3316236 on 2017/02/22 by Maciej.Mroz

	#jira UE-42045

	Nativization
	Fixed Warning: TEnumAsByte is not intended for use with enum

Change 3316253 on 2017/02/22 by Robert.Manuszewski

	Fixes for the async log file writer hangs and crashes.

	- potential fix for the logging system hang when running out of disk space while flushing log
	- fix for unexpected concurrency assert when flushing the log buffer to disk

Change 3316293 on 2017/02/22 by Steve.Robb

	GetTypeHash and lexicographical comparison operators (operator<() etc.) for TTuple.

Change 3316342 on 2017/02/22 by Maciej.Mroz

	Nativization: Wrappers (stubs) required only by other wrappers are properly generated.

	#codereview: Mike.Beach

Change 3316344 on 2017/02/22 by Maciej.Mroz

	Fixed crash in nativized Odin
	Async loading properly handles nativized structs.

Change 3316359 on 2017/02/22 by Steve.Robb

	GitHub #3287 : Ignore #pragma in USTRUCTs

	#jira UE-42248

Change 3316389 on 2017/02/22 by Matthew.Griffin

	Switched Installed Engine Filters to multiline properties to make them more readable
	Added Oodle to list of excluded plugins
	#jira UE-42030

Change 3316392 on 2017/02/22 by Ben.Marsh

	UBT: Split out FileReference/DirectoryReference classes into their own file.

Change 3316394 on 2017/02/22 by Ben.Marsh

	UBT: Move FileReference/DirectoryReference extension methods into the appropriate file.

Change 3316411 on 2017/02/22 by Ben.Marsh

	UAT: Remove file functions that take multiple arguments. There's not really a compelling use case for these to exist over looping from the calling code.

Change 3316446 on 2017/02/22 by Ben.Marsh

	UAT: Try disabling function name prefix to log output from UAT, to see if it improves readability. Function names are still included in the log file for debugging.

Change 3316575 on 2017/02/22 by Ben.Marsh

	UAT: Remove unused functionality for dealing with labels, and output a more human readable list of P4 settings at startup.

Change 3318481 on 2017/02/22 by Steve.Robb

	Use of FMath::IsPowerOfTwo in check.
	Static assert to ensure that an inline set allocator will have a hash size of a power of two.

Change 3318496 on 2017/02/22 by Steve.Robb

	Fix for TSet visualizers.

Change 3318919 on 2017/02/23 by Steve.Robb

	Fix for hot reloading UScriptStruct-derived objects in a module, where the CDOs of these objects haven't had PrepareCppStructOps() called on them.

	#jira UE-42178

Change 3318942 on 2017/02/23 by Steve.Robb

	Removal of a redundant insertion which can cause problems on reallocation of the map.

Change 3319010 on 2017/02/23 by Ben.Marsh

	UBT: Fix exception when a file that was previously part of the working set is deleted.

Change 3319134 on 2017/02/23 by Robert.Manuszewski

	Better fix for a deadlock when flushing log while it's already being flushed due to flush timer on the async log writer thread.

Change 3319249 on 2017/02/23 by Matthew.Griffin

	Added a function to check if running with debug game libs instead of checking command line in multiple places
	Added -RunConfig parameter, which has equivalent result to -debug if value of parameter starts with 'debug'
	Added -RunConfig=$(Configuration) as a default commandline argument for Mac so that editor can use debug game libs
	Removed -Shipping argument from VCProject generation as it's not used anymore

Change 3319253 on 2017/02/23 by Maciej.Mroz

	#jira UE-41846

	New mechanism to gather modules necessary for Nativized Assets. The modules are listed based on included headers. Previously the dependencies was gathered only in FBlueprintNativeCodeGenManifest::GatherModuleDependencies.

Change 3319591 on 2017/02/23 by Ben.Marsh

	Don't strip prefixes beginning with WARNING: or ERROR: using the Postp filter.

Change 3320357 on 2017/02/23 by Steven.Hutton

	Slight changes to Add Crash method - Returning select fields instead of entity objects in queries for perf reasons.

Change 3320361 on 2017/02/23 by Steven.Hutton

	Performance improvements subsequent to the recent database changes.

Change 3320446 on 2017/02/23 by Steven.Hutton

	adding my temporary performance tracker class - reports to a private slack channel with add crash performance data.

Change 3320479 on 2017/02/23 by Ben.Marsh

	Fix CIS errors.

Change 3320576 on 2017/02/23 by Jin.Zhang

	Update CrashReporter to use AWS

Change 3320742 on 2017/02/23 by Jin.Zhang

	Merging crash caching

Change 3321119 on 2017/02/24 by Robert.Manuszewski

	DLL injection protection support for non-monolithic builds

Change 3323308 on 2017/02/27 by Matthew.Griffin

	Moved compilation of SwarmInterface after its dependencies so that we will see a build failure immediately if they change version in future

Change 3323423 on 2017/02/27 by Chad.Garyet

	Adding a script to check and warn about csproj targeted .net versions being mismatched

	#JIRA UE-39624

Change 3323442 on 2017/02/27 by Ben.Marsh

	UBT: Output an error if an engine module references a game module.

Change 3323743 on 2017/02/27 by Ben.Marsh

	PR #3303: Resolved PVS scan issues (Contributed by projectgheist)

Change 3323748 on 2017/02/27 by Ben.Marsh

	Convert whitespace to tabs.

Change 3324851 on 2017/02/28 by Chris.Wood

	Add Odin symbol locations to engine config for MDD on CR server.

	NotForLicensees

Change 3324979 on 2017/02/28 by Gil.Gribb

	Fixed bad merge of priority change in the EDL.

Change 3326889 on 2017/03/01 by Steven.Hutton

	Update to buggs controller to generate faster queries.

Change 3326910 on 2017/03/01 by Robert.Manuszewski

	Removing legacy #if from PackageFileSummary.

Change 3327118 on 2017/03/01 by Gil.Gribb

	UE4 - Fixed race that resulted in a memory leak when reading compressed paks.

Change 3327633 on 2017/03/01 by Gil.Gribb

	UE4 - Added a cvar to control the pak precacher thottle.

Change 3327674 on 2017/03/01 by Steve.Robb

	Unified boilerplate between all generated code files.

Change 3328544 on 2017/03/01 by Chris.Wood

	CrashReportProcess.config update (CRP v1.2.17)

	Tweaks to a few values.
	Update website URL to explicitly point to old, non-cloud site on devweb-02.

Change 3328714 on 2017/03/01 by Chris.Wood

	Correct CRP config regression. Point website at new cloud site. Still v1.2.17

Change 3329192 on 2017/03/02 by Matthew.Griffin

	Added Shared Build Id file to the list of Precompiled Build Dependencies in a target receipt so that it's brought into an installed build

Change 3329285 on 2017/03/02 by Ben.Marsh

	UGS: Allow a project to specify a filters for the streams that should be displayed for fast-switching to. The QuickSelectStreamList seting in the [Options] section of the project settings references a depot path containing a list of strings used to filter the stream list. An option is shown to switch back to showing all available streams, if desired.

Change 3330636 on 2017/03/02 by Ben.Marsh

	UBT: Bump version number of C++ include cache to force it to be rebuilt with additional include information for the default RC files.

Change 3331262 on 2017/03/03 by Robert.Manuszewski

	Merging Dev-LoadTimes to Dev-Core (Garbage Collection performance improvements)

	- Improved GC multithreading
	- Improved BeginDestroy performance
	- Introduced ULevelActorCluster for StaticMeshActor and ReflectionCapture actor clustering (can be toggled through project settings or console command gc.ActorClusterEnabled)
	- A few improvements to AddReferencedObjects functions
	- Misc improvements to GC code
	- Garbage Collector now properly handles clusters which had their objects marked as pending kill
	- Blueprints can now create clusters too (can be toggled through project settings or console command gc.BlueprintClusteringEnabled, defaults to disabled)

Change 3331285 on 2017/03/03 by Robert.Manuszewski

	A few fixes for the previous check-in.

Change 3332001 on 2017/03/03 by Ben.Marsh

	UBT: Add support for generating a UDN file containing the valid settings for BuildConfiguration.xml. Pass -configdoc=<filename> on the command line to generate such a file.

Change 3332022 on 2017/03/03 by Ben.Marsh

	Update documentation for where to find the BuildConfiguration settings.

Change 3332031 on 2017/03/03 by Ben.Marsh

	Remove documentation for Windows XP support; it has been removed in the 4.16 release.

Change 3332256 on 2017/03/03 by Ben.Marsh

	UBT: Add support for generating a UDN page containing module and target settings.

Change 3332458 on 2017/03/03 by Ben.Marsh

	UBT: Improvements to generated documentation.

Change 3332459 on 2017/03/03 by Ben.Marsh

	Add generated documentation for .target.cs files, .build.cs files, and BuildConfiguration.xml files.

Change 3332460 on 2017/03/03 by Ben.Marsh

	UBT: Make LinkTypePrivate actually private, so it doesn't show up in the docs.

Change 3332899 on 2017/03/06 by Robert.Manuszewski

	Making sure actor clustering is not used in the editor (fix for actors being deleted when GC runs in the editor)

	#jira UE-42548

Change 3332955 on 2017/03/06 by Maciej.Mroz

	Nativization distinguishes client and server platform:
	- Separated lists on additional assets, additional modules, excluded assets, excluded modules, excluded paths (in config)
	- Context (compilation options, nativization options and platform) is deliveren to BPCOmpilerCppBackend in FCompilerNativizationOptions struct.
	- Wrappers (for unconverted BPs) are created only when they are directly called.

	- Fortnite dedicated server can be nativized

Change 3332990 on 2017/03/06 by Ben.Marsh

	UBT: Add more comprehensive wrapper methods for System.IO.File and System.IO.Directory to FileReference and DirectoryReference.

Change 3333032 on 2017/03/06 by Ben.Marsh

	Documentation for build tools

Change 3333037 on 2017/03/06 by Ben.Marsh

	Add a build step to extract UAT and UBT documentation from XML comments.

Change 3333089 on 2017/03/06 by Ben.Marsh

	UAT: Re-enable logging the calling function to the console in UAT. Needs a pass for readability first.

Change 3333651 on 2017/03/06 by Gil.Gribb

	UE4 - Fix a werid recursive situation where StaticLoadObject could return an object that has not finished loading. Also produces a fatal error if this sometimes happens. EDL only.

Change 3335236 on 2017/03/07 by Ben.Marsh

	UGS: Set the sync changelist separately to the compatibility changelist.

Change 3335261 on 2017/03/07 by Gil.Gribb

	UE4 - Fixed batched render fences when BeginDestroy calls FlushRenderingCommands.

Change 3335740 on 2017/03/07 by Gil.Gribb

	maybe fix static analysis warning

Change 3335945 on 2017/03/07 by Steve.Robb

	Move FFindInstancedReferenceSubobjectHelper code out of header.
	Add map/set property support to allow instanced members of these container types to be handled during CPFUO.

	https://udn.unrealengine.com/questions/349232/tmap-with-instanced-object-as-value-gets-cleared-o.html

Change 3336693 on 2017/03/07 by Ben.Marsh

	UBT: Use shared PCHs for game plugins by default, to reduce time spent generating individual PCHs.

Change 3336694 on 2017/03/07 by Steve.Robb

	Static assert added to TMap to prevent the use of keys which don't implement a GetTypeHash.
	Fixes to types which relied on implicit conversions when calling GetTypeHash.
	Workaround in SAssetView.h and PropertyEditorModule.h for an apparent VC bug where the compiler wrongly instantiates TPointerIsConvertibleFromTo for certain forward-declared types, causing future TSharedPtr conversions to fail.

	#jira UE-42441

Change 3336698 on 2017/03/07 by Steve.Robb

	Hardcoded endpoint handling replaced with a generic string.
	Obsolete .proto and .java code generation removed.

Change 3336811 on 2017/03/07 by Wes.Hunt

	Add a game blacklist to the crash report processor. Fixed a syntax error in Config.cs, added a XML comment to shut up a warning.

Change 3336973 on 2017/03/08 by Steve.Robb

	Fix for missing GetTypeHash in a plugin.

Change 3336996 on 2017/03/08 by Steve.Robb

	Significant refactor of code generation, to try and make data flow more apparent.

Change 3337571 on 2017/03/08 by Steve.Robb

	CIS fixes for missing GetTypeHash functions.
	Non-unity fix.

Change 3337588 on 2017/03/08 by Gil.Gribb

	UE4 - Fixed obscure check with flushing rhi resources.

Change 3337620 on 2017/03/08 by Steve.Robb

	WITH_HOT_RELOAD_CTORS macros removed.
	UseVTableConstructors config option removed.

Change 3339369 on 2017/03/09 by Steve.Robb

	GetTypeHash overload for nn::account::Uid.

Change 3339464 on 2017/03/09 by Daniel.Lamb

	Fixed assert in 4.15 to do with trying to gather dependency info from invalid packages.
	#jira UE-42583
	#test Editor + Cook + Run shootergame

Change 3339465 on 2017/03/09 by Maciej.Mroz

	Fixed serialization issue, after UserDefinedEnum was used in EnumProperty.

Change 3339469 on 2017/03/09 by Maciej.Mroz

	Fixed Nativization problem, when default value is passed as non-const reference.

Change 3340178 on 2017/03/09 by Daniel.Lamb

	Added support for in memory only packages.  The Cooker ignores these and added core functions to recognize these packages.
	Other systems will need to add support where nessisary.

Change 3341002 on 2017/03/10 by Maciej.Mroz

	Nativization: Fixed FFindHeadersToInclude. Headers necessary for owners of subobjects are properly included.

Change 3341076 on 2017/03/10 by Steve.Robb

	Fix for FBakedTextureSourceInfo move semantics.

	#jira UE-42658

Change 3341160 on 2017/03/10 by Gil.Gribb

	UE4 - Fix hazard with SetMaterialUsage from a thread.

Change 3341409 on 2017/03/10 by Steve.Robb

	Reduction of the generated code size for StaticRegisterNatives functions.

Change 3341523 on 2017/03/10 by Steve.Robb

	Code generation simplified.

Change 3341800 on 2017/03/10 by Ben.Marsh

	UnrealVS: Fix UnrealVS compatibility with RTM version of Visual Studio 2017. 2017 toolchain for extensions is no longer able to build <= 2015 extensions due to validation of the VSIX manifest, so create a separate solution for it.

Change 3342034 on 2017/03/10 by Ben.Marsh

	Fix compiler setting not being loaded correctly into the Windows target settings dialog.

	#jira UE-42746

Change 3342041 on 2017/03/10 by Ben.Marsh

	Fix -ErrorOnEngineContentUse not being set in the cooker options correctly.

Change 3342094 on 2017/03/10 by Steve.Robb

	Fix to deteministic name order during code generation.

Change 3342251 on 2017/03/10 by Daniel.Lamb

	Integrate fix for resave lightmaps commandlet when upgrading from no mapbuilddatapackages to mapbuilddatapackages.
	#thanks Tim.Hagberg

	#test None

Change 3342961 on 2017/03/13 by Robert.Manuszewski

	Fixing memory leak when playing while running -nullrhi on the commandline in cooked games caused by shader resources not being destroyed.

	#jira FORT-38977

Change 3343022 on 2017/03/13 by Steve.Robb

	GetTypeHash fixes for FUniqueNetIdLive.

	#jira UE-42788

Change 3343448 on 2017/03/13 by Steve.Robb

	Compiled-in defer object order fixed.
	Debuggability of the deferred registration map improved.

	#jira UE-42828

[CL 3345747 by Ben Marsh in Main branch]
2017-03-14 15:48:33 -04:00

698 lines
19 KiB
C++

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
RenderResource.h: Render resource definitions.
=============================================================================*/
#pragma once
#include "CoreMinimal.h"
#include "Containers/List.h"
#include "RHI.h"
#include "RenderCore.h"
/**
* A rendering resource which is owned by the rendering thread.
*/
class RENDERCORE_API FRenderResource
{
public:
/** @return The global initialized resource list. */
static TLinkedList<FRenderResource*>*& GetResourceList();
/** Default constructor. */
FRenderResource()
: FeatureLevel(ERHIFeatureLevel::Num)
, bInitialized(false)
{}
/** Constructor when we know what feature level this resource should support */
FRenderResource(ERHIFeatureLevel::Type InFeatureLevel)
: FeatureLevel(InFeatureLevel)
, bInitialized(false)
{}
/** Destructor used to catch unreleased resources. */
virtual ~FRenderResource();
/**
* Initializes the dynamic RHI resource and/or RHI render target used by this resource.
* Called when the resource is initialized, or when reseting all RHI resources.
* Resources that need to initialize after a D3D device reset must implement this function.
* This is only called by the rendering thread.
*/
virtual void InitDynamicRHI() {}
/**
* Releases the dynamic RHI resource and/or RHI render target resources used by this resource.
* Called when the resource is released, or when reseting all RHI resources.
* Resources that need to release before a D3D device reset must implement this function.
* This is only called by the rendering thread.
*/
virtual void ReleaseDynamicRHI() {}
/**
* Initializes the RHI resources used by this resource.
* Called when entering the state where both the resource and the RHI have been initialized.
* This is only called by the rendering thread.
*/
virtual void InitRHI() {}
/**
* Releases the RHI resources used by this resource.
* Called when leaving the state where both the resource and the RHI have been initialized.
* This is only called by the rendering thread.
*/
virtual void ReleaseRHI() {}
/**
* Initializes the resource.
* This is only called by the rendering thread.
*/
virtual void InitResource();
/**
* Prepares the resource for deletion.
* This is only called by the rendering thread.
*/
virtual void ReleaseResource();
/**
* If the resource's RHI resources have been initialized, then release and reinitialize it. Otherwise, do nothing.
* This is only called by the rendering thread.
*/
void UpdateRHI();
// Probably temporary code that sends a task back to renderthread_local and blocks waiting for it to call InitResource
void InitResourceFromPossiblyParallelRendering();
/** @return The resource's friendly name. Typically a UObject name. */
virtual FString GetFriendlyName() const { return TEXT("undefined"); }
// Accessors.
FORCEINLINE bool IsInitialized() const { return bInitialized; }
// For those situations when the default ctor had to be used
inline void SetFeatureLevel(ERHIFeatureLevel::Type InFeatureLevel)
{
FeatureLevel = InFeatureLevel;
}
protected:
// This is used during mobile editor preview refactor, this will eventually be replaced with a parameter to InitRHI() etc..
ERHIFeatureLevel::Type GetFeatureLevel() const { return FeatureLevel == ERHIFeatureLevel::Num ? GMaxRHIFeatureLevel : FeatureLevel; }
FORCEINLINE bool HasValidFeatureLevel() const { return FeatureLevel < ERHIFeatureLevel::Num; }
private:
ERHIFeatureLevel::Type FeatureLevel;
/** This resource's link in the global resource list. */
TLinkedList<FRenderResource*> ResourceLink;
/** True if the resource has been initialized. */
bool bInitialized;
};
/**
* Sends a message to the rendering thread to initialize a resource.
* This is called in the game thread.
*/
extern RENDERCORE_API void BeginInitResource(FRenderResource* Resource);
/**
* Sends a message to the rendering thread to update a resource.
* This is called in the game thread.
*/
extern RENDERCORE_API void BeginUpdateResourceRHI(FRenderResource* Resource);
/**
* Sends a message to the rendering thread to release a resource.
* This is called in the game thread.
*/
extern RENDERCORE_API void BeginReleaseResource(FRenderResource* Resource);
/**
* Enables the batching of calls to BeginReleaseResource
* This is called in the game thread.
*/
extern RENDERCORE_API void StartBatchedRelease();
/**
* Disables the batching of calls to BeginReleaseResource
* This is called in the game thread.
*/
extern RENDERCORE_API void EndBatchedRelease();
/**
* Sends a message to the rendering thread to release a resource, and spins until the rendering thread has processed the message.
* This is called in the game thread.
*/
extern RENDERCORE_API void ReleaseResourceAndFlush(FRenderResource* Resource);
/** Used to declare a render resource that is initialized/released by static initialization/destruction. */
template<class ResourceType>
class TGlobalResource : public ResourceType
{
public:
/** Default constructor. */
TGlobalResource()
{
InitGlobalResource();
}
/** Initialization constructor: 1 parameter. */
template<typename T1>
explicit TGlobalResource(T1 Param1)
: ResourceType(Param1)
{
InitGlobalResource();
}
/** Initialization constructor: 1 parameter. */
template<typename T1, typename T2>
explicit TGlobalResource(T1 Param1, T2 Param2)
: ResourceType(Param1, Param2)
{
InitGlobalResource();
}
/** Destructor. */
virtual ~TGlobalResource()
{
ReleaseGlobalResource();
}
private:
/**
* Initialize the global resource.
*/
void InitGlobalResource()
{
if(IsInRenderingThread())
{
// If the resource is constructed in the rendering thread, directly initialize it.
((ResourceType*)this)->InitResource();
}
else
{
// If the resource is constructed outside of the rendering thread, enqueue a command to initialize it.
BeginInitResource((ResourceType*)this);
}
}
/**
* Release the global resource.
*/
void ReleaseGlobalResource()
{
// This should be called in the rendering thread, or at shutdown when the rendering thread has exited.
// However, it may also be called at shutdown after an error, when the rendering thread is still running.
// To avoid a second error in that case we don't assert.
#if 0
check(IsInRenderingThread());
#endif
// Cleanup the resource.
((ResourceType*)this)->ReleaseResource();
}
};
enum EMipFadeSettings
{
MipFade_Normal = 0,
MipFade_Slow,
MipFade_NumSettings,
};
/** Mip fade settings, selectable by chosing a different EMipFadeSettings. */
struct FMipFadeSettings
{
FMipFadeSettings( float InFadeInSpeed, float InFadeOutSpeed )
: FadeInSpeed( InFadeInSpeed )
, FadeOutSpeed( InFadeOutSpeed )
{
}
/** How many seconds to fade in one mip-level. */
float FadeInSpeed;
/** How many seconds to fade out one mip-level. */
float FadeOutSpeed;
};
/** Whether to enable mip-level fading or not: +1.0f if enabled, -1.0f if disabled. */
extern RENDERCORE_API float GEnableMipLevelFading;
/** Global mip fading settings, indexed by EMipFadeSettings. */
extern RENDERCORE_API FMipFadeSettings GMipFadeSettings[MipFade_NumSettings];
/**
* Functionality for fading in/out texture mip-levels.
*/
struct FMipBiasFade
{
/** Default constructor that sets all values to default (no mips). */
FMipBiasFade()
: TotalMipCount(0.0f)
, MipCountDelta(0.0f)
, StartTime(0.0f)
, MipCountFadingRate(0.0f)
, BiasOffset(0.0f)
{
}
/** Number of mip-levels in the texture. */
float TotalMipCount;
/** Number of mip-levels to fade (negative if fading out / decreasing the mipcount). */
float MipCountDelta;
/** Timestamp when the fade was started. */
float StartTime;
/** Number of seconds to interpolate through all MipCountDelta (inverted). */
float MipCountFadingRate;
/** Difference between total texture mipcount and the starting mipcount for the fade. */
float BiasOffset;
/**
* Sets up a new interpolation target for the mip-bias.
* @param ActualMipCount Number of mip-levels currently in memory
* @param TargetMipCount Number of mip-levels we're changing to
* @param LastRenderTime Timestamp when it was last rendered (FApp::CurrentTime time space)
* @param FadeSetting Which fade speed settings to use
*/
RENDERCORE_API void SetNewMipCount( float ActualMipCount, float TargetMipCount, double LastRenderTime, EMipFadeSettings FadeSetting );
/**
* Calculates the interpolated mip-bias based on the current time.
* @return Interpolated mip-bias value
*/
inline float CalcMipBias() const
{
float DeltaTime = GRenderingRealtimeClock.GetCurrentTime() - StartTime;
float TimeFactor = FMath::Min<float>(DeltaTime * MipCountFadingRate, 1.0f);
float MipBias = BiasOffset - MipCountDelta*TimeFactor;
return FMath::FloatSelect(GEnableMipLevelFading, MipBias, 0.0f);
}
/**
* Checks whether the mip-bias is still interpolating.
* @return true if the mip-bias is still interpolating
*/
inline bool IsFading( ) const
{
float DeltaTime = GRenderingRealtimeClock.GetCurrentTime() - StartTime;
float TimeFactor = DeltaTime * MipCountFadingRate;
return (FMath::Abs<float>(MipCountDelta) > SMALL_NUMBER && TimeFactor < 1.0f);
}
};
/** A textures resource. */
class FTexture : public FRenderResource
{
public:
/** The texture's RHI resource. */
FTextureRHIRef TextureRHI;
/** The sampler state to use for the texture. */
FSamplerStateRHIRef SamplerStateRHI;
/** Sampler state to be used in deferred passes when discontinuities in ddx / ddy would cause too blurry of a mip to be used. */
FSamplerStateRHIRef DeferredPassSamplerStateRHI;
/** The last time the texture has been bound */
mutable double LastRenderTime;
/** Base values for fading in/out mip-levels. */
FMipBiasFade MipBiasFade;
/** true if the texture is in a greyscale texture format. */
bool bGreyScaleFormat;
/**
* true if the texture is in the same gamma space as the intended rendertarget (e.g. screenshots).
* The texture will have sRGB==false and bIgnoreGammaConversions==true, causing a non-sRGB texture lookup
* and no gamma-correction in the shader.
*/
bool bIgnoreGammaConversions;
/**
* Is the pixel data in this texture sRGB?
**/
bool bSRGB;
/** Default constructor. */
FTexture()
: TextureRHI(NULL)
, SamplerStateRHI(NULL)
, DeferredPassSamplerStateRHI(NULL)
, LastRenderTime(-FLT_MAX)
, bGreyScaleFormat(false)
, bIgnoreGammaConversions(false)
, bSRGB(false)
{}
// Destructor
virtual ~FTexture() {}
/** Returns the width of the texture in pixels. */
virtual uint32 GetSizeX() const
{
return 0;
}
/** Returns the height of the texture in pixels. */
virtual uint32 GetSizeY() const
{
return 0;
}
// FRenderResource interface.
virtual void ReleaseRHI() override
{
TextureRHI.SafeRelease();
SamplerStateRHI.SafeRelease();
DeferredPassSamplerStateRHI.SafeRelease();
}
virtual FString GetFriendlyName() const override { return TEXT("FTexture"); }
};
/** A texture reference resource. */
class RENDERCORE_API FTextureReference : public FRenderResource
{
public:
/** The texture reference's RHI resource. */
FTextureReferenceRHIRef TextureReferenceRHI;
private:
/** The last time the texture has been rendered via this reference. */
FLastRenderTimeContainer LastRenderTimeRHI;
/** True if the texture reference has been initialized from the game thread. */
bool bInitialized_GameThread;
public:
/** Default constructor. */
FTextureReference();
// Destructor
virtual ~FTextureReference();
/** Returns the last time the texture has been rendered via this reference. */
double GetLastRenderTime() const { return LastRenderTimeRHI.GetLastRenderTime(); }
/** Invalidates the last render time. */
void InvalidateLastRenderTime();
/** Returns true if the texture reference has been initialized from the game thread. */
bool IsInitialized_GameThread() const { return bInitialized_GameThread; }
/** Kicks off the initialization process on the game thread. */
void BeginInit_GameThread();
/** Kicks off the release process on the game thread. */
void BeginRelease_GameThread();
// FRenderResource interface.
virtual void InitRHI();
virtual void ReleaseRHI();
virtual FString GetFriendlyName() const;
};
/** A vertex buffer resource */
class RENDERCORE_API FVertexBuffer : public FRenderResource
{
public:
FVertexBufferRHIRef VertexBufferRHI;
/** Destructor. */
virtual ~FVertexBuffer() {}
// FRenderResource interface.
virtual void ReleaseRHI() override
{
VertexBufferRHI.SafeRelease();
}
virtual FString GetFriendlyName() const override { return TEXT("FVertexBuffer"); }
};
/**
* A vertex buffer with a single color component. This is used on meshes that don't have a color component
* to keep from needing a separate vertex factory to handle this case.
*/
class FNullColorVertexBuffer : public FVertexBuffer
{
public:
/**
* Initialize the RHI for this rendering resource
*/
virtual void InitRHI() override
{
// create a static vertex buffer
FRHIResourceCreateInfo CreateInfo;
void* LockedData = nullptr;
VertexBufferRHI = RHICreateAndLockVertexBuffer(sizeof(uint32), BUF_Static | BUF_ZeroStride | BUF_ShaderResource, CreateInfo, LockedData);
uint32* Vertices = (uint32*)LockedData;
Vertices[0] = FColor(255, 255, 255, 255).DWColor();
RHIUnlockVertexBuffer(VertexBufferRHI);
VertexBufferSRV = RHICreateShaderResourceView(VertexBufferRHI, sizeof(FColor), PF_R8G8B8A8);
}
virtual void ReleaseRHI() override
{
VertexBufferSRV.SafeRelease();
FVertexBuffer::ReleaseRHI();
}
FShaderResourceViewRHIRef VertexBufferSRV;
};
/** The global null color vertex buffer, which is set with a stride of 0 on meshes without a color component. */
extern RENDERCORE_API TGlobalResource<FNullColorVertexBuffer> GNullColorVertexBuffer;
/** An index buffer resource. */
class FIndexBuffer : public FRenderResource
{
public:
FIndexBufferRHIRef IndexBufferRHI;
/** Destructor. */
virtual ~FIndexBuffer() {}
// FRenderResource interface.
virtual void ReleaseRHI() override
{
IndexBufferRHI.SafeRelease();
}
virtual FString GetFriendlyName() const override { return TEXT("FIndexBuffer"); }
};
/**
* A system for dynamically allocating GPU memory for vertices.
*/
class RENDERCORE_API FGlobalDynamicVertexBuffer
{
public:
/**
* Information regarding an allocation from this buffer.
*/
struct FAllocation
{
/** The location of the buffer in main memory. */
uint8* Buffer;
/** The vertex buffer to bind for draw calls. */
FVertexBuffer* VertexBuffer;
/** The offset in to the vertex buffer. */
uint32 VertexOffset;
/** Default constructor. */
FAllocation()
: Buffer(NULL)
, VertexBuffer(NULL)
, VertexOffset(0)
{
}
/** Returns true if the allocation is valid. */
FORCEINLINE bool IsValid() const
{
return Buffer != NULL;
}
};
/** Default constructor. */
FGlobalDynamicVertexBuffer();
/** Destructor. */
~FGlobalDynamicVertexBuffer();
/**
* Allocates space in the global vertex buffer.
* @param SizeInBytes - The amount of memory to allocate in bytes.
* @returns An FAllocation with information regarding the allocated memory.
*/
FAllocation Allocate(uint32 SizeInBytes);
/**
* Commits allocated memory to the GPU.
* WARNING: Once this buffer has been committed to the GPU, allocations
* remain valid only until the next call to Allocate!
*/
void Commit();
/**
* Obtain a reference to the global dynamic vertex buffer instance.
*/
static FGlobalDynamicVertexBuffer& Get();
private:
/** The pool of vertex buffers from which allocations are made. */
struct FDynamicVertexBufferPool* Pool;
};
/**
* A system for dynamically allocating GPU memory for indices.
*/
class RENDERCORE_API FGlobalDynamicIndexBuffer
{
public:
/**
* Information regarding an allocation from this buffer.
*/
struct FAllocation
{
/** The location of the buffer in main memory. */
uint8* Buffer;
/** The vertex buffer to bind for draw calls. */
FIndexBuffer* IndexBuffer;
/** The offset in to the index buffer. */
uint32 FirstIndex;
/** Default constructor. */
FAllocation()
: Buffer(NULL)
, IndexBuffer(NULL)
, FirstIndex(0)
{
}
/** Returns true if the allocation is valid. */
FORCEINLINE bool IsValid() const
{
return Buffer != NULL;
}
};
/** Default constructor. */
FGlobalDynamicIndexBuffer();
/** Destructor. */
~FGlobalDynamicIndexBuffer();
/**
* Allocates space in the global index buffer.
* @param NumIndices - The number of indices to allocate.
* @param IndexStride - The size of an index (2 or 4 bytes).
* @returns An FAllocation with information regarding the allocated memory.
*/
FAllocation Allocate(uint32 NumIndices, uint32 IndexStride);
/**
* Helper function to allocate.
* @param NumIndices - The number of indices to allocate.
* @returns an FAllocation with information regarding the allocated memory.
*/
template <typename IndexType>
inline FAllocation Allocate(uint32 NumIndices)
{
return Allocate(NumIndices, sizeof(IndexType));
}
/**
* Commits allocated memory to the GPU.
* WARNING: Once this buffer has been committed to the GPU, allocations
* remain valid only until the next call to Allocate!
*/
void Commit();
/**
* Obtain a reference to the global dynamic index buffer instance.
*/
static FGlobalDynamicIndexBuffer& Get();
private:
/** The pool of vertex buffers from which allocations are made. */
struct FDynamicIndexBufferPool* Pools[2];
};
/**
* A list of the most recently used bound shader states.
* This is used to keep bound shader states that have been used recently from being freed, as they're likely to be used again soon.
*/
template<uint32 Size, bool TThreadSafe = true>
class TBoundShaderStateHistory : public FRenderResource
{
public:
/** Initialization constructor. */
TBoundShaderStateHistory():
NextBoundShaderStateIndex(0)
{}
/** Adds a bound shader state to the history. */
FORCEINLINE void Add(FBoundShaderStateRHIParamRef BoundShaderState)
{
if (TThreadSafe && GRHISupportsParallelRHIExecute)
{
BoundShaderStateHistoryLock.Lock();
}
BoundShaderStates[NextBoundShaderStateIndex] = BoundShaderState;
NextBoundShaderStateIndex = (NextBoundShaderStateIndex + 1) % Size;
if (TThreadSafe && GRHISupportsParallelRHIExecute)
{
BoundShaderStateHistoryLock.Unlock();
}
}
FBoundShaderStateRHIParamRef GetLast()
{
check(!GRHISupportsParallelRHIExecute);
// % doesn't work as we want on negative numbers, so handle the wraparound manually
uint32 LastIndex = NextBoundShaderStateIndex == 0 ? Size - 1 : NextBoundShaderStateIndex - 1;
return BoundShaderStates[LastIndex];
}
// FRenderResource interface.
virtual void ReleaseRHI()
{
if (TThreadSafe && GRHISupportsParallelRHIExecute)
{
BoundShaderStateHistoryLock.Lock();
}
for(uint32 Index = 0;Index < Size;Index++)
{
BoundShaderStates[Index].SafeRelease();
}
if (TThreadSafe && GRHISupportsParallelRHIExecute)
{
BoundShaderStateHistoryLock.Unlock();
}
}
private:
FBoundShaderStateRHIRef BoundShaderStates[Size];
uint32 NextBoundShaderStateIndex;
FCriticalSection BoundShaderStateHistoryLock;
};