Files
UnrealEngineUWP/Engine/Source/Runtime/Renderer/Private/PostProcess/VisualizeTexture.cpp
Gil Gribb 80f6fa5fa7 Copying //UE4/Dev-Rendering to //UE4/Dev-Main (Source: //UE4/Dev-Rendering @ 3231693)
#lockdown Nick.Penwarden
#rb none

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

Change 3219796 on 2016/12/02 by Rolando.Caloca

	DR - vk - Increase timeout to 60ms

Change 3219884 on 2016/12/02 by Daniel.Wright

	Assert to help track down rare crash locking capsule indirect shadow vertex buffer

Change 3219885 on 2016/12/02 by Daniel.Wright

	Fixed saving a package that doesn't exist on disk but exists in p4 at a newer revision when the user chooses 'Mark Writable'

Change 3219886 on 2016/12/02 by Daniel.Wright

	Don't create projected shadows when r.ShadowQuality is 0
	* Fixes crash in the forward path trying to render shadows
	* In the deferred path, the shadowmap was still being rendered and only the projection skipped, now all cost will be skipped

Change 3219887 on 2016/12/02 by Daniel.Wright

	Changed ClearRenderTarget2D default alpha to 1, which is necessary for correct compositing

Change 3219893 on 2016/12/02 by Daniel.Wright

	AMD AGS library with approved TPS
	Disabled DFAO on AMD pre-GCN PC video cards to workaround a driver bug which won't be fixed (Radeon 6xxx and below)

Change 3219913 on 2016/12/02 by Daniel.Wright

	Level unload of a lighting scenario propagates the lighting scenario change - fixes crash when precomputed lighting volume data gets unloaded

Change 3220029 on 2016/12/02 by Daniel.Wright

	Async shader compiling now recreates scene proxies which are affected by the material which was compiled.  This fixes crashes which were occuring as proxies cache various material properties, but applying compiled materials would not update these cached properties (bRequiresAdjacencyInformation).
	* A new ensure has been added in FMeshElementCollector::AddMesh and FBatchingSPDI::DrawMesh to catch attempts to render with a material not reported in GetUsedMaterials
	* Fixed UParticleSystemComponent::GetUsedMaterials and UMaterialBillboardComponent::GetUsedMaterials
	* FMaterialUpdateContext should be changed to use the same pattern, but that hasn't been done yet

Change 3220108 on 2016/12/02 by Daniel.Wright

	Fixed shadowmap channel assignment for stationary lights which are not in a lighting scenario level, when a lighting scenario level is present

Change 3220504 on 2016/12/03 by Mark.Satterthwaite

	Metal Desktop Tessellation support from Unicorn.
	- Apple: Metal tessellation support added to MetalShaderFormat, MetalRHI and incl. changes to engine runtime/shaders for Desktop renderer and enabled in ElementalDemo by default (OS X 10.11 will run SM4).
	- Epic: Support for different Metal shader standards on Mac, iOS & tvOS which required moving some RHI functions around as this is a project setting and not a compile-time constant.
	- Epic: Fragment shader UAV support, which is also tied to newer Metal shader standard like Tessellation.
	- Epic: Significant refactor of MetalRHI's internals to clearly separate state-caching from render-pass management and command-encoding.
	- Epic: Internal MetalRHI validation code is now cleanly separated out into custom implementations of the Metal @protocol's and is on by default.
	- Epic: Various fixes to Layered Rendering for Metal.
	- Omits Mobile Tessellation support which needs further revision.

Change 3220881 on 2016/12/04 by Mark.Satterthwaite

	Compiles fixes for iOS & static analysis fixes from Windows.

Change 3221180 on 2016/12/05 by Guillaume.Abadie

	Avoid compiling PreviousFrameSwitch's both Current Frame and Previous Frame inputs every time.

Change 3221217 on 2016/12/05 by Chris.Bunner

	More NVAPI warning fixups.

Change 3221219 on 2016/12/05 by Chris.Bunner

	When comparing overriden properties used to force instance recompilation we need to check against the base material, not assume the immediate parent.
	#jira UE-37792

Change 3221220 on 2016/12/05 by Chris.Bunner

	Exported GetAllStaticSwitchParamNames and GetAllStaticComponentMaskParamNames.
	#jira UE-35132

Change 3221221 on 2016/12/05 by Chris.Bunner

	PR #2785: Fix comment typo in RendererInterface.h (Contributed by dustin-biser)
	#jira UE-35760

Change 3221223 on 2016/12/05 by Chris.Bunner

	Default to include dev-code when compiling material preview stats.
	#jira UE-20321

Change 3221534 on 2016/12/05 by Rolando.Caloca

	DR - Added FDynamicRHI::GetName()

Change 3221833 on 2016/12/05 by Chris.Bunner

	Set correct output extent on PostProcessUpscale (allows users to extend chain correctly).
	#jira UE-36989

Change 3221852 on 2016/12/05 by Chris.Bunner

	32-bit/ch EXR screenshot and frame dump output.
	Fixed row increment bug in 128-bit/px surface format readback.
	#jira UE-37962

Change 3222059 on 2016/12/05 by Rolando.Caloca

	DR - vk - Fix memory type not found

Change 3222104 on 2016/12/05 by Rolando.Caloca

	DR - Lambdaize
	- Added quicker method to check if system textures are initialized

Change 3222290 on 2016/12/05 by Mark.Satterthwaite

	Trivial fixes to reporting Metal shader pipeline errors - need to check if Hull & Domain exist.

Change 3222864 on 2016/12/06 by Rolando.Caloca

	DR - Fix mem leak when exiting

Change 3222873 on 2016/12/06 by Rolando.Caloca

	DR - vk - Minor info to help track down leaks

Change 3222875 on 2016/12/06 by Rolando.Caloca

	DR - Fix mem leak with VisualizeTexture
	#jira UE-39360

Change 3223226 on 2016/12/06 by Chris.Bunner

	Static analysis warning workaround.

Change 3223235 on 2016/12/06 by Ben.Woodhouse

	Integrate from NREAL: Set a custom projection matrix on a SceneCapture2D

Change 3223343 on 2016/12/06 by Chris.Bunner

	Moved HLOD persistent data to viewstate to fix per-view compatability.
	#jira UE-37539

Change 3223349 on 2016/12/06 by Chris.Bunner

	Fixed HLOD with FreezeRendering command.
	#jira UE-29839

Change 3223371 on 2016/12/06 by Michael.Trepka

	Removed obsolete check() in FMetalSurface constructor

Change 3223450 on 2016/12/06 by Chris.Bunner

	Added explicit ScRGB output device selection rather than Nvidia-only hardcoded checks. Allows easier support for Mac and other devices moving forward.

Change 3223638 on 2016/12/06 by Michael.Trepka

	Restored part of the check() in FMetalSurface constructor removed in CL 3223371

Change 3223642 on 2016/12/06 by Mark.Satterthwaite

	Experimental Metal EDR/HDR output support for Mac (iOS/tvOS need custom formats & shaders so they are not supported yet).
	- Only available on macOS Sierra (10.12) for Macs with HDR displays (e.g. Retina iMacs).
	- Enable with -metaledr command-line argument as it is off-by-default.
	- Sets up the CAMetalLayer & the back-buffer for RGBA_FP16 output on Mac using DCI-P3 as the color gamut and ACES 1000 nit ScRGB output encoding.

Change 3223830 on 2016/12/06 by Rolando.Caloca

	DR - vk - Better error when finding an invalid Vulkan driver
	#jira UE-37495

Change 3223869 on 2016/12/06 by Rolando.Caloca

	DR - vk - Reuse fences

