Files
UnrealEngineUWP/Engine/Source/Runtime/Renderer/Private/DistanceFieldAmbientOcclusion.cpp
Marcus Wassmer 2826204161 Copying //UE4/Dev-Rendering to //UE4/Dev-Main (Source: //UE4/Dev-Rendering @ 3357411)
#lockdown Nick.Penwarden
#rb none

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

Change 3244756 on 2017/01/03 by Marcus.Wassmer

	Copying //Tasks/UE4/Dev-Niagara@3244743 to Dev-Rendering (//UE4/Dev-Rendering)

Change 3248667 on 2017/01/05 by Olaf.Piesche

	Resaving default asset because of engine verison issue; maybe unnecessary, but resaving niagara engine content to be sure

	#jira UE-40160

Change 3249324 on 2017/01/06 by Marcus.Wassmer

	Resave with an actual version to stop cook warning

Change 3249611 on 2017/01/06 by Marcus.Wassmer

	Just remove warning-causing niagara data for now.

Change 3308052 on 2017/02/16 by Rolando.Caloca

	DR - Check for Vulkan SDK, and only use it if it's newer or the same as the headers we distribute

Change 3308109 on 2017/02/16 by Rolando.Caloca

	DR - Upgrade glslang to 1.0.39.1

Change 3308111 on 2017/02/16 by Rolando.Caloca

	DR - Update Vulkan distribution to 1.0.39.1

Change 3308153 on 2017/02/16 by Rolando.Caloca

	DR - Updated glslang libs

Change 3308842 on 2017/02/17 by Rolando.Caloca

	DR - Fixed copy/paste

Change 3310007 on 2017/02/17 by Chris.Bunner

	Back out CL 3221219 - causing MIC generation issues and superseded by CL 3273971.

	#jira UE-37792

Change 3310154 on 2017/02/17 by Chris.Bunner

	Assert when attempting to add a custom material attribute already in the base attributes list.

Change 3310155 on 2017/02/17 by Chris.Bunner

	PR #3231: Validate material index before accessing (Contributed by projectgheist)

	#jira UE-41774, UE-41788

Change 3310162 on 2017/02/17 by Chris.Bunner

	PR #3252: Added MobileMaterialInterface to UsedMaterials (Contributed by projectgheist)

	#jira UE-41823, UE-41950

Change 3310176 on 2017/02/17 by Chris.Bunner

	Merging CL 3233886: AMD HDR support (requires r.AMDSupportsHDRDisplayOutput=1 in ini).
	Update to AGS 5.0.5.
	Partial code tidy up.

Change 3310187 on 2017/02/17 by Chris.Bunner

	Preserve constant expressions rather than always casting after translating a material attribute. Losing the notion of constant means we can't correctly detect used properties and falsely enable e.g. PDO. Happened because of the incorrect component masks in BreakMaterialNodes which then had to be downcast to the correct type which is done as an inline fragment rather than swizzle expression.

	#jira UE-41594

Change 3310215 on 2017/02/17 by Chris.Bunner

	Prevent SpeedTree node compiling for skeletal meshes (not supported as uses more UV sets than available).
	More descriptive error for missing Cubemap UV input on TextureSample material node .

	#jira UE-33098

Change 3310838 on 2017/02/18 by Joe.Graf

	Moved some private functions to public for a licensee

	#CodeReview: matt.kuhlenschmidt
	#rb: n/a

Change 3311876 on 2017/02/20 by Rolando.Caloca

	DR - Expose skin cache cvar r.SkinCache.AccumulationBufferSizeInKB

	#jira UE-42014

Change 3314139 on 2017/02/21 by Rolando.Caloca

	DR - Minor cleanup pass
	- Remove FVulkanPendingState
	- Renamed some classes for clarity
	- Hoist pending UAVs for flush out to pending compute state

Change 3314642 on 2017/02/21 by Rolando.Caloca

	DR - Some more renaming

Change 3315431 on 2017/02/21 by Ben.Salem

	Properly set default values for test time out and tick. We now will default to ticking once per second, and tracking the macro stats of GPU/Render/Game thread time.

	#tests Ran showdown demo several times

Change 3316710 on 2017/02/22 by Rolando.Caloca

	DR - hlslcc - Fix refract intrinsic

Change 3316718 on 2017/02/22 by Rolando.Caloca

	DR - hlslcc - Built libs to pick up change from 3316710 - refract fix

Change 3316820 on 2017/02/22 by Benjamin.Hyder

	updating Tm-TrigNodes map

Change 3317192 on 2017/02/22 by Benjamin.Hyder

	Updating QA-Decals map

Change 3317528 on 2017/02/22 by Benjamin.Hyder

	Updating QA-Decals map

Change 3317639 on 2017/02/22 by Benjamin.Hyder

	Updating Decal on Complex Mesh example in QA-Decals

Change 3317764 on 2017/02/22 by Benjamin.Hyder

	Final updates to QA-Decals

Change 3318319 on 2017/02/22 by Rolando.Caloca

	DR - minor reorg/rename

Change 3318379 on 2017/02/22 by Rolando.Caloca

	DR - more cleanup

Change 3321181 on 2017/02/24 by Rolando.Caloca

	DR - Fix GL bug

Change 3321247 on 2017/02/24 by Rolando.Caloca

	DR - Fix misc bugs

Change 3321898 on 2017/02/24 by Chris.Bunner

	Only issue clear TLV dispatch if required.

	#jira UERNDR-193

Change 3321904 on 2017/02/24 by Chris.Bunner

	Added comment for potential future optimization.

Change 3322013 on 2017/02/24 by Uriel.Doyon

	Fixed separate translucency being affected by Gaussian DOF
	#jira UE-40489

Change 3322517 on 2017/02/24 by Uriel.Doyon

	Fixed issue with InvestigateTexture command removing budget limit.
	Fixed StreamingBounds show flag not working. It nows shows the streaming bound for the currently selected textures.
	#jira UE-40485

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

	Removing DDC job from dev-rendering

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

	Removing RDU agent type

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

	removing NCL/LHR/SEA agent types to clean up space

Change 3323639 on 2017/02/27 by Benjamin.Hyder

	More updates to QA-Decals

Change 3324207 on 2017/02/27 by Uriel.Doyon

	Fixed typo ScaleTexturesByGlobalMyBias ->  ScaleTexturesByGlobalMipBias
	Removed bad merge in FStreamingTextureLevelContext::GetBuildDataIndexRef

Change 3324396 on 2017/02/27 by Uriel.Doyon

	Fixed an issue with the Streaming Bounds show flag interferring with the static level data initialization
	#jira UE-40485

Change 3325227 on 2017/02/28 by Chris.Bunner

	Fix-up AMD AGS libs.

Change 3325566 on 2017/02/28 by Uriel.Doyon

	Fixed possible out-of-bound access in GetUsedTexture() when passing ERHIFeatureLevel::Num

Change 3326009 on 2017/02/28 by Uriel.Doyon

	Better fix for 3325566, as the previous fix would ignore the material instance overrides.

Change 3327058 on 2017/03/01 by Benjamin.Hyder

	Preparing TM_Shadermodels map for automation

Change 3328222 on 2017/03/01 by Chris.Bunner

	Prevent decals from drawing in separate translucency pass. Whilst user control and material relevance were already removed, if the flag was checked before being disabled (by swapping to decal domain) this was still being read in the render loop, now explicitly ignores decals.

	#jira UE-42449, UE-42446

Change 3329848 on 2017/03/02 by Uriel.Doyon

	Added some extra logs to help track UE-42168

Change 3329977 on 2017/03/02 by Rolando.Caloca

	DR - Fix bad clear value

Change 3330008 on 2017/03/02 by Benjamin.Hyder

	More preparations for QA-Decals automation

Change 3330754 on 2017/03/02 by Daniel.Wright

	Prominent comment explaining reflection env async compute usage and why it's not overlapped with anything

Change 3331451 on 2017/03/03 by Marc.Olano

	Manually unroll simplex noise loop to avoid PSO bug on AMD/Metal

Change 3331839 on 2017/03/03 by Rolando.Caloca

	DR - hlslcc - add missing file to project

Change 3332247 on 2017/03/03 by Rolando.Caloca

	DR - Fix for integrated intel
	PR #3305
	#jira UE-42393

Change 3332259 on 2017/03/03 by Rolando.Caloca

	DR - Fix bad index into pixel formats
	PR #3237
	#jira UE-41855

Change 3332305 on 2017/03/03 by Rolando.Caloca

	DR - OpenGL SRV for index buffers
	PR #3271
	#jira UE-32618

Change 3332313 on 2017/03/03 by Rolando.Caloca

	DR - Fix for integrated intel (properly)
	PR #3305
	#jira UE-42393

Change 3332317 on 2017/03/03 by Rolando.Caloca

	DR - OpenGL SRV for index buffers (properly)
	PR #3271
	#jira UE-32618

Change 3332368 on 2017/03/03 by Rolando.Caloca

	DR - Minor fixes so -sm4 and -sm5 can be used on windows with OpenGL/Vulkan

Change 3333690 on 2017/03/06 by Daniel.Wright

	[Copy] Changing movable skylight properties no longer affects static draw lists

