Files
UnrealEngineUWP/Engine/Source/Runtime/Renderer/Private/SceneRendering.cpp
Chris Bunner ab9d8e35b1 Copying //UE4/Dev-Rendering to //UE4/Dev-Main (Source: //UE4/Dev-Rendering @ 3388261)
#lockdown Nick.Penwarden
#rb None

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

Change 3358140 on 2017/03/22 by Rolando.Caloca

	DR - Fix copy to cube face
	- Compile fix when using dump layer
	- Add new error enum

Change 3358301 on 2017/03/22 by Mitchell.Wilson

	Initial check in of LODs in InfiltratorForward. First pass on optimization in level. Adding a visibility track for SceneCapture2D in tunnel section.

Change 3358477 on 2017/03/22 by Mitchell.Wilson

	Updating Skeletal Mesh DPW_Robot_Export to resolve screen size being too low for LOD1. Cleaned up LOD1 which was showing some visible popping when transitioning.

Change 3358529 on 2017/03/22 by Mark.Satterthwaite

	Globally disable clang's "constant-logical-operand" warning when running under Distcc - it is much easier and less invasive than constantly fixing the code.

Change 3358745 on 2017/03/22 by Mark.Satterthwaite

	Disable another warning (parentheses-equality) under Distcc because again the separation of preprocessing from compilation means it turns up where it isn't expected.

Change 3358837 on 2017/03/22 by Joe.Graf

	Merge of pull request #3214 for the RenderDocPlugin

	#CodeReview: matt.kuhlenschmidt, marcus.wassmer
	#rb: marcus.wassmer

Change 3359112 on 2017/03/22 by Ben.Salem

	Update perf monitor to include frame time by default. Also, use only  game/PIE world timers when in editor, instead of all worlds combined.

	#tests Ran several Showdown test runs with plugin!

Change 3359363 on 2017/03/22 by Joe.Graf

	First pass at non-unity & no pch compilation

Change 3359449 on 2017/03/22 by Joe.Graf

	Added missing null check when exporting a EXR on Linux (UE-40268)

	#CodeReview: dmitry.rekman
	#rb: n/a

Change 3360349 on 2017/03/23 by Guillaume.Abadie

	Fixes TAA's AA_FORCE_ALPHA_CLAMP causing DOF layouts.

	#jira UE-42920

Change 3360405 on 2017/03/23 by Marcus.Wassmer

	Better method for detecting Kepler

Change 3360718 on 2017/03/23 by Daniel.Wright

	Planar reflections handle views smaller than the render target in a general way
	* Fixes planar reflections with adaptive pixel density (ViewFamily size larger than actual views combined)
	* Planar reflections are now supported in splitscreen

Change 3360758 on 2017/03/23 by Daniel.Wright

	[Copy] Added new light property bCastVolumetricShadow, which defaults to true for directional and sky lights, but false for point / spot lights as supporting volumetric fog shadowing has significant GPU overhead

Change 3360762 on 2017/03/23 by Daniel.Wright

	[Copy] Texture flags are now properly routed to RHICreateTexture3D from the render target pool

Change 3360768 on 2017/03/23 by Daniel.Wright

	[Copy] Disabled GPUProfiler histogram by default, controlled by r.ProfileGPU.ShowEventHistogram

Change 3360770 on 2017/03/23 by Daniel.Wright

	[Copy] Disabled fast clears on CustomDepth, saves .2ms on xbox

Change 3360771 on 2017/03/23 by Daniel.Wright

	[Copy] Particle lights no longer force tiled deferred lighting.  Tiled deferred lighting is only used if enough unshadowed lights + particle lights are on screen.  Saves 1.5ms Xbox with one particle light.

Change 3360774 on 2017/03/23 by Daniel.Wright

	[Copy] Distance field cvar comments

Change 3360782 on 2017/03/23 by Daniel.Wright

	[Copy] Disabled selection color on Volume materials

Change 3360795 on 2017/03/23 by Daniel.Wright

	[Copy] Volume materials now specify Albedo and Extinction, which is more intuitive than Scattering and Absorption.  Albedo is [0-1] reflectance, while Extinction is a world space density.

Change 3360799 on 2017/03/23 by Daniel.Wright

	[Copy] Cinematic scalability levels get 2x volumetric fog resolution in x and y

Change 3360806 on 2017/03/23 by Daniel.Wright

	[Copy] Fixed volumetric fog being offset when viewport min is not 0

Change 3360809 on 2017/03/23 by Daniel.Wright

	[Copy] Volumetric fog now adds a bias to the inverse squared light falloff denominator, prevents extreme aliasing from the hotspot.  Can be controlled with r.VolumetricFog.InverseSquaredLightDistanceBiasScale.

Change 3361651 on 2017/03/23 by Brian.Karis

	Higher quality sharp SSR at quality 4

Change 3361678 on 2017/03/23 by Brian.Karis

	Fresnel darkens diffuse for clearcoat.

Change 3361683 on 2017/03/23 by Brian.Karis

	Fixed SSR artifact

Change 3361691 on 2017/03/23 by Brian.Karis

	Chagned min roughness limit

Change 3361707 on 2017/03/23 by Brian.Karis

	Added inverse film tone map

Change 3361726 on 2017/03/23 by Brian.Karis

	Better precision inverse

Change 3361758 on 2017/03/23 by Brian.Karis

	Material flag normal curvature to roughness is no longer forward only.

Change 3361765 on 2017/03/23 by Brian.Karis

	Update ACES

Change 3361774 on 2017/03/23 by Brian.Karis

	Cleaned up alpha support and disabled screen edge clipping.

Change 3362478 on 2017/03/24 by Guillaume.Abadie

	Cherry pick 3316084's PostProcessing.cpp: Fixes a bug in Circle DOF where the apply pass was no longer using the downres DOF's TAA output.

	#author Brian.Karis

	#jira UE-42920

Change 3362738 on 2017/03/24 by Rolando.Caloca

	DR - Hide scene capture on IF

Change 3362890 on 2017/03/24 by Guillaume.Abadie

	Renames r.SceneAlpha to r.PostProcessing.PropagateAlpha

Change 3363665 on 2017/03/24 by Mark.Satterthwaite

	PR #3414: Add command line option "-noheartbeatthread" to disable heart beat thread (Contributed by JeffRous)

Change 3363866 on 2017/03/24 by Arne.Schober

	DR - Updated NVAPI
	#RB Marcus.Wassmer

Change 3364300 on 2017/03/24 by Brian.Karis

	SSR use dynamic velocity

Change 3364372 on 2017/03/24 by Brian.Karis

	Fix changing off axis projection velocities.

Change 3364373 on 2017/03/24 by Brian.Karis

	Enabled velocity drawing in scene captures

Change 3365531 on 2017/03/27 by Guillaume.Abadie

	Computes the material's screen position material expression directly from the pixel shader SvPosition

Change 3365764 on 2017/03/27 by Chris.Bunner

	Lowering severity of crash for missing values in scalability.ini.

	#jira UE-41331

Change 3365916 on 2017/03/27 by Guillaume.Abadie

	Exposes the viewport offset within the view property material expression

Change 3365979 on 2017/03/27 by Brian.Karis

	Fixed skylight intensity from double applying

Change 3365987 on 2017/03/27 by Brian.Karis

	Stopped post process indirect lighting intensity from scaling skylight reflections

Change 3365991 on 2017/03/27 by Brian.Karis

	Fix for static analysis

Change 3366028 on 2017/03/27 by Daniel.Wright

	Volumetric fog supports static shadowing from Stationary lights
	* Using bilinear on static shadowmap depths + 1 PCF to smooth out results

Change 3366029 on 2017/03/27 by Daniel.Wright

	Static shadow depth maps for Stationary point and spot lights are 2x higher res by default (4x more texels), which is more appropriate for volumetric fog

Change 3366055 on 2017/03/27 by Guillaume.Abadie

	Cherry picks 3251469: Implements scene capture component's CaptureSortPriority to control GPU execution order in order to manage inter dependencies.

Change 3366447 on 2017/03/27 by Simon.Tourangeau

	Fix IES light profile importer.
	- Bug in the LM-63-1986 format importer.

Change 3366836 on 2017/03/27 by Brian.Karis

	ClearUAV now supports int types

Change 3367435 on 2017/03/28 by Benjamin.Hyder

	Submitting Decal Automation map for initial approval

Change 3367572 on 2017/03/28 by Chris.Bunner

	Changed ClampedPow {max(abs(x),0.00001)} to PositiveClampedPow {max(x,0)} to give more expected results to Power node in material graphs.

	#jira UE-42989

Change 3367756 on 2017/03/28 by Olaf.Piesche

	Niagara material usage flags

Change 3367835 on 2017/03/28 by Marcus.Wassmer

	Fix crash when TileRenderer runs before anything else.  Make explicit behavior when rendering at a time when there is no valid scene.

Change 3367837 on 2017/03/28 by Marcus.Wassmer

	Missed a file.

Change 3367838 on 2017/03/28 by Richard.Wallis

	Updated items from original shelved version by Mark Satt:

	- Added MetalBackend.cpp to change main function string to have an initial crc + code length zero's

	**Description below taken from Mark Satt's original verison of this in CL3343280**

	Updated for Dev-Rendering's PSOs & integrates Richard's work on RHI shader libraries.

	Replace the FShaderCache's cook-time binary shader cache with Dmitriy Dyomin's standalone FShaderCodeLibrary that saves all shader byte-code arrays to files named by the FSHAHash. This de-duplicates shaders so we only ever store the byte code once. Includes optional support for generating a platform specific library file - which Metal implements to provide a single Metal library. The platform-native implementation can perform more de-duplication and in the case of Metal has lower file overheads and will compress more efficiently.

	- All of the support code for the FShaderCache's cook caching is gone, which affects all platforms. The FShaderCodeLibrary is currently  supported by Cook-By-The-Book but can be used with iterate or child cookers - only DLC cooking requires further work.
	- With further modifications it should be possible to support Cook-on-the-Fly as well (output directories would be needed in FShaderCodeLibrary::InitForCooking) and the file-access pattern should be changed to use async. IO so that Material loading is not considered complete until all required byte-code arrays are loaded into the FShaderCodeLibrary.
	- For Metal archiving shaders this way will compile with debug information and the FShaderCodeLibrary, with some help from extensions to IShaderFormat, will save the debug information out into separate files during cooking - these can then be used to debug the game without having to locally recompile, recook & repackage but the shipped byte-code is stripped. Global shader caches are also subject to de-duplication in the library in order to support Metal's shader stripping.
	- File Move operations need to respect the 'Replace' flag - for FShaderCodeLibrary to work we need Move to be atomic.
	- This bumps the object version and will cause all content to recook.
	- Native library support is optional - only Metal currently implements one, but so could Vulkan and D3D12. For Metal the big advantages are further de-duplication where different materials generate the same MetalSL text but a different FSHAHash, that the single Metal library has lower overhead and that as a single file it all compresses far better (esp. with LZMA - 5x smaller).

Change 3367854 on 2017/03/28 by Mark.Satterthwaite

	Don't track or record draw call resources for non-OpenGL shader platforms in the shader-cache as it is unnecessary and makes it slower on the CPU than it needs to be.

Change 3367877 on 2017/03/28 by Brian.Karis

	Fixed linux build hopefully

Change 3368001 on 2017/03/28 by Mark.Satterthwaite

	Compile fixes from Richard's checkin caused by not having visibility to all platforms from my original shelves.

Change 3368019 on 2017/03/28 by Mark.Satterthwaite

	And another fix for Windows compilation of MetalShaderFormat.

Change 3368042 on 2017/03/28 by Mark.Satterthwaite

	And a couple of simpler MSVC errors.

Change 3368271 on 2017/03/28 by Mark.Satterthwaite

	Make SceneRenderTargets compile again.

Change 3368691 on 2017/03/28 by Daniel.Wright

	[Copy from BenW] Renamed r.Shadow.MaxCSMShadowResolution to r.Shadow.MaxCSMResolution to match scalability inis

Change 3369689 on 2017/03/29 by Marcus.Wassmer

	Fix non editor compile for now

Change 3369862 on 2017/03/29 by Marcus.Wassmer

	Get the rest of the things compiling again.

Change 3369896 on 2017/03/29 by Chris.Bunner

	Enabling AMD HDR support by default.

	#jira UE-42113

Change 3370535 on 2017/03/29 by Marcus.Wassmer

	DR - Fix template explicit instantiation for ClearUAV permutations
	#RB Brian.Karis, Arne.Schober

Change 3370704 on 2017/03/29 by Rolando.Caloca

	DR - Rewrote GPU Skin Cache
	- Per section buffers
	- Limited memory per non-editor worlds (control with r.SkinCache.SceneMemoryLimitInMB)
	Copied from 3370529

Change 3371389 on 2017/03/30 by Richard.Wallis

	Remove temp working directories after archive packages built.

Change 3371641 on 2017/03/30 by Rolando.Caloca

	DR - Copy 3371640 (fix mem leak)

Change 3372436 on 2017/03/30 by Uriel.Doyon

	Added flags in UPrimitiveComponent to keep track of its state in the streaming manager.
	This allows to avoid unnecessary callback and processing in begin destroy reattach and being destroy logic.

	Removed the limitation of only processing UMeshComponent when handling spawed primitive.
	This releases the level manager from having to manage dynamic primitives.
	This improves performance by not having to manage dynamic references in the level manager.

	Primitives managed as dynamic now have a callback when ever their proxy is udpated, handling
	many cases automatically where previously a manual callback to notify would have been required.

	Fixed an issue where primitives with no reference to streaming textures would loose they dynamic state
	because of lack of references in the streamer.

Change 3372740 on 2017/03/30 by Chris.Bunner

	[Experimental] Partial compute post process pipeline (r.PostProcess.PreferCompute).
	StencilSceneTexture added to deferred list.
	A few known issues to be fixed in a follow-up CL.

Change 3372765 on 2017/03/30 by Uriel.Doyon

	Disabled concurrent call to NotifyPrimitiveUpdated while we don't have a safe concurrent update

Change 3372979 on 2017/03/30 by Richard.Hinckley

	#jira UE-43501
	The stencil buffer can now use single-channel bitmasks that ignore depth. This makes it possible to detect overlaps between stencil objects.

Change 3373053 on 2017/03/30 by Simon.Tourangeau

	LPV Fade support
	- mostly integrated from CL 2959511

Change 3373272 on 2017/03/30 by Uriel.Doyon

	Added support for the concurrent update of dynamic primitives by the streaming manager.

Change 3373450 on 2017/03/30 by Rolando.Caloca

	DR - FNT - Fix bad data for odd texcoord channels used on skin cache passthrough factory
	Copy 3373364

	#jira UE-43492

Change 3373470 on 2017/03/30 by Marcus.Wassmer

	Nvidia Aftermath support

Change 3374187 on 2017/03/31 by Chris.Bunner

	Volume texture support for CombineLUTs/Tonemap compute pass.
	Refactored common param code to shared sub-class in CombineLUTs and Tonemap PS/CS.
	Skip compute post process out-of-bounds writes.
	Unsigned type conversion fixes.
	Trimmed compute post process shader inputs.

Change 3374233 on 2017/03/31 by Chris.Bunner

	Removed several redundant post process compute fences and resource transitions.
	Added testing CVar to force compute post processes to async (r.PostProcess.ForceAsyncDispatch).

Change 3374412 on 2017/03/31 by Rolando.Caloca

	DR - Fix static analysis

Change 3374544 on 2017/03/31 by Richard.Wallis

	FShaderCache Parallel-Context-Aware Merged with FShaderCache Single Library.

	Future Work
	- This was done before Engine PSO were in so this now needs a refector in the recording and playback on pipeline states instead an emulate PSO in OpenGL Driver.
	- Remove FShaderCacheState and replace the logic with FGraphicsPipelineStateInitializer which should be able to record from the RHI current pipeline state
	- This would reduce the Locking required as it's naturally per thread/context and only the final record would need a lock

Change 3374588 on 2017/03/31 by Richard.Wallis

	Windows Compile Fixes

Change 3374810 on 2017/03/31 by Benjamin.Hyder

	updating recommended GPU drivers

Change 3375207 on 2017/03/31 by Rolando.Caloca

	DR - vk - Fixed swapchain format selection for some Linux platforms

Change 3375248 on 2017/03/31 by Rolando.Caloca

	DR - vk - Prefer D32S8

Change 3375495 on 2017/03/31 by Rolando.Caloca

	DR - vk - Update to sdk 1.0.42.2

Change 3375496 on 2017/03/31 by Rolando.Caloca

	DR - Force compiling with updated Vulkan SDK

Change 3375636 on 2017/03/31 by Mark.Satterthwaite

	Copying Metal improvements from task stream, with some modifications:
	- Off-by-default implementations for MTLFence & MTLHeap, including some small changes to the RHI interface for parallel contexts.
	- Support for Apple's Instruments "Points of Interest" tool.
	- Consolidation of some Mac & iOS compiler, memory and thread handling code.
	- Fixes for Metal not having implicit buffer SRV typecasting for DistanceField effects.
	- Improvements to the internal FMetalDebug layer, still off by default.
	- Limited support for Xcode automatic code-signing for iOS/tvOS.
	- Minimisation of render-target changes in some rendering code, esp. SceneOcclusion, DBufferDecals.
	- Added RHISetResourceAliasability_RenderThread to FDynamicRHI for RHIs to implement simple render-target aliasing.
	- Added FApplePlatformObject, a custom block allocator for Objective-C types (with NSZombie support) which is now used in MetalRHI to decrease allocation costs of Objective-C types.
	- Smattering of lesser fixes.