Change 3223906 on 2016/12/06 by Guillaume.Abadie

	Fix alpha through TempAA artifact causing a small darker edge layouts.

Change 3224199 on 2016/12/06 by Mark.Satterthwaite

	Fix a dumb copy-paste error from the HDR changes to Metal.

Change 3224220 on 2016/12/06 by Mark.Satterthwaite

	Fix various errors with Metal UAV & Render-Pass Restart support so that we can use the Pixel Shader culling for DistanceField effects.
	- Unfortunately Metal requires that a texture be bound to start a render-pass, so reuse the dummy depth-stencil surface from the problematic editor preview tile rendering.

Change 3224236 on 2016/12/06 by Mark.Satterthwaite

	IWYU CIS compile fix for iOS.

Change 3224366 on 2016/12/06 by Mark.Satterthwaite

	Simplify some of the changes from CL# 3224220 so that we don't perform unnecessary clears.
	- If the RenderPass is broken to issue compute or blit operations then treat the cached RenderTargetsInfo as invalid, unless the RenderPass is restarted.
	- This guarantees that we don't erroneously ignore calls to SetRenderTargets if the calling code issues a dispatch between two RenderPasses that use the same RenderTargetsInfo.

Change 3224416 on 2016/12/06 by Uriel.Doyon

	New default implementation for UPrimitiveComponent::GetStreamingTextureInfo using a conservative heuristic where the textures are stretched across the bounds.
	Optimized UPrimitiveComponent::GetStreamingTextureInfoWithNULLRemoval by not handling registered components with no proxy (essentially hidden game / collision primitives).

	Added blueprint support for texture streaming built data through FStaticMeshComponentInstanceData.

	Fix for material texture streaming data not being available on some cooked builds.

	Enabled split requests on all texture load requests (first loading everything visible and then loaded everything not visible).
	This is controlled by "r.Streaming.MinMipForSplitRequest" which defines the minimum mip for which to allow splitting.
	Forced residency are now loaded in two steps (visible, then forced), improving reactiveness.

	Updated "stat streaming" to include "UnkownRefMips" which represent texture with no known component referencing them,
	and also "LastRenderTimeMips" which related to timed primitives.
	Changed "Forced Mips" so that it only shows mips that are loaded become of forced residency.

	"Texture Streaming Build" now updates the map check after execution.

	Removed Orphaned texture logic as this has  become irrelevant with the latest retention priority logic.

	Updated "r.streaming.usenewmetrics" so that it shows behavior before and after 4.12 improvements.

Change 3224532 on 2016/12/07 by Uriel.Doyon

	Integrated CL 3223965 :

	Building texture streaming data for materials does not wait for pending shaders to finish compilation anymore.
	Added more options to allow the user to cancel this build also.

Change 3224714 on 2016/12/07 by Ben.Woodhouse

	Cherry pick CL 3223972 from //fortnite/main:

	Disable Geometry shader onchip on XB1. This saves 4ms for a single shadow casting point light @ 512x512 (4.8ms to 1.8ms)

Change 3224715 on 2016/12/07 by Ben.Woodhouse

	New version of d3dx12.h from Microsoft which incorporates my suggested static analysis fixes. This avoids us diverging from the official version

Change 3224975 on 2016/12/07 by Rolando.Caloca

	DR - vk - Dump improvements

Change 3225012 on 2016/12/07 by Rolando.Caloca

	DR - Show warning if trying to use num samples != (1,2,4,8,16)

Change 3225126 on 2016/12/07 by Chris.Bunner

	Added 'force 128-bit rendering pipeline' to high-res screenshot tool.
	#jira UE-39345

Change 3225449 on 2016/12/07 by Chris.Bunner

	Updated engine rendering defaults to better match current best practices.
	#jira UE-38081

Change 3225485 on 2016/12/07 by Chris.Bunner

	Moved QuantizeSceneBufferSize to RenderCore and added call for PostProcess settings. Fixes screenpercentage out-of-bounds reads in some cases.
	#jira UE-19394

Change 3225486 on 2016/12/07 by Chris.Bunner

	Only disable TAA during HighResScreenshots if we don't have a reasonable frame-delay enabled.

Change 3225505 on 2016/12/07 by Daniel.Wright

	Fixed exponential height fog disappearing with no skybox

Change 3225655 on 2016/12/07 by Benjamin.Hyder

	Updating TM-Shadermodels to include Translucent lighting, Two sided, updated cloth animation, and adjusted lighting.

Change 3225668 on 2016/12/07 by Chris.Bunner

	Dirty owning packages when user manually forces regeneration of all reflection captures.
	#jira UE-38759

Change 3226139 on 2016/12/07 by Rolando.Caloca

	DR - Fix recompute tangents disabling skin cache
	- Make some macros into lambdas
	#jira UE-39143

Change 3226212 on 2016/12/07 by Daniel.Wright

	Features which require a full prepass use DDM_AllOpaque instead of DDM_AllOccluders, which can be skipped if the component has bUseAsOccluder=false

Change 3226213 on 2016/12/07 by Daniel.Wright

	Scene Capture 2D can specify a global clip plane, which is useful for portals
	* Requires the global clip plane project setting to be enabled

Change 3226214 on 2016/12/07 by Daniel.Wright

	Improved deferred shadowing with MSAA by upsampling light attenuation intelligently in the base pass
	* If the current fragment's depth doesn't match what was used for deferred shadowing, the neighbor (cross pattern) with the nearest depth's shadowing is used
	* Edge artifacts can still occur where the upsample fails or the shadow factor was computed per-sample due to depth / stencil testing
	* Indirect Occlusion from capsule shadows also uses the nearest depth neighbor UV for no extra cost
	* Base pass on 970 GTX 1.69ms -> 1.85ms (.16ms) in RoboRecall

Change 3226258 on 2016/12/07 by Rolando.Caloca

	DR - Typo fix

Change 3226259 on 2016/12/07 by Rolando.Caloca

	DR - compile fix
	#jira UE-39143

Change 3226932 on 2016/12/08 by Chris.Bunner

	Re-saved Infiltrator maps to update reflection captures.
	#jira UE-38759

Change 3227063 on 2016/12/08 by Mark.Satterthwaite

	For Metal platforms ONLY temporarily disable USE_LIGHT_GRID_REFLECTION_CAPTURE_CULLING to avoid UE-37436 while the Nvidia driver team investigate why this doesn't work for them but does for the others. This won't affect non-Metal platforms and the intent is to revert this prior to 4.16 provided we can work through the problem with Nvidia.
	#jira UE-37436

Change 3227120 on 2016/12/08 by Gil.Gribb

	Merging //UE4/Dev-Main@3226895 to Dev-Rendering (//UE4/Dev-Rendering)

Change 3227211 on 2016/12/08 by Arne.Schober

	DR - UE-38585 - Fixing crash where HierInstStaticMesh duplication fails. Also reverting the fix from UE-28189 which is redundant.

Change 3227257 on 2016/12/08 by Marc.Olano

	Extension to PseudoVolumeTexture for more flexible layout
	Change by ryan.brucks

Change 3227286 on 2016/12/08 by Rolando.Caloca

	DR - Fix crash when using custom expressions and using reserved keywords
	#jira UE-39311

Change 3227376 on 2016/12/08 by Mark.Satterthwaite

	Must not include a private header inside the MenuStack public header as that causes compile errors in plugins.