Change 3333693 on 2017/03/06 by Daniel.Wright

	[Copy] Added 'r.AOListMeshDistanceFields' which dumps out mesh distance fields sorted by memory size, useful for directing content optimizations

Change 3333705 on 2017/03/06 by Daniel.Wright

	[Copy] Mesh distance fields are now 8 bit fixed point by default, but can be changed back to 16 bit floating piont with a project setting.
	* 8 bit uses half memory but introduces error for thin surfaces or large meshes.

Change 3333721 on 2017/03/06 by David.Hill

	DecalProxy:
	Copy float FadeScreenSize to FDeferredDecalProxy for use in the render thread.  This avoids  pointer chasing to the UDecalComponent (game thread component).

Change 3333772 on 2017/03/06 by Daniel.Wright

	[Copy] Scene motion blur data is only updated for the main renderer frames.  Fixes scene captures and planar reflections breaking object motion blur.

Change 3333790 on 2017/03/06 by Daniel.Wright

	[Copy] Mesh distance field generation uses Embree, for a 2.5x speedup
	* Can switch back to old kDOP generation with 'r.DistanceFieldBuild.UseEmbree 0' for debugging

Change 3333822 on 2017/03/06 by Daniel.Wright

	[Copy] Moved mesh distance field code into MeshDistanceFieldUtilities.cpp
	* Moved FMeshUtilities to its own header so the 8k line MeshUtilites.cpp file can be further split up

Change 3333827 on 2017/03/06 by Daniel.Wright

	[Copy] Range compress 8bit distance fields - gets one extra bit of precision on average

Change 3333828 on 2017/03/06 by Daniel.Wright

	[Copy] Raised High ShadowQuality to 2048 as 1024 for CSM is way too low

Change 3333831 on 2017/03/06 by Daniel.Wright

	Non-editor compile fix

Change 3333836 on 2017/03/06 by Daniel.Wright

	[Copy] Workaround for gobal distance field volume textures being bloated by 4x on PS4 due to the recommended tiling modes.  They now use a 2d tiling mode which avoids the bloat, saving 96Mb.

Change 3333843 on 2017/03/06 by Daniel.Wright

	[Copy] Added OcclusionExponent to skylight component
	* Useful for brightening up indoors without losing contact shadows as MinOcclusion does

Change 3333845 on 2017/03/06 by Daniel.Wright

	[Copy] Capsule shadow BP functions

Change 3333850 on 2017/03/06 by Daniel.Wright

	[Copy] Added OcclusionCombineMode to skylight component

Change 3333854 on 2017/03/06 by Daniel.Wright

	[Copy] Gnm properly registers clears as GPU work so those events show up in profilegpu

Change 3333857 on 2017/03/06 by Daniel.Wright

	[Copy] Clear light attenuation for local lights with a quad covering their screen extents
	* Clearing the entire light attenuation buffer costs .1ms on PS4.  This optimization lowers the minimum cost of a shadow casting light from .15ms -> .03ms.
	* Shadowed lights in Fortnite with 25 lights 3.7ms -> 1.42ms on PS4

Change 3333860 on 2017/03/06 by Daniel.Wright

	[Copy] Flush deferred deletes when reallocating distance field atlas to reduce peak memory

Change 3333861 on 2017/03/06 by Daniel.Wright

	[Copy] Disable all distance field features on Intel cards as HD 4000 hangs in the RHICreateTexture3D call to allocate the large atlas

Change 3333869 on 2017/03/06 by Daniel.Wright

	[Copy] Volumetric Fog using a volume texture mapped to the camera frustum
	* Volumetric fog can be enabled on an Exponential Height Fog component with additional controls
	* Lights have a VolumetricScatteringIntensity
	* New cvars r.VolumetricFog, r.VolumetricFog.GridPixelSize, r.VolumetricFog.GridSizeZ, r.VolumetricFog.DepthDistributionScale
	* Lighting features supported:
	   * Directional light with CSM and a light function
	   * Point / spot lights without shadows / light functions / IES profiles
	   * Skylight with occlusion from distance fields
	* Analytical height fog covers the view range past where the volumetric fog ends
	* Temporal reprojection is used on the volumetric fog scattering and extinction to achieve stability
	* Translucency integrates properly into volumetric fog
	* Height fog StartDistance is not supported by volumetric fog and should be set to 0.

Change 3333894 on 2017/03/06 by Daniel.Wright

	[Copy] Initialize GDummyVolumetricFogGlobalDataUniformBuffer outside of parallel rendering

Change 3333902 on 2017/03/06 by Daniel.Wright

	[Copy] Better handling of volumetric fog enabled with distance of 0

Change 3333903 on 2017/03/06 by Daniel.Wright

	[Copy] Fixed volumetric fog trying to render light functions for a point light

Change 3333908 on 2017/03/06 by Daniel.Wright

	[Copy] Volumetric materials
	* Added new material domain Volume, which can output Scattering, Absorption and Emissive.  All properties are in world space densities.
	* Particle systems using the Volume domain are voxelized based on their ParticlePosition and ParticleRadius
	* Volumetric fog integration is now energy conservative - scattering is integrated against transmission over the depth of each slice.
	* Added bOverrideLightColorsWithFogInscatteringColors to exponential height fog, which can be enabled to make Volumetric Fog match Height fog more closely

Change 3334134 on 2017/03/06 by Daniel.Wright

	[Copy from Michael Trepka] Added Embree 2.14.0 and changed MeshUtilities to use it as this solves issues with Embree leaking TLS keys. UnrealLightmass is still using older Embree 2.7.0 until we can find time to properly test it with the new version. Also, invalidated distance field DDC to force it to rebuild with updated Embree.

Change 3334420 on 2017/03/06 by Daniel.Wright

	Fixed RTDF shadows

Change 3335467 on 2017/03/07 by Benjamin.Hyder

	Initial submission of QA-Decals map to EngineTest

Change 3335556 on 2017/03/07 by Daniel.Wright

	Changed mesh distance field default format back to R16f

Change 3338020 on 2017/03/08 by Daniel.Wright

	Disable volumetric fog in vertex shaders for feature levels which don't support it

Change 3339394 on 2017/03/09 by Chris.Bunner

	Correctly handle material texture translation error edge case.

	#jira UE-42579, UE-42670

Change 3339992 on 2017/03/09 by Daniel.Wright

	Only compile volumetric fog shaders on supporting platforms

Change 3341858 on 2017/03/10 by Arne.Schober

	Copying //UE4/Dev-Rendering-PSO to Dev-Rendering (//UE4/Dev-Rendering)

	#RB Rolando.Caloca, Marcus.Wassmer, Daniel.Wright, Nick.Penwarden, Mark.Satterthwaite

Change 3342004 on 2017/03/10 by Arne.Schober

	Copying //UE4/Dev-Rendering-PSO to Dev-Rendering (//UE4/Dev-Rendering)
	Fix unity build

	#RB Marcus.Wassmer

Change 3343307 on 2017/03/13 by Marcus.Wassmer

	Update showflags when we are guaranteed it will happen in all possible ways to spawn the scenecapture. (drag into editor, PIE, -game, etc)

Change 3343732 on 2017/03/13 by Rolando.Caloca

	DR - Vulkan compute pipeline & refactor

Change 3344846 on 2017/03/14 by Rolando.Caloca

	DR - Android compile fixes

Change 3344883 on 2017/03/14 by Rolando.Caloca

	DR - Add missing stencil load/store to PSO initializer

Change 3344985 on 2017/03/14 by Rolando.Caloca

	DR - Made load/store actions uint8

Change 3345141 on 2017/03/14 by Rolando.Caloca

	DR - vk - Rework render pass hash

Change 3345304 on 2017/03/14 by Benjamin.Hyder

	Updating TM-Distancefields map to include TemplateFloor mesh

Change 3345387 on 2017/03/14 by Rolando.Caloca

	DR - Add _RenderThread calls for Create*Shader so RHIs can choose not to stall when creating

Change 3345388 on 2017/03/14 by Rolando.Caloca

	DR - Do not stall when creating shaders on Vulkan

Change 3345722 on 2017/03/14 by Chris.Bunner

	PR #3357: MinimalAPI add to many material expressions (Contributed by DeanoC)

	#jira UE-42752

Change 3345723 on 2017/03/14 by Chris.Bunner

	Reduce log verbosity causing spamming during  landscape editing.

	#jira UE-42714

Change 3345725 on 2017/03/14 by Chris.Bunner

	[Duplicate 3341860] Fixed material translation error with multiple connections from custom interpolator nodes.

Change 3345726 on 2017/03/14 by Chris.Bunner

	Typo fixes.

Change 3345732 on 2017/03/14 by Rolando.Caloca

	DR - Decouple vertex declaration off BSS

Change 3345746 on 2017/03/14 by Chris.Bunner

	Added sign() intrinsic material graph node and delisted material function workaround.

Change 3346042 on 2017/03/14 by Chris.Bunner

	Implement missing size query interface for FRenderTargetResources.

	#jira UE-41672

Change 3346387 on 2017/03/14 by Daniel.Wright

	[Copy] Added VolumetricScatteringIntensity to particle lights