Change 3375654 on 2017/03/31 by Mark.Satterthwaite

	Incremental Windows build fix.

Change 3375656 on 2017/04/01 by Mark.Satterthwaite

	Correct extern declaration, including the module export macro which Mac unhelpfully doesn't enforce (for now...).

Change 3375797 on 2017/04/01 by Mark.Satterthwaite

	Nullability qualifiers to fix Mac build-farm compilation: perversely this is not a problem for local builds...

Change 3375798 on 2017/04/01 by Mark.Satterthwaite

	Fix the first mis-merge in ParticleGpuSimulation - these changes clearly weren't properly resolved in the task-stream.

Change 3375835 on 2017/04/01 by Mark.Satterthwaite

	Try again with nullability and fix the occlusion changes as the PSO work wasn't merged correctly.

Change 3376143 on 2017/04/02 by Mark.Satterthwaite

	Switch back to flat dSYMs for Dev-Rendering - they don't work with Instruments etc. but they are required by our build system.

Change 3376324 on 2017/04/03 by Chris.Bunner

	Fixed cvar re-registration log spam and flagged a testing-only cvar as such.

Change 3376726 on 2017/04/03 by Benjamin.Hyder

	Submitting initial HDR test map (WIP)

Change 3376756 on 2017/04/03 by Guillaume.Abadie

	Fixes scene captures ordering's backward compatibility.

	Before, 2d scene captures were rendered before cube scene captures. The CaptureSortPriority broke backward compatibility by settings this new member to 0 in the USceneCaptureComponent's constructor. Since it is a higher come first policy, this CL set the default of this value to 1 in USceneCaptureComponent2D's constructor.

Change 3377378 on 2017/04/03 by Arne.Schober

	DR - Fix ShaderRecompiling over and over again
	#RB Chris.Bunner

Change 3377512 on 2017/04/03 by Daniel.Wright

	[Copy] Fixed profilegpu in d3d12 - initialize FLongGPUTaskPS when it is safe to do so, and fixed FSlateRHIRenderer's incorrect usage of draw events

Change 3377518 on 2017/04/03 by Daniel.Wright

	[Copy] Distance field atlas coalesces updates to reduce RHIUpdateTexture3D memory overhead on d3d12

Change 3377526 on 2017/04/03 by Daniel.Wright

	[Copy] "Ran out of GPU queries!" log only happens once

Change 3377535 on 2017/04/03 by Daniel.Wright

	[Copy] Fixed unreferenced local variable

Change 3377539 on 2017/04/03 by Daniel.Wright

	[Copy] Xbox One RHIGetResourceInfo takes ESRAM into account - fixes render target pool 'VRamInKB request failed' messages

Change 3377546 on 2017/04/03 by Daniel.Wright

	[Copy] Added r.LightMaxDrawDistanceScale for local light scalability

Change 3377553 on 2017/04/03 by Daniel.Wright

	[Copy] Removed NEW_ESRAM_ALLOCATOR define and old unused path

Change 3377560 on 2017/04/03 by Daniel.Wright

	[Copy] Fixed two d3d12 refcounting bugs causing -norhithread crashes

Change 3377565 on 2017/04/03 by Daniel.Wright

	[Copy] Fixed Xbox One deleting GPU resources before the GPU is done reading from them (GRHINeedsExtraDeletionLatency was false)

Change 3377572 on 2017/04/03 by Daniel.Wright

	[Copy] Disabled point / spot lights with MaxDrawDistance on LowPC

Change 3377586 on 2017/04/03 by Daniel.Wright

	Fixed compile error

Change 3377699 on 2017/04/03 by David.Hill

	FFT Code.  Moved over from raven and refactored

	#review-3374589 @guillaume.abadie

Change 3377910 on 2017/04/03 by David.Hill

	GPU FFT: Fix Linux Build
	adding a missing template<> to an IMPLEMENT_SHADER_TYPE

Change 3378751 on 2017/04/04 by Marcus.Wassmer

	HQ particle lights now spawn attached to the same socket as their parent module.

Change 3378819 on 2017/04/04 by Richard.Wallis

	Should be no need to protect shader cache against RHI thread now.

Change 3378823 on 2017/04/04 by Richard.Wallis

	FRHIShaderLibrary Opaque Type

	- Base FRHIShaderLibrary has no Create*Shader functions and is passed to Overloaded RHICreate*Shader functions instead of creation directly through the library.
	- Assumed that only Native libraries will end up in the RHICreate*Shader functions.
	- ShaderCache and ShaderCode Libraries now inherit from a common factory interface.

Change 3378883 on 2017/04/04 by Arne.Schober

	DR - Fix DCC build

Change 3378885 on 2017/04/04 by Richard.Wallis

	Metal resource cast compile fix post merge.

Change 3378946 on 2017/04/04 by Chris.Bunner

	SM4 assert fix.

Change 3378953 on 2017/04/04 by Chris.Bunner

	Fixed type-correctness on legacy BreakMA material nodes and set more flexible formats to global attributes which should result in much more forgiving graphs for users.
	Allowed material nodes to opt out of mask-based pin coloration.
	#tests Compiled most Paragon materials + QAGame test maps.

	#jira UE-39885

Change 3379189 on 2017/04/04 by Arne.Schober

	DR - Fix aftermath staging

Change 3379229 on 2017/04/04 by Arne.Schober

	DR - Fix missing include

Change 3379374 on 2017/04/04 by Mark.Satterthwaite

	Revert an accidentally merged change in MacPlatformProcess that relies on further changes from the Metal task stream.

Change 3379505 on 2017/04/04 by Rolando.Caloca

	DR - Fix mismatched interpolators

Change 3379539 on 2017/04/04 by Mark.Satterthwaite

	No FFT for any hlslcc platform - the IR for one or more RWTexture2D isn't quite right...

	#jira UE-43626

Change 3379561 on 2017/04/04 by Rolando.Caloca

	DR - Fix root signature issues on D3D12 PC

Change 3379590 on 2017/04/04 by Mark.Satterthwaite

	Back out changelist 3379539 & change the shader slightly instead, the HLSLCC library generates bogus IR when you have an inout RWTexture.

	#jira UE-43626

Change 3379917 on 2017/04/04 by Uriel.Doyon

	Fix to input mismatch

Change 3380578 on 2017/04/05 by Chris.Bunner

	Shader type fixes.

	#jira UE-43652

Change 3380639 on 2017/04/05 by Rolando.Caloca

	DR - Expose GetOrCreate PSO and document

Change 3380821 on 2017/04/05 by Guillaume.Abadie

	Fixes a crash in USceneCaptureComponent::UpdateDeferredCaptures()

	#jira UE-43642

Change 3381092 on 2017/04/05 by Guillaume.Abadie

	Cherry pick 3362517: Implements TAA's scene color unpremultiplication from alpha channel to reduce DOF alpha channel temporal ghosting.

	This CL take the oportunity to transform AA_ALPHA to an compile time enumeration, and add a basic TAA compile time configuration validation to improve readability of the different TAA passes' configurations.

Change 3381300 on 2017/04/05 by Mark.Satterthwaite

	Quick fix for changes to MetalRHI's render-thread safe texture creation not correctly handling AVFoundation video player handing us an IOSurface.

	#jira UE-43597

Change 3381359 on 2017/04/05 by Guillaume.Abadie

	Back out changelist 3381092

Change 3381421 on 2017/04/05 by Mark.Satterthwaite

	Amended CL #3380995 from Richard Wallis to address crash in the Material Editor under the validation layer - when there are no textures bound the default pass descriptor assigns store actions, which means we can't override them with our deferred store actions.

	#jira UE-43689

Change 3381422 on 2017/04/05 by Mark.Satterthwaite

	Absolute time queries can't be batched in Metal but I also can't rely on them being started with a call to BeginQuery - only EndQuery.

	#jira UE-43691

Change 3381503 on 2017/04/05 by Daniel.Wright

	More intuitive controls for Volumetric Fog
	* Removed ScatteringScale / AbsorptionScale on Exponential Height Fog and added Albedo / Extinction
	* InscatteringColorCubemap is now supported by Volumetric Fog
	* Particle lights have a default VolumetricScatteringIntensity of 0 to avoid trailing
	* Tweaked GVolumetricFogDepthDistributionScale better for nearby details
	* Volume Materials have twice the interpolators available

Change 3381527 on 2017/04/05 by Mark.Satterthwaite

	Disable Private GPU storage for PVRTC texture formats on iOS Metal - these require more changes to the blit-encoder usage as PVRTC has strange requirements.

Change 3381671 on 2017/04/05 by Mark.Satterthwaite

	Better error message for failure to compile shaders remotely from PC for Metal.

Change 3381769 on 2017/04/05 by Rolando.Caloca

	DR - Added lock texture array 2d on Vulkan

Change 3382003 on 2017/04/05 by Mark.Satterthwaite

	Remove the automatic Metal aliasing/re-use when releasing some resource types as it doesn't work as intended.

Change 3382030 on 2017/04/05 by Zachary.Wilson

	Fix compiling Metal text shaders from PC broken in merge from task stream.
	#submitter mark.satterthwaite

	#jira UE-43652

Change 3382880 on 2017/04/06 by Mark.Satterthwaite

	Michael Trepka's CL #3379927:
	VolumetricFogVoxelization implementation for Mac

Change 3383315 on 2017/04/06 by Mark.Satterthwaite

	Partially revert CL #3382003 - the emulated Metal heaps require invoking makeAliasable in order to reclaim memory.

	#jira UE-43739

Change 3384639 on 2017/04/07 by Marcus.Wassmer

	Move ShaderResource version bump to RenderingObjectVersion

Change 3384704 on 2017/04/07 by Mark.Satterthwaite

	Compile fix for merge.

Change 3384933 on 2017/04/07 by Rolando.Caloca

	DR - Fix skin cache crash with BP (copy 3384714)

Change 3385104 on 2017/04/07 by Mark.Satterthwaite

	Fix MetalRHI's abs(int2) handling - it can't be translated to fabs(int2) as that won't compile. Also rebuild hlslcc for my sanity.

	#jira UE-43783

Change 3385105 on 2017/04/07 by Mark.Satterthwaite

	Force a shader rebuild to ensure that everybody picks up the fix for #jira UE-43783

	#jira UE-43783

Change 3385118 on 2017/04/07 by Arne.Schober

	DR - [OR-37359] - Fix disapearing Decals when StencilLod Fade is enabled
	#RB none

Change 3385149 on 2017/04/07 by Marcus.Wassmer

	Fix skincache motion blur

Change 3385189 on 2017/04/07 by Rolando.Caloca

	DR - Fix swapchain format for editor on Vulkan

Change 3385287 on 2017/04/07 by Mark.Satterthwaite

	Enable SM5 on Intel as of 10.12.4 and later.

Change 3385347 on 2017/04/07 by Rolando.Caloca

	DR - Temp fix for GL4 corruption on editor
	#jira UE-43785

Change 3385363 on 2017/04/07 by Rolando.Caloca

	DR - Actually fix all win platforms for GL bug
	#jira UE-43785

Change 3385557 on 2017/04/07 by Arne.Schober

	DR - [UE-43205] - Fix mesh paint
	#RB none

Change 3385608 on 2017/04/07 by Daniel.Wright

	Fixed SampleCmp being used on a non-depth texture, causing a d3d error

Change 3385980 on 2017/04/10 by Rolando.Caloca

	DR - Remove transition functions RHIClearColor* RHIClearDepthStencilTexture

Change 3386042 on 2017/04/10 by Rolando.Caloca

	DR - Fix metal merge issue

Change 3386157 on 2017/04/10 by Rolando.Caloca

	DR - Remove VS2013 libs generation off hlslcc & glslang (to match main)

Change 3386356 on 2017/04/10 by Chris.Bunner

	Resolving merge errors.

Change 3386414 on 2017/04/10 by Chris.Bunner

	Resolved merge issue in RendererScene.cpp.

Change 3386700 on 2017/04/10 by Mark.Satterthwaite

	Silence documentation warnings.

Change 3387178 on 2017/04/10 by Chris.Bunner

	Removed invalid mask correction on MakeMA material nodes.

Change 3388177 on 2017/04/11 by Marcus.Wassmer

	Disable ensure that is no longer relevant now that we bind clear colors on texture creation

Change 3388261 on 2017/04/11 by Chris.Bunner

	Static analysis fix.

[CL 3388266 by Chris Bunner in Main branch]
2017-04-11 10:32:07 -04:00