Change 3227415 on 2016/12/08 by Mark.Satterthwaite

	Fix shader compilation due to my disabling of USE_LIGHT_GRID_REFLECTION_CAPTURE_CULLING on Metal - InstancedCompositeTileReflectionCaptureIndices needs to be defined even though Metal doesn't support instanced-stereo rendering.

Change 3227516 on 2016/12/08 by Daniel.Wright

	Implemented UWidgetComponent::GetUsedMaterials

Change 3227521 on 2016/12/08 by Guillaume.Abadie

	Fixes post process volume's indirect lighting color.

	#jira UE-38888

Change 3227567 on 2016/12/08 by Marc.Olano

	New upscale filters: Lanczos-2 (new default), Lanczos-3 and Gaussian Unsharp Mask

Change 3227628 on 2016/12/08 by Daniel.Wright

	Removed redundant ResolveSceneDepthTexture from the merge

Change 3227635 on 2016/12/08 by Daniel.Wright

	Forward renderer supports shadowing from movable lights and light functions
	* Only 4 shadow casting movable or stationary lights can overlap at any point in space, otherwise the movable lights will lose their shadows and an on-screen message will be displayed
	* Light functions only work on shadow casting lights since they need a shadowmap channel to be assigned

Change 3227660 on 2016/12/08 by Rolando.Caloca

	DR - vk - Fix r.MobileMSAA on Vulkan
	- r.MobileMSAA is now read-only (to be fixed on 4.16)
	- Show time for PSO creation hitches
	#jira UE-39184