Change 3346389 on 2017/03/14 by Daniel.Wright

	[Copy] Clamp Volumetric material attributes to fp16 range to avoid INFs
	Disable volumetric fog when the fog show flag is disabled

Change 3346392 on 2017/03/14 by Daniel.Wright

	[Copy] Fixed skylight being much too bright on volumetric fog

Change 3346406 on 2017/03/14 by Daniel.Wright

	[Copy] CSM resolution is now controlled by r.Shadow.MaxCSMResolution.
	* Changed HighPC to use 1024 MaxShadowResolution (max for all non-CSM shadows), saves 60Mb in Fortnite

Change 3346412 on 2017/03/14 by Daniel.Wright

	[Copy] TexCreate_ReduceMemoryWithTilingMode for translucency lighting 3d textures, saves 13Mb

Change 3346414 on 2017/03/14 by Daniel.Wright

	[Copy] TexCreate_ReduceMemoryWithTilingMode for volumetric fog 3d textures, saves 13Mb

Change 3346415 on 2017/03/14 by Daniel.Wright

	[Copy] Missing file from cl 3338451

Change 3346421 on 2017/03/14 by Daniel.Wright

	[Copy] Fixed NaNs in volumetric fog due to rendering when height fog is disabled
	* Volumetric fog converts NaNs to black now so they don't spread

Change 3346422 on 2017/03/14 by Daniel.Wright

	[Copy] Fixed NaN in volumetric fog with low density values

Change 3346423 on 2017/03/14 by Daniel.Wright

	[Copy] Changed default VolumetricFogScatteringDistribution to .2

Change 3346430 on 2017/03/14 by Daniel.Wright

	[Copy] New translucent material option to compute fog per pixel instead of the default per vertex

Change 3346432 on 2017/03/14 by Daniel.Wright

	[Copy] Moved Volumetric Fog parameters to view uniform buffer for translucency pass
	Fixed lifetimes of temporary Volumetric Fog render targets

Change 3346526 on 2017/03/14 by Daniel.Wright

	[Copy] Volumetric Fog supports point and spot light shadows
	* These lights are injected separately so that per-light resources can be bound (shadow depth map, static shadow depth map)
	* Forward lighting of local lights can be forced with 'r.VolumetricFog.InjectShadowedLightsSeparately 0'
	* Shadowed lights come at a cost: 2.9ms for volumetric fog on 970 -> 4.2ms with shadowing

Change 3347053 on 2017/03/15 by Rolando.Caloca

	DR - android compile fix

Change 3347384 on 2017/03/15 by Rolando.Caloca

	DR - Fix merge issue

Change 3347643 on 2017/03/15 by Marcus.Wassmer

	Fix some bugs with the 'disable stationary skylight ffor the project' feature.
	Fixes lighting in Persona on Paragon.

Change 3347979 on 2017/03/15 by Rolando.Caloca

	DR - Allow to automatically apply cached rendertargets to PSO initializer

Change 3348024 on 2017/03/15 by Rolando.Caloca

	DR - Remove NullPS on Vulkan to avoid deadlock

Change 3348303 on 2017/03/15 by Rolando.Caloca

	DR - Fix for debugging SCW with material SRT

Change 3348357 on 2017/03/15 by Marcus.Wassmer

	Fix stencildither and a stencilref bug that was probably breaking decals sometimes.

Change 3348549 on 2017/03/15 by Marcus.Wassmer

	Hopefully fix static analysis for potential nullptr access.

Change 3348614 on 2017/03/15 by Marcus.Wassmer

	Duplicate some switch changes to fix crash on launch.

Change 3349369 on 2017/03/16 by Gil.Gribb

	Fixed botched merge

Change 3349947 on 2017/03/16 by Rolando.Caloca

	DR - Fix for mismatched primitive type

Change 3349956 on 2017/03/16 by Benjamin.Hyder

	initial updates to TM-DistanceFields map

Change 3350151 on 2017/03/16 by Rolando.Caloca

	DR - Fix UT compile issue

Change 3350155 on 2017/03/16 by Rolando.Caloca

	DR - Catch mismatched primitive type on PSOs on D3D11

Change 3350192 on 2017/03/16 by Daniel.Wright

	Fix for point light shadow depths rendering with wrong cull mode due to PSO refactor

Change 3350736 on 2017/03/16 by Daniel.Wright

	Fixed formatting from merge

Change 3350881 on 2017/03/16 by Rolando.Caloca

	DR - Fix texture arrays as UAVs on Metal

Change 3350927 on 2017/03/16 by Rolando.Caloca

	DR - Fix warning

Change 3350935 on 2017/03/16 by Daniel.Wright

	Fix for materials with non-Surface domains being skipped in mesh passes

Change 3351583 on 2017/03/17 by Marcus.Wassmer

	Fix clang platforms

Change 3351917 on 2017/03/17 by Marcus.Wassmer

	Fix linux compile

Change 3351973 on 2017/03/17 by Marcus.Wassmer

	Fix mismatched rendertargetformat

Change 3352038 on 2017/03/17 by Daniel.Wright

	Enabled GetAndOrCreateGraphicsPipelineState ensures in Development for testing

Change 3352110 on 2017/03/17 by Marcus.Wassmer

	Fix missing RT PSO apply

Change 3352695 on 2017/03/17 by Arne.Schober

	DR - Remove PSO Rendertarget check in DX12 Resolve with Shader.
	#RB Rolando.Caloca

Change 3352960 on 2017/03/17 by Arne.Schober

	DR - Fix some things that slipped trough the PSO merge
	#RB none

Change 3353150 on 2017/03/18 by Rolando.Caloca

	DR - compile fix

Change 3353205 on 2017/03/18 by Arne.Schober

	DR - Fix Incremental Compile and PS4 runtime error where CMASK is not allowed for ThickTile Mode

	#RB none

Change 3353207 on 2017/03/18 by Arne.Schober

	DR - Fix Confusion

	#RB none

Change 3355183 on 2017/03/20 by Nick.Bullard

	Fixed up Content orginzation for Decals automation tests in EngineTest

Change 3355627 on 2017/03/20 by Arne.Schober

	DR - [UE-43094] - removed ensure in comporiton graph as control of the clear color cannot be gurantueed.

Change 3356342 on 2017/03/21 by Marcus.Wassmer

	Fix clang errors

Change 3356591 on 2017/03/21 by Arne.Schober

	DR - Fix ensure message
	#RB none

Change 3356873 on 2017/03/21 by Arne.Schober

	DR - Fix comparission of undefined values in RendertargetApply Check

Change 3357261 on 2017/03/21 by Marcus.Wassmer

	Fix LinuxEditor compile

Change 3357294 on 2017/03/21 by Marcus.Wassmer

	Add missing SSE functions

Change 3357351 on 2017/03/21 by Frank.Fella

	Fix win32 and linux compiler errors

Change 3357370 on 2017/03/21 by Arne.Schober

	DR - disable ensure in test builds

	#RB Marcus.Wassmer

[CL 3357449 by Marcus Wassmer in Main branch]
2017-03-21 17:46:52 -04:00