2376 lines
92 KiB
C++

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
SceneRendering.cpp: Scene rendering.
=============================================================================*/
#include "SceneRendering.h"
#include "ProfilingDebugging/ProfilingHelpers.h"
#include "UObject/UObjectHash.h"
#include "UObject/UObjectIterator.h"
#include "EngineGlobals.h"
#include "CanvasItem.h"
#include "CanvasTypes.h"
#include "Components/ReflectionCaptureComponent.h"
#include "Components/SceneCaptureComponent2D.h"
#include "Components/SceneCaptureComponentCube.h"
#include "StaticMeshDrawList.h"
#include "DeferredShadingRenderer.h"
#include "DynamicPrimitiveDrawing.h"
#include "RenderTargetTemp.h"
#include "RendererModule.h"
#include "ScenePrivate.h"
#include "PostProcess/SceneFilterRendering.h"
#include "PostProcess/RenderingCompositionGraph.h"
#include "PostProcess/PostProcessEyeAdaptation.h"
#include "CompositionLighting/CompositionLighting.h"
#include "SceneViewExtension.h"
#include "PostProcess/PostProcessBusyWait.h"
#include "PostProcess/PostProcessCircleDOF.h"
#include "AtmosphereRendering.h"
#include "Matinee/MatineeActor.h"
#include "ComponentRecreateRenderStateContext.h"
#include "PostProcess/PostProcessSubsurface.h"
#include "HdrCustomResolveShaders.h"
#include "WideCustomResolveShaders.h"
#include "PipelineStateCache.h"
#include "GPUSkinCache.h"
/*-----------------------------------------------------------------------------
Globals
-----------------------------------------------------------------------------*/
extern ENGINE_API FLightMap2D* GDebugSelectedLightmap;
extern ENGINE_API UPrimitiveComponent* GDebugSelectedComponent;
DECLARE_FLOAT_COUNTER_STAT(TEXT("Custom Depth"), Stat_GPU_CustomDepth, STATGROUP_GPU);
static TAutoConsoleVariable<int32> CVarCustomDepthTemporalAAJitter(
TEXT("r.CustomDepthTemporalAAJitter"),
1,
TEXT("If disabled the Engine will remove the TemporalAA Jitter from the Custom Depth Pass. Only has effect when TemporalAA is used."),
ECVF_RenderThreadSafe
);
/**
* Console variable controlling whether or not occlusion queries are allowed.
*/
static TAutoConsoleVariable<int32> CVarAllowOcclusionQueries(
TEXT("r.AllowOcclusionQueries"),
1,
TEXT("If zero, occlusion queries will not be used to cull primitives."),
ECVF_RenderThreadSafe
);
static TAutoConsoleVariable<float> CVarDemosaicVposOffset(
TEXT("r.DemosaicVposOffset"),
0.0f,
TEXT("This offset is added to the rasterized position used for demosaic in the ES2 tonemapping shader. It exists to workaround driver bugs on some Android devices that have a half-pixel offset."),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarRefractionQuality(
TEXT("r.RefractionQuality"),
2,
TEXT("Defines the distorion/refraction quality which allows to adjust for quality or performance.\n")
TEXT("<=0: off (fastest)\n")
TEXT(" 1: low quality (not yet implemented)\n")
TEXT(" 2: normal quality (default)\n")
TEXT(" 3: high quality (e.g. color fringe, not yet implemented)"),
ECVF_Scalability | ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarInstancedStereo(
TEXT("vr.InstancedStereo"),
0,
TEXT("0 to disable instanced stereo (default), 1 to enable."),
ECVF_ReadOnly | ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarMultiView(
TEXT("vr.MultiView"),
0,
TEXT("0 to disable multi-view instanced stereo, 1 to enable.\n")
TEXT("Currently only supported by the PS4 RHI."),
ECVF_ReadOnly | ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarMobileMultiView(
TEXT("vr.MobileMultiView"),
0,
TEXT("0 to disable mobile multi-view, 1 to enable.\n"),
ECVF_ReadOnly | ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarMobileMultiViewDirect(
TEXT("vr.MobileMultiView.Direct"),
0,
TEXT("0 to disable mobile multi-view direct, 1 to enable.\n")
TEXT("When enabled the scene color render target array is provided by the hmd plugin so we can skip the blit.\n"),
ECVF_ReadOnly | ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarMonoscopicFarField(
TEXT("vr.MonoscopicFarField"),
0,
TEXT("0 to disable (default), 1 to enable."),
ECVF_ReadOnly | ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarMonoscopicFarFieldMode(
TEXT("vr.MonoscopicFarFieldMode"),
1,
TEXT("Experimental, mobile only")
TEXT(", 0 to disable, 1 to enable (default)")
TEXT(", 2 stereo near field only")
TEXT(", 3 stereo near field with far field pixel depth test disabled")
TEXT(", 4 mono far field only"),
ECVF_Scalability | ECVF_RenderThreadSafe);
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
static TAutoConsoleVariable<float> CVarGeneralPurposeTweak(
TEXT("r.GeneralPurposeTweak"),
1.0f,
TEXT("Useful for low level shader development to get quick iteration time without having to change any c++ code.\n")
TEXT("Value maps to Frame.GeneralPurposeTweak inside the shaders.\n")
TEXT("Example usage: Multiplier on some value to tweak, toggle to switch between different algorithms (Default: 1.0)\n")
TEXT("DON'T USE THIS FOR ANYTHING THAT IS CHECKED IN. Compiled out in SHIPPING to make cheating a bit harder."),
ECVF_RenderThreadSafe);
static TAutoConsoleVariable<int32> CVarDisplayInternals(
TEXT("r.DisplayInternals"),
0,
TEXT("Allows to enable screen printouts that show the internals on the engine/renderer\n")
TEXT("This is mostly useful to be able to reason why a screenshots looks different.\n")
TEXT(" 0: off (default)\n")
TEXT(" 1: enabled"),
ECVF_RenderThreadSafe | ECVF_Cheat);
#endif
/**
* Console variable controlling the maximum number of shadow cascades to render with.
* DO NOT READ ON THE RENDERING THREAD. Use FSceneView::MaxShadowCascades.
*/
static TAutoConsoleVariable<int32> CVarMaxShadowCascades(
TEXT("r.Shadow.CSM.MaxCascades"),
10,
TEXT("The maximum number of cascades with which to render dynamic directional light shadows."),
ECVF_Scalability | ECVF_RenderThreadSafe
);
static TAutoConsoleVariable<int32> CVarMaxMobileShadowCascades(
TEXT("r.Shadow.CSM.MaxMobileCascades"),
2,
TEXT("The maximum number of cascades with which to render dynamic directional light shadows when using the mobile renderer."),
ECVF_Scalability | ECVF_RenderThreadSafe
);
static TAutoConsoleVariable<int32> CVarForwardShading(
TEXT("r.ForwardShading"),
0,
TEXT("Whether to use forward shading on desktop platforms - requires Shader Model 5 hardware.\n")
TEXT("Forward shading has lower constant cost, but fewer features supported. 0:off, 1:on\n")
TEXT("This rendering path is a work in progress with many unimplemented features, notably only a single reflection capture is applied per object and no translucency dynamic shadow receiving."),
ECVF_RenderThreadSafe | ECVF_ReadOnly);
static TAutoConsoleVariable<int32> CVarSupportSimpleForwardShading(
TEXT("r.SupportSimpleForwardShading"),
0,
TEXT("Whether to compile the shaders to support r.SimpleForwardShading being enabled (PC only)."),
ECVF_RenderThreadSafe | ECVF_ReadOnly);
static TAutoConsoleVariable<int32> CVarSimpleForwardShading(
TEXT("r.SimpleForwardShading"),
0,
TEXT("Whether to use the simple forward shading base pass shaders which only support lightmaps + stationary directional light + stationary skylight\n")
TEXT("All other lighting features are disabled when true. This is useful for supporting very low end hardware, and is only supported on PC platforms.\n")
TEXT("0:off, 1:on"),
ECVF_RenderThreadSafe | ECVF_Scalability);
static TAutoConsoleVariable<float> CVarNormalCurvatureToRoughnessBias(
TEXT("r.NormalCurvatureToRoughnessBias"),
0.0f,
TEXT("Biases the roughness resulting from screen space normal changes for materials with NormalCurvatureToRoughness enabled. Valid range [-1, 1]"),
ECVF_RenderThreadSafe | ECVF_Scalability);
static TAutoConsoleVariable<float> CVarNormalCurvatureToRoughnessExponent(
TEXT("r.NormalCurvatureToRoughnessExponent"),
0.333f,
TEXT("Exponent on the roughness resulting from screen space normal changes for materials with NormalCurvatureToRoughness enabled."),
ECVF_RenderThreadSafe | ECVF_Scalability);
static TAutoConsoleVariable<float> CVarNormalCurvatureToRoughnessScale(
TEXT("r.NormalCurvatureToRoughnessScale"),
1.0f,
TEXT("Scales the roughness resulting from screen space normal changes for materials with NormalCurvatureToRoughness enabled. Valid range [0, 2]"),
ECVF_RenderThreadSafe | ECVF_Scalability);
/*-----------------------------------------------------------------------------
FParallelCommandListSet
-----------------------------------------------------------------------------*/
static TAutoConsoleVariable<int32> CVarRHICmdSpewParallelListBalance(
TEXT("r.RHICmdSpewParallelListBalance"),
0,
TEXT("For debugging, spews the size of the parallel command lists. This stalls and otherwise wrecks performance.\n")
TEXT(" 0: off (default)\n")
TEXT(" 1: enabled (default)"));
static TAutoConsoleVariable<int32> CVarRHICmdBalanceParallelLists(
TEXT("r.RHICmdBalanceParallelLists"),
2,
TEXT("Allows to enable a preprocess of the drawlists to try to balance the load equally among the command lists.\n")
TEXT(" 0: off \n")
TEXT(" 1: enabled")
TEXT(" 2: experiemental, uses previous frame results (does not do anything in split screen etc)"));
static TAutoConsoleVariable<int32> CVarRHICmdMinCmdlistForParallelSubmit(
TEXT("r.RHICmdMinCmdlistForParallelSubmit"),
2,
TEXT("Minimum number of parallel translate command lists to submit. If there are fewer than this number, they just run on the RHI thread and immediate context."));
static TAutoConsoleVariable<int32> CVarRHICmdMinDrawsPerParallelCmdList(
TEXT("r.RHICmdMinDrawsPerParallelCmdList"),
64,
TEXT("The minimum number of draws per cmdlist. If the total number of draws is less than this, then no parallel work will be done at all. This can't always be honored or done correctly. More effective with RHICmdBalanceParallelLists."));
static TAutoConsoleVariable<int32> CVarWideCustomResolve(
TEXT("r.WideCustomResolve"),
0,
TEXT("Use a wide custom resolve filter when MSAA is enabled")
TEXT("0: Disabled [hardware box filter]")
TEXT("1: Wide (r=1.25, 12 samples)")
TEXT("2: Wider (r=1.4, 16 samples)")
TEXT("3: Widest (r=1.5, 20 samples)"),
ECVF_RenderThreadSafe | ECVF_Scalability
);
static FParallelCommandListSet* GOutstandingParallelCommandListSet = nullptr;
DECLARE_CYCLE_STAT(TEXT("DeferredShadingSceneRenderer MotionBlurStartFrame"), STAT_FDeferredShadingSceneRenderer_MotionBlurStartFrame, STATGROUP_SceneRendering);
DECLARE_CYCLE_STAT(TEXT("DeferredShadingSceneRenderer UpdateMotionBlurCache"), STAT_FDeferredShadingSceneRenderer_UpdateMotionBlurCache, STATGROUP_SceneRendering);
FParallelCommandListSet::FParallelCommandListSet(TStatId InExecuteStat, const FViewInfo& InView, FRHICommandListImmediate& InParentCmdList, bool bInParallelExecute, bool bInCreateSceneContext)
: View(InView)
, DrawRenderState(InView)
, ParentCmdList(InParentCmdList)
, Snapshot(nullptr)
, ExecuteStat(InExecuteStat)
, NumAlloc(0)
, bParallelExecute(GRHISupportsParallelRHIExecute && bInParallelExecute)
, bCreateSceneContext(bInCreateSceneContext)
{
Width = CVarRHICmdWidth.GetValueOnRenderThread();
MinDrawsPerCommandList = CVarRHICmdMinDrawsPerParallelCmdList.GetValueOnRenderThread();
bSpewBalance = !!CVarRHICmdSpewParallelListBalance.GetValueOnRenderThread();
int32 IntBalance = CVarRHICmdBalanceParallelLists.GetValueOnRenderThread();
bBalanceCommands = !!IntBalance;
bBalanceCommandsWithLastFrame = IntBalance > 1;
CommandLists.Reserve(Width * 8);
Events.Reserve(Width * 8);
NumDrawsIfKnown.Reserve(Width * 8);
check(!GOutstandingParallelCommandListSet);
GOutstandingParallelCommandListSet = this;
}
FRHICommandList* FParallelCommandListSet::AllocCommandList()
{
NumAlloc++;
return new FRHICommandList;
}
void FParallelCommandListSet::Dispatch(bool bHighPriority)
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_FParallelCommandListSet_Dispatch);
check(IsInRenderingThread() && FMemStack::Get().GetNumMarks() == 1); // we do not want this popped before the end of the scene and it better be the scene allocator
check(CommandLists.Num() == Events.Num());
check(CommandLists.Num() == NumAlloc);
if (bSpewBalance)
{
// finish them all
for (auto& Event : Events)
{
FTaskGraphInterface::Get().WaitUntilTaskCompletes(Event, ENamedThreads::RenderThread_Local);
}
// spew sizes
int32 Index = 0;
for (auto CmdList : CommandLists)
{
UE_LOG(LogTemp, Display, TEXT("CmdList %2d/%2d : %8dKB"), Index, CommandLists.Num(), (CmdList->GetUsedMemory() + 1023) / 1024);
Index++;
}
}
bool bActuallyDoParallelTranslate = bParallelExecute && CommandLists.Num() >= CVarRHICmdMinCmdlistForParallelSubmit.GetValueOnRenderThread();
if (bActuallyDoParallelTranslate)
{
int32 Total = 0;
bool bIndeterminate = false;
for (int32 Count : NumDrawsIfKnown)
{
if (Count < 0)
{
bIndeterminate = true;
break; // can't determine how many are in this one; assume we should run parallel translate
}
Total += Count;
}
if (!bIndeterminate && Total < MinDrawsPerCommandList)
{
UE_CLOG(bSpewBalance, LogTemp, Display, TEXT("Disabling parallel translate because the number of draws is known to be small."));
bActuallyDoParallelTranslate = false;
}
}
if (bActuallyDoParallelTranslate)
{
UE_CLOG(bSpewBalance, LogTemp, Display, TEXT("%d cmdlists for parallel translate"), CommandLists.Num());
check(GRHISupportsParallelRHIExecute);
NumAlloc -= CommandLists.Num();
ParentCmdList.QueueParallelAsyncCommandListSubmit(&Events[0], bHighPriority, &CommandLists[0], &NumDrawsIfKnown[0], CommandLists.Num(), (MinDrawsPerCommandList * 4) / 3, bSpewBalance);
SetStateOnCommandList(ParentCmdList);
}
else
{
UE_CLOG(bSpewBalance, LogTemp, Display, TEXT("%d cmdlists (no parallel translate desired)"), CommandLists.Num());
for (int32 Index = 0; Index < CommandLists.Num(); Index++)
{
ParentCmdList.QueueAsyncCommandListSubmit(Events[Index], CommandLists[Index]);
NumAlloc--;
}
}
CommandLists.Reset();
Snapshot = nullptr;
Events.Reset();
QUICK_SCOPE_CYCLE_COUNTER(STAT_FParallelCommandListSet_Dispatch_ServiceLocalQueue);
FTaskGraphInterface::Get().ProcessThreadUntilIdle(ENamedThreads::RenderThread_Local);
}
FParallelCommandListSet::~FParallelCommandListSet()
{
check(GOutstandingParallelCommandListSet == this);
GOutstandingParallelCommandListSet = nullptr;
check(IsInRenderingThread() && FMemStack::Get().GetNumMarks() == 1); // we do not want this popped before the end of the scene and it better be the scene allocator
checkf(CommandLists.Num() == 0, TEXT("Derived class of FParallelCommandListSet did not call Dispatch in virtual destructor"));
checkf(NumAlloc == 0, TEXT("Derived class of FParallelCommandListSet did not call Dispatch in virtual destructor"));
}
FRHICommandList* FParallelCommandListSet::NewParallelCommandList()
{
FRHICommandList* Result = AllocCommandList();
Result->ExecuteStat = ExecuteStat;
SetStateOnCommandList(*Result);
if (bCreateSceneContext)
{
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(ParentCmdList);
check(&SceneContext == &FSceneRenderTargets::Get_FrameConstantsOnly()); // the immediate should not have an overridden context
if (!Snapshot)
{
Snapshot = SceneContext.CreateSnapshot(View);
}
Snapshot->SetSnapshotOnCmdList(*Result);
check(&SceneContext != &FSceneRenderTargets::Get(*Result)); // the new commandlist should have a snapshot
}
return Result;
}
void FParallelCommandListSet::AddParallelCommandList(FRHICommandList* CmdList, FGraphEventRef& CompletionEvent, int32 InNumDrawsIfKnown)
{
check(IsInRenderingThread() && FMemStack::Get().GetNumMarks() == 1); // we do not want this popped before the end of the scene and it better be the scene allocator
check(CommandLists.Num() == Events.Num());
CommandLists.Add(CmdList);
Events.Add(CompletionEvent);
NumDrawsIfKnown.Add(InNumDrawsIfKnown);
}
void FParallelCommandListSet::WaitForTasks()
{
if (GOutstandingParallelCommandListSet)
{
GOutstandingParallelCommandListSet->WaitForTasksInternal();
}
}
void FParallelCommandListSet::WaitForTasksInternal()
{
check(IsInRenderingThread());
QUICK_SCOPE_CYCLE_COUNTER(STAT_FParallelCommandListSet_WaitForTasks);
FGraphEventArray WaitOutstandingTasks;
for (int32 Index = 0; Index < Events.Num(); Index++)
{
if (!Events[Index]->IsComplete())
{
WaitOutstandingTasks.Add(Events[Index]);
}
}
if (WaitOutstandingTasks.Num())
{
check(!FTaskGraphInterface::Get().IsThreadProcessingTasks(ENamedThreads::RenderThread_Local));
FTaskGraphInterface::Get().WaitUntilTasksComplete(WaitOutstandingTasks, ENamedThreads::RenderThread_Local);
}
}
/*-----------------------------------------------------------------------------
FViewInfo
-----------------------------------------------------------------------------*/
/**
* Initialization constructor. Passes all parameters to FSceneView constructor
*/
FViewInfo::FViewInfo(const FSceneViewInitOptions& InitOptions)
: FSceneView(InitOptions)
, IndividualOcclusionQueries((FSceneViewState*)InitOptions.SceneViewStateInterface, 1)
, GroupedOcclusionQueries((FSceneViewState*)InitOptions.SceneViewStateInterface, FOcclusionQueryBatcher::OccludedPrimitiveQueryBatchSize)
{
Init();
}
/**
* Initialization constructor.
* @param InView - copy to init with
*/
FViewInfo::FViewInfo(const FSceneView* InView)
: FSceneView(*InView)
, IndividualOcclusionQueries((FSceneViewState*)InView->State,1)
, GroupedOcclusionQueries((FSceneViewState*)InView->State,FOcclusionQueryBatcher::OccludedPrimitiveQueryBatchSize)
, CustomVisibilityQuery(nullptr)
{
Init();
}
void FViewInfo::Init()
{
CachedViewUniformShaderParameters = nullptr;
bHasTranslucentViewMeshElements = 0;
bPrevTransformsReset = false;
bIgnoreExistingQueries = false;
bDisableQuerySubmissions = false;
bDisableDistanceBasedFadeTransitions = false;
ShadingModelMaskInView = 0;
NumVisibleStaticMeshElements = 0;
PrecomputedVisibilityData = 0;
bSceneHasDecals = 0;
bIsViewInfo = true;
bUsesGlobalDistanceField = false;
bUsesLightingChannels = false;
bTranslucentSurfaceLighting = false;
bUsesSceneDepth = false;
ExponentialFogParameters = FVector4(0,1,1,0);
ExponentialFogColor = FVector::ZeroVector;
FogMaxOpacity = 1;
ExponentialFogParameters3 = FVector4(0, 0, 0, 0);
SinCosInscatteringColorCubemapRotation = FVector2D(0, 0);
FogInscatteringColorCubemap = NULL;
FogInscatteringTextureParameters = FVector::ZeroVector;
bUseDirectionalInscattering = false;
DirectionalInscatteringExponent = 0;
DirectionalInscatteringStartDistance = 0;
InscatteringLightDirection = FVector(0);
DirectionalInscatteringColor = FLinearColor(ForceInit);
for (int32 CascadeIndex = 0; CascadeIndex < TVC_MAX; CascadeIndex++)
{
TranslucencyLightingVolumeMin[CascadeIndex] = FVector(0);
TranslucencyVolumeVoxelSize[CascadeIndex] = 0;
TranslucencyLightingVolumeSize[CascadeIndex] = FVector(0);
}
const int32 MaxMobileShadowCascadeCount = FMath::Clamp(CVarMaxMobileShadowCascades.GetValueOnAnyThread(), 1, MAX_MOBILE_SHADOWCASCADES);
const int32 MaxShadowCascadeCountUpperBound = GetFeatureLevel() >= ERHIFeatureLevel::SM4 ? 10 : MaxMobileShadowCascadeCount;
MaxShadowCascades = FMath::Clamp<int32>(CVarMaxShadowCascades.GetValueOnAnyThread(), 1, MaxShadowCascadeCountUpperBound);
ShaderMap = GetGlobalShaderMap(FeatureLevel);
ViewState = (FSceneViewState*)State;
bIsSnapshot = false;
bAllowStencilDither = false;
ForwardLightingResources = &ForwardLightingResourcesStorage;
NumBoxReflectionCaptures = 0;
NumSphereReflectionCaptures = 0;
FurthestReflectionCaptureDistance = 0;
// Disable HDR encoding for editor elements.
EditorSimpleElementCollector.BatchedElements.EnableMobileHDREncoding(false);
}
FViewInfo::~FViewInfo()
{
for(int32 ResourceIndex = 0;ResourceIndex < DynamicResources.Num();ResourceIndex++)
{
DynamicResources[ResourceIndex]->ReleasePrimitiveResource();
}
if (CustomVisibilityQuery)
{
CustomVisibilityQuery->Release();
}
}
void FViewInfo::SetupSkyIrradianceEnvironmentMapConstants(FVector4* OutSkyIrradianceEnvironmentMap) const
{
FScene* Scene = nullptr;
if (Family->Scene)
{
Scene = Family->Scene->GetRenderScene();
}
if (Scene
&& Scene->SkyLight
// Skylights with static lighting already had their diffuse contribution baked into lightmaps
&& !Scene->SkyLight->bHasStaticLighting
&& Family->EngineShowFlags.SkyLighting)
{
const FSHVectorRGB3& SkyIrradiance = Scene->SkyLight->IrradianceEnvironmentMap;
const float SqrtPI = FMath::Sqrt(PI);
const float Coefficient0 = 1.0f / (2 * SqrtPI);
const float Coefficient1 = FMath::Sqrt(3) / (3 * SqrtPI);
const float Coefficient2 = FMath::Sqrt(15) / (8 * SqrtPI);
const float Coefficient3 = FMath::Sqrt(5) / (16 * SqrtPI);
const float Coefficient4 = .5f * Coefficient2;
// Pack the SH coefficients in a way that makes applying the lighting use the least shader instructions
// This has the diffuse convolution coefficients baked in
// See "Stupid Spherical Harmonics (SH) Tricks"
OutSkyIrradianceEnvironmentMap[0].X = -Coefficient1 * SkyIrradiance.R.V[3];
OutSkyIrradianceEnvironmentMap[0].Y = -Coefficient1 * SkyIrradiance.R.V[1];
OutSkyIrradianceEnvironmentMap[0].Z = Coefficient1 * SkyIrradiance.R.V[2];
OutSkyIrradianceEnvironmentMap[0].W = Coefficient0 * SkyIrradiance.R.V[0] - Coefficient3 * SkyIrradiance.R.V[6];
OutSkyIrradianceEnvironmentMap[1].X = -Coefficient1 * SkyIrradiance.G.V[3];
OutSkyIrradianceEnvironmentMap[1].Y = -Coefficient1 * SkyIrradiance.G.V[1];
OutSkyIrradianceEnvironmentMap[1].Z = Coefficient1 * SkyIrradiance.G.V[2];
OutSkyIrradianceEnvironmentMap[1].W = Coefficient0 * SkyIrradiance.G.V[0] - Coefficient3 * SkyIrradiance.G.V[6];
OutSkyIrradianceEnvironmentMap[2].X = -Coefficient1 * SkyIrradiance.B.V[3];
OutSkyIrradianceEnvironmentMap[2].Y = -Coefficient1 * SkyIrradiance.B.V[1];
OutSkyIrradianceEnvironmentMap[2].Z = Coefficient1 * SkyIrradiance.B.V[2];
OutSkyIrradianceEnvironmentMap[2].W = Coefficient0 * SkyIrradiance.B.V[0] - Coefficient3 * SkyIrradiance.B.V[6];
OutSkyIrradianceEnvironmentMap[3].X = Coefficient2 * SkyIrradiance.R.V[4];
OutSkyIrradianceEnvironmentMap[3].Y = -Coefficient2 * SkyIrradiance.R.V[5];
OutSkyIrradianceEnvironmentMap[3].Z = 3 * Coefficient3 * SkyIrradiance.R.V[6];
OutSkyIrradianceEnvironmentMap[3].W = -Coefficient2 * SkyIrradiance.R.V[7];
OutSkyIrradianceEnvironmentMap[4].X = Coefficient2 * SkyIrradiance.G.V[4];
OutSkyIrradianceEnvironmentMap[4].Y = -Coefficient2 * SkyIrradiance.G.V[5];
OutSkyIrradianceEnvironmentMap[4].Z = 3 * Coefficient3 * SkyIrradiance.G.V[6];
OutSkyIrradianceEnvironmentMap[4].W = -Coefficient2 * SkyIrradiance.G.V[7];
OutSkyIrradianceEnvironmentMap[5].X = Coefficient2 * SkyIrradiance.B.V[4];
OutSkyIrradianceEnvironmentMap[5].Y = -Coefficient2 * SkyIrradiance.B.V[5];
OutSkyIrradianceEnvironmentMap[5].Z = 3 * Coefficient3 * SkyIrradiance.B.V[6];
OutSkyIrradianceEnvironmentMap[5].W = -Coefficient2 * SkyIrradiance.B.V[7];
OutSkyIrradianceEnvironmentMap[6].X = Coefficient4 * SkyIrradiance.R.V[8];
OutSkyIrradianceEnvironmentMap[6].Y = Coefficient4 * SkyIrradiance.G.V[8];
OutSkyIrradianceEnvironmentMap[6].Z = Coefficient4 * SkyIrradiance.B.V[8];
OutSkyIrradianceEnvironmentMap[6].W = 1;
}
else
{
FMemory::Memzero(OutSkyIrradianceEnvironmentMap, sizeof(FVector4) * 7);
}
}
void UpdateNoiseTextureParameters(FViewUniformShaderParameters& ViewUniformShaderParameters)
{
if (GSystemTextures.PerlinNoiseGradient.GetReference())
{
ViewUniformShaderParameters.PerlinNoiseGradientTexture = (FTexture2DRHIRef&)GSystemTextures.PerlinNoiseGradient->GetRenderTargetItem().ShaderResourceTexture;
SetBlack2DIfNull(ViewUniformShaderParameters.PerlinNoiseGradientTexture);
}
check(ViewUniformShaderParameters.PerlinNoiseGradientTexture);
ViewUniformShaderParameters.PerlinNoiseGradientTextureSampler = TStaticSamplerState<SF_Point, AM_Wrap, AM_Wrap, AM_Wrap>::GetRHI();
if (GSystemTextures.PerlinNoise3D.GetReference())
{
ViewUniformShaderParameters.PerlinNoise3DTexture = (FTexture3DRHIRef&)GSystemTextures.PerlinNoise3D->GetRenderTargetItem().ShaderResourceTexture;
SetBlack3DIfNull(ViewUniformShaderParameters.PerlinNoise3DTexture);
}
check(ViewUniformShaderParameters.PerlinNoise3DTexture);
ViewUniformShaderParameters.PerlinNoise3DTextureSampler = TStaticSamplerState<SF_Bilinear, AM_Wrap, AM_Wrap, AM_Wrap>::GetRHI();
}
/** Creates the view's uniform buffers given a set of view transforms. */
void FViewInfo::SetupUniformBufferParameters(
FSceneRenderTargets& SceneContext,
const FViewMatrices& InViewMatrices,
const FViewMatrices& InPrevViewMatrices,
FBox* OutTranslucentCascadeBoundsArray,
int32 NumTranslucentCascades,
FViewUniformShaderParameters& ViewUniformShaderParameters) const
{
check(Family);
// Create the view's uniform buffer.
// Mobile multi-view is not side by side
const FIntRect EffectiveViewRect = (bIsMobileMultiViewEnabled) ? FIntRect(0, 0, ViewRect.Width(), ViewRect.Height()) : ViewRect;
// TODO: We should use a view and previous view uniform buffer to avoid code duplication and keep consistency
SetupCommonViewUniformBufferParameters(
ViewUniformShaderParameters,
SceneContext.GetBufferSizeXY(),
SceneContext.GetMSAACount(),
EffectiveViewRect,
InViewMatrices,
InPrevViewMatrices
);
const bool bCheckerboardSubsurfaceRendering = FRCPassPostProcessSubsurface::RequiresCheckerboardSubsurfaceRendering( SceneContext.GetSceneColorFormat() );
ViewUniformShaderParameters.bCheckerboardSubsurfaceProfileRendering = bCheckerboardSubsurfaceRendering ? 1.0f : 0.0f;
FScene* Scene = nullptr;
if (Family->Scene)
{
Scene = Family->Scene->GetRenderScene();
}
if (Scene)
{
if (Scene->SimpleDirectionalLight)
{
ViewUniformShaderParameters.DirectionalLightColor = Scene->SimpleDirectionalLight->Proxy->GetColor() / PI;
ViewUniformShaderParameters.DirectionalLightDirection = -Scene->SimpleDirectionalLight->Proxy->GetDirection();
}
else
{
ViewUniformShaderParameters.DirectionalLightColor = FLinearColor::Black;
ViewUniformShaderParameters.DirectionalLightDirection = FVector::ZeroVector;
}
// Atmospheric fog parameters
if (ShouldRenderAtmosphere(*Family) && Scene->AtmosphericFog)
{
ViewUniformShaderParameters.AtmosphericFogSunPower = Scene->AtmosphericFog->SunMultiplier;
ViewUniformShaderParameters.AtmosphericFogPower = Scene->AtmosphericFog->FogMultiplier;
ViewUniformShaderParameters.AtmosphericFogDensityScale = Scene->AtmosphericFog->InvDensityMultiplier;
ViewUniformShaderParameters.AtmosphericFogDensityOffset = Scene->AtmosphericFog->DensityOffset;
ViewUniformShaderParameters.AtmosphericFogGroundOffset = Scene->AtmosphericFog->GroundOffset;
ViewUniformShaderParameters.AtmosphericFogDistanceScale = Scene->AtmosphericFog->DistanceScale;
ViewUniformShaderParameters.AtmosphericFogAltitudeScale = Scene->AtmosphericFog->AltitudeScale;
ViewUniformShaderParameters.AtmosphericFogHeightScaleRayleigh = Scene->AtmosphericFog->RHeight;
ViewUniformShaderParameters.AtmosphericFogStartDistance = Scene->AtmosphericFog->StartDistance;
ViewUniformShaderParameters.AtmosphericFogDistanceOffset = Scene->AtmosphericFog->DistanceOffset;
ViewUniformShaderParameters.AtmosphericFogSunDiscScale = Scene->AtmosphericFog->SunDiscScale;
ViewUniformShaderParameters.AtmosphericFogSunColor = Scene->SunLight ? Scene->SunLight->Proxy->GetColor() : Scene->AtmosphericFog->DefaultSunColor;
ViewUniformShaderParameters.AtmosphericFogSunDirection = Scene->SunLight ? -Scene->SunLight->Proxy->GetDirection() : -Scene->AtmosphericFog->DefaultSunDirection;
ViewUniformShaderParameters.AtmosphericFogRenderMask = Scene->AtmosphericFog->RenderFlag & (EAtmosphereRenderFlag::E_DisableGroundScattering | EAtmosphereRenderFlag::E_DisableSunDisk);
ViewUniformShaderParameters.AtmosphericFogInscatterAltitudeSampleNum = Scene->AtmosphericFog->InscatterAltitudeSampleNum;
}
else
{
ViewUniformShaderParameters.AtmosphericFogSunPower = 0.f;
ViewUniformShaderParameters.AtmosphericFogPower = 0.f;
ViewUniformShaderParameters.AtmosphericFogDensityScale = 0.f;
ViewUniformShaderParameters.AtmosphericFogDensityOffset = 0.f;
ViewUniformShaderParameters.AtmosphericFogGroundOffset = 0.f;
ViewUniformShaderParameters.AtmosphericFogDistanceScale = 0.f;
ViewUniformShaderParameters.AtmosphericFogAltitudeScale = 0.f;
ViewUniformShaderParameters.AtmosphericFogHeightScaleRayleigh = 0.f;
ViewUniformShaderParameters.AtmosphericFogStartDistance = 0.f;
ViewUniformShaderParameters.AtmosphericFogDistanceOffset = 0.f;
ViewUniformShaderParameters.AtmosphericFogSunDiscScale = 1.f;
//Added check so atmospheric light color and vector can use a directional light without needing an atmospheric fog actor in the scene
ViewUniformShaderParameters.AtmosphericFogSunColor = Scene->SunLight ? Scene->SunLight->Proxy->GetColor() : FLinearColor::Black;
ViewUniformShaderParameters.AtmosphericFogSunDirection = Scene->SunLight ? -Scene->SunLight->Proxy->GetDirection() : FVector::ZeroVector;
ViewUniformShaderParameters.AtmosphericFogRenderMask = EAtmosphereRenderFlag::E_EnableAll;
ViewUniformShaderParameters.AtmosphericFogInscatterAltitudeSampleNum = 0;
}
}
else
{
// Atmospheric fog parameters
ViewUniformShaderParameters.AtmosphericFogSunPower = 0.f;
ViewUniformShaderParameters.AtmosphericFogPower = 0.f;
ViewUniformShaderParameters.AtmosphericFogDensityScale = 0.f;
ViewUniformShaderParameters.AtmosphericFogDensityOffset = 0.f;
ViewUniformShaderParameters.AtmosphericFogGroundOffset = 0.f;
ViewUniformShaderParameters.AtmosphericFogDistanceScale = 0.f;
ViewUniformShaderParameters.AtmosphericFogAltitudeScale = 0.f;
ViewUniformShaderParameters.AtmosphericFogHeightScaleRayleigh = 0.f;
ViewUniformShaderParameters.AtmosphericFogStartDistance = 0.f;
ViewUniformShaderParameters.AtmosphericFogDistanceOffset = 0.f;
ViewUniformShaderParameters.AtmosphericFogSunDiscScale = 1.f;
ViewUniformShaderParameters.AtmosphericFogSunColor = FLinearColor::Black;
ViewUniformShaderParameters.AtmosphericFogSunDirection = FVector::ZeroVector;
ViewUniformShaderParameters.AtmosphericFogRenderMask = EAtmosphereRenderFlag::E_EnableAll;
ViewUniformShaderParameters.AtmosphericFogInscatterAltitudeSampleNum = 0;
}
ViewUniformShaderParameters.AtmosphereTransmittanceTexture_UB = OrBlack2DIfNull(AtmosphereTransmittanceTexture);
ViewUniformShaderParameters.AtmosphereIrradianceTexture_UB = OrBlack2DIfNull(AtmosphereIrradianceTexture);
ViewUniformShaderParameters.AtmosphereInscatterTexture_UB = OrBlack3DIfNull(AtmosphereInscatterTexture);
ViewUniformShaderParameters.AtmosphereTransmittanceTextureSampler_UB = TStaticSamplerState<SF_Bilinear>::GetRHI();
ViewUniformShaderParameters.AtmosphereIrradianceTextureSampler_UB = TStaticSamplerState<SF_Bilinear>::GetRHI();
ViewUniformShaderParameters.AtmosphereInscatterTextureSampler_UB = TStaticSamplerState<SF_Bilinear>::GetRHI();
// This should probably be in SetupCommonViewUniformBufferParameters, but drags in too many dependencies
UpdateNoiseTextureParameters(ViewUniformShaderParameters);
SetupDefaultGlobalDistanceFieldUniformBufferParameters(ViewUniformShaderParameters);
SetupVolumetricFogUniformBufferParameters(ViewUniformShaderParameters);
uint32 StateFrameIndexMod8 = 0;
if(State)
{
ViewUniformShaderParameters.TemporalAAParams = FVector4(
ViewState->GetCurrentTemporalAASampleIndex(),
ViewState->GetCurrentTemporalAASampleCount(),
TemporalJitterPixelsX,
TemporalJitterPixelsY);
StateFrameIndexMod8 = ViewState->GetFrameIndexMod8();
}
else
{
ViewUniformShaderParameters.TemporalAAParams = FVector4(0, 1, 0, 0);
}
ViewUniformShaderParameters.StateFrameIndexMod8 = StateFrameIndexMod8;
{
// If rendering in stereo, the right eye uses the left eye's translucency lighting volume.
const FViewInfo* PrimaryView = this;
if (StereoPass == eSSP_RIGHT_EYE)
{
int32 ViewIndex = Family->Views.Find(this);
if (Family->Views.IsValidIndex(ViewIndex) && Family->Views.IsValidIndex(ViewIndex - 1))
{
const FSceneView* LeftEyeView = Family->Views[ViewIndex - 1];
if (LeftEyeView->bIsViewInfo && LeftEyeView->StereoPass == eSSP_LEFT_EYE)
{
PrimaryView = static_cast<const FViewInfo*>(LeftEyeView);
}
}
}
PrimaryView->CalcTranslucencyLightingVolumeBounds(OutTranslucentCascadeBoundsArray, NumTranslucentCascades);
}
for (int32 CascadeIndex = 0; CascadeIndex < NumTranslucentCascades; CascadeIndex++)
{
const float VolumeVoxelSize = (OutTranslucentCascadeBoundsArray[CascadeIndex].Max.X - OutTranslucentCascadeBoundsArray[CascadeIndex].Min.X) / GTranslucencyLightingVolumeDim;
const FVector VolumeSize = OutTranslucentCascadeBoundsArray[CascadeIndex].Max - OutTranslucentCascadeBoundsArray[CascadeIndex].Min;
ViewUniformShaderParameters.TranslucencyLightingVolumeMin[CascadeIndex] = FVector4(OutTranslucentCascadeBoundsArray[CascadeIndex].Min, 1.0f / GTranslucencyLightingVolumeDim);
ViewUniformShaderParameters.TranslucencyLightingVolumeInvSize[CascadeIndex] = FVector4(FVector(1.0f) / VolumeSize, VolumeVoxelSize);
}
// The exposure scale is just a scalar but needs to be a float4 to workaround a driver bug on IOS.
// After 4.2 we can put the workaround in the cross compiler.
float ExposureScale = FRCPassPostProcessEyeAdaptation::ComputeExposureScaleValue( *this );
ViewUniformShaderParameters.ExposureScale = FVector4(ExposureScale, ExposureScale, ExposureScale, 1.0f);
ViewUniformShaderParameters.DepthOfFieldFocalDistance = FinalPostProcessSettings.DepthOfFieldFocalDistance;
ViewUniformShaderParameters.DepthOfFieldSensorWidth = FinalPostProcessSettings.DepthOfFieldSensorWidth;
ViewUniformShaderParameters.DepthOfFieldFocalRegion = FinalPostProcessSettings.DepthOfFieldFocalRegion;
// clamped to avoid div by 0 in shader
ViewUniformShaderParameters.DepthOfFieldNearTransitionRegion = FMath::Max(0.01f, FinalPostProcessSettings.DepthOfFieldNearTransitionRegion);
// clamped to avoid div by 0 in shader
ViewUniformShaderParameters.DepthOfFieldFarTransitionRegion = FMath::Max(0.01f, FinalPostProcessSettings.DepthOfFieldFarTransitionRegion);
ViewUniformShaderParameters.DepthOfFieldScale = FinalPostProcessSettings.DepthOfFieldScale;
ViewUniformShaderParameters.DepthOfFieldFocalLength = 50.0f;
ViewUniformShaderParameters.bSubsurfacePostprocessEnabled = GCompositionLighting.IsSubsurfacePostprocessRequired() ? 1.0f : 0.0f;
{
// This is the CVar default
float Value = 1.0f;
// Compiled out in SHIPPING to make cheating a bit harder.
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
Value = CVarGeneralPurposeTweak.GetValueOnRenderThread();
#endif
ViewUniformShaderParameters.GeneralPurposeTweak = Value;
}
ViewUniformShaderParameters.DemosaicVposOffset = 0.0f;
{
ViewUniformShaderParameters.DemosaicVposOffset = CVarDemosaicVposOffset.GetValueOnRenderThread();
}
ViewUniformShaderParameters.IndirectLightingColorScale = FVector(FinalPostProcessSettings.IndirectLightingColor.R * FinalPostProcessSettings.IndirectLightingIntensity,
FinalPostProcessSettings.IndirectLightingColor.G * FinalPostProcessSettings.IndirectLightingIntensity,
FinalPostProcessSettings.IndirectLightingColor.B * FinalPostProcessSettings.IndirectLightingIntensity);
ViewUniformShaderParameters.NormalCurvatureToRoughnessScaleBias.X = FMath::Clamp(CVarNormalCurvatureToRoughnessScale.GetValueOnAnyThread(), 0.0f, 2.0f);
ViewUniformShaderParameters.NormalCurvatureToRoughnessScaleBias.Y = FMath::Clamp(CVarNormalCurvatureToRoughnessBias.GetValueOnAnyThread(), -1.0f, 1.0f);
ViewUniformShaderParameters.NormalCurvatureToRoughnessScaleBias.Z = FMath::Clamp(CVarNormalCurvatureToRoughnessExponent.GetValueOnAnyThread(), .05f, 20.0f);
ViewUniformShaderParameters.RenderingReflectionCaptureMask = bIsReflectionCapture ? 1.0f : 0.0f;
ViewUniformShaderParameters.AmbientCubemapTint = FinalPostProcessSettings.AmbientCubemapTint;
ViewUniformShaderParameters.AmbientCubemapIntensity = FinalPostProcessSettings.AmbientCubemapIntensity;
{
// Enables HDR encoding mode selection without recompile of all PC shaders during ES2 emulation.
ViewUniformShaderParameters.HDR32bppEncodingMode = 0;
if (IsMobileHDR32bpp())
{
ViewUniformShaderParameters.HDR32bppEncodingMode = IsMobileHDRMosaic() ? 1.0f : 2.0f;
}
}
ViewUniformShaderParameters.CircleDOFParams = CircleDofHalfCoc(*this);
if (Family->Scene)
{
Scene = Family->Scene->GetRenderScene();
}
ERHIFeatureLevel::Type RHIFeatureLevel = Scene == nullptr ? GMaxRHIFeatureLevel : Scene->GetFeatureLevel();
if (Scene && Scene->SkyLight)
{
FSkyLightSceneProxy* SkyLight = Scene->SkyLight;
ViewUniformShaderParameters.SkyLightColor = SkyLight->LightColor;
bool bApplyPrecomputedBentNormalShadowing =
SkyLight->bCastShadows
&& SkyLight->bWantsStaticShadowing;
ViewUniformShaderParameters.SkyLightParameters = bApplyPrecomputedBentNormalShadowing ? 1 : 0;
}
else
{
ViewUniformShaderParameters.SkyLightColor = FLinearColor::Black;
ViewUniformShaderParameters.SkyLightParameters = 0;
}
// Make sure there's no padding since we're going to cast to FVector4*
checkSlow(sizeof(ViewUniformShaderParameters.SkyIrradianceEnvironmentMap) == sizeof(FVector4)* 7);
SetupSkyIrradianceEnvironmentMapConstants((FVector4*)&ViewUniformShaderParameters.SkyIrradianceEnvironmentMap);
ViewUniformShaderParameters.MobilePreviewMode =
(GIsEditor &&
(RHIFeatureLevel == ERHIFeatureLevel::ES2 || RHIFeatureLevel == ERHIFeatureLevel::ES3_1) &&
GMaxRHIFeatureLevel > ERHIFeatureLevel::ES3_1) ? 1.0f : 0.0f;
// Padding between the left and right eye may be introduced by an HMD, which instanced stereo needs to account for.
if ((Family != nullptr) && (StereoPass != eSSP_FULL) && (Family->Views.Num() > 1))
{
check(Family->Views.Num() >= 2);
const float FamilySizeX = static_cast<float>(Family->InstancedStereoWidth);
const float EyePaddingSize = static_cast<float>(Family->Views[1]->ViewRect.Min.X - Family->Views[0]->ViewRect.Max.X);
ViewUniformShaderParameters.HMDEyePaddingOffset = (FamilySizeX - EyePaddingSize) / FamilySizeX;
}
else
{
ViewUniformShaderParameters.HMDEyePaddingOffset = 1.0f;
}
ViewUniformShaderParameters.ReflectionCubemapMaxMip = FMath::FloorLog2(UReflectionCaptureComponent::GetReflectionCaptureSize_RenderThread());
ViewUniformShaderParameters.ShowDecalsMask = Family->EngineShowFlags.Decals ? 1.0f : 0.0f;
extern int32 GDistanceFieldAOSpecularOcclusionMode;
ViewUniformShaderParameters.DistanceFieldAOSpecularOcclusionMode = GDistanceFieldAOSpecularOcclusionMode;
ViewUniformShaderParameters.IndirectCapsuleSelfShadowingIntensity = Scene ? Scene->DynamicIndirectShadowsSelfShadowingIntensity : 1.0f;
extern FVector GetReflectionEnvironmentRoughnessMixingScaleBiasAndLargestWeight();
ViewUniformShaderParameters.ReflectionEnvironmentRoughnessMixingScaleBiasAndLargestWeight = GetReflectionEnvironmentRoughnessMixingScaleBiasAndLargestWeight();
ViewUniformShaderParameters.StereoPassIndex = (StereoPass != eSSP_RIGHT_EYE) ? 0 : 1;
}
void FViewInfo::InitRHIResources()
{
FBox VolumeBounds[TVC_MAX];
check(IsInRenderingThread());
CachedViewUniformShaderParameters = MakeUnique<FViewUniformShaderParameters>();
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(FRHICommandListExecutor::GetImmediateCommandList());
SetupUniformBufferParameters(
SceneContext,
VolumeBounds,
TVC_MAX,
*CachedViewUniformShaderParameters);
ViewUniformBuffer = TUniformBufferRef<FViewUniformShaderParameters>::CreateUniformBufferImmediate(*CachedViewUniformShaderParameters, UniformBuffer_SingleFrame);
for (int32 CascadeIndex = 0; CascadeIndex < TVC_MAX; CascadeIndex++)
{
TranslucencyLightingVolumeMin[CascadeIndex] = VolumeBounds[CascadeIndex].Min;
TranslucencyVolumeVoxelSize[CascadeIndex] = (VolumeBounds[CascadeIndex].Max.X - VolumeBounds[CascadeIndex].Min.X) / GTranslucencyLightingVolumeDim;
TranslucencyLightingVolumeSize[CascadeIndex] = VolumeBounds[CascadeIndex].Max - VolumeBounds[CascadeIndex].Min;
}
// Initialize the dynamic resources used by the view's FViewElementDrawer.
for(int32 ResourceIndex = 0;ResourceIndex < DynamicResources.Num();ResourceIndex++)
{
DynamicResources[ResourceIndex]->InitPrimitiveResource();
}
}
// These are not real view infos, just dumb memory blocks
static TArray<FViewInfo*> ViewInfoSnapshots;
// these are never freed, even at program shutdown
static TArray<FViewInfo*> FreeViewInfoSnapshots;
FViewInfo* FViewInfo::CreateSnapshot() const
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_FViewInfo_CreateSnapshot);
check(IsInRenderingThread()); // we do not want this popped before the end of the scene and it better be the scene allocator
FViewInfo* Result;
if (FreeViewInfoSnapshots.Num())
{
Result = FreeViewInfoSnapshots.Pop(false);
}
else
{
Result = (FViewInfo*)FMemory::Malloc(sizeof(FViewInfo), ALIGNOF(FViewInfo));
}
FMemory::Memcpy(*Result, *this);
// we want these to start null without a reference count, since we clear a ref later
TUniformBufferRef<FViewUniformShaderParameters> NullViewUniformBuffer;
FMemory::Memcpy(Result->ViewUniformBuffer, NullViewUniformBuffer);
FMemory::Memcpy(Result->DownsampledTranslucencyViewUniformBuffer, NullViewUniformBuffer);
TUniformBufferRef<FMobileDirectionalLightShaderParameters> NullMobileDirectionalLightUniformBuffer;
for (size_t i = 0; i < ARRAY_COUNT(Result->MobileDirectionalLightUniformBuffers); i++)
FMemory::Memcpy(Result->MobileDirectionalLightUniformBuffers[i], NullMobileDirectionalLightUniformBuffer);
TUniquePtr<FViewUniformShaderParameters> NullViewParameters;
FMemory::Memcpy(Result->CachedViewUniformShaderParameters, NullViewParameters);
Result->bIsSnapshot = true;
ViewInfoSnapshots.Add(Result);
return Result;
}
void FViewInfo::DestroyAllSnapshots()
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_FViewInfo_DestroyAllSnapshots);
check(IsInRenderingThread());
// we will only keep double the number actually used, plus a few
int32 NumToRemove = FreeViewInfoSnapshots.Num() - (ViewInfoSnapshots.Num() + 2);
if (NumToRemove > 0)
{
for (int32 Index = 0; Index < NumToRemove; Index++)
{
FMemory::Free(FreeViewInfoSnapshots[Index]);
}
FreeViewInfoSnapshots.RemoveAt(0, NumToRemove, false);
}
for (FViewInfo* Snapshot : ViewInfoSnapshots)
{
Snapshot->ViewUniformBuffer.SafeRelease();
Snapshot->CachedViewUniformShaderParameters.Reset();
FreeViewInfoSnapshots.Add(Snapshot);
}
ViewInfoSnapshots.Reset();
}
FSceneViewState* FViewInfo::GetEffectiveViewState() const
{
FSceneViewState* EffectiveViewState = ViewState;
// When rendering in stereo we want to use the same exposure for both eyes.
if (StereoPass == eSSP_RIGHT_EYE)
{
int32 ViewIndex = Family->Views.Find(this);
if (Family->Views.IsValidIndex(ViewIndex))
{
// The left eye is always added before the right eye.
ViewIndex = ViewIndex - 1;
if (Family->Views.IsValidIndex(ViewIndex))
{
const FSceneView* PrimaryView = Family->Views[ViewIndex];
if (PrimaryView->StereoPass == eSSP_LEFT_EYE)
{
EffectiveViewState = (FSceneViewState*)PrimaryView->State;
}
}
}
}
return EffectiveViewState;
}
IPooledRenderTarget* FViewInfo::GetEyeAdaptation(FRHICommandList& RHICmdList) const
{
return GetEyeAdaptationRT(RHICmdList);
}
IPooledRenderTarget* FViewInfo::GetEyeAdaptationRT(FRHICommandList& RHICmdList) const
{
FSceneViewState* EffectiveViewState = GetEffectiveViewState();
IPooledRenderTarget* Result = NULL;
if (EffectiveViewState)
{
Result = EffectiveViewState->GetCurrentEyeAdaptationRT(RHICmdList);
}
return Result;
}
IPooledRenderTarget* FViewInfo::GetLastEyeAdaptationRT(FRHICommandList& RHICmdList) const
{
FSceneViewState* EffectiveViewState = GetEffectiveViewState();
IPooledRenderTarget* Result = NULL;
if (EffectiveViewState)
{
Result = EffectiveViewState->GetLastEyeAdaptationRT(RHICmdList);
}
return Result;
}
void FViewInfo::SwapEyeAdaptationRTs() const
{
FSceneViewState* EffectiveViewState = GetEffectiveViewState();
if (EffectiveViewState)
{
EffectiveViewState->SwapEyeAdaptationRTs();
}
}
bool FViewInfo::HasValidEyeAdaptation() const
{
FSceneViewState* EffectiveViewState = GetEffectiveViewState();
if (EffectiveViewState)
{
return EffectiveViewState->HasValidEyeAdaptation();
}
return false;
}
void FViewInfo::SetValidEyeAdaptation() const
{
FSceneViewState* EffectiveViewState = GetEffectiveViewState();
if (EffectiveViewState)
{
EffectiveViewState->SetValidEyeAdaptation();
}
}
void FViewInfo::SetValidTonemappingLUT() const
{
FSceneViewState* EffectiveViewState = GetEffectiveViewState();
if (EffectiveViewState) EffectiveViewState->SetValidTonemappingLUT();
}
const FTextureRHIRef* FViewInfo::GetTonemappingLUTTexture() const
{
const FTextureRHIRef* TextureRHIRef = NULL;
FSceneViewState* EffectiveViewState = GetEffectiveViewState();
if (EffectiveViewState && EffectiveViewState->HasValidTonemappingLUT())
{
TextureRHIRef = EffectiveViewState->GetTonemappingLUTTexture();
}
return TextureRHIRef;
};
FSceneRenderTargetItem* FViewInfo::GetTonemappingLUTRenderTarget(FRHICommandList& RHICmdList, const int32 LUTSize, const bool bUseVolumeLUT, const bool bNeedUAV) const
{
FSceneRenderTargetItem* TargetItem = NULL;
FSceneViewState* EffectiveViewState = GetEffectiveViewState();
if (EffectiveViewState)
{
TargetItem = &(EffectiveViewState->GetTonemappingLUTRenderTarget(RHICmdList, LUTSize, bUseVolumeLUT, bNeedUAV));
}
return TargetItem;
}
void FDisplayInternalsData::Setup(UWorld *World)
{
DisplayInternalsCVarValue = 0;
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
DisplayInternalsCVarValue = CVarDisplayInternals.GetValueOnGameThread();
if(IsValid())
{
MatineeTime = -1.0f;
uint32 Count = 0;
for (TObjectIterator<AMatineeActor> It; It; ++It)
{
AMatineeActor* MatineeActor = *It;
if(MatineeActor->GetWorld() == World && MatineeActor->bIsPlaying)
{
MatineeTime = MatineeActor->InterpPosition;
++Count;
}
}
if(Count > 1)
{
MatineeTime = -2;
}
check(IsValid());
extern ENGINE_API uint32 GStreamAllResourcesStillInFlight;
NumPendingStreamingRequests = GStreamAllResourcesStillInFlight;
}
#endif
}
void FSortedShadowMaps::Release()
{
for (int32 AtlasIndex = 0; AtlasIndex < ShadowMapAtlases.Num(); AtlasIndex++)
{
ShadowMapAtlases[AtlasIndex].RenderTargets.Release();
}
for (int32 AtlasIndex = 0; AtlasIndex < RSMAtlases.Num(); AtlasIndex++)
{
RSMAtlases[AtlasIndex].RenderTargets.Release();
}
for (int32 AtlasIndex = 0; AtlasIndex < ShadowMapCubemaps.Num(); AtlasIndex++)
{
ShadowMapCubemaps[AtlasIndex].RenderTargets.Release();
}
PreshadowCache.RenderTargets.Release();
}
/*-----------------------------------------------------------------------------
FSceneRenderer
-----------------------------------------------------------------------------*/
FSceneRenderer::FSceneRenderer(const FSceneViewFamily* InViewFamily,FHitProxyConsumer* HitProxyConsumer)
: Scene(InViewFamily->Scene ? InViewFamily->Scene->GetRenderScene() : NULL)
, ViewFamily(*InViewFamily)
, bUsedPrecomputedVisibility(false)
{
check(Scene != NULL);
check(IsInGameThread());
ViewFamily.FrameNumber = Scene ? Scene->GetFrameNumber() : GFrameNumber;
// Copy the individual views.
bool bAnyViewIsLocked = false;
Views.Empty(InViewFamily->Views.Num());
for(int32 ViewIndex = 0;ViewIndex < InViewFamily->Views.Num();ViewIndex++)
{
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
for(int32 ViewIndex2 = 0;ViewIndex2 < InViewFamily->Views.Num();ViewIndex2++)
{
if (ViewIndex != ViewIndex2 && InViewFamily->Views[ViewIndex]->State != NULL)
{
// Verify that each view has a unique view state, as the occlusion query mechanism depends on it.
check(InViewFamily->Views[ViewIndex]->State != InViewFamily->Views[ViewIndex2]->State);
}
}
#endif
// Construct a FViewInfo with the FSceneView properties.
FViewInfo* ViewInfo = new(Views) FViewInfo(InViewFamily->Views[ViewIndex]);
ViewFamily.Views[ViewIndex] = ViewInfo;
ViewInfo->Family = &ViewFamily;
bAnyViewIsLocked |= ViewInfo->bIsLocked;
#if WITH_EDITOR
// Should we allow the user to select translucent primitives?
ViewInfo->bAllowTranslucentPrimitivesInHitProxy =
GEngine->AllowSelectTranslucent() || // User preference enabled?
!ViewInfo->IsPerspectiveProjection(); // Is orthographic view?
#endif
// Batch the view's elements for later rendering.
if(ViewInfo->Drawer)
{
FViewElementPDI ViewElementPDI(ViewInfo,HitProxyConsumer);
ViewInfo->Drawer->Draw(ViewInfo,&ViewElementPDI);
}
}
// If any viewpoint has been locked, set time to zero to avoid time-based
// rendering differences in materials.
if (bAnyViewIsLocked)
{
ViewFamily.CurrentRealTime = 0.0f;
ViewFamily.CurrentWorldTime = 0.0f;
}
if(HitProxyConsumer)
{
// Set the hit proxies show flag.
ViewFamily.EngineShowFlags.SetHitProxies(1);
}
// launch custom visibility queries for views
if (GCustomCullingImpl)
{
for(int32 ViewIndex = 0;ViewIndex < Views.Num();ViewIndex++)
{
FViewInfo& ViewInfo = Views[ViewIndex];
ViewInfo.CustomVisibilityQuery = GCustomCullingImpl->CreateQuery(ViewInfo);
}
}
ViewFamily.ComputeFamilySize();
// copy off the requests
// (I apologize for the const_cast, but didn't seem worth refactoring just for the freezerendering command)
bHasRequestedToggleFreeze = const_cast<FRenderTarget*>(InViewFamily->RenderTarget)->HasToggleFreezeCommand();
FeatureLevel = Scene->GetFeatureLevel();
}
bool FSceneRenderer::DoOcclusionQueries(ERHIFeatureLevel::Type InFeatureLevel) const
{
return !IsMobilePlatform(GShaderPlatformForFeatureLevel[InFeatureLevel])
&& CVarAllowOcclusionQueries.GetValueOnRenderThread() != 0;
}
FSceneRenderer::~FSceneRenderer()
{
// To prevent keeping persistent references to single frame buffers, clear any such reference at this point.
ClearPrimitiveSingleFramePrecomputedLightingBuffers();
if(Scene)
{
// Destruct the projected shadow infos.
for(TSparseArray<FLightSceneInfoCompact>::TConstIterator LightIt(Scene->Lights);LightIt;++LightIt)
{
if( VisibleLightInfos.IsValidIndex(LightIt.GetIndex()) )
{
FVisibleLightInfo& VisibleLightInfo = VisibleLightInfos[LightIt.GetIndex()];
for(int32 ShadowIndex = 0;ShadowIndex < VisibleLightInfo.MemStackProjectedShadows.Num();ShadowIndex++)
{
// FProjectedShadowInfo's in MemStackProjectedShadows were allocated on the rendering thread mem stack,
// Their memory will be freed when the stack is freed with no destructor call, so invoke the destructor explicitly
VisibleLightInfo.MemStackProjectedShadows[ShadowIndex]->~FProjectedShadowInfo();
}
}
}
}
// Manually release references to TRefCountPtrs that are allocated on the mem stack, which doesn't call dtors
SortedShadowsForShadowDepthPass.Release();
}
/**
* Finishes the view family rendering.
*/
void FSceneRenderer::RenderFinish(FRHICommandListImmediate& RHICmdList)
{
SCOPED_DRAW_EVENT(RHICmdList, RenderFinish);
if(FRCPassPostProcessBusyWait::IsPassRequired())
{
// mostly view independent but to be safe we use the first view
FViewInfo& View = Views[0];
FMemMark Mark(FMemStack::Get());
FRenderingCompositePassContext CompositeContext(RHICmdList, View);
FRenderingCompositeOutputRef BusyWait;
{
// for debugging purpose, can be controlled by console variable
FRenderingCompositePass* Node = CompositeContext.Graph.RegisterPass(new(FMemStack::Get()) FRCPassPostProcessBusyWait());
BusyWait = FRenderingCompositeOutputRef(Node);
}
if(BusyWait.IsValid())
{
CompositeContext.Process(BusyWait.GetPass(), TEXT("RenderFinish"));
}
}
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
{
bool bShowPrecomputedVisibilityWarning = false;
static const auto* CVarPrecomputedVisibilityWarning = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.PrecomputedVisibilityWarning"));
if (CVarPrecomputedVisibilityWarning && CVarPrecomputedVisibilityWarning->GetValueOnRenderThread() == 1)
{
bShowPrecomputedVisibilityWarning = !bUsedPrecomputedVisibility;
}
bool bShowGlobalClipPlaneWarning = false;
if (Scene->PlanarReflections.Num() > 0)
{
static const auto* CVarClipPlane = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.AllowGlobalClipPlane"));
if (CVarClipPlane && CVarClipPlane->GetValueOnRenderThread() == 0)
{
bShowGlobalClipPlaneWarning = true;
}
}
const FReadOnlyCVARCache& ReadOnlyCVARCache = Scene->ReadOnlyCVARCache;
static auto* CVarSkinCacheOOM = IConsoleManager::Get().FindTConsoleVariableDataFloat(TEXT("r.SkinCache.SceneMemoryLimitInMB"));
uint64 GPUSkinCacheExtraRequiredMemory = 0;
extern ENGINE_API bool IsGPUSkinCacheAvailable();
if (IsGPUSkinCacheAvailable())
{
if (FGPUSkinCache* SkinCache = Scene->GetGPUSkinCache())
{
GPUSkinCacheExtraRequiredMemory = SkinCache->GetExtraRequiredMemoryAndReset();
}
}
const bool bShowSkinCacheOOM = CVarSkinCacheOOM != nullptr && GPUSkinCacheExtraRequiredMemory > 0;
extern int32 GDistanceFieldAO;
const bool bShowDFAODisabledWarning = !GDistanceFieldAO && (ViewFamily.EngineShowFlags.VisualizeMeshDistanceFields || ViewFamily.EngineShowFlags.VisualizeGlobalDistanceField || ViewFamily.EngineShowFlags.VisualizeDistanceFieldAO);
const bool bShowAtmosphericFogWarning = Scene->AtmosphericFog != nullptr && !ReadOnlyCVARCache.bEnableAtmosphericFog;
const bool bStationarySkylight = Scene->SkyLight && Scene->SkyLight->bWantsStaticShadowing;
const bool bShowSkylightWarning = bStationarySkylight && !ReadOnlyCVARCache.bEnableStationarySkylight;
const bool bShowPointLightWarning = UsedWholeScenePointLightNames.Num() > 0 && !ReadOnlyCVARCache.bEnablePointLightShadows;
const bool bShowShadowedLightOverflowWarning = Scene->OverflowingDynamicShadowedLights.Num() > 0;
// Mobile-specific warnings
const bool bMobile = (FeatureLevel <= ERHIFeatureLevel::ES3_1);
const bool bShowMobileLowQualityLightmapWarning = bMobile && !ReadOnlyCVARCache.bEnableLowQualityLightmaps && ReadOnlyCVARCache.bAllowStaticLighting;
const bool bShowMobileDynamicCSMWarning = bMobile && Scene->NumMobileStaticAndCSMLights_RenderThread > 0 && !(ReadOnlyCVARCache.bMobileEnableStaticAndCSMShadowReceivers && ReadOnlyCVARCache.bMobileAllowDistanceFieldShadows);
const bool bShowMobileMovableDirectionalLightWarning = bMobile && Scene->NumMobileMovableDirectionalLights_RenderThread > 0 && !ReadOnlyCVARCache.bMobileAllowMovableDirectionalLights;
const bool bAnyWarning = bShowPrecomputedVisibilityWarning || bShowGlobalClipPlaneWarning || bShowAtmosphericFogWarning || bShowSkylightWarning || bShowPointLightWarning || bShowDFAODisabledWarning || bShowShadowedLightOverflowWarning || bShowMobileDynamicCSMWarning || bShowMobileLowQualityLightmapWarning || bShowMobileMovableDirectionalLightWarning || bShowSkinCacheOOM;
for(int32 ViewIndex = 0;ViewIndex < Views.Num();ViewIndex++)
{
FViewInfo& View = Views[ViewIndex];
if (!View.bIsReflectionCapture && !View.bIsSceneCapture )
{
// display a message saying we're frozen
FSceneViewState* ViewState = (FSceneViewState*)View.State;
bool bViewParentOrFrozen = ViewState && (ViewState->HasViewParent() || ViewState->bIsFrozen);
bool bLocked = View.bIsLocked;
if (bViewParentOrFrozen || bLocked || bAnyWarning)
{
SCOPED_CONDITIONAL_DRAW_EVENTF(RHICmdList, EventView, Views.Num() > 1, TEXT("View%d"), ViewIndex);
FRenderTargetTemp TempRenderTarget(View);
// create a temporary FCanvas object with the temp render target
// so it can get the screen size
int32 Y = 130;
FCanvas Canvas(&TempRenderTarget, NULL, View.Family->CurrentRealTime, View.Family->CurrentWorldTime, View.Family->DeltaWorldTime, FeatureLevel);
if (bViewParentOrFrozen)
{
const FText StateText =
ViewState->bIsFrozen ?
NSLOCTEXT("SceneRendering", "RenderingFrozen", "Rendering frozen...")
:
NSLOCTEXT("SceneRendering", "OcclusionChild", "Occlusion Child");
Canvas.DrawShadowedText(10, Y, StateText, GetStatsFont(), FLinearColor(0.8, 1.0, 0.2, 1.0));
Y += 14;
}
if (bShowPrecomputedVisibilityWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "NoPrecomputedVisibility", "NO PRECOMPUTED VISIBILITY");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bShowGlobalClipPlaneWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "NoGlobalClipPlane", "GLOBAL CLIP PLANE PROJECT SETTING NOT ENABLED");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bShowDFAODisabledWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "DFAODisabled", "Distance Field AO is disabled through scalability");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bShowAtmosphericFogWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "AtmosphericFog", "PROJECT DOES NOT SUPPORT ATMOSPHERIC FOG");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bShowSkylightWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "Skylight", "PROJECT DOES NOT SUPPORT STATIONARY SKYLIGHT: ");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bShowPointLightWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "PointLight", "PROJECT DOES NOT SUPPORT WHOLE SCENE POINT LIGHT SHADOWS: ");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
for (FName LightName : UsedWholeScenePointLightNames)
{
Canvas.DrawShadowedText(10, Y, FText::FromString(LightName.ToString()), GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
}
if (bShowShadowedLightOverflowWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "ShadowedLightOverflow", "TOO MANY OVERLAPPING SHADOWED MOVABLE LIGHTS, SHADOW CASTING DISABLED: ");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
for (FName LightName : Scene->OverflowingDynamicShadowedLights)
{
Canvas.DrawShadowedText(10, Y, FText::FromString(LightName.ToString()), GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
}
if (bShowMobileLowQualityLightmapWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "MobileLQLightmap", "MOBILE PROJECTS SUPPORTING STATIC LIGHTING MUST HAVE LQ LIGHTMAPS ENABLED");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bShowMobileMovableDirectionalLightWarning)
{
static const FText Message = NSLOCTEXT("Renderer", "MobileMovableDirectional", "PROJECT HAS MOVABLE DIRECTIONAL LIGHTS ON MOBILE DISABLED");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bShowMobileDynamicCSMWarning)
{
static const FText Message = (!ReadOnlyCVARCache.bMobileEnableStaticAndCSMShadowReceivers)
? NSLOCTEXT("Renderer", "MobileDynamicCSM", "PROJECT HAS MOBILE CSM SHADOWS FROM STATIONARY DIRECTIONAL LIGHTS DISABLED")
: NSLOCTEXT("Renderer", "MobileDynamicCSMDistFieldShadows", "MOBILE CSM+STATIC REQUIRES DISTANCE FIELD SHADOWS ENABLED FOR PROJECT");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bShowSkinCacheOOM)
{
FString String = FString::Printf(TEXT("OUT OF MEMORY FOR SKIN CACHE, REQUIRES %.3f extra MB (currently at %.3f)"), (float)GPUSkinCacheExtraRequiredMemory / 1048576.0f, CVarSkinCacheOOM->GetValueOnAnyThread());
Canvas.DrawShadowedText(10, Y, FText::FromString(String), GetStatsFont(), FLinearColor(1.0, 0.05, 0.05, 1.0));
Y += 14;
}
if (bLocked)
{
static const FText Message = NSLOCTEXT("Renderer", "ViewLocked", "VIEW LOCKED");
Canvas.DrawShadowedText(10, Y, Message, GetStatsFont(), FLinearColor(0.8, 1.0, 0.2, 1.0));
Y += 14;
}
Canvas.Flush_RenderThread(RHICmdList);
}
}
}
}
#endif //!(UE_BUILD_SHIPPING || UE_BUILD_TEST)
// Save the post-occlusion visibility stats for the frame and freezing info
for(int32 ViewIndex = 0;ViewIndex < Views.Num();ViewIndex++)
{
const FViewInfo& View = Views[ViewIndex];
INC_DWORD_STAT_BY(STAT_VisibleStaticMeshElements,View.NumVisibleStaticMeshElements);
INC_DWORD_STAT_BY(STAT_VisibleDynamicPrimitives,View.VisibleDynamicPrimitives.Num());
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
// update freezing info
FSceneViewState* ViewState = (FSceneViewState*)View.State;
if (ViewState)
{
// if we're finished freezing, now we are frozen
if (ViewState->bIsFreezing)
{
ViewState->bIsFreezing = false;
ViewState->bIsFrozen = true;
ViewState->bIsFrozenViewMatricesCached = true;
ViewState->CachedViewMatrices = View.ViewMatrices;
}
// handle freeze toggle request
if (bHasRequestedToggleFreeze)
{
// do we want to start freezing or stop?
ViewState->bIsFreezing = !ViewState->bIsFrozen;
ViewState->bIsFrozen = false;
ViewState->bIsFrozenViewMatricesCached = false;
ViewState->FrozenPrimitives.Empty();
}
}
#endif
}
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
// clear the commands
bHasRequestedToggleFreeze = false;
if(ViewFamily.EngineShowFlags.OnScreenDebug)
{
for(int32 ViewIndex = 0;ViewIndex < Views.Num();ViewIndex++)
{
const FViewInfo& View = Views[ViewIndex];
if(!View.IsPerspectiveProjection())
{
continue;
}
GRenderTargetPool.PresentContent(RHICmdList, View);
}
}
#endif
for(int32 ViewExt = 0; ViewExt < ViewFamily.ViewExtensions.Num(); ++ViewExt)
{
ViewFamily.ViewExtensions[ViewExt]->PostRenderViewFamily_RenderThread(RHICmdList, ViewFamily);
for(int32 ViewIndex = 0; ViewIndex < ViewFamily.Views.Num(); ++ViewIndex)
{
ViewFamily.ViewExtensions[ViewExt]->PostRenderView_RenderThread(RHICmdList, Views[ViewIndex]);
}
}
// Notify the RHI we are done rendering a scene.
RHICmdList.EndScene();
}
FSceneRenderer* FSceneRenderer::CreateSceneRenderer(const FSceneViewFamily* InViewFamily, FHitProxyConsumer* HitProxyConsumer)
{
EShadingPath ShadingPath = InViewFamily->Scene->GetShadingPath();
if (ShadingPath == EShadingPath::Deferred)
{
return new FDeferredShadingSceneRenderer(InViewFamily, HitProxyConsumer);
}
else
{
check(ShadingPath == EShadingPath::Mobile);
return new FMobileSceneRenderer(InViewFamily, HitProxyConsumer);
}
}
void ServiceLocalQueue();
void FSceneRenderer::RenderCustomDepthPassAtLocation(FRHICommandListImmediate& RHICmdList, int32 Location)
{
extern TAutoConsoleVariable<int32> CVarCustomDepthOrder;
int32 CustomDepthOrder = FMath::Clamp(CVarCustomDepthOrder.GetValueOnRenderThread(), 0, 1);
if(CustomDepthOrder == Location)
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_FDeferredShadingSceneRenderer_CustomDepthPass);
RenderCustomDepthPass(RHICmdList);
ServiceLocalQueue();
}
}
void FSceneRenderer::RenderCustomDepthPass(FRHICommandListImmediate& RHICmdList)
{
// do we have primitives in this pass?
bool bPrimitives = false;
if(!Scene->World || (Scene->World->WorldType != EWorldType::EditorPreview && Scene->World->WorldType != EWorldType::Inactive))
{
for(int32 ViewIndex = 0; ViewIndex < Views.Num(); ++ViewIndex)
{
const FViewInfo& View = Views[ViewIndex];
if(View.CustomDepthSet.NumPrims())
{
bPrimitives = true;
break;
}
}
}
// Render CustomDepth
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
if (SceneContext.BeginRenderingCustomDepth(RHICmdList, bPrimitives))
{
SCOPED_DRAW_EVENT(RHICmdList, CustomDepth);
SCOPED_GPU_STAT(RHICmdList, Stat_GPU_CustomDepth);
for(int32 ViewIndex = 0;ViewIndex < Views.Num();ViewIndex++)
{
SCOPED_CONDITIONAL_DRAW_EVENTF(RHICmdList, EventView, Views.Num() > 1, TEXT("View%d"), ViewIndex);
FViewInfo& View = Views[ViewIndex];
FDrawingPolicyRenderState DrawRenderState(View);
RHICmdList.SetViewport(View.ViewRect.Min.X, View.ViewRect.Min.Y, 0.0f, View.ViewRect.Max.X, View.ViewRect.Max.Y, 1.0f);
DrawRenderState.SetBlendState(TStaticBlendState<>::GetRHI());
const bool bWriteCustomStencilValues = SceneContext.IsCustomDepthPassWritingStencil();
if (!bWriteCustomStencilValues)
{
DrawRenderState.SetDepthStencilState(TStaticDepthStencilState<true, CF_DepthNearOrEqual>::GetRHI());
}
if ((CVarCustomDepthTemporalAAJitter.GetValueOnRenderThread() == 0) && (View.AntiAliasingMethod == AAM_TemporalAA))
{
FBox VolumeBounds[TVC_MAX];
FViewMatrices ModifiedViewMatricies = View.ViewMatrices;
ModifiedViewMatricies.HackRemoveTemporalAAProjectionJitter();
FViewUniformShaderParameters OverriddenViewUniformShaderParameters;
View.SetupUniformBufferParameters(
SceneContext,
ModifiedViewMatricies,
ModifiedViewMatricies,
VolumeBounds,
TVC_MAX,
OverriddenViewUniformShaderParameters);
DrawRenderState.SetViewUniformBuffer(TUniformBufferRef<FViewUniformShaderParameters>::CreateUniformBufferImmediate(OverriddenViewUniformShaderParameters, UniformBuffer_SingleFrame));
View.CustomDepthSet.DrawPrims(RHICmdList, View, DrawRenderState, bWriteCustomStencilValues);
}
else
{
View.CustomDepthSet.DrawPrims(RHICmdList, View, DrawRenderState, bWriteCustomStencilValues);
}
}
// resolve using the current ResolveParams
SceneContext.FinishRenderingCustomDepth(RHICmdList);
}
}
void FSceneRenderer::OnStartFrame(FRHICommandListImmediate& RHICmdList)
{
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
GRenderTargetPool.VisualizeTexture.OnStartFrame(Views[0]);
CompositionGraph_OnStartFrame();
SceneContext.bScreenSpaceAOIsValid = false;
SceneContext.bCustomDepthIsValid = false;
for(int32 ViewIndex = 0; ViewIndex < Views.Num(); ++ViewIndex)
{
FSceneView& View = Views[ViewIndex];
FSceneViewStateInterface* State = View.State;
if(State)
{
State->OnStartFrame(View, ViewFamily);
}
}
}
bool FSceneRenderer::ShouldCompositeEditorPrimitives(const FViewInfo& View)
{
// If the show flag is enabled
if (!View.Family->EngineShowFlags.CompositeEditorPrimitives)
{
return false;
}
if (View.Family->EngineShowFlags.VisualizeHDR || View.Family->UseDebugViewPS())
{
// certain visualize modes get obstructed too much
return false;
}
if (GIsEditor && View.Family->EngineShowFlags.Wireframe)
{
// In Editor we want wire frame view modes to be in MSAA
return true;
}
// Any elements that needed compositing were drawn then compositing should be done
if (View.ViewMeshElements.Num() || View.TopViewMeshElements.Num() || View.BatchedViewElements.HasPrimsToDraw() || View.TopBatchedViewElements.HasPrimsToDraw() || View.VisibleEditorPrimitives.Num())
{
return true;
}
return false;
}
void FSceneRenderer::WaitForTasksClearSnapshotsAndDeleteSceneRenderer(FRHICommandListImmediate& RHICmdList, FSceneRenderer* SceneRenderer)
{
// we are about to destroy things that are being used for async tasks, so we wait here for them.
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_DeleteSceneRenderer_WaitForTasks);
RHICmdList.ImmediateFlush(EImmediateFlushType::WaitForOutstandingTasksOnly);
}
FViewInfo::DestroyAllSnapshots(); // this destroys viewinfo snapshots
FSceneRenderTargets::Get(RHICmdList).DestroyAllSnapshots(); // this will destroy the render target snapshots
static const IConsoleVariable* AsyncDispatch = IConsoleManager::Get().FindConsoleVariable(TEXT("r.RHICmdAsyncRHIThreadDispatch"));
if (AsyncDispatch->GetInt() == 0)
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_DeleteSceneRenderer_Dispatch);
RHICmdList.ImmediateFlush(EImmediateFlushType::WaitForDispatchToRHIThread); // we want to make sure this all gets to the rhi thread this frame and doesn't hang around
}
// Delete the scene renderer.
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_DeleteSceneRenderer);
delete SceneRenderer;
}
}
void FSceneRenderer::UpdatePrimitivePrecomputedLightingBuffers()
{
// Use a bit array to prevent primitives from being updated more than once.
FSceneBitArray UpdatedPrimitiveMap;
UpdatedPrimitiveMap.Init(false, Scene->Primitives.Num());
for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
{
FViewInfo& View = Views[ViewIndex];
for (int32 Index = 0; Index < View.DirtyPrecomputedLightingBufferPrimitives.Num(); ++Index)
{
FPrimitiveSceneInfo* PrimitiveSceneInfo = View.DirtyPrecomputedLightingBufferPrimitives[Index];
FBitReference bInserted = UpdatedPrimitiveMap[PrimitiveSceneInfo->GetIndex()];
if (!bInserted)
{
PrimitiveSceneInfo->UpdatePrecomputedLightingBuffer();
bInserted = true;
}
else
{
// This will prevent clearing it twice.
View.DirtyPrecomputedLightingBufferPrimitives[Index] = nullptr;
}
}
}
}
void FSceneRenderer::ClearPrimitiveSingleFramePrecomputedLightingBuffers()
{
for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
{
FViewInfo& View = Views[ViewIndex];
for (int32 Index = 0; Index < View.DirtyPrecomputedLightingBufferPrimitives.Num(); ++Index)
{
FPrimitiveSceneInfo* PrimitiveSceneInfo = View.DirtyPrecomputedLightingBufferPrimitives[Index];
if (PrimitiveSceneInfo) // Could be null if it was a duplicate.
{
PrimitiveSceneInfo->ClearPrecomputedLightingBuffer(true);
}
}
}
}
/*-----------------------------------------------------------------------------
FRendererModule
-----------------------------------------------------------------------------*/
/**
* Helper function performing actual work in render thread.
*
* @param SceneRenderer Scene renderer to use for rendering.
*/
static void ViewExtensionPreRender_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneRenderer* SceneRenderer)
{
FMemMark MemStackMark(FMemStack::Get());
// update any resources that needed a deferred update
FDeferredUpdateResource::UpdateResources(RHICmdList);
for (int ViewExt = 0; ViewExt < SceneRenderer->ViewFamily.ViewExtensions.Num(); ViewExt++)
{
SceneRenderer->ViewFamily.ViewExtensions[ViewExt]->PreRenderViewFamily_RenderThread(RHICmdList, SceneRenderer->ViewFamily);
for (int ViewIndex = 0; ViewIndex < SceneRenderer->ViewFamily.Views.Num(); ViewIndex++)
{
SceneRenderer->ViewFamily.ViewExtensions[ViewExt]->PreRenderView_RenderThread(RHICmdList, SceneRenderer->Views[ViewIndex]);
}
}
}
/**
* Helper function performing actual work in render thread.
*
* @param SceneRenderer Scene renderer to use for rendering.
*/
static void RenderViewFamily_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneRenderer* SceneRenderer)
{
FMemMark MemStackMark(FMemStack::Get());
// update any resources that needed a deferred update
FDeferredUpdateResource::UpdateResources(RHICmdList);
if(SceneRenderer->ViewFamily.EngineShowFlags.OnScreenDebug)
{
GRenderTargetPool.SetEventRecordingActive(true);
}
{
SCOPE_CYCLE_COUNTER(STAT_TotalSceneRenderingTime);
if(SceneRenderer->ViewFamily.EngineShowFlags.HitProxies)
{
// Render the scene's hit proxies.
SceneRenderer->RenderHitProxies(RHICmdList);
}
else
{
// Render the scene.
SceneRenderer->Render(RHICmdList);
}
// Only reset per-frame scene state once all views have processed their frame, including those in planar reflections
for (int32 CacheType = 0; CacheType < ARRAY_COUNT(SceneRenderer->Scene->DistanceFieldSceneData.PrimitiveModifiedBounds); CacheType++)
{
SceneRenderer->Scene->DistanceFieldSceneData.PrimitiveModifiedBounds[CacheType].Reset();
}
{
SCOPE_CYCLE_COUNTER(STAT_FDeferredShadingSceneRenderer_UpdateMotionBlurCache);
SceneRenderer->Scene->MotionBlurInfoData.UpdateMotionBlurCache(SceneRenderer->Scene);
}
#if STATS
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_RenderViewFamily_RenderThread_MemStats);
// Update scene memory stats that couldn't be tracked continuously
SET_MEMORY_STAT(STAT_StaticDrawListMemory, FStaticMeshDrawListBase::TotalBytesUsed);
SET_MEMORY_STAT(STAT_RenderingSceneMemory, SceneRenderer->Scene->GetSizeBytes());
SIZE_T ViewStateMemory = 0;
for (int32 ViewIndex = 0; ViewIndex < SceneRenderer->Views.Num(); ViewIndex++)
{
if (SceneRenderer->Views[ViewIndex].State)
{
ViewStateMemory += SceneRenderer->Views[ViewIndex].State->GetSizeBytes();
}
}
SET_MEMORY_STAT(STAT_ViewStateMemory, ViewStateMemory);
SET_MEMORY_STAT(STAT_RenderingMemStackMemory, FMemStack::Get().GetByteCount());
SET_MEMORY_STAT(STAT_LightInteractionMemory, FLightPrimitiveInteraction::GetMemoryPoolSize());
}
#endif
GRenderTargetPool.SetEventRecordingActive(false);
FSceneRenderer::WaitForTasksClearSnapshotsAndDeleteSceneRenderer(RHICmdList, SceneRenderer);
}
#if STATS
QUICK_SCOPE_CYCLE_COUNTER(STAT_RenderViewFamily_RenderThread_RHIGetGPUFrameCycles);
if (FPlatformProperties::SupportsWindowedMode() == false)
{
/** Update STATS with the total GPU time taken to render the last frame. */
SET_CYCLE_COUNTER(STAT_TotalGPUFrameTime, RHIGetGPUFrameCycles());
}
#endif
}
void OnChangeSimpleForwardShading(IConsoleVariable* Var)
{
static const auto SupportSimpleForwardShadingCVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.SupportSimpleForwardShading"));
static const auto SimpleForwardShadingCVar = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.SimpleForwardShading"));
if (SimpleForwardShadingCVar->GetValueOnAnyThread() != 0)
{
if (SupportSimpleForwardShadingCVar->GetValueOnAnyThread() == 0)
{
UE_LOG(LogRenderer, Warning, TEXT("r.SimpleForwardShading ignored as r.SupportSimpleForwardShading is not enabled"));
}
else if (!PlatformSupportsSimpleForwardShading(GMaxRHIShaderPlatform))
{
UE_LOG(LogRenderer, Warning, TEXT("r.SimpleForwardShading ignored, only supported on PC shader platforms. Current shader platform %s"), *LegacyShaderPlatformToShaderFormat(GMaxRHIShaderPlatform).ToString());
}
}
// Propgate cvar change to static draw lists
FGlobalComponentRecreateRenderStateContext Context;
}
void OnChangeCVarRequiringRecreateRenderState(IConsoleVariable* Var)
{
// Propgate cvar change to static draw lists
FGlobalComponentRecreateRenderStateContext Context;
}
FRendererModule::FRendererModule()
: CustomCullingImpl(nullptr)
{
CVarSimpleForwardShading.AsVariable()->SetOnChangedCallback(FConsoleVariableDelegate::CreateStatic(&OnChangeSimpleForwardShading));
static auto CVarEarlyZPass = IConsoleManager::Get().FindConsoleVariable(TEXT("r.EarlyZPass"));
CVarEarlyZPass->SetOnChangedCallback(FConsoleVariableDelegate::CreateStatic(&OnChangeCVarRequiringRecreateRenderState));
static auto CVarEarlyZPassMovable = IConsoleManager::Get().FindConsoleVariable(TEXT("r.EarlyZPassMovable"));
CVarEarlyZPassMovable->SetOnChangedCallback(FConsoleVariableDelegate::CreateStatic(&OnChangeCVarRequiringRecreateRenderState));
}
void FRendererModule::CreateAndInitSingleView(FRHICommandListImmediate& RHICmdList, class FSceneViewFamily* ViewFamily, const struct FSceneViewInitOptions* ViewInitOptions)
{
// Create and add the new view
FViewInfo* NewView = new FViewInfo(*ViewInitOptions);
ViewFamily->Views.Add(NewView);
SetRenderTarget(RHICmdList, ViewFamily->RenderTarget->GetRenderTargetTexture(), nullptr, ESimpleRenderTargetMode::EClearColorExistingDepth);
FViewInfo* View = (FViewInfo*)ViewFamily->Views[0];
View->InitRHIResources();
}
void FRendererModule::BeginRenderingViewFamily(FCanvas* Canvas, FSceneViewFamily* ViewFamily)
{
UWorld* World = nullptr;
check(ViewFamily->Scene);
FScene* const Scene = ViewFamily->Scene->GetRenderScene();
if (Scene)
{
World = Scene->GetWorld();
if (World)
{
//guarantee that all render proxies are up to date before kicking off a BeginRenderViewFamily.
World->SendAllEndOfFrameUpdates();
}
}
// Flush the canvas first.
Canvas->Flush_GameThread();
if (Scene)
{
// We allow caching of per-frame, per-scene data
Scene->IncrementFrameNumber();
ViewFamily->FrameNumber = Scene->GetFrameNumber();
}
else
{
// this is passes to the render thread, better access that than GFrameNumberRenderThread
ViewFamily->FrameNumber = GFrameNumber;
}
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
{
extern TSharedPtr<ISceneViewExtension, ESPMode::ThreadSafe> GetRendererViewExtension();
ViewFamily->ViewExtensions.Add(GetRendererViewExtension());
}
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
for (int ViewExt = 0; ViewExt < ViewFamily->ViewExtensions.Num(); ViewExt++)
{
ViewFamily->ViewExtensions[ViewExt]->BeginRenderViewFamily(*ViewFamily);
}
if (Scene)
{
// Set the world's "needs full lighting rebuild" flag if the scene has any uncached static lighting interactions.
if(World)
{
// Note: reading NumUncachedStaticLightingInteractions on the game thread here which is written to by the rendering thread
// This is reliable because the RT uses interlocked mechanisms to update it
World->SetMapNeedsLightingFullyRebuilt(Scene->NumUncachedStaticLightingInteractions);
}
// Construct the scene renderer. This copies the view family attributes into its own structures.
FSceneRenderer* SceneRenderer = FSceneRenderer::CreateSceneRenderer(ViewFamily, Canvas->GetHitProxyConsumer());
bool bWorldIsPaused = ViewFamily->bWorldIsPaused;
ENQUEUE_RENDER_COMMAND(MotionBlurStartFrame)(
[Scene, bWorldIsPaused](FRHICommandList& RHICmdList)
{
SCOPE_CYCLE_COUNTER(STAT_FDeferredShadingSceneRenderer_MotionBlurStartFrame);
Scene->MotionBlurInfoData.StartFrame(bWorldIsPaused);
});
if (!SceneRenderer->ViewFamily.EngineShowFlags.HitProxies)
{
USceneCaptureComponent::UpdateDeferredCaptures(Scene);
}
// We need to execute the pre-render view extensions before we do any view dependent work.
// Anything between here and FDrawSceneCommand will add to HMD view latency
ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER(
FViewExtensionPreDrawCommand,
FSceneRenderer*, SceneRenderer, SceneRenderer,
{
ViewExtensionPreRender_RenderThread(RHICmdList, SceneRenderer);
});
if (!SceneRenderer->ViewFamily.EngineShowFlags.HitProxies)
{
for (int32 ReflectionIndex = 0; ReflectionIndex < SceneRenderer->Scene->PlanarReflections_GameThread.Num(); ReflectionIndex++)
{
UPlanarReflectionComponent* ReflectionComponent = SceneRenderer->Scene->PlanarReflections_GameThread[ReflectionIndex];
SceneRenderer->Scene->UpdatePlanarReflectionContents(ReflectionComponent, *SceneRenderer);
}
}
SceneRenderer->ViewFamily.DisplayInternalsData.Setup(World);
ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER(
FDrawSceneCommand,
FSceneRenderer*,SceneRenderer,SceneRenderer,
{
RenderViewFamily_RenderThread(RHICmdList, SceneRenderer);
FlushPendingDeleteRHIResources_RenderThread();
});
}
}
void FRendererModule::PostRenderAllViewports()
{
// Increment FrameNumber before render the scene. Wrapping around is no problem.
// This is the only spot we change GFrameNumber, other places can only read.
++GFrameNumber;
}
void FRendererModule::UpdateMapNeedsLightingFullyRebuiltState(UWorld* World)
{
World->SetMapNeedsLightingFullyRebuilt(World->Scene->GetRenderScene()->NumUncachedStaticLightingInteractions);
}
void FRendererModule::DrawRectangle(
FRHICommandList& RHICmdList,
float X,
float Y,
float SizeX,
float SizeY,
float U,
float V,
float SizeU,
float SizeV,
FIntPoint TargetSize,
FIntPoint TextureSize,
class FShader* VertexShader,
EDrawRectangleFlags Flags
)
{
::DrawRectangle( RHICmdList, X, Y, SizeX, SizeY, U, V, SizeU, SizeV, TargetSize, TextureSize, VertexShader, Flags );
}
TGlobalResource<FFilterVertexDeclaration>& FRendererModule::GetFilterVertexDeclaration()
{
return GFilterVertexDeclaration;
}
void FRendererModule::RegisterPostOpaqueRenderDelegate(const FPostOpaqueRenderDelegate& InPostOpaqueRenderDelegate)
{
this->PostOpaqueRenderDelegate = InPostOpaqueRenderDelegate;
}
void FRendererModule::RegisterOverlayRenderDelegate(const FPostOpaqueRenderDelegate& InOverlayRenderDelegate)
{
this->OverlayRenderDelegate = InOverlayRenderDelegate;
}
void FRendererModule::RenderPostOpaqueExtensions(const FSceneView& View, FRHICommandListImmediate& RHICmdList, FSceneRenderTargets& SceneContext)
{
check(IsInRenderingThread());
FPostOpaqueRenderParameters RenderParameters;
RenderParameters.ViewMatrix = View.ViewMatrices.GetViewMatrix();
RenderParameters.ProjMatrix = View.ViewMatrices.GetProjectionMatrix();
RenderParameters.DepthTexture = SceneContext.GetSceneDepthSurface()->GetTexture2D();
RenderParameters.SmallDepthTexture = SceneContext.GetSmallDepthSurface()->GetTexture2D();
RenderParameters.ViewportRect = View.ViewRect;
RenderParameters.RHICmdList = &RHICmdList;
RenderParameters.Uid = (void*)(&View);
PostOpaqueRenderDelegate.ExecuteIfBound(RenderParameters);
}
void FRendererModule::RenderOverlayExtensions(const FSceneView& View, FRHICommandListImmediate& RHICmdList, FSceneRenderTargets& SceneContext)
{
check(IsInRenderingThread());
FPostOpaqueRenderParameters RenderParameters;
RenderParameters.ViewMatrix = View.ViewMatrices.GetViewMatrix();
RenderParameters.ProjMatrix = View.ViewMatrices.GetProjectionMatrix();
RenderParameters.DepthTexture = SceneContext.GetSceneDepthSurface()->GetTexture2D();
RenderParameters.SmallDepthTexture = SceneContext.GetSmallDepthSurface()->GetTexture2D();
RenderParameters.ViewportRect = View.ViewRect;
RenderParameters.RHICmdList = &RHICmdList;
RenderParameters.Uid=(void*)(&View);
OverlayRenderDelegate.ExecuteIfBound(RenderParameters);
}
void FRendererModule::RenderPostResolvedSceneColorExtension(FRHICommandListImmediate& RHICmdList, class FSceneRenderTargets& SceneContext)
{
PostResolvedSceneColorCallbacks.Broadcast(RHICmdList, SceneContext);
}
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
class FConsoleVariableAutoCompleteVisitor
{
public:
// @param Name must not be 0
// @param CVar must not be 0
static void OnConsoleVariable(const TCHAR *Name, IConsoleObject* CObj, uint32& Crc)
{
IConsoleVariable* CVar = CObj->AsVariable();
if(CVar)
{
if(CObj->TestFlags(ECVF_Scalability) || CObj->TestFlags(ECVF_ScalabilityGroup))
{
// float should work on int32 as well
float Value = CVar->GetFloat();
Crc = FCrc::MemCrc32(&Value, sizeof(Value), Crc);
}
}
}
};
static uint32 ComputeScalabilityCVarHash()
{
uint32 Ret = 0;
IConsoleManager::Get().ForEachConsoleObjectThatStartsWith(FConsoleObjectVisitor::CreateStatic< uint32& >(&FConsoleVariableAutoCompleteVisitor::OnConsoleVariable, Ret));
return Ret;
}
static void DisplayInternals(FRHICommandListImmediate& RHICmdList, FSceneView& InView)
{
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
auto Family = InView.Family;
// if r.DisplayInternals != 0
if(Family->EngineShowFlags.OnScreenDebug && Family->DisplayInternalsData.IsValid())
{
// could be 0
auto State = InView.State;
FCanvas Canvas((FRenderTarget*)Family->RenderTarget, NULL, Family->CurrentRealTime, Family->CurrentWorldTime, Family->DeltaWorldTime, InView.GetFeatureLevel());
Canvas.SetRenderTargetRect(FIntRect(0, 0, Family->RenderTarget->GetSizeXY().X, Family->RenderTarget->GetSizeXY().Y));
SetRenderTarget(RHICmdList, Family->RenderTarget->GetRenderTargetTexture(), FTextureRHIRef());
// further down to not intersect with "LIGHTING NEEDS TO BE REBUILT"
FVector2D Pos(30, 140);
const int32 FontSizeY = 14;
// dark background
const uint32 BackgroundHeight = 30;
Canvas.DrawTile(Pos.X - 4, Pos.Y - 4, 500 + 8, FontSizeY * BackgroundHeight + 8, 0, 0, 1, 1, FLinearColor(0,0,0,0.6f), 0, true);
UFont* Font = GEngine->GetSmallFont();
FCanvasTextItem SmallTextItem( Pos, FText::GetEmpty(), GEngine->GetSmallFont(), FLinearColor::White );
SmallTextItem.SetColor(FLinearColor::White);
SmallTextItem.Text = FText::FromString(FString::Printf(TEXT("r.DisplayInternals = %d"), Family->DisplayInternalsData.DisplayInternalsCVarValue));
Canvas.DrawItem(SmallTextItem, Pos);
SmallTextItem.SetColor(FLinearColor::Gray);
Pos.Y += 2 * FontSizeY;
#define CANVAS_HEADER(txt) \
{ \
SmallTextItem.SetColor(FLinearColor::Gray); \
SmallTextItem.Text = FText::FromString(txt); \
Canvas.DrawItem(SmallTextItem, Pos); \
Pos.Y += FontSizeY; \
}
#define CANVAS_LINE(bHighlight, txt, ... ) \
{ \
SmallTextItem.SetColor(bHighlight ? FLinearColor::Red : FLinearColor::Gray); \
SmallTextItem.Text = FText::FromString(FString::Printf(txt, __VA_ARGS__)); \
Canvas.DrawItem(SmallTextItem, Pos); \
Pos.Y += FontSizeY; \
}
CANVAS_HEADER(TEXT("command line options:"))
{
bool bHighlight = !(FApp::UseFixedTimeStep() && FApp::bUseFixedSeed);
CANVAS_LINE(bHighlight, TEXT(" -UseFixedTimeStep: %u"), FApp::UseFixedTimeStep())
CANVAS_LINE(bHighlight, TEXT(" -FixedSeed: %u"), FApp::bUseFixedSeed)
CANVAS_LINE(false, TEXT(" -gABC= (changelist): %d"), GetChangeListNumberForPerfTesting())
}
CANVAS_HEADER(TEXT("Global:"))
CANVAS_LINE(false, TEXT(" FrameNumberRT: %u"), GFrameNumberRenderThread)
CANVAS_LINE(false, TEXT(" Scalability CVar Hash: %x (use console command \"Scalability\")"), ComputeScalabilityCVarHash())
//not really useful as it is non deterministic and should not be used for rendering features: CANVAS_LINE(false, TEXT(" FrameNumberRT: %u"), GFrameNumberRenderThread)
CANVAS_LINE(false, TEXT(" FrameCounter: %u"), GFrameCounter)
CANVAS_LINE(false, TEXT(" rand()/SRand: %x/%x"), FMath::Rand(), FMath::GetRandSeed())
{
bool bHighlight = Family->DisplayInternalsData.NumPendingStreamingRequests != 0;
CANVAS_LINE(bHighlight, TEXT(" FStreamAllResourcesLatentCommand: %d"), bHighlight)
}
{
static auto* Var = IConsoleManager::Get().FindTConsoleVariableDataInt(TEXT("r.Streaming.FramesForFullUpdate"));
int32 Value = Var->GetValueOnRenderThread();
bool bHighlight = Value != 0;
CANVAS_LINE(bHighlight, TEXT(" r.Streaming.FramesForFullUpdate: %u%s"), Value, bHighlight ? TEXT(" (should be 0)") : TEXT(""));
}
if(State)
{
CANVAS_HEADER(TEXT("State:"))
CANVAS_LINE(false, TEXT(" TemporalAASample: %u"), State->GetCurrentTemporalAASampleIndex())
CANVAS_LINE(false, TEXT(" FrameIndexMod8: %u"), State->GetFrameIndexMod8())
CANVAS_LINE(false, TEXT(" LODTransition: %.2f"), State->GetTemporalLODTransition())
}
CANVAS_HEADER(TEXT("Family:"))
CANVAS_LINE(false, TEXT(" Time (Real/World/DeltaWorld): %.2f/%.2f/%.2f"), Family->CurrentRealTime, Family->CurrentWorldTime, Family->DeltaWorldTime)
CANVAS_LINE(false, TEXT(" MatineeTime: %f"), Family->DisplayInternalsData.MatineeTime)
CANVAS_LINE(false, TEXT(" FrameNumber: %u"), Family->FrameNumber)
CANVAS_LINE(false, TEXT(" ExposureSettings: %s"), *Family->ExposureSettings.ToString())
CANVAS_LINE(false, TEXT(" GammaCorrection: %.2f"), Family->GammaCorrection)
CANVAS_HEADER(TEXT("View:"))
CANVAS_LINE(false, TEXT(" TemporalJitter: %.2f/%.2f"), InView.TemporalJitterPixelsX, InView.TemporalJitterPixelsY)
CANVAS_LINE(false, TEXT(" ViewProjectionMatrix Hash: %x"), InView.ViewMatrices.GetViewProjectionMatrix().ComputeHash())
CANVAS_LINE(false, TEXT(" ViewLocation: %s"), *InView.ViewLocation.ToString())
CANVAS_LINE(false, TEXT(" ViewRotation: %s"), *InView.ViewRotation.ToString())
CANVAS_LINE(false, TEXT(" ViewRect: %s"), *InView.ViewRect.ToString())
FViewInfo& ViewInfo = (FViewInfo&)InView;
CANVAS_LINE(false, TEXT(" DynMeshElements/TranslPrim: %d/%d"), ViewInfo.DynamicMeshElements.Num(), ViewInfo.TranslucentPrimSet.NumPrims())
#undef CANVAS_LINE
#undef CANVAS_HEADER
Canvas.Flush_RenderThread(RHICmdList);
}
#endif
}
TSharedPtr<ISceneViewExtension, ESPMode::ThreadSafe> GetRendererViewExtension()
{
class FRendererViewExtension : public ISceneViewExtension
{
public:
virtual void SetupViewFamily(FSceneViewFamily& InViewFamily) {}
virtual void SetupView(FSceneViewFamily& InViewFamily, FSceneView& InView) {}
virtual void BeginRenderViewFamily(FSceneViewFamily& InViewFamily) {}
virtual void PreRenderViewFamily_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneViewFamily& InViewFamily) {}
virtual void PreRenderView_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneView& InView) {}
virtual int32 GetPriority() const { return 0; }
virtual void PostRenderView_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneView& InView)
{
DisplayInternals(RHICmdList, InView);
}
};
TSharedPtr<FRendererViewExtension, ESPMode::ThreadSafe> ptr(new FRendererViewExtension);
return StaticCastSharedPtr<ISceneViewExtension>(ptr);
}
#endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
/**
* Saves a previously rendered scene color target
*/
void FSceneRenderer::ResolveSceneColor(FRHICommandList& RHICmdList)
{
SCOPED_DRAW_EVENT(RHICmdList, ResolveSceneColor);
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
auto& CurrentSceneColor = SceneContext.GetSceneColor();
uint32 CurrentNumSamples = CurrentSceneColor->GetDesc().NumSamples;
const EShaderPlatform CurrentShaderPlatform = GShaderPlatformForFeatureLevel[SceneContext.GetCurrentFeatureLevel()];
if (CurrentNumSamples <= 1 || !RHISupportsSeparateMSAAAndResolveTextures(CurrentShaderPlatform))
{
RHICmdList.CopyToResolveTarget(SceneContext.GetSceneColorSurface(), SceneContext.GetSceneColorTexture(), true, FResolveRect(0, 0, ViewFamily.FamilySizeX, ViewFamily.FamilySizeY));
}
else
{
// Custom shader based color resolve for HDR color to emulate mobile.
SetRenderTarget(RHICmdList, SceneContext.GetSceneColorTexture(), FTextureRHIParamRef());
for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
{
const FViewInfo& View = Views[ViewIndex];
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI();
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<>::GetRHI();
GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI();
RHICmdList.SetStreamSource(0, NULL, 0, 0);
// Resolve views individually
// In the case of adaptive resolution, the view family will be much larger than the views individually
RHICmdList.SetScissorRect(true, View.ViewRect.Min.X, View.ViewRect.Min.Y, View.ViewRect.Max.X, View.ViewRect.Max.Y);
int32 ResolveWidth = CVarWideCustomResolve.GetValueOnRenderThread();
if (CurrentNumSamples <= 1)
{
ResolveWidth = 0;
}
if (ResolveWidth != 0)
{
ResolveFilterWide(RHICmdList, GraphicsPSOInit, SceneContext.GetCurrentFeatureLevel(), CurrentSceneColor->GetRenderTargetItem().TargetableTexture, FIntPoint(0, 0), CurrentNumSamples, ResolveWidth);
}
else
{
auto ShaderMap = GetGlobalShaderMap(SceneContext.GetCurrentFeatureLevel());
TShaderMapRef<FHdrCustomResolveVS> VertexShader(ShaderMap);
if (CurrentNumSamples == 2)
{
TShaderMapRef<FHdrCustomResolve2xPS> PixelShader(ShaderMap);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GetVertexDeclarationFVector4();
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, CurrentSceneColor->GetRenderTargetItem().TargetableTexture);
RHICmdList.DrawPrimitive(PT_TriangleList, 0, 1, 1);
}
else if (CurrentNumSamples == 4)
{
TShaderMapRef<FHdrCustomResolve4xPS> PixelShader(ShaderMap);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GetVertexDeclarationFVector4();
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, CurrentSceneColor->GetRenderTargetItem().TargetableTexture);
RHICmdList.DrawPrimitive(PT_TriangleList, 0, 1, 1);
}
else if (CurrentNumSamples == 8)
{
TShaderMapRef<FHdrCustomResolve8xPS> PixelShader(ShaderMap);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GetVertexDeclarationFVector4();
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, CurrentSceneColor->GetRenderTargetItem().TargetableTexture);
RHICmdList.DrawPrimitive(PT_TriangleList, 0, 1, 1);
}
else
{
// Everything other than 2,4,8 samples is not implemented.
check(0);
}
}
}
RHICmdList.SetScissorRect(false, 0, 0, 0, 0);
}
}
FTextureRHIParamRef FSceneRenderer::GetMultiViewSceneColor(const FSceneRenderTargets& SceneContext) const
{
const FViewInfo& View = Views[0];
if (View.bIsMobileMultiViewEnabled && !View.bIsMobileMultiViewDirectEnabled)
{
return SceneContext.MobileMultiViewSceneColor->GetRenderTargetItem().TargetableTexture;
}
else
{
return static_cast<FTextureRHIRef>(ViewFamily.RenderTarget->GetRenderTargetTexture());
}
}