Change 3227704 on 2016/12/08 by Mark.Satterthwaite

	Fix Mac HDR causing incorrect output color encoding being used, HDR support is now entirely off unless you pass -metaledr which will enable it regardless of whether the current display supports HDR (as we haven't written the detection code yet). Fixed the LUT/UI compositing along the way - Mac Metal wasn't using volume LUT as it should have been, RHISupportsVertexShaderLayer now correctly returns false for non-Mac Metal platforms.

Change 3227705 on 2016/12/08 by Daniel.Wright

	Replaced built-in samplers in the nearest depth translucency upsample because the built-in samplers are no longer bound on PC (cl 2852426)

Change 3227787 on 2016/12/08 by Chris.Bunner

	Added extent clear to motion blur pass to catch misized buffers bringing in errors.
	Added early out to clear call when excluded region matches RT region.
	#jira UE-39437

Change 3228177 on 2016/12/08 by Marc.Olano

	Fix DCC sqrt(int) error

Change 3228285 on 2016/12/08 by Chris.Bunner

	Back out changelist 3225449.
	#jira UE-39528

Change 3228680 on 2016/12/09 by Gil.Gribb

	Merging //UE4/Dev-Main@3228528 to Dev-Rendering (//UE4/Dev-Rendering)

Change 3228940 on 2016/12/09 by Mark.Satterthwaite

	Editor fixes for 4.15:
	- PostProcessTonemap can't fail to bind a texture to the ColorLUT or the subsequent rendering will be garbage: the changes for optimising stereo rendering forgot to account for the Editor's use of Views without States for the asset preview thumbnails. Amended the CombineLUT post-processing to allocate a local output texture when there's no ViewState and read from this when this situation arises which makes everything function again.
	- Don't start render-passes without a valid render-target-array in MetalRHI.

Change 3228950 on 2016/12/09 by Mark.Satterthwaite

	Make GPUSkinCache run on Mac Metal - it wasn't working because it was forcibly disabled on all platforms but for Windows D3D 11.
	- Fixed the Skeleton editor tree trying to access a widget before it has been constructed.
	- Enable GPUSkinCache for Metal SM5: doesn't render correctly, even on AMD, so needs Radar's filing and investigation.
	#jira UE-39256

Change 3229013 on 2016/12/09 by Mark.Satterthwaite

	Further tidy up in SSkeletonTreeView as suggested by Nick.A.

Change 3229101 on 2016/12/09 by Chris.Bunner

	Log compile error fix and updated cvar comments.

Change 3229236 on 2016/12/09 by Ben.Woodhouse

	XB1 D3D11 and D3D12: Use the DXGI frame statistics to get accurate GPU time unaffected by bubbles

Change 3229430 on 2016/12/09 by Ben.Woodhouse

	PR #2680: Optimized histogram generation. (Contributed by PjotrSvetachov)

	Profiled on nvidia 980GTX (2x faster), and on XB1 (marginally faster)

Change 3229580 on 2016/12/09 by Marcus.Wassmer

	DepthBoundsTest for AMD.

Change 3229701 on 2016/12/09 by Michael.Trepka

	Changed "OS X" to "macOS" in few places where we display it and updated the code that asks users to update to latest version to check for 10.12.2

Change 3229706 on 2016/12/09 by Chris.Bunner

	Added GameUserSettings controls for HDR display output.
	Removed Metal commandline as this should replace the need for it.

Change 3229774 on 2016/12/09 by Michael.Trepka

	Disabled OpenGL on Mac. -opengl is now ignored, we always use Metal. On old Macs that do not support Metal we show a message saying that the app requires Metal and exit.

Change 3229819 on 2016/12/09 by Chris.Bunner

	Updated engine rendering defaults to better match current best practices.
	#jira UE-38081

Change 3229948 on 2016/12/09 by Rolando.Caloca

	DR - Fix d3d debug error
	#jira UE-39589

Change 3230341 on 2016/12/11 by Mark.Satterthwaite

	Don't fatally assert that the game-thread stalled waiting for the rendering thread in the Editor executable, even when running -game as the rendering thread can take a while to respond if shaders need to be compiled.
	#jira UE-39613

Change 3230860 on 2016/12/12 by Marcus.Wassmer

	Experimental Nvidia AFR support.

Change 3230930 on 2016/12/12 by Mark.Satterthwaite

	Disable RHICmdList state-caching on Mac - Metal already does this internally and depends on receiving all state changes in order to function.

Change 3231252 on 2016/12/12 by Marcus.Wassmer

	Fix NumGPU detection. (SLI only crash)

Change 3231486 on 2016/12/12 by Mark.Satterthwaite

	Fix a stupid mistake in MetalStateCache::CommitResourceTable that would unnecessarily rebind samplers.

Change 3231661 on 2016/12/12 by Mark.Satterthwaite

	Retain the RHI samplers in MetalRHI to guarantee lifetime.

[CL 3231696 by Gil Gribb in Main branch]
2016-12-12 17:47:42 -05:00

1038 lines
33 KiB
C++

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
VisualizeTexture.cpp: Post processing visualize texture.
=============================================================================*/
#include "PostProcess/VisualizeTexture.h"
#include "ShaderParameters.h"
#include "RHIStaticStates.h"
#include "Shader.h"
#include "StaticBoundShaderState.h"
#include "SceneUtils.h"
#include "HAL/FileManager.h"
#include "Misc/FileHelper.h"
#include "Misc/Paths.h"
#include "Misc/App.h"
#include "CanvasTypes.h"
#include "UnrealEngine.h"
#include "PostProcess/RenderTargetPool.h"
#include "PostProcess/SceneRenderTargets.h"
#include "GlobalShader.h"
#include "RenderTargetTemp.h"
#include "ScreenRendering.h"
#include "PostProcess/SceneFilterRendering.h"
#include "PostProcess/PostProcessing.h"
/** A pixel shader which filters a texture. */
// @param TextureType 0:Cube, 1:1D(not yet supported), 2:2D no MSAA, 3:3D, 4:Cube[], 5:2D MSAA, 6:2D DepthStencil no MSAA (needed to avoid D3DDebug error)
template<uint32 TextureType>
class VisualizeTexturePS : public FGlobalShader
{
DECLARE_SHADER_TYPE(VisualizeTexturePS,Global);
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return true;
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform, OutEnvironment);
OutEnvironment.SetDefine(TEXT("TEXTURE_TYPE"), TextureType);
}
/** Default constructor. */
VisualizeTexturePS() {}
/** Initialization constructor. */
VisualizeTexturePS(const ShaderMetaType::CompiledShaderInitializerType& Initializer):
FGlobalShader(Initializer)
{
VisualizeTexture2D.Bind(Initializer.ParameterMap,TEXT("VisualizeTexture2D"));
VisualizeDepthStencilTexture.Bind(Initializer.ParameterMap, TEXT("VisualizeDepthStencilTexture"));
VisualizeTexture2DSampler.Bind(Initializer.ParameterMap,TEXT("VisualizeTexture2DSampler"));
VisualizeTexture2DMS.Bind(Initializer.ParameterMap,TEXT("VisualizeTexture2DMS"));
VisualizeTexture3D.Bind(Initializer.ParameterMap,TEXT("VisualizeTexture3D"));
VisualizeTexture3DSampler.Bind(Initializer.ParameterMap,TEXT("VisualizeTexture3DSampler"));
VisualizeTextureCube.Bind(Initializer.ParameterMap,TEXT("VisualizeTextureCube"));
VisualizeTextureCubeSampler.Bind(Initializer.ParameterMap,TEXT("VisualizeTextureCubeSampler"));
VisualizeTextureCubeArray.Bind(Initializer.ParameterMap,TEXT("VisualizeTextureCubeArray"));
VisualizeTextureCubeArraySampler.Bind(Initializer.ParameterMap,TEXT("VisualizeTextureCubeArraySampler"));
VisualizeParam.Bind(Initializer.ParameterMap,TEXT("VisualizeParam"));
TextureExtent.Bind(Initializer.ParameterMap,TEXT("TextureExtent"));
}
/** Serializer */
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << VisualizeTexture2D;
Ar << VisualizeDepthStencilTexture;
Ar << VisualizeTexture2DSampler;
Ar << VisualizeTexture2DMS;
Ar << VisualizeTexture3D;
Ar << VisualizeTexture3DSampler;
Ar << VisualizeTextureCube;
Ar << VisualizeTextureCubeSampler;
Ar << VisualizeTextureCubeArray;
Ar << VisualizeTextureCubeArraySampler;
Ar << VisualizeParam;
Ar << TextureExtent;
return bShaderHasOutdatedParameters;
}
void SetParameters(FRHICommandList& RHICmdList, const FVisualizeTextureData& Data)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
{
// alternates between 0 and 1 with a short pause
const float FracTimeScale = 2.0f;
float FracTime = FApp::GetCurrentTime() * FracTimeScale - floor(FApp::GetCurrentTime() * FracTimeScale);
float BlinkState = (FracTime > 0.5f) ? 1.0f : 0.0f;
FVector4 VisualizeParamValue[3];
float Add = 0.0f;
float FracScale = 1.0f;
// w * almost_1 to avoid frac(1) => 0
VisualizeParamValue[0] = FVector4(Data.RGBMul, Data.SingleChannelMul, Add, FracScale * 0.9999f);
VisualizeParamValue[1] = FVector4(BlinkState, Data.bSaturateInsteadOfFrac ? 1.0f : 0.0f, Data.ArrayIndex, Data.CustomMip);
VisualizeParamValue[2] = FVector4(Data.InputValueMapping, 0.0f, Data.SingleChannel );
SetShaderValueArray(RHICmdList, ShaderRHI, VisualizeParam, VisualizeParamValue, 3);
}
{
FVector4 TextureExtentValue(Data.Desc.Extent.X, Data.Desc.Extent.Y, Data.Desc.Depth, 0);
SetShaderValue(RHICmdList, ShaderRHI, TextureExtent, TextureExtentValue);
}
SetSRVParameter(RHICmdList, ShaderRHI, VisualizeDepthStencilTexture, Data.StencilSRV );
SetTextureParameter(RHICmdList, ShaderRHI, VisualizeTexture2D, VisualizeTexture2DSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), (FTextureRHIRef&)Data.RenderTargetItem.ShaderResourceTexture);
SetTextureParameter(RHICmdList, ShaderRHI, VisualizeTexture2DMS, (FTextureRHIRef&)Data.RenderTargetItem.TargetableTexture);
SetTextureParameter(RHICmdList, ShaderRHI, VisualizeTexture3D, VisualizeTexture3DSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), (FTextureRHIRef&)Data.RenderTargetItem.ShaderResourceTexture);
SetTextureParameter(RHICmdList, ShaderRHI, VisualizeTextureCube, VisualizeTextureCubeSampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), (FTextureRHIRef&)Data.RenderTargetItem.ShaderResourceTexture);
SetTextureParameter(RHICmdList, ShaderRHI, VisualizeTextureCubeArray, VisualizeTextureCubeArraySampler, TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), (FTextureRHIRef&)Data.RenderTargetItem.ShaderResourceTexture);
}
static const TCHAR* GetSourceFilename()
{
return TEXT("VisualizeTexture");
}
static const TCHAR* GetFunctionName()
{
return TEXT("VisualizeTexturePS");
}
protected:
FShaderResourceParameter VisualizeTexture2D;
FShaderResourceParameter VisualizeDepthStencilTexture;
FShaderResourceParameter VisualizeTexture2DSampler;
FShaderResourceParameter VisualizeTexture2DMS;
FShaderResourceParameter VisualizeTexture3D;
FShaderResourceParameter VisualizeTexture3DSampler;
FShaderResourceParameter VisualizeTextureCube;
FShaderResourceParameter VisualizeTextureCubeSampler;
FShaderResourceParameter VisualizeTextureCubeArray;
FShaderResourceParameter VisualizeTextureCubeArraySampler;
FShaderParameter VisualizeParam;
FShaderParameter TextureExtent;
};
// #define avoids a lot of code duplication
#define VARIATION1(A) typedef VisualizeTexturePS<A> VisualizeTexturePS##A; \
IMPLEMENT_SHADER_TYPE2(VisualizeTexturePS##A, SF_Pixel);
VARIATION1(0) VARIATION1(2) VARIATION1(3) VARIATION1(4) VARIATION1(5) VARIATION1(6)
#undef VARIATION1
/** Encapsulates a simple copy pixel shader. */
class FVisualizeTexturePresentPS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FVisualizeTexturePresentPS, Global);
static bool ShouldCache(EShaderPlatform Platform)
{
return true;
}
/** Default constructor. */
FVisualizeTexturePresentPS() {}
public:
FShaderResourceParameter VisualizeTexture2D;
FShaderResourceParameter VisualizeTexture2DSampler;
/** Initialization constructor. */
FVisualizeTexturePresentPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
VisualizeTexture2D.Bind(Initializer.ParameterMap,TEXT("VisualizeTexture2D"));
VisualizeTexture2DSampler.Bind(Initializer.ParameterMap,TEXT("VisualizeTexture2DSampler"));
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << VisualizeTexture2D << VisualizeTexture2DSampler;
return bShaderHasOutdatedParameters;
}
void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, const IPooledRenderTarget& Src)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters(RHICmdList, ShaderRHI, View);
SetTextureParameter(RHICmdList, ShaderRHI, VisualizeTexture2D, VisualizeTexture2DSampler,
TStaticSamplerState<SF_Point,AM_Clamp,AM_Clamp,AM_Clamp>::GetRHI(), (FTextureRHIRef&)Src.GetRenderTargetItem().ShaderResourceTexture);
}
};
IMPLEMENT_SHADER_TYPE(,FVisualizeTexturePresentPS,TEXT("VisualizeTexture"),TEXT("PresentPS"),SF_Pixel);
template<uint32 TextureType> void VisualizeTextureForTextureType(FRHICommandList& RHICmdList, ERHIFeatureLevel::Type FeatureLevel, const FVisualizeTextureData& Data)
{
auto ShaderMap = GetGlobalShaderMap(FeatureLevel);
TShaderMapRef<FScreenVS> VertexShader(ShaderMap);
TShaderMapRef<VisualizeTexturePS<TextureType> > PixelShader(ShaderMap);
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(RHICmdList, FeatureLevel, BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
PixelShader->SetParameters(RHICmdList, Data);
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
DrawRectangle(
RHICmdList,
// XY
0, 0,
// SizeXY
SceneContext.GetBufferSizeXY().X, SceneContext.GetBufferSizeXY().Y,
// UV
Data.Tex00.X, Data.Tex00.Y,
// SizeUV
Data.Tex11.X - Data.Tex00.X, Data.Tex11.Y - Data.Tex00.Y,
// TargetSize
SceneContext.GetBufferSizeXY(),
// TextureSize
FIntPoint(1, 1),
*VertexShader,
EDRF_UseTriangleOptimization);
}
void RenderVisualizeTexture(FRHICommandListImmediate& RHICmdList, ERHIFeatureLevel::Type FeatureLevel, const FVisualizeTextureData& Data)
{
RHICmdList.CopyToResolveTarget(Data.RenderTargetItem.ShaderResourceTexture, Data.RenderTargetItem.ShaderResourceTexture, true, FResolveParams());
if(Data.Desc.Is2DTexture())
{
// 2D
if(Data.Desc.NumSamples > 1)
{
// MSAA
VisualizeTextureForTextureType<5>(RHICmdList, FeatureLevel, Data);
}
else
{
if(Data.Desc.Format == PF_DepthStencil)
{
// DepthStencil non MSAA (needed to avoid D3DDebug error)
VisualizeTextureForTextureType<6>(RHICmdList, FeatureLevel, Data);
}
else
{
// non MSAA
VisualizeTextureForTextureType<2>(RHICmdList, FeatureLevel, Data);
}
}
}
else if(Data.Desc.Is3DTexture())
{
VisualizeTextureForTextureType<3>(RHICmdList, FeatureLevel, Data);
}
else if(Data.Desc.IsCubemap())
{
if(Data.Desc.IsArray())
{
// Cube[]
VisualizeTextureForTextureType<4>(RHICmdList, FeatureLevel, Data);
}
else
{
// Cube
VisualizeTextureForTextureType<0>(RHICmdList, FeatureLevel, Data);
}
}
}
FVisualizeTexture::FVisualizeTexture()
{
Mode = 0;
RGBMul = 1.0f;
SingleChannelMul = 0.0f;
SingleChannel = -1;
AMul = 0.0f;
UVInputMapping = 3;
Flags = 0;
ObservedDebugNameReusedGoal = 0xffffffff;
ArrayIndex = 0;
CustomMip = 0;
bSaveBitmap = false;
bOutputStencil = false;
bFullList = false;
SortOrder = -1;
bEnabled = true;
}
void FVisualizeTexture::Destroy()
{
VisualizeTextureContent.SafeRelease();
StencilSRV.SafeRelease();
}
FIntRect FVisualizeTexture::ComputeVisualizeTextureRect(FIntPoint InputTextureSize) const
{
FIntRect ret = ViewRect;
FIntPoint ViewExtent = ViewRect.Size();
// set ViewRect
switch(UVInputMapping)
{
// pixel perfect centered (not yet for volume textures)
case 2:
{
FIntPoint Center = ViewExtent / 2;
FIntPoint HalfMin = InputTextureSize / 2;
FIntPoint HalfMax = InputTextureSize - HalfMin;
ret = FIntRect(Center - HalfMin, Center + HalfMax);
break;
}
// whole texture in PIP
case 3:
{
int32 LeftOffset = AspectRatioConstrainedViewRect.Min.X;
int32 BottomOffset = AspectRatioConstrainedViewRect.Max.Y - ViewRect.Max.Y;
ret = FIntRect(LeftOffset + 80, ViewExtent.Y - ViewExtent.Y / 3 - 10 + BottomOffset, ViewExtent.X / 3 + 10, ViewExtent.Y - 10 + BottomOffset) + ViewRect.Min;
break;
}
default:
{
break;
}
}
return ret;
}
void FVisualizeTexture::GenerateContent(FRHICommandListImmediate& RHICmdList, const FSceneRenderTargetItem& RenderTargetItem, const FPooledRenderTargetDesc& Desc)
{
// otherwise StartFrame() wasn't called
check(ViewRect != FIntRect(0, 0, 0, 0))
FTexture2DRHIRef VisTexture = (FTexture2DRHIRef&)RenderTargetItem.ShaderResourceTexture;
if(!IsValidRef(VisTexture) || !Desc.IsValid())
{
// todo: improve
return;
}
FIntRect VisualizeTextureRect = ComputeVisualizeTextureRect(Desc.Extent);
FIntPoint Size = VisualizeTextureRect.Size();
// clamp to reasonable value to prevent crash
Size.X = FMath::Max(Size.X, 1);
Size.Y = FMath::Max(Size.Y, 1);
FPooledRenderTargetDesc OutputDesc(FPooledRenderTargetDesc::Create2DDesc(Size, PF_B8G8R8A8, FClearValueBinding::None, TexCreate_None, TexCreate_RenderTargetable | TexCreate_ShaderResource, false));
GRenderTargetPool.FindFreeElement(RHICmdList, OutputDesc, VisualizeTextureContent, TEXT("VisualizeTexture"));
if(!VisualizeTextureContent)
{
return;
}
const FSceneRenderTargetItem& DestRenderTarget = VisualizeTextureContent->GetRenderTargetItem();
SetRenderTarget(RHICmdList, DestRenderTarget.TargetableTexture, FTextureRHIRef(), true);
RHICmdList.ClearColorTexture(DestRenderTarget.TargetableTexture, FLinearColor(1, 1, 0, 1), FIntRect());
RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
FIntPoint RTExtent = FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY();
FVector2D Tex00 = FVector2D(0, 0);
FVector2D Tex11 = FVector2D(1, 1);
uint32 LocalVisualizeTextureInputMapping = UVInputMapping;
if(!Desc.Is2DTexture())
{
LocalVisualizeTextureInputMapping = 1;
}
// set UV
switch(LocalVisualizeTextureInputMapping)
{
// UV in left top
case 0:
Tex11 = FVector2D((float)ViewRect.Width() / RTExtent.X, (float)ViewRect.Height() / RTExtent.Y);
break;
// whole texture
default:
break;
}
bool bIsDefault = StencilSRVSrc == GBlackTexture->TextureRHI;
bool bDepthStencil = Desc.Is2DTexture() && Desc.Format == PF_DepthStencil;
//clear if this is a new different Stencil buffer, or it's not a stencil buffer and we haven't switched to the default yet.
bool bNeedsClear = bDepthStencil && (StencilSRVSrc != RenderTargetItem.TargetableTexture);
bNeedsClear |= !bDepthStencil && !bIsDefault;
if (bNeedsClear)
{
StencilSRVSrc = nullptr;
StencilSRV.SafeRelease();
}
//always set something into the StencilSRV slot for platforms that require a full resource binding, even if
//dynamic branching will cause them not to be used.
if(bDepthStencil && !StencilSRVSrc)
{
StencilSRVSrc = RenderTargetItem.TargetableTexture;
StencilSRV = RHICreateShaderResourceView((FTexture2DRHIRef&) RenderTargetItem.TargetableTexture, 0, 1, PF_X24_G8);
}
else if(!StencilSRVSrc)
{
StencilSRVSrc = GBlackTexture->TextureRHI;
StencilSRV = RHICreateShaderResourceView((FTexture2DRHIRef&) GBlackTexture->TextureRHI, 0, 1, PF_B8G8R8A8);
}
FVisualizeTextureData VisualizeTextureData(RenderTargetItem, Desc);
// distinguish between standard depth and shadow depth to produce more reasonable default value mapping in the pixel shader.
const bool bDepthTexture = (Desc.TargetableFlags & TexCreate_DepthStencilTargetable) != 0;
const bool bShadowDepth = (Desc.Format == PF_ShadowDepth);
VisualizeTextureData.RGBMul = RGBMul;
VisualizeTextureData.SingleChannelMul = SingleChannelMul;
VisualizeTextureData.SingleChannel = SingleChannel;
VisualizeTextureData.AMul = AMul;
VisualizeTextureData.Tex00 = Tex00;
VisualizeTextureData.Tex11 = Tex11;
VisualizeTextureData.bSaturateInsteadOfFrac = (Flags & 1) != 0;
VisualizeTextureData.InputValueMapping = bShadowDepth ? 2 : (bDepthTexture ? 1 : 0);
VisualizeTextureData.ArrayIndex = ArrayIndex;
VisualizeTextureData.CustomMip = CustomMip;
VisualizeTextureData.StencilSRV = StencilSRV;
if(!(Desc.Flags & TexCreate_CPUReadback)) // We cannot make a texture lookup on such elements
{
SCOPED_DRAW_EVENT(RHICmdList, VisualizeTexture);
// continue rendering to HDR if necessary
RenderVisualizeTexture(RHICmdList, FeatureLevel, VisualizeTextureData);
}
{
SCOPED_DRAW_EVENT(RHICmdList, VisCopy);
RHICmdList.CopyToResolveTarget(DestRenderTarget.TargetableTexture, DestRenderTarget.ShaderResourceTexture, false, FResolveParams());
}
VisualizeTextureDesc = Desc;
// save to disk
if(bSaveBitmap)
{
bSaveBitmap = false;
uint32 MipAdjustedExtentX = FMath::Clamp(Desc.Extent.X >> CustomMip, 0, Desc.Extent.X);
uint32 MipAdjustedExtentY = FMath::Clamp(Desc.Extent.Y >> CustomMip, 0, Desc.Extent.Y);
FIntPoint Extent(MipAdjustedExtentX, MipAdjustedExtentY);
FReadSurfaceDataFlags ReadDataFlags;
ReadDataFlags.SetLinearToGamma(false);
ReadDataFlags.SetOutputStencil(bOutputStencil);
ReadDataFlags.SetMip(CustomMip);
FTextureRHIRef Texture = RenderTargetItem.TargetableTexture ? RenderTargetItem.TargetableTexture : RenderTargetItem.ShaderResourceTexture;
check(Texture);
TArray<FColor> Bitmap;
RHICmdList.ReadSurfaceData(Texture, FIntRect(0, 0, Extent.X, Extent.Y), Bitmap, ReadDataFlags);
// if the format and texture type is supported
if(Bitmap.Num())
{
// Create screenshot folder if not already present.
IFileManager::Get().MakeDirectory(*FPaths::ScreenShotDir(), true);
const FString ScreenFileName(FPaths::ScreenShotDir() / TEXT("VisualizeTexture"));
uint32 ExtendXWithMSAA = Bitmap.Num() / Extent.Y;
// Save the contents of the array to a bitmap file. (24bit only so alpha channel is dropped)
FFileHelper::CreateBitmap(*ScreenFileName, ExtendXWithMSAA, Extent.Y, Bitmap.GetData());
UE_LOG(LogConsoleResponse, Display, TEXT("Content was saved to \"%s\""), *FPaths::ScreenShotDir());
}
else
{
UE_LOG(LogConsoleResponse, Error, TEXT("Failed to save BMP for VisualizeTexture, format or texture type is not supported"));
}
}
}
void FVisualizeTexture::PresentContent(FRHICommandListImmediate& RHICmdList, const FViewInfo& View)
{
if(Mode != 0)
{
// old mode is used, lets copy the specified texture to do it similar to the new system
FPooledRenderTarget* Element = GRenderTargetPool.GetElementById(Mode - 1);
if(Element)
{
GenerateContent(RHICmdList, Element->GetRenderTargetItem(), Element->GetDesc());
}
}
const FTexture2DRHIRef& RenderTargetTexture = View.Family->RenderTarget->GetRenderTargetTexture();
if(!VisualizeTextureContent
|| !IsValidRef(RenderTargetTexture)
|| !bEnabled)
{
// visualize feature is deactivated
return;
}
FPooledRenderTargetDesc Desc = VisualizeTextureDesc;
auto& RenderTarget = View.Family->RenderTarget->GetRenderTargetTexture();
SetRenderTarget(RHICmdList, RenderTarget, FTextureRHIRef(), true);
RHICmdList.SetViewport(0, 0, 0.0f, RenderTarget->GetSizeX(), RenderTarget->GetSizeY(), 1.0f);
RHICmdList.SetBlendState(TStaticBlendState<>::GetRHI());
RHICmdList.SetRasterizerState(TStaticRasterizerState<>::GetRHI());
RHICmdList.SetDepthStencilState(TStaticDepthStencilState<false, CF_Always>::GetRHI());
auto ShaderMap = View.ShaderMap;
TShaderMapRef<FPostProcessVS> VertexShader(ShaderMap);
TShaderMapRef<FVisualizeTexturePresentPS> PixelShader(ShaderMap);
static FGlobalBoundShaderState BoundShaderState;
SetGlobalBoundShaderState(RHICmdList, FeatureLevel, BoundShaderState, GFilterVertexDeclaration.VertexDeclarationRHI, *VertexShader, *PixelShader);
VertexShader->SetParameters(RHICmdList, View);
PixelShader->SetParameters(RHICmdList, View, *VisualizeTextureContent);
FIntRect DestRect = View.ViewRect;
FIntRect VisualizeTextureRect = ComputeVisualizeTextureRect(Desc.Extent);
{
SCOPED_DRAW_EVENT(RHICmdList, VisCopyToMain);
// Draw a quad mapping scene color to the view's render target
DrawRectangle(
RHICmdList,
VisualizeTextureRect.Min.X, VisualizeTextureRect.Min.Y,
VisualizeTextureRect.Width(), VisualizeTextureRect.Height(),
0, 0,
VisualizeTextureRect.Width(), VisualizeTextureRect.Height(),
FIntPoint(RenderTarget->GetSizeX(), RenderTarget->GetSizeY()),
VisualizeTextureRect.Size(),
*VertexShader,
EDRF_Default);
}
FRenderTargetTemp TempRenderTarget(View, View.UnscaledViewRect.Size());
FCanvas Canvas(&TempRenderTarget, NULL, View.Family->CurrentRealTime, View.Family->CurrentWorldTime, View.Family->DeltaWorldTime, View.GetFeatureLevel());
float X = 100 + View.ViewRect.Min.X;
float Y = 160 + View.ViewRect.Min.Y;
float YStep = 14;
{
uint32 ReuseCount = ObservedDebugNameReusedCurrent;
FString ExtendedName;
if(ReuseCount)
{
uint32 ReuseGoal = FMath::Min(ReuseCount - 1, ObservedDebugNameReusedGoal);
// was reused this frame
ExtendedName = FString::Printf(TEXT("%s@%d @0..%d"), Desc.DebugName, ReuseGoal, ReuseCount - 1);
}
else
{
// was not reused this frame but can be referenced
ExtendedName = FString::Printf(TEXT("%s"), Desc.DebugName);
}
FString Channels = TEXT("RGB");
switch( SingleChannel )
{
case 0: Channels = TEXT("R"); break;
case 1: Channels = TEXT("G"); break;
case 2: Channels = TEXT("B"); break;
case 3: Channels = TEXT("A"); break;
}
float Multiplier = ( SingleChannel == -1 ) ? RGBMul : SingleChannelMul;
FString Line = FString::Printf(TEXT("VisualizeTexture: %d \"%s\" %s*%g UV%d"),
Mode,
*ExtendedName,
*Channels,
Multiplier,
UVInputMapping);
Canvas.DrawShadowedString( X, Y += YStep, *Line, GetStatsFont(), FLinearColor(1, 1, 1));
}
{
FString Line = FString::Printf(TEXT(" TextureInfoString(): %s"), *(Desc.GenerateInfoString()));
Canvas.DrawShadowedString( X + 10, Y += YStep, *Line, GetStatsFont(), FLinearColor(1, 1, 1));
}
{
FString Line = FString::Printf(TEXT(" BufferSize:(%d,%d)"), FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY().X, FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY().Y);
Canvas.DrawShadowedString( X + 10, Y += YStep, *Line, GetStatsFont(), FLinearColor(1, 1, 1));
}
const FSceneViewFamily& ViewFamily = *View.Family;
for(int32 ViewId = 0; ViewId < ViewFamily.Views.Num(); ++ViewId)
{
const FSceneView& ViewIt = *ViewFamily.Views[ViewId];
FString Line = FString::Printf(TEXT(" View #%d: (%d,%d)-(%d,%d)"), ViewId + 1,
ViewIt.ViewRect.Min.X, ViewIt.ViewRect.Min.Y, ViewIt.ViewRect.Max.X, ViewIt.ViewRect.Max.Y);
Canvas.DrawShadowedString( X + 10, Y += YStep, *Line, GetStatsFont(), FLinearColor(1, 1, 1));
}
X += 40;
if(Desc.Flags & TexCreate_CPUReadback)
{
Canvas.DrawShadowedString( X, Y += YStep, TEXT("Content cannot be visualized on the GPU (TexCreate_CPUReadback)"), GetStatsFont(), FLinearColor(1,1,0));
}
else
{
Canvas.DrawShadowedString( X, Y += YStep, TEXT("Blinking Red: <0"), GetStatsFont(), FLinearColor(1,0,0));
Canvas.DrawShadowedString( X, Y += YStep, TEXT("Blinking Blue: NAN or Inf"), GetStatsFont(), FLinearColor(0,0,1));
// add explicit legend for SceneDepth and ShadowDepth as the display coloring is an artificial choice.
const bool bDepthTexture = (Desc.TargetableFlags & TexCreate_DepthStencilTargetable) != 0;
const bool bShadowDepth = (Desc.Format == PF_ShadowDepth);
if (bShadowDepth)
{
Canvas.DrawShadowedString(X, Y += YStep, TEXT("Color Key: Linear with white near and teal distant"), GetStatsFont(), FLinearColor(54.f / 255.f, 117.f / 255.f, 136.f / 255.f));
}
else if (bDepthTexture)
{
Canvas.DrawShadowedString(X, Y += YStep, TEXT("Color Key: Nonlinear with white distant"), GetStatsFont(), FLinearColor(0.5, 0, 0));
}
}
Canvas.Flush_RenderThread(RHICmdList);
}
void FVisualizeTexture::SetObserveTarget(const FString& InObservedDebugName, uint32 InObservedDebugNameReusedGoal)
{
ObservedDebugName = InObservedDebugName;
ObservedDebugNameReusedGoal = InObservedDebugNameReusedGoal;
}
void FVisualizeTexture::SetCheckPoint(FRHICommandList& RHICmdList, const IPooledRenderTarget* PooledRenderTarget)
{
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
check(IsInRenderingThread());
if (!PooledRenderTarget || !bEnabled)
{
// Don't checkpoint on ES2 to avoid TMap alloc/reallocations
return;
}
const FSceneRenderTargetItem& RenderTargetItem = PooledRenderTarget->GetRenderTargetItem();
const FPooledRenderTargetDesc& Desc = PooledRenderTarget->GetDesc();
const TCHAR* DebugName = Desc.DebugName;
uint32* UsageCountPtr = VisualizeTextureCheckpoints.Find(DebugName);
if(!UsageCountPtr)
{
// create a new element with count 0
UsageCountPtr = &VisualizeTextureCheckpoints.Add(DebugName, 0);
}
// is this is the name we are observing with visualize texture?
// First check if we need to find anything to avoid string the comparison
if (!ObservedDebugName.IsEmpty() && ObservedDebugName == DebugName)
{
// if multiple times reused during the frame, is that the one we want to look at?
if(*UsageCountPtr == ObservedDebugNameReusedGoal || ObservedDebugNameReusedGoal == 0xffffffff)
{
FRHICommandListImmediate& RHICmdListIm = FRHICommandListExecutor::GetImmediateCommandList();
if (RHICmdListIm.IsExecuting())
{
UE_LOG(LogConsoleResponse, Fatal, TEXT("We can't create a checkpoint because that requires the immediate commandlist, which is currently executing. You might try disabling parallel rendering."));
}
else
{
if (&RHICmdList != &RHICmdListIm)
{
UE_LOG(LogConsoleResponse, Warning, TEXT("Attempt to checkpoint a render target from a non-immediate command list. We will flush it and hope that works. If it doesn't you might try disabling parallel rendering."));
RHICmdList.Flush();
}
GenerateContent(RHICmdListIm, RenderTargetItem, Desc);
if (&RHICmdList != &RHICmdListIm)
{
RHICmdListIm.Flush();
}
}
}
}
// only needed for VisualizeTexture (todo: optimize out when possible)
*UsageCountPtr = *UsageCountPtr + 1;
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
}
struct FSortedLines
{
FString Line;
int32 SortIndex;
uint32 PoolIndex;
FORCEINLINE bool operator<( const FSortedLines &B ) const
{
// first large ones
if(SortIndex < B.SortIndex)
{
return true;
}
if(SortIndex > B.SortIndex)
{
return false;
}
return Line < B.Line;
}
};
void FVisualizeTexture::DebugLog(bool bExtended)
{
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
{
TArray<FSortedLines> SortedLines;
for(uint32 i = 0, Num = GRenderTargetPool.GetElementCount(); i < Num; ++i)
{
FPooledRenderTarget* RT = GRenderTargetPool.GetElementById(i);
if(!RT)
{
continue;
}
FPooledRenderTargetDesc Desc = RT->GetDesc();
if(bFullList || (Desc.Flags & TexCreate_HideInVisualizeTexture) == 0)
{
uint32 SizeInKB = (RT->ComputeMemorySize() + 1023) / 1024;
FString UnusedStr;
if(RT->GetUnusedForNFrames() > 0)
{
if(!bFullList)
{
continue;
}
UnusedStr = FString::Printf(TEXT(" unused(%d)"), RT->GetUnusedForNFrames());
}
FSortedLines Element;
Element.PoolIndex = i;
// sort by index
Element.SortIndex = i;
FString InfoString = Desc.GenerateInfoString();
if(SortOrder == -1)
{
// constant works well with the average name length
const uint32 TotelSpacerSize = 36;
uint32 SpaceCount = FMath::Max<int32>(0, TotelSpacerSize - InfoString.Len());
for(uint32 Space = 0; Space < SpaceCount; ++Space)
{
InfoString.AppendChar((TCHAR)' ');
}
// sort by index
Element.Line = FString::Printf(TEXT("%s %s %d KB%s"), *InfoString, Desc.DebugName, SizeInKB, *UnusedStr);
}
else if(SortOrder == 0)
{
// sort by name
Element.Line = FString::Printf(TEXT("%s %s %d KB%s"), Desc.DebugName, *InfoString, SizeInKB, *UnusedStr);
Element.SortIndex = 0;
}
else if(SortOrder == 1)
{
// sort by size (large ones first)
Element.Line = FString::Printf(TEXT("%d KB %s %s%s"), SizeInKB, *InfoString, Desc.DebugName, *UnusedStr);
Element.SortIndex = -(int32)SizeInKB;
}
else
{
check(0);
}
if(Desc.Flags & TexCreate_FastVRAM)
{
FRHIResourceInfo Info;
FTextureRHIRef Texture = RT->GetRenderTargetItem().ShaderResourceTexture;
if(!IsValidRef(Texture))
{
Texture = RT->GetRenderTargetItem().TargetableTexture;
}
if(IsValidRef(Texture))
{
RHIGetResourceInfo(Texture, Info);
}
if(Info.VRamAllocation.AllocationSize)
{
// note we do KB for more readable numbers but this can cause quantization loss
Element.Line += FString::Printf(TEXT(" VRamInKB(Start/Size):%d/%d"),
Info.VRamAllocation.AllocationStart / 1024,
(Info.VRamAllocation.AllocationSize + 1023) / 1024);
}
else
{
Element.Line += TEXT(" VRamInKB(Start/Size):<NONE>");
}
}
SortedLines.Add(Element);
}
}
SortedLines.Sort();
{
for(int32 Index = 0; Index < SortedLines.Num(); Index++)
{
const FSortedLines& Entry = SortedLines[Index];
UE_LOG(LogConsoleResponse, Log, TEXT(" %3d = %s"), Entry.PoolIndex + 1, *Entry.Line);
}
}
// clean flags for next use
bFullList = false;
SortOrder = -1;
}
UE_LOG(LogConsoleResponse, Log, TEXT(""));
// log names (alternative method to look at the rendertargets)
if(bExtended)
{
UE_LOG(LogConsoleResponse, Log, TEXT("CheckpointName (what was rendered this frame, use <Name>@<Number> to get intermediate versions):"));
TArray<FString> Entries;
// sorted by pointer for efficiency, now we want to print sorted alphabetically
for (TMap<const TCHAR*, uint32>:: TIterator It(GRenderTargetPool.VisualizeTexture.VisualizeTextureCheckpoints); It; ++It)
{
const TCHAR* Key = It.Key();
uint32 Value = It.Value();
/* if(Value)
{
// was reused this frame
Entries.Add(FString::Printf(TEXT("%s @0..%d"), *Key.GetPlainNameString(), Value - 1));
}
else
*/ {
// was not reused this frame but can be referenced
Entries.Add(Key);
}
}
Entries.Sort();
// that number works well with the name length we have
const uint32 ColumnCount = 5;
const uint32 SpaceBetweenColumns = 1;
uint32 ColumnHeight = FMath::DivideAndRoundUp((uint32)Entries.Num(), ColumnCount);
// width of the column in characters, init with 0
uint32 ColumnWidths[ColumnCount] = {};
for(int32 Index = 0; Index < Entries.Num(); ++Index)
{
uint32 Column = Index / ColumnHeight;
const FString& Entry = *Entries[Index];
ColumnWidths[Column] = FMath::Max(ColumnWidths[Column], (uint32)Entry.Len());
}
// print them sorted, if possible multiple in a line
{
FString Line;
for(int32 OutputIndex = 0; OutputIndex < Entries.Num(); ++OutputIndex)
{
// 0..ColumnCount-1
uint32 Column = OutputIndex % ColumnCount;
int32 Row = OutputIndex / ColumnCount;
uint32 Index = Row + Column * ColumnHeight;
bool bLineEnd = true;
if(Index < (uint32)Entries.Num())
{
bLineEnd = (Column + 1 == ColumnCount);
// for human readability we order them to be per column
const FString& Entry = *Entries[Index];
Line += Entry;
int32 SpaceCount = ColumnWidths[Column] + SpaceBetweenColumns - Entry.Len();
// otehrwise a fomer pass was producing bad data
check(SpaceCount >= 0);
for(int32 Space = 0; Space < SpaceCount; ++Space)
{
Line.AppendChar((TCHAR)' ');
}
}
if(bLineEnd)
{
Line = Line.TrimTrailing();
UE_LOG(LogConsoleResponse, Log, TEXT(" %s"), *Line);
Line.Empty();
}
}
}
}
{
uint32 WholeCount;
uint32 WholePoolInKB;
uint32 UsedInKB;
GRenderTargetPool.GetStats(WholeCount, WholePoolInKB, UsedInKB);
UE_LOG(LogConsoleResponse, Log, TEXT("Pool: %d/%d MB (referenced/allocated)"), (UsedInKB + 1023) / 1024, (WholePoolInKB + 1023) / 1024);
}
#endif
}
// @return 0 if not found
IPooledRenderTarget* FVisualizeTexture::GetObservedElement() const
{
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
IPooledRenderTarget* RT = VisualizeTextureContent.GetReference();
if(!RT && Mode >= 0)
{
uint32 Id = Mode - 1;
RT = GRenderTargetPool.GetElementById(Id);
}
return RT;
#else
return 0;
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
}
void FVisualizeTexture::OnStartFrame(const FSceneView& View)
{
FeatureLevel = View.GetFeatureLevel();
bEnabled = true;
ViewRect = View.UnscaledViewRect;
AspectRatioConstrainedViewRect = View.Family->EngineShowFlags.CameraAspectRatioBars ? View.CameraConstrainedViewRect : ViewRect;
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
// VisualizeTexture observed render target is set each frame
VisualizeTextureContent.SafeRelease();
VisualizeTextureDesc = FPooledRenderTargetDesc();
VisualizeTextureDesc.DebugName = TEXT("VisualizeTexture");
ObservedDebugNameReusedCurrent = 0;
// only needed for VisualizeTexture (todo: optimize out when possible)
{
for (TMap<const TCHAR*, uint32>:: TIterator It(VisualizeTextureCheckpoints); It; ++It)
{
uint32& Value = It.Value();
// 0 as it was not used this frame yet
Value = 0;
}
}
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
}
void FVisualizeTexture::QueryInfo( FQueryVisualizeTexureInfo& Out )
{
for(uint32 i = 0, Num = GRenderTargetPool.GetElementCount(); i < Num; ++i)
{
FPooledRenderTarget* RT = GRenderTargetPool.GetElementById(i);
if(!RT)
{
continue;
}
FPooledRenderTargetDesc Desc = RT->GetDesc();
uint32 SizeInKB = (RT->ComputeMemorySize() + 1023) / 1024;
FString Entry = FString::Printf(TEXT("%s %d %s %d"),
*Desc.GenerateInfoString(),
i + 1,
Desc.DebugName ? Desc.DebugName : TEXT("<Unnamed>"),
SizeInKB);
Out.Entries.Add(Entry);
}
}