1102 lines
41 KiB
C++

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
DistanceFieldAmbientOcclusion.cpp
=============================================================================*/
#include "DistanceFieldAmbientOcclusion.h"
#include "DeferredShadingRenderer.h"
#include "PostProcess/PostProcessing.h"
#include "PostProcess/SceneFilterRendering.h"
#include "DistanceFieldLightingShared.h"
#include "ScreenRendering.h"
#include "DistanceFieldLightingPost.h"
#include "OneColorShader.h"
#include "GlobalDistanceField.h"
#include "FXSystem.h"
#include "PostProcess/PostProcessSubsurface.h"
#include "DistanceFieldGlobalIllumination.h"
#include "RendererModule.h"
#include "PipelineStateCache.h"
int32 GDistanceFieldAO = 1;
FAutoConsoleVariableRef CVarDistanceFieldAO(
TEXT("r.DistanceFieldAO"),
GDistanceFieldAO,
TEXT("Whether the distance field AO feature is allowed, which is used to implement shadows of Movable sky lights from static meshes."),
ECVF_Scalability | ECVF_RenderThreadSafe
);
int32 GDistanceFieldAOApplyToStaticIndirect = 0;
FAutoConsoleVariableRef CVarDistanceFieldAOApplyToStaticIndirect(
TEXT("r.AOApplyToStaticIndirect"),
GDistanceFieldAOApplyToStaticIndirect,
TEXT("Whether to apply DFAO as indirect shadowing even to static indirect sources (lightmaps + stationary skylight + reflection captures)"),
ECVF_Scalability | ECVF_RenderThreadSafe
);
int32 GDistanceFieldAOSpecularOcclusionMode = 1;
FAutoConsoleVariableRef CVarDistanceFieldAOSpecularOcclusionMode(
TEXT("r.AOSpecularOcclusionMode"),
GDistanceFieldAOSpecularOcclusionMode,
TEXT("Determines how specular should be occluded by DFAO\n")
TEXT("0: Apply non-directional AO to specular.\n")
TEXT("1: (default) Intersect the reflection cone with the unoccluded cone produced by DFAO. This gives more accurate occlusion than 0, but can bring out DFAO sampling artifacts.\n"),
ECVF_Scalability | ECVF_RenderThreadSafe
);
bool IsDistanceFieldGIAllowed(const FViewInfo& View)
{
return DoesPlatformSupportDistanceFieldGI(View.GetShaderPlatform())
&& (View.Family->EngineShowFlags.VisualizeDistanceFieldGI || (View.Family->EngineShowFlags.DistanceFieldGI && GDistanceFieldGI && View.Family->EngineShowFlags.GlobalIllumination));
}
float GAOStepExponentScale = .5f;
FAutoConsoleVariableRef CVarAOStepExponentScale(
TEXT("r.AOStepExponentScale"),
GAOStepExponentScale,
TEXT("Exponent used to distribute AO samples along a cone direction."),
ECVF_RenderThreadSafe
);
float GAOMaxViewDistance = 20000;
FAutoConsoleVariableRef CVarAOMaxViewDistance(
TEXT("r.AOMaxViewDistance"),
GAOMaxViewDistance,
TEXT("The maximum distance that AO will be computed at."),
ECVF_RenderThreadSafe
);
int32 GAOComputeShaderNormalCalculation = 0;
FAutoConsoleVariableRef CVarAOComputeShaderNormalCalculation(
TEXT("r.AOComputeShaderNormalCalculation"),
GAOComputeShaderNormalCalculation,
TEXT("Whether to use the compute shader version of the distance field normal computation."),
ECVF_RenderThreadSafe
);
int32 GAOSampleSet = 1;
FAutoConsoleVariableRef CVarAOSampleSet(
TEXT("r.AOSampleSet"),
GAOSampleSet,
TEXT("0 = Original set, 1 = Relaxed set"),
ECVF_RenderThreadSafe
);
int32 GAOOverwriteSceneColor = 0;
FAutoConsoleVariableRef CVarAOOverwriteSceneColor(
TEXT("r.AOOverwriteSceneColor"),
GAOOverwriteSceneColor,
TEXT(""),
ECVF_RenderThreadSafe
);
int32 GMaxDistanceFieldObjectsPerCullTile = 256;
FAutoConsoleVariableRef CVarMaxDistanceFieldObjectsPerCullTile(
TEXT("r.AOMaxObjectsPerCullTile"),
GMaxDistanceFieldObjectsPerCullTile,
TEXT("Determines how much memory should be allocated in distance field object culling data structures. Too much = memory waste, too little = flickering due to buffer overflow."),
ECVF_RenderThreadSafe | ECVF_ReadOnly
);
TGlobalResource<FTemporaryIrradianceCacheResources> GTemporaryIrradianceCacheResources;
int32 GDistanceFieldAOTileSizeX = 16;
int32 GDistanceFieldAOTileSizeY = 16;
DEFINE_LOG_CATEGORY(LogDistanceField);
IMPLEMENT_UNIFORM_BUFFER_STRUCT(FAOSampleData2,TEXT("AOSamples2"));
FDistanceFieldAOParameters::FDistanceFieldAOParameters(float InOcclusionMaxDistance, float InContrast)
{
Contrast = FMath::Clamp(InContrast, .01f, 2.0f);
InOcclusionMaxDistance = FMath::Clamp(InOcclusionMaxDistance, 2.0f, 3000.0f);
if (GAOGlobalDistanceField != 0)
{
extern float GAOGlobalDFStartDistance;
ObjectMaxOcclusionDistance = FMath::Min(InOcclusionMaxDistance, GAOGlobalDFStartDistance);
GlobalMaxOcclusionDistance = InOcclusionMaxDistance >= GAOGlobalDFStartDistance ? InOcclusionMaxDistance : 0;
}
else
{
ObjectMaxOcclusionDistance = InOcclusionMaxDistance;
GlobalMaxOcclusionDistance = 0;
}
}
FIntPoint GetBufferSizeForAO()
{
return FIntPoint::DivideAndRoundDown(FSceneRenderTargets::Get_FrameConstantsOnly().GetBufferSizeXY(), GAODownsampleFactor);
}
// Sample set restricted to not self-intersect a surface based on cone angle .475882232
// Coverage of hemisphere = 0.755312979
const FVector SpacedVectors9[] =
{
FVector(-0.573257625, 0.625250816, 0.529563010),
FVector(0.253354192, -0.840093017, 0.479640961),
FVector(-0.421664953, -0.718063235, 0.553700149),
FVector(0.249163717, 0.796005428, 0.551627457),
FVector(0.375082791, 0.295851320, 0.878512800),
FVector(-0.217619032, 0.00193520682, 0.976031899),
FVector(-0.852834642, 0.0111727007, 0.522061586),
FVector(0.745701790, 0.239393353, 0.621787369),
FVector(-0.151036426, -0.465937436, 0.871831656)
};
// Generated from SpacedVectors9 by applying repulsion forces until convergence
const FVector RelaxedSpacedVectors9[] =
{
FVector(-0.467612, 0.739424, 0.484347),
FVector(0.517459, -0.705440, 0.484346),
FVector(-0.419848, -0.767551, 0.484347),
FVector(0.343077, 0.804802, 0.484347),
FVector(0.364239, 0.244290, 0.898695),
FVector(-0.381547, 0.185815, 0.905481),
FVector(-0.870176, -0.090559, 0.484347),
FVector(0.874448, 0.027390, 0.484346),
FVector(0.032967, -0.435625, 0.899524)
};
void GetSpacedVectors(TArray<FVector, TInlineAllocator<9> >& OutVectors)
{
OutVectors.Empty(ARRAY_COUNT(SpacedVectors9));
if (GAOSampleSet == 0)
{
for (int32 i = 0; i < ARRAY_COUNT(SpacedVectors9); i++)
{
OutVectors.Add(SpacedVectors9[i]);
}
}
else
{
for (int32 i = 0; i < ARRAY_COUNT(RelaxedSpacedVectors9); i++)
{
OutVectors.Add(RelaxedSpacedVectors9[i]);
}
}
}
// Cone half angle derived from each cone covering an equal solid angle
float GAOConeHalfAngle = FMath::Acos(1 - 1.0f / (float)ARRAY_COUNT(SpacedVectors9));
// Number of AO sample positions along each cone
// Must match shader code
uint32 GAONumConeSteps = 10;
bool bListMemoryNextFrame = false;
void OnListMemory(UWorld* InWorld)
{
bListMemoryNextFrame = true;
}
FAutoConsoleCommandWithWorld ListMemoryConsoleCommand(
TEXT("r.AOListMemory"),
TEXT(""),
FConsoleCommandWithWorldDelegate::CreateStatic(OnListMemory)
);
bool bListMeshDistanceFieldsMemoryNextFrame = false;
void OnListMeshDistanceFields(UWorld* InWorld)
{
bListMeshDistanceFieldsMemoryNextFrame = true;
}
FAutoConsoleCommandWithWorld ListMeshDistanceFieldsMemoryConsoleCommand(
TEXT("r.AOListMeshDistanceFields"),
TEXT(""),
FConsoleCommandWithWorldDelegate::CreateStatic(OnListMeshDistanceFields)
);
class FComputeDistanceFieldNormalPS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FComputeDistanceFieldNormalPS, Global);
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor);
OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), GDistanceFieldAOTileSizeX);
OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), GDistanceFieldAOTileSizeY);
}
/** Default constructor. */
FComputeDistanceFieldNormalPS() {}
/** Initialization constructor. */
FComputeDistanceFieldNormalPS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
DeferredParameters.Bind(Initializer.ParameterMap);
AOParameters.Bind(Initializer.ParameterMap);
}
void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, const FDistanceFieldAOParameters& Parameters)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, ShaderRHI, View.ViewUniformBuffer);
AOParameters.Set(RHICmdList, ShaderRHI, Parameters);
DeferredParameters.Set(RHICmdList, ShaderRHI, View);
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << DeferredParameters;
Ar << AOParameters;
return bShaderHasOutdatedParameters;
}
private:
FDeferredPixelShaderParameters DeferredParameters;
FAOParameters AOParameters;
};
IMPLEMENT_SHADER_TYPE(,FComputeDistanceFieldNormalPS,TEXT("DistanceFieldScreenGridLighting"),TEXT("ComputeDistanceFieldNormalPS"),SF_Pixel);
class FComputeDistanceFieldNormalCS : public FGlobalShader
{
DECLARE_SHADER_TYPE(FComputeDistanceFieldNormalCS, Global);
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM5) && DoesPlatformSupportDistanceFieldAO(Platform);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor);
OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEX"), GDistanceFieldAOTileSizeX);
OutEnvironment.SetDefine(TEXT("THREADGROUP_SIZEY"), GDistanceFieldAOTileSizeY);
}
/** Default constructor. */
FComputeDistanceFieldNormalCS() {}
/** Initialization constructor. */
FComputeDistanceFieldNormalCS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
DistanceFieldNormal.Bind(Initializer.ParameterMap, TEXT("DistanceFieldNormal"));
DeferredParameters.Bind(Initializer.ParameterMap);
AOParameters.Bind(Initializer.ParameterMap);
}
void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FSceneRenderTargetItem& DistanceFieldNormalValue, const FDistanceFieldAOParameters& Parameters)
{
const FComputeShaderRHIParamRef ShaderRHI = GetComputeShader();
FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, ShaderRHI, View.ViewUniformBuffer);
RHICmdList.TransitionResource(EResourceTransitionAccess::ERWBarrier, EResourceTransitionPipeline::EComputeToCompute, DistanceFieldNormalValue.UAV);
DistanceFieldNormal.SetTexture(RHICmdList, ShaderRHI, DistanceFieldNormalValue.ShaderResourceTexture, DistanceFieldNormalValue.UAV);
AOParameters.Set(RHICmdList, ShaderRHI, Parameters);
DeferredParameters.Set(RHICmdList, ShaderRHI, View);
}
void UnsetParameters(FRHICommandList& RHICmdList, FSceneRenderTargetItem& DistanceFieldNormalValue)
{
DistanceFieldNormal.UnsetUAV(RHICmdList, GetComputeShader());
RHICmdList.TransitionResource(EResourceTransitionAccess::EReadable, EResourceTransitionPipeline::EComputeToCompute, DistanceFieldNormalValue.UAV);
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << DistanceFieldNormal;
Ar << DeferredParameters;
Ar << AOParameters;
return bShaderHasOutdatedParameters;
}
private:
FRWShaderParameter DistanceFieldNormal;
FDeferredPixelShaderParameters DeferredParameters;
FAOParameters AOParameters;
};
IMPLEMENT_SHADER_TYPE(,FComputeDistanceFieldNormalCS,TEXT("DistanceFieldScreenGridLighting"),TEXT("ComputeDistanceFieldNormalCS"),SF_Compute);
void ComputeDistanceFieldNormal(FRHICommandListImmediate& RHICmdList, const TArray<FViewInfo>& Views, FSceneRenderTargetItem& DistanceFieldNormal, const FDistanceFieldAOParameters& Parameters)
{
if (GAOComputeShaderNormalCalculation)
{
SetRenderTarget(RHICmdList, NULL, NULL);
for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
{
const FViewInfo& View = Views[ViewIndex];
uint32 GroupSizeX = FMath::DivideAndRoundUp(View.ViewRect.Size().X / GAODownsampleFactor, GDistanceFieldAOTileSizeX);
uint32 GroupSizeY = FMath::DivideAndRoundUp(View.ViewRect.Size().Y / GAODownsampleFactor, GDistanceFieldAOTileSizeY);
{
SCOPED_DRAW_EVENT(RHICmdList, ComputeNormalCS);
TShaderMapRef<FComputeDistanceFieldNormalCS> ComputeShader(View.ShaderMap);
RHICmdList.SetComputeShader(ComputeShader->GetComputeShader());
ComputeShader->SetParameters(RHICmdList, View, DistanceFieldNormal, Parameters);
DispatchComputeShader(RHICmdList, *ComputeShader, GroupSizeX, GroupSizeY, 1);
ComputeShader->UnsetParameters(RHICmdList, DistanceFieldNormal);
}
}
}
else
{
SetRenderTarget(RHICmdList, DistanceFieldNormal.TargetableTexture, NULL, true);
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<FM_Solid, CM_None>::GetRHI();
GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI();
GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI();
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
for (int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++)
{
const FViewInfo& View = Views[ViewIndex];
SCOPED_DRAW_EVENT(RHICmdList, ComputeNormal);
RHICmdList.SetViewport(0, 0, 0.0f, View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor, 1.0f);
TShaderMapRef<FPostProcessVS> VertexShader(View.ShaderMap);
TShaderMapRef<FComputeDistanceFieldNormalPS> PixelShader(View.ShaderMap);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GFilterVertexDeclaration.VertexDeclarationRHI;
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, View, Parameters);
DrawRectangle(
RHICmdList,
0, 0,
View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor,
0, 0,
View.ViewRect.Width(), View.ViewRect.Height(),
FIntPoint(View.ViewRect.Width() / GAODownsampleFactor, View.ViewRect.Height() / GAODownsampleFactor),
FSceneRenderTargets::Get(RHICmdList).GetBufferSizeXY(),
*VertexShader);
}
RHICmdList.TransitionResource(EResourceTransitionAccess::EReadable, DistanceFieldNormal.TargetableTexture);
}
}
/** Generates a pseudo-random position inside the unit sphere, uniformly distributed over the volume of the sphere. */
FVector GetUnitPosition2(FRandomStream& RandomStream)
{
FVector Result;
// Use rejection sampling to generate a valid sample
do
{
Result.X = RandomStream.GetFraction() * 2 - 1;
Result.Y = RandomStream.GetFraction() * 2 - 1;
Result.Z = RandomStream.GetFraction() * 2 - 1;
} while( Result.SizeSquared() > 1.f );
return Result;
}
/** Generates a pseudo-random unit vector, uniformly distributed over all directions. */
FVector GetUnitVector2(FRandomStream& RandomStream)
{
return GetUnitPosition2(RandomStream).GetUnsafeNormal();
}
void GenerateBestSpacedVectors()
{
static bool bGenerated = false;
bool bApplyRepulsion = false;
if (bApplyRepulsion && !bGenerated)
{
bGenerated = true;
FVector OriginalSpacedVectors9[ARRAY_COUNT(SpacedVectors9)];
for (int32 i = 0; i < ARRAY_COUNT(OriginalSpacedVectors9); i++)
{
OriginalSpacedVectors9[i] = SpacedVectors9[i];
}
float CosHalfAngle = 1 - 1.0f / (float)ARRAY_COUNT(OriginalSpacedVectors9);
// Used to prevent self-shadowing on a plane
float AngleBias = .03f;
float MinAngle = FMath::Acos(CosHalfAngle) + AngleBias;
float MinZ = FMath::Sin(MinAngle);
// Relaxation iterations by repulsion
for (int32 Iteration = 0; Iteration < 10000; Iteration++)
{
for (int32 i = 0; i < ARRAY_COUNT(OriginalSpacedVectors9); i++)
{
FVector Force(0.0f, 0.0f, 0.0f);
for (int32 j = 0; j < ARRAY_COUNT(OriginalSpacedVectors9); j++)
{
if (i != j)
{
FVector Distance = OriginalSpacedVectors9[i] - OriginalSpacedVectors9[j];
float Dot = OriginalSpacedVectors9[i] | OriginalSpacedVectors9[j];
if (Dot > 0)
{
// Repulsion force
Force += .001f * Distance.GetSafeNormal() * Dot * Dot * Dot * Dot;
}
}
}
FVector NewPosition = OriginalSpacedVectors9[i] + Force;
NewPosition.Z = FMath::Max(NewPosition.Z, MinZ);
NewPosition = NewPosition.GetSafeNormal();
OriginalSpacedVectors9[i] = NewPosition;
}
}
for (int32 i = 0; i < ARRAY_COUNT(OriginalSpacedVectors9); i++)
{
UE_LOG(LogDistanceField, Log, TEXT("FVector(%f, %f, %f),"), OriginalSpacedVectors9[i].X, OriginalSpacedVectors9[i].Y, OriginalSpacedVectors9[i].Z);
}
int32 temp = 0;
}
bool bBruteForceGenerateConeDirections = false;
if (bBruteForceGenerateConeDirections)
{
FVector BestSpacedVectors9[9];
float BestCoverage = 0;
// Each cone covers an area of ConeSolidAngle = HemisphereSolidAngle / NumCones
// HemisphereSolidAngle = 2 * PI
// ConeSolidAngle = 2 * PI * (1 - cos(ConeHalfAngle))
// cos(ConeHalfAngle) = 1 - 1 / NumCones
float CosHalfAngle = 1 - 1.0f / (float)ARRAY_COUNT(BestSpacedVectors9);
// Prevent self-intersection in sample set
float MinAngle = FMath::Acos(CosHalfAngle);
float MinZ = FMath::Sin(MinAngle);
FRandomStream RandomStream(123567);
// Super slow random brute force search
for (int i = 0; i < 1000000; i++)
{
FVector CandidateSpacedVectors[ARRAY_COUNT(BestSpacedVectors9)];
for (int j = 0; j < ARRAY_COUNT(CandidateSpacedVectors); j++)
{
FVector NewSample;
// Reject invalid directions until we get a valid one
do
{
NewSample = GetUnitVector2(RandomStream);
}
while (NewSample.Z <= MinZ);
CandidateSpacedVectors[j] = NewSample;
}
float Coverage = 0;
int NumSamples = 10000;
// Determine total cone coverage with monte carlo estimation
for (int sample = 0; sample < NumSamples; sample++)
{
FVector NewSample;
do
{
NewSample = GetUnitVector2(RandomStream);
}
while (NewSample.Z <= 0);
bool bIntersects = false;
for (int j = 0; j < ARRAY_COUNT(CandidateSpacedVectors); j++)
{
if (FVector::DotProduct(CandidateSpacedVectors[j], NewSample) > CosHalfAngle)
{
bIntersects = true;
break;
}
}
Coverage += bIntersects ? 1 / (float)NumSamples : 0;
}
if (Coverage > BestCoverage)
{
BestCoverage = Coverage;
for (int j = 0; j < ARRAY_COUNT(CandidateSpacedVectors); j++)
{
BestSpacedVectors9[j] = CandidateSpacedVectors[j];
}
}
}
int32 temp = 0;
}
}
void ListDistanceFieldLightingMemory(const FViewInfo& View, FSceneRenderer& SceneRenderer)
{
const FScene* Scene = (const FScene*)View.Family->Scene;
UE_LOG(LogRenderer, Log, TEXT("Shared GPU memory (excluding render targets)"));
if (Scene->DistanceFieldSceneData.NumObjectsInBuffer > 0)
{
UE_LOG(LogRenderer, Log, TEXT(" Scene Object data %.3fMb"), Scene->DistanceFieldSceneData.ObjectBuffers->GetSizeBytes() / 1024.0f / 1024.0f);
}
UE_LOG(LogRenderer, Log, TEXT(" %s"), *GDistanceFieldVolumeTextureAtlas.GetSizeString());
extern FString GetObjectBufferMemoryString();
UE_LOG(LogRenderer, Log, TEXT(" %s"), *GetObjectBufferMemoryString());
UE_LOG(LogRenderer, Log, TEXT(""));
UE_LOG(LogRenderer, Log, TEXT("Distance Field AO"));
UE_LOG(LogRenderer, Log, TEXT(" Temporary cache %.3fMb"), GTemporaryIrradianceCacheResources.GetSizeBytes() / 1024.0f / 1024.0f);
UE_LOG(LogRenderer, Log, TEXT(" Culled objects %.3fMb"), GAOCulledObjectBuffers.Buffers.GetSizeBytes() / 1024.0f / 1024.0f);
FTileIntersectionResources* TileIntersectionResources = ((FSceneViewState*)View.State)->AOTileIntersectionResources;
if (TileIntersectionResources)
{
UE_LOG(LogRenderer, Log, TEXT(" Tile Culled objects %.3fMb"), TileIntersectionResources->GetSizeBytes() / 1024.0f / 1024.0f);
}
FAOScreenGridResources* ScreenGridResources = ((FSceneViewState*)View.State)->AOScreenGridResources;
if (ScreenGridResources)
{
UE_LOG(LogRenderer, Log, TEXT(" Screen grid temporaries %.3fMb"), ScreenGridResources->GetSizeBytesForAO() / 1024.0f / 1024.0f);
}
UE_LOG(LogRenderer, Log, TEXT(""));
UE_LOG(LogRenderer, Log, TEXT("Ray Traced Distance Field Shadows"));
for (TSparseArray<FLightSceneInfoCompact>::TConstIterator LightIt(Scene->Lights); LightIt; ++LightIt)
{
const FLightSceneInfoCompact& LightSceneInfoCompact = *LightIt;
FLightSceneInfo* LightSceneInfo = LightSceneInfoCompact.LightSceneInfo;
FVisibleLightInfo& VisibleLightInfo = SceneRenderer.VisibleLightInfos[LightSceneInfo->Id];
for (int32 ShadowIndex = 0; ShadowIndex < VisibleLightInfo.ShadowsToProject.Num(); ShadowIndex++)
{
FProjectedShadowInfo* ProjectedShadowInfo = VisibleLightInfo.ShadowsToProject[ShadowIndex];
if (ProjectedShadowInfo->bRayTracedDistanceField && LightSceneInfo->TileIntersectionResources)
{
UE_LOG(LogRenderer, Log, TEXT(" Light Tile Culled objects %.3fMb"), LightSceneInfo->TileIntersectionResources->GetSizeBytes() / 1024.0f / 1024.0f);
}
}
}
extern void ListGlobalDistanceFieldMemory();
ListGlobalDistanceFieldMemory();
UE_LOG(LogRenderer, Log, TEXT(""));
UE_LOG(LogRenderer, Log, TEXT("Distance Field GI"));
if (Scene->DistanceFieldSceneData.SurfelBuffers)
{
UE_LOG(LogRenderer, Log, TEXT(" Scene surfel data %.3fMb"), Scene->DistanceFieldSceneData.SurfelBuffers->GetSizeBytes() / 1024.0f / 1024.0f);
}
if (Scene->DistanceFieldSceneData.InstancedSurfelBuffers)
{
UE_LOG(LogRenderer, Log, TEXT(" Instanced scene surfel data %.3fMb"), Scene->DistanceFieldSceneData.InstancedSurfelBuffers->GetSizeBytes() / 1024.0f / 1024.0f);
}
if (ScreenGridResources)
{
UE_LOG(LogRenderer, Log, TEXT(" Screen grid temporaries %.3fMb"), ScreenGridResources->GetSizeBytesForGI() / 1024.0f / 1024.0f);
}
extern void ListDistanceFieldGIMemory(const FViewInfo& View);
ListDistanceFieldGIMemory(View);
}
bool SupportsDistanceFieldAO(ERHIFeatureLevel::Type FeatureLevel, EShaderPlatform ShaderPlatform)
{
return GDistanceFieldAO
// Pre-GCN AMD cards have a driver bug that prevents the global distance field from being generated correctly
// Better to disable entirely than to display garbage
&& !GRHIDeviceIsAMDPreGCNArchitecture
// Intel HD 4000 hangs in the RHICreateTexture3D call to allocate the large distance field atlas, and virtually no Intel cards can afford it anyway
&& !IsRHIDeviceIntel()
&& FeatureLevel >= ERHIFeatureLevel::SM5
&& DoesPlatformSupportDistanceFieldAO(ShaderPlatform);
}
bool ShouldRenderDeferredDynamicSkyLight(const FScene* Scene, const FSceneViewFamily& ViewFamily)
{
return Scene->SkyLight
&& Scene->SkyLight->ProcessedTexture
&& !Scene->SkyLight->bWantsStaticShadowing
&& !Scene->SkyLight->bHasStaticLighting
&& ViewFamily.EngineShowFlags.SkyLighting
&& Scene->GetFeatureLevel() >= ERHIFeatureLevel::SM4
&& !IsAnyForwardShadingEnabled(Scene->GetShaderPlatform())
&& !ViewFamily.EngineShowFlags.VisualizeLightCulling;
}
bool FDeferredShadingSceneRenderer::ShouldPrepareForDistanceFieldAO() const
{
return SupportsDistanceFieldAO(Scene->GetFeatureLevel(), Scene->GetShaderPlatform())
&& ((ShouldRenderDeferredDynamicSkyLight(Scene, ViewFamily) && Scene->SkyLight->bCastShadows && ViewFamily.EngineShowFlags.DistanceFieldAO)
|| ViewFamily.EngineShowFlags.VisualizeMeshDistanceFields
|| ViewFamily.EngineShowFlags.VisualizeGlobalDistanceField
|| ViewFamily.EngineShowFlags.VisualizeDistanceFieldAO
|| ViewFamily.EngineShowFlags.VisualizeDistanceFieldGI
|| (GDistanceFieldAOApplyToStaticIndirect && ViewFamily.EngineShowFlags.DistanceFieldAO));
}
bool FDeferredShadingSceneRenderer::ShouldPrepareDistanceFieldScene() const
{
if (!ensure(Scene != nullptr))
{
return false;
}
if (IsRHIDeviceIntel())
{
// Intel HD 4000 hangs in the RHICreateTexture3D call to allocate the large distance field atlas, and virtually no Intel cards can afford it anyway
return false;
}
bool bShouldPrepareForAO = SupportsDistanceFieldAO(Scene->GetFeatureLevel(), Scene->GetShaderPlatform()) && ShouldPrepareForDistanceFieldAO();
bool bShouldPrepareGlobalDistanceField = ShouldPrepareGlobalDistanceField();
bool bShouldPrepareForDFInsetIndirectShadow = ShouldPrepareForDFInsetIndirectShadow();
// Prepare the distance field scene (object buffers and distance field atlas) if any feature needs it
return bShouldPrepareGlobalDistanceField || bShouldPrepareForAO || ShouldPrepareForDistanceFieldShadows() || bShouldPrepareForDFInsetIndirectShadow;
}
bool FDeferredShadingSceneRenderer::ShouldPrepareGlobalDistanceField() const
{
if (!ensure(Scene != nullptr))
{
return false;
}
bool bShouldPrepareForAO = SupportsDistanceFieldAO(Scene->GetFeatureLevel(), Scene->GetShaderPlatform())
&& (ShouldPrepareForDistanceFieldAO()
|| ((Views.Num() > 0) && Views[0].bUsesGlobalDistanceField)
|| ((Scene->FXSystem != nullptr) && Scene->FXSystem->UsesGlobalDistanceField()));
return bShouldPrepareForAO && UseGlobalDistanceField();
}
void FDeferredShadingSceneRenderer::RenderDFAOAsIndirectShadowing(
FRHICommandListImmediate& RHICmdList,
const TRefCountPtr<IPooledRenderTarget>& VelocityTexture,
TRefCountPtr<IPooledRenderTarget>& DynamicBentNormalAO)
{
if (GDistanceFieldAOApplyToStaticIndirect && ShouldRenderDistanceFieldAO())
{
// Use the skylight's max distance if there is one, to be consistent with DFAO shadowing on the skylight
const float OcclusionMaxDistance = Scene->SkyLight && !Scene->SkyLight->bWantsStaticShadowing ? Scene->SkyLight->OcclusionMaxDistance : Scene->DefaultMaxDistanceFieldOcclusionDistance;
TRefCountPtr<IPooledRenderTarget> DummyOutput;
RenderDistanceFieldLighting(RHICmdList, FDistanceFieldAOParameters(OcclusionMaxDistance), VelocityTexture, DynamicBentNormalAO, DummyOutput, true, false, false);
}
}
bool FDeferredShadingSceneRenderer::RenderDistanceFieldLighting(
FRHICommandListImmediate& RHICmdList,
const FDistanceFieldAOParameters& Parameters,
const TRefCountPtr<IPooledRenderTarget>& VelocityTexture,
TRefCountPtr<IPooledRenderTarget>& OutDynamicBentNormalAO,
TRefCountPtr<IPooledRenderTarget>& OutDynamicIrradiance,
bool bModulateToSceneColor,
bool bVisualizeAmbientOcclusion,
bool bVisualizeGlobalIllumination)
{
//@todo - support multiple views
const FViewInfo& View = Views[0];
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
if (SupportsDistanceFieldAO(View.GetFeatureLevel(), View.GetShaderPlatform())
&& Views.Num() == 1
// ViewState is used to cache tile intersection resources which have to be sized based on the view
&& View.State
&& View.IsPerspectiveProjection())
{
QUICK_SCOPE_CYCLE_COUNTER(STAT_RenderDistanceFieldLighting);
if (GDistanceFieldVolumeTextureAtlas.VolumeTextureRHI && Scene->DistanceFieldSceneData.NumObjectsInBuffer)
{
check(!Scene->DistanceFieldSceneData.HasPendingOperations());
const bool bUseDistanceFieldGI = IsDistanceFieldGIAllowed(View);
SCOPED_DRAW_EVENT(RHICmdList, DistanceFieldLighting);
GenerateBestSpacedVectors();
if (bListMemoryNextFrame)
{
bListMemoryNextFrame = false;
ListDistanceFieldLightingMemory(View, *this);
}
if (bListMeshDistanceFieldsMemoryNextFrame)
{
bListMeshDistanceFieldsMemoryNextFrame = false;
GDistanceFieldVolumeTextureAtlas.ListMeshDistanceFields();
}
CullObjectsToView(RHICmdList, Scene, View, Parameters, GAOCulledObjectBuffers);
TRefCountPtr<IPooledRenderTarget> DistanceFieldNormal;
{
const FIntPoint BufferSize = GetBufferSizeForAO();
FPooledRenderTargetDesc Desc(FPooledRenderTargetDesc::Create2DDesc(BufferSize, PF_FloatRGBA, FClearValueBinding::Transparent, TexCreate_None, TexCreate_RenderTargetable | TexCreate_UAV, false));
GRenderTargetPool.FindFreeElement(RHICmdList, Desc, DistanceFieldNormal, TEXT("DistanceFieldNormal"));
}
ComputeDistanceFieldNormal(RHICmdList, Views, DistanceFieldNormal->GetRenderTargetItem(), Parameters);
// Intersect objects with screen tiles, build lists
FIntPoint TileListGroupSize = BuildTileObjectLists(RHICmdList, Scene, Views, DistanceFieldNormal->GetRenderTargetItem(), Parameters);
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, DistanceFieldNormal);
if (bUseDistanceFieldGI)
{
extern void UpdateVPLs(
FRHICommandListImmediate& RHICmdList,
const FViewInfo& View,
const FScene* Scene,
const FDistanceFieldAOParameters& Parameters);
UpdateVPLs(RHICmdList, View, Scene, Parameters);
}
TRefCountPtr<IPooledRenderTarget> BentNormalOutput;
TRefCountPtr<IPooledRenderTarget> IrradianceOutput;
RenderDistanceFieldAOScreenGrid(
RHICmdList,
View,
TileListGroupSize,
Parameters,
VelocityTexture,
DistanceFieldNormal,
BentNormalOutput,
IrradianceOutput);
RenderCapsuleShadowsForMovableSkylight(RHICmdList, BentNormalOutput);
GRenderTargetPool.VisualizeTexture.SetCheckPoint(RHICmdList, BentNormalOutput);
if (bVisualizeAmbientOcclusion || bVisualizeGlobalIllumination)
{
SceneContext.BeginRenderingSceneColor(RHICmdList, ESimpleRenderTargetMode::EExistingColorAndDepth, FExclusiveDepthStencil::DepthRead_StencilNop);
}
else
{
FPooledRenderTargetDesc Desc = SceneContext.GetSceneColor()->GetDesc();
// Make sure we get a signed format
Desc.Format = PF_FloatRGBA;
GRenderTargetPool.FindFreeElement(RHICmdList, Desc, OutDynamicBentNormalAO, TEXT("DynamicBentNormalAO"));
if (bUseDistanceFieldGI)
{
Desc.Format = PF_FloatRGB;
GRenderTargetPool.FindFreeElement(RHICmdList, Desc, OutDynamicIrradiance, TEXT("DynamicIrradiance"));
}
FTextureRHIParamRef RenderTargets[3] =
{
OutDynamicBentNormalAO->GetRenderTargetItem().TargetableTexture,
NULL,
NULL
};
int32 NumRenderTargets = 1;
if (bModulateToSceneColor)
{
RenderTargets[NumRenderTargets] = SceneContext.GetSceneColorSurface();
NumRenderTargets++;
}
if (bUseDistanceFieldGI)
{
RenderTargets[NumRenderTargets] = OutDynamicIrradiance->GetRenderTargetItem().TargetableTexture;
NumRenderTargets++;
}
SetRenderTargets(RHICmdList, NumRenderTargets, RenderTargets, SceneContext.GetSceneDepthSurface(), ESimpleRenderTargetMode::EExistingColorAndDepth, FExclusiveDepthStencil::DepthRead_StencilNop);
}
// Upsample to full resolution, write to output
UpsampleBentNormalAO(RHICmdList, Views, BentNormalOutput, IrradianceOutput, bModulateToSceneColor, bVisualizeAmbientOcclusion, bVisualizeGlobalIllumination);
if (!bVisualizeAmbientOcclusion && !bVisualizeGlobalIllumination)
{
RHICmdList.CopyToResolveTarget(OutDynamicBentNormalAO->GetRenderTargetItem().TargetableTexture, OutDynamicBentNormalAO->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams());
if (bUseDistanceFieldGI)
{
RHICmdList.CopyToResolveTarget(OutDynamicIrradiance->GetRenderTargetItem().TargetableTexture, OutDynamicIrradiance->GetRenderTargetItem().ShaderResourceTexture, false, FResolveParams());
}
}
return true;
}
}
return false;
}
template<bool bApplyShadowing, bool bSupportIrradiance>
class TDynamicSkyLightDiffusePS : public FGlobalShader
{
DECLARE_SHADER_TYPE(TDynamicSkyLightDiffusePS, Global);
public:
static bool ShouldCache(EShaderPlatform Platform)
{
return IsFeatureLevelSupported(Platform, ERHIFeatureLevel::SM4);
}
static void ModifyCompilationEnvironment(EShaderPlatform Platform, FShaderCompilerEnvironment& OutEnvironment)
{
FGlobalShader::ModifyCompilationEnvironment(Platform,OutEnvironment);
OutEnvironment.SetDefine(TEXT("DOWNSAMPLE_FACTOR"), GAODownsampleFactor);
OutEnvironment.SetDefine(TEXT("APPLY_SHADOWING"), bApplyShadowing);
OutEnvironment.SetDefine(TEXT("SUPPORT_IRRADIANCE"), bSupportIrradiance);
}
/** Default constructor. */
TDynamicSkyLightDiffusePS() {}
/** Initialization constructor. */
TDynamicSkyLightDiffusePS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
: FGlobalShader(Initializer)
{
DeferredParameters.Bind(Initializer.ParameterMap);
DynamicBentNormalAOTexture.Bind(Initializer.ParameterMap, TEXT("BentNormalAOTexture"));
DynamicBentNormalAOSampler.Bind(Initializer.ParameterMap, TEXT("BentNormalAOSampler"));
DynamicIrradianceTexture.Bind(Initializer.ParameterMap, TEXT("IrradianceTexture"));
DynamicIrradianceSampler.Bind(Initializer.ParameterMap, TEXT("IrradianceSampler"));
ContrastAndNormalizeMulAdd.Bind(Initializer.ParameterMap, TEXT("ContrastAndNormalizeMulAdd"));
OcclusionExponent.Bind(Initializer.ParameterMap, TEXT("OcclusionExponent"));
OcclusionTintAndMinOcclusion.Bind(Initializer.ParameterMap, TEXT("OcclusionTintAndMinOcclusion"));
OcclusionCombineMode.Bind(Initializer.ParameterMap, TEXT("OcclusionCombineMode"));
}
void SetParameters(FRHICommandList& RHICmdList, const FSceneView& View, FTextureRHIParamRef DynamicBentNormalAO, IPooledRenderTarget* DynamicIrradiance, const FDistanceFieldAOParameters& Parameters, const FSkyLightSceneProxy* SkyLight)
{
const FPixelShaderRHIParamRef ShaderRHI = GetPixelShader();
FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, ShaderRHI, View.ViewUniformBuffer);
DeferredParameters.Set(RHICmdList, ShaderRHI, View);
SetTextureParameter(RHICmdList, ShaderRHI, DynamicBentNormalAOTexture, DynamicBentNormalAOSampler, TStaticSamplerState<SF_Point>::GetRHI(), DynamicBentNormalAO);
if (DynamicIrradianceTexture.IsBound())
{
SetTextureParameter(RHICmdList, ShaderRHI, DynamicIrradianceTexture, DynamicIrradianceSampler, TStaticSamplerState<SF_Point>::GetRHI(), DynamicIrradiance->GetRenderTargetItem().ShaderResourceTexture);
}
// Scale and bias to remap the contrast curve to [0,1]
const float Min = 1 / (1 + FMath::Exp(-Parameters.Contrast * (0 * 10 - 5)));
const float Max = 1 / (1 + FMath::Exp(-Parameters.Contrast * (1 * 10 - 5)));
const float Mul = 1.0f / (Max - Min);
const float Add = -Min / (Max - Min);
SetShaderValue(RHICmdList, ShaderRHI, ContrastAndNormalizeMulAdd, FVector(Parameters.Contrast, Mul, Add));
SetShaderValue(RHICmdList, ShaderRHI, OcclusionExponent, SkyLight->OcclusionExponent);
FVector4 OcclusionTintAndMinOcclusionValue = FVector4(SkyLight->OcclusionTint);
OcclusionTintAndMinOcclusionValue.W = SkyLight->MinOcclusion;
SetShaderValue(RHICmdList, ShaderRHI, OcclusionTintAndMinOcclusion, OcclusionTintAndMinOcclusionValue);
SetShaderValue(RHICmdList, ShaderRHI, OcclusionCombineMode, SkyLight->OcclusionCombineMode == OCM_Minimum ? 0.0f : 1.0f);
}
// FShader interface.
virtual bool Serialize(FArchive& Ar) override
{
bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
Ar << DeferredParameters;
Ar << DynamicBentNormalAOTexture;
Ar << DynamicBentNormalAOSampler;
Ar << DynamicIrradianceTexture;
Ar << DynamicIrradianceSampler;
Ar << ContrastAndNormalizeMulAdd;
Ar << OcclusionExponent;
Ar << OcclusionTintAndMinOcclusion;
Ar << OcclusionCombineMode;
return bShaderHasOutdatedParameters;
}
private:
FDeferredPixelShaderParameters DeferredParameters;
FShaderResourceParameter DynamicBentNormalAOTexture;
FShaderResourceParameter DynamicBentNormalAOSampler;
FShaderResourceParameter DynamicIrradianceTexture;
FShaderResourceParameter DynamicIrradianceSampler;
FShaderParameter ContrastAndNormalizeMulAdd;
FShaderParameter OcclusionExponent;
FShaderParameter OcclusionTintAndMinOcclusion;
FShaderParameter OcclusionCombineMode;
};
#define IMPLEMENT_SKYLIGHT_PS_TYPE(bApplyShadowing, bSupportIrradiance) \
typedef TDynamicSkyLightDiffusePS<bApplyShadowing, bSupportIrradiance> TDynamicSkyLightDiffusePS##bApplyShadowing##bSupportIrradiance; \
IMPLEMENT_SHADER_TYPE(template<>,TDynamicSkyLightDiffusePS##bApplyShadowing##bSupportIrradiance,TEXT("SkyLighting"),TEXT("SkyLightDiffusePS"),SF_Pixel);
IMPLEMENT_SKYLIGHT_PS_TYPE(true, true)
IMPLEMENT_SKYLIGHT_PS_TYPE(false, true)
IMPLEMENT_SKYLIGHT_PS_TYPE(true, false)
IMPLEMENT_SKYLIGHT_PS_TYPE(false, false)
bool FDeferredShadingSceneRenderer::ShouldRenderDistanceFieldAO() const
{
return ViewFamily.EngineShowFlags.DistanceFieldAO
&& !ViewFamily.EngineShowFlags.VisualizeDistanceFieldAO
&& !ViewFamily.EngineShowFlags.VisualizeDistanceFieldGI
&& !ViewFamily.EngineShowFlags.VisualizeMeshDistanceFields
&& !ViewFamily.EngineShowFlags.VisualizeGlobalDistanceField;
}
void FDeferredShadingSceneRenderer::RenderDynamicSkyLighting(FRHICommandListImmediate& RHICmdList, const TRefCountPtr<IPooledRenderTarget>& VelocityTexture, TRefCountPtr<IPooledRenderTarget>& DynamicBentNormalAO)
{
if (ShouldRenderDeferredDynamicSkyLight(Scene, ViewFamily))
{
SCOPED_DRAW_EVENT(RHICmdList, SkyLightDiffuse);
bool bApplyShadowing = false;
FDistanceFieldAOParameters Parameters(Scene->SkyLight->OcclusionMaxDistance, Scene->SkyLight->Contrast);
TRefCountPtr<IPooledRenderTarget> DynamicIrradiance;
if (Scene->SkyLight->bCastShadows
&& !GDistanceFieldAOApplyToStaticIndirect
&& ShouldRenderDistanceFieldAO()
&& ViewFamily.EngineShowFlags.AmbientOcclusion)
{
bApplyShadowing = RenderDistanceFieldLighting(RHICmdList, Parameters, VelocityTexture, DynamicBentNormalAO, DynamicIrradiance, false, false, false);
}
FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
SceneContext.BeginRenderingSceneColor(RHICmdList, ESimpleRenderTargetMode::EExistingColorAndDepth, FExclusiveDepthStencil::DepthRead_StencilRead);
FGraphicsPipelineStateInitializer GraphicsPSOInit;
RHICmdList.ApplyCachedRenderTargets(GraphicsPSOInit);
for( int32 ViewIndex = 0; ViewIndex < Views.Num(); ViewIndex++ )
{
const FViewInfo& View = Views[ViewIndex];
RHICmdList.SetViewport(View.ViewRect.Min.X, View.ViewRect.Min.Y, 0.0f, View.ViewRect.Max.X, View.ViewRect.Max.Y, 1.0f);
GraphicsPSOInit.RasterizerState = TStaticRasterizerState<FM_Solid, CM_None>::GetRHI();
GraphicsPSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI();
if (GAOOverwriteSceneColor)
{
GraphicsPSOInit.BlendState = TStaticBlendState<>::GetRHI();
}
else
{
const bool bCheckerboardSubsurfaceRendering = FRCPassPostProcessSubsurface::RequiresCheckerboardSubsurfaceRendering(SceneContext.GetSceneColorFormat());
if (bCheckerboardSubsurfaceRendering)
{
GraphicsPSOInit.BlendState = TStaticBlendState<CW_RGB, BO_Add, BF_One, BF_One>::GetRHI();
}
else
{
GraphicsPSOInit.BlendState = TStaticBlendState<CW_RGBA, BO_Add, BF_One, BF_One, BO_Add, BF_One, BF_One>::GetRHI();
}
}
const bool bUseDistanceFieldGI = IsDistanceFieldGIAllowed(View) && IsValidRef(DynamicIrradiance);
TShaderMapRef< FPostProcessVS > VertexShader(View.ShaderMap);
GraphicsPSOInit.BoundShaderState.VertexDeclarationRHI = GFilterVertexDeclaration.VertexDeclarationRHI;
GraphicsPSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*VertexShader);
GraphicsPSOInit.PrimitiveType = PT_TriangleList;
if (bApplyShadowing)
{
if (bUseDistanceFieldGI)
{
TShaderMapRef<TDynamicSkyLightDiffusePS<true, true> > PixelShader(View.ShaderMap);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, View, DynamicBentNormalAO->GetRenderTargetItem().ShaderResourceTexture, DynamicIrradiance, Parameters, Scene->SkyLight);
}
else
{
TShaderMapRef<TDynamicSkyLightDiffusePS<true, false> > PixelShader(View.ShaderMap);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, View, DynamicBentNormalAO->GetRenderTargetItem().ShaderResourceTexture, DynamicIrradiance, Parameters, Scene->SkyLight);
}
}
else
{
if (bUseDistanceFieldGI)
{
TShaderMapRef<TDynamicSkyLightDiffusePS<false, true> > PixelShader(View.ShaderMap);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, View, GWhiteTexture->TextureRHI, NULL, Parameters, Scene->SkyLight);
}
else
{
TShaderMapRef<TDynamicSkyLightDiffusePS<false, false> > PixelShader(View.ShaderMap);
GraphicsPSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*PixelShader);
SetGraphicsPipelineState(RHICmdList, GraphicsPSOInit);
PixelShader->SetParameters(RHICmdList, View, GWhiteTexture->TextureRHI, NULL, Parameters, Scene->SkyLight);
}
}
DrawRectangle(
RHICmdList,
0, 0,
View.ViewRect.Width(), View.ViewRect.Height(),
View.ViewRect.Min.X, View.ViewRect.Min.Y,
View.ViewRect.Width(), View.ViewRect.Height(),
FIntPoint(View.ViewRect.Width(), View.ViewRect.Height()),
SceneContext.GetBufferSizeXY(),
*VertexShader);
}
}
}