Files
UnrealEngineUWP/Engine/Shaders/MobileBasePassPixelShader.usf
Ryan Vance 8044633af9 Copying //UE4/Dev-VR to //UE4/Dev-Main (Source: //UE4/Dev-VR @ 3383750)
#lockdown Nick.Penwarden

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

Change 3012064 on 2016/06/13 by Nick.Whiting

	Merging Main -> DevVR

Change 3048060 on 2016/07/13 by Nick.Whiting

	Integrating CL 3045721 from //depot/Partners/Google/AndroidVR-DevVR
	Upgrade Android and iOS GVR SDK to the latest.
	Fix the flipped vignette issue when using Unreal's post processing distortion.
	Change the Daydream & Cardboard mode to use scanline racing.
	Deprecate the ability to turn off individual UI elements.

Change 3235307 on 2016/12/14 by Keli.Hlodversson

	Filter out excluded HMD modules during FEngineLoop:PreInitHMDDevice. The final selection still happens in UEngine::InitializeHMDDevice as all HMD plugins have not been loaded during PreInit

Change 3235308 on 2016/12/14 by Ryan.Vance

	#jira UEVR-478

	Monoscopic far field improvements

	Shader changes are now gated behind the read only cvar vr.MonoscopicFarField. Changing this requires a shader compile.
	Moved the mono rendering mode to the cvar vr.MonoscopicFarFieldMode. This is writable, so users can enable/disable mono rendering on the fly if the above cvar is enabled.
	Only write to the alpha channel in the mobile base pass if the object is opaque and MONOSCOPIC_FAR_FIELD is defined.
	Addressed code review comments.

Change 3235397 on 2016/12/14 by Keli.Hlodversson

	[Oculus] Only enable GearVR platform on Windows if Oculus service is running
	Original author: Loren.McQuade

Change 3235762 on 2016/12/14 by Keli.Hlodversson

	Add explicit parentheses to placate the build bots.

Change 3242318 on 2016/12/21 by Ryan.Vance

	Working around pixel density crash.

Change 3242522 on 2016/12/21 by Ryan.Vance

	Missing flag clear so our adaptive test was always returning true.

Change 3243173 on 2016/12/22 by Ryan.Vance

	Integrating post present callback implementation from 4.14.1

Change 3248633 on 2017/01/05 by Keli.Hlodversson

	Copying //Tasks/UE4/Dev-VR-Refactoring to Dev-VR-Minimal (//UE4/Dev-VR-Minimal)

Change 3248723 on 2017/01/05 by Keli.Hlodversson

	Fix after merge. EnablePositionalTracking no longer exists.

Change 3249484 on 2017/01/06 by Keli.Hlodversson

	Add missing includes

Change 3249714 on 2017/01/06 by Keli.Hlodversson

	Remove monolithic header include

Change 3249980 on 2017/01/06 by Keli.Hlodversson

	SteamVR: Remove leftover unused WindowMirrorMode member variable

Change 3252432 on 2017/01/10 by Keli.Hlodversson

	Submitting change by Loren McQuade to fix monolithic builds.

	Unshelved from pending changelist '3251436':

Change 3257373 on 2017/01/13 by Keli.Hlodversson

	#jira UEVR-411: Finish renaming/removing/remodelling the remaining Oculus (Rift+GearVR) commands
	#jira UEVR-412: Rename and merge remaining Morpheus console commands
	#jira UEVR-417: Remove Exec from IHeadMountedDisplay

Change 3269971 on 2017/01/24 by Jeff.Fisher

	UEVR-498 move controller is missing world to meters
	UEVR-522 PS4 motion controller worldscale support.
	-Passing world to meters scale into getControllerOrientationAndPosition because the thing asking about it ought to be part of a world, and know what it should be.  This also avoids making PS4 motion controllers dependent on the HMD.  Note Google VR Controller doesn't do position, so doesnt' care about scale.  Oculus already had internal threadsafe tracking of world scale, so I left that.  Steam handles world scale below our input level.
	-Also adding PlayerIndex member to FSceneView so we can figure out which view the MotionControllerComponent should get its worldscale from for the late render thread update.
	#jira UEVR-498
	#review-3384107

Change 3288308 on 2017/02/06 by Jeff.Fisher

	UEVR-517 Detect MotionController Connectivity
	-PS4 can only track 2 controllers and 1 hmd.  Support for dealing with that is needed.
	-Also need to support multiple motion controller components mapped to a single controller.  Licencees have done that before.
	-Created a new interface IMotionTrackingSystemManagement, and implements it for PS4Tracker on PS4.
	-Created a MotionTrackedDeviceFunctionLibrary to expose that interface to blueprint.
	-With those one can enable and disable tracking on ps4 controllers and query their state to stay within the controller tracking limit.
	-PS4Tracker also keeps a blackboard of the enable/disable state so that one can enable or disable controllers that have not been connected yet, and have them enable tracking or not when they are connected.
	-DS4 controller no longer jumps back to 000 if it loses tracking.
	#review-3384107
	#jira UEVR-517

Change 3288309 on 2017/02/06 by Keli.Hlodversson

	Add file missing from CL#3257373.

Change 3288311 on 2017/02/06 by Jeff.Fisher

	UEVR-517 Detect MotionController Connectivity - Test content.
	-tm-motionControllers has a third mode where all playstation motion controllers for player 0 are availalbe.  You can toggle them to track or not with ctrl-P,G,L,R for pad, gun, leftmove, rightmove or with alt-P,G,L,R.  Ctrl tests doing so via MotionControllerComponent.  Alt tests doing so by player index and controller type enum.
	-ctrl-A disables tracking of all controllers
	-alt-A disables tracking of all controllers for player 0
	-ctrl-D toggles enabling new controllers by default
	-Also fixed one button not working in one of the other test modes for the Aim (gun) controller.
	-The controller 'models' have an arrow out the front.  It is black if disabled.  Red if enabled, but no tracker is active, yellow if tracked but inertial only, and green if fully tracked by the camera.
	-This logic is in the QA_MoCoAll blueprint.

Change 3291601 on 2017/02/07 by Jeff.Fisher

	UEVR-536 PSVR motion controller tracking problem with multiple controllers
	-Previous code called GetRelativeTransform from the render thread, but the game thread could update it at any time.  This caches that transform so that it can be safely used in the render thread.
	#jira UEVR-536
	#review-3384107 @Ryan.Vance

Change 3292460 on 2017/02/08 by Jeff.Fisher

	PS4 sceVrTrackerGetResult() error warning logging improved, and explanatory comment added.

Change 3308771 on 2017/02/17 by Keli.Hlodversson

	Rename GoogleVR console commands
	#jira UEVR-412

Change 3309156 on 2017/02/17 by Keli.Hlodversson

	Track changes in r.ScreenPercentage on GoogleVR and set RenderTargetSize accordingly.

Change 3311999 on 2017/02/20 by Keli.Hlodversson

	Create a default implementation for RecordAnalytics.

	Also create an initial stub for FHeadMountedDisplayBase for future default implementations of common HMD functionality.
	Make implementing IHeadMountedDisplay::GetDeviceName mandatory instead of defaulting to "Unknown"
	#jira UE-21878
	#jira UEVR-213

Change 3313467 on 2017/02/20 by Ryan.Vance

	#jira UE-41604

	3278583
	pCustomPresent->AllocateRenderTargetTexture may return false, if we blindly return true we can end up with an invalid render target since the fall back sceneviewport will be skipped.

	3278536
	Adding ovrError_NoHmd to our sanity check in OnStartGameFrame.

Change 3314002 on 2017/02/21 by Keli.Hlodversson

	Fix compilation on PS4 and Linux

Change 3326722 on 2017/03/01 by Jeff.Fisher

	Merging //UE4/Dev-Main to Dev-VR (//UE4/Dev-VR)
	Integrating 4.15 from main.

Change 3327567 on 2017/03/01 by Jeff.Fisher

	UEVR-588 Oculus crash on "stereo on" when the proximity sensor is not triggered.
	Duplicating from Release-4.15 cl 3327481, 3327542
	-Don't ovr_SubmitFrame when the layers need to be recreated.  They stay dirty until rendering is unpaused.
	#jira UEVR-588

	#review-3384107

Change 3328098 on 2017/03/01 by Jeff.Fisher

	4.15 merge fixes
	-Fixed deprecated enum name function usage.
	-Fixed world scale usage in GoogleVRController.
	-Fixed compile break in PS4Tracker.

Change 3328271 on 2017/03/01 by Jeff.Fisher

	2.15 merge
	-restroging GoogleVRController::GetWorldToMetersScale... cause it is used everywhere.

Change 3328307 on 2017/03/01 by Jeff.Fisher

	4.15 merge
	-More googlevr worldscale fixes.

Change 3328312 on 2017/03/01 by Jeff.Fisher

	4.15 merge
	-removing 2 unused includes

Change 3330610 on 2017/03/02 by Jeff.Fisher

	4.15 merge
	-fixing linux build

Change 3333952 on 2017/03/06 by Keli.Hlodversson

	Implement common stereo layer management base class and use it in SteamVR and PS4. Fixes an outstanding bug in SteamVR where texures are updated every frame regardles of whether the continous update flag is set or not.

	#jira UEVR-628
	#jira UE-42555

Change 3334961 on 2017/03/07 by Keli.Hlodversson

	Add missing include to fix non-unity builds

Change 3336200 on 2017/03/07 by Keli.Hlodversson

	Fix compilation issues. (https://ec-01.epicgames.net/commander/link/jobDetails/jobs/7568252?jobName=UE4+Dev-VR+-+CL+3334961+-+Nightly+Build&s=Jobs)
	* Pre VS2015 compilers don't like mixing wide and unmarked strings in concatenation. Unfortunately LOCTEXT hides the call to the TEXT macro, completely hinding the prefix (which only gets added to the first fragment.)
	* Switch apparently doesn't know how to format a size_t for analytics either.
	Also: Typo in backwards compatibility command name alias

Change 3337347 on 2017/03/08 by Jeff.Fisher

	UE-42631 Stereo off while prox sensor uncovered causes low framerate
	-Setting maxfps appropriately on 'stereo on/off'.
	#review-3384107
	#jira UE-42631

Change 3338385 on 2017/03/08 by Ryan.Vance

	r.DisableDistortion was only being used for the mobile renderer

Change 3342301 on 2017/03/10 by patrickr.donovan

	Test updates to TM-VRSmoke.
	Increased lightmap resolution on QA_MeshTypes meshes to improve readbility and reliablility of tests involving said asset.
	Rebuilt lighting.

Change 3348133 on 2017/03/15 by Ryan.Vance

	Moving mono cvars to scene rendering to avoid cross module references. There's not a good reason to have them in the hmd module anyway.

Change 3348836 on 2017/03/15 by Ryan.Vance

	Direct multi-view support for gear vr
	Monoscopic far field with multi-view (blit and direct) support for gear vr
	Support for translucent objects on both sides of the mono clip plane (due to a sorting issue, objects that straddle the plane composite incorrectly)
	Fixed missing discards/clears in the multi-view blit

Change 3348843 on 2017/03/15 by Ryan.Vance

	Fixing color/depth target size mismatch when screen percentage scaling results in a size that isn't divisible by 16.

Change 3349276 on 2017/03/16 by Keli.Hlodversson

	Fixing compile errors in GoogleVR after merge from main.

Change 3350932 on 2017/03/16 by Ryan.Vance

	Re-enabling the gearvr plugin on windows.

Change 3351977 on 2017/03/17 by Jeff.Fisher

	Fixing masked member variable.

Change 3352314 on 2017/03/17 by Ryan.Vance

	We need to ensure that we don't select different lod levels for each eye.

Change 3352993 on 2017/03/17 by Nick.Whiting

	Integrating CL 3345824 from Android-DevVR to Dev-VR.  Support for device depth pass in SceneCaptureComponent2D

Change 3355185 on 2017/03/20 by Nick.Whiting

	Added ability to disable the autoloading splash screen, which would prevent the hide splash screen node from ever working

Change 3355676 on 2017/03/20 by Nick.Whiting

	PR #3384: [GNUX] SteamVR, OpenGL patch. (Contributed by yaakuro), with some minor modifications

Change 3357286 on 2017/03/21 by Jeff.Fisher

	Fixing GenerateProjectFiles, looks like the .config. was removed from these references in main some time ago.

Change 3357435 on 2017/03/21 by Jeff.Fisher

	Fixing editor build break, looks like a merge mistake.

Change 3359960 on 2017/03/23 by Keli.Hlodversson

	Prevent potential crash when drawing tracking sensor location. Also only fetch HMD location once instead of once per tracking sensor.

Change 3361230 on 2017/03/23 by Jeff.Fisher

	Fixing linux build opengl include problem... maybe.

Change 3361638 on 2017/03/23 by Jeff.Fisher

	Another guess at fixing linux build.

Change 3364224 on 2017/03/24 by Keli.Hlodversson

	Initial implementation of UEVR-576 - Base emulated layer implementation

	#jira UEVR-668 - Base emulated layer implementation: Initial framework for overrideable default implementation
	#jira UEVR-669 - Base emulated layer implementation: Face Locked Layers Support
	#jira UEVR-670 - Base emulated layer implementation: Tracker Locked Layers Support
	#jira UEVR-671 - Base emulated layer implementation: World Locked Layers Support
	#jira UEVR-672 - Base emulated layer implementation: Add support for optionally rendering face locked layers into a separate layer

Change 3364242 on 2017/03/24 by Keli.Hlodversson

	SteamVR layers do not support negatve Layer priorities

Change 3364263 on 2017/03/24 by Jeff.Fisher

	Merging //UE4/Dev-Main to Dev-VR (//UE4/Dev-VR)
	Monoscopicfarfieldrendering was just 'accept source', Ryan is going to look at fixing it up.

Change 3364472 on 2017/03/24 by Jeff.Fisher

	Merge fix

Change 3364475 on 2017/03/24 by Jeff.Fisher

	Fixing gearvr include.

Change 3364486 on 2017/03/24 by Jeff.Fisher

	merge fix

Change 3364532 on 2017/03/24 by Ryan.Vance

	pso update for mono rendering and stereo layers.

Change 3364599 on 2017/03/24 by Ryan.Vance

	Oculus changes for SI1.12

Change 3365159 on 2017/03/26 by Jeff.Fisher

	include fix

Change 3365182 on 2017/03/26 by Jeff.Fisher

	include fix

Change 3366087 on 2017/03/27 by Ryan.Vance

	Remaining files from Oculus changes for SI1.12 merge request.
	Fixing a bug in OnlineSubsystem.
	Temporarily changing the eye padding change to be a shader clear to work around a clear color binding issue.

Change 3366492 on 2017/03/27 by Ryan.Vance

	#jira UE-43294
	Moved the clear before we setup state for drawing the mirror window content. It was stomping over state after the pso changes.
	Going to leave the shader clear in the rift prerender for clearing the eye padding for now.

Change 3366929 on 2017/03/27 by Ryan.Vance

	Fixing compile error

Change 3368549 on 2017/03/28 by Jeff.Fisher

	Merging Change: 3357998 from //UE4/Partner-Google-VR/Engine/... to Dev-VR
	Upgrade Google VR Plugin to v1.3:
	*Upgraded GVR NDK to 1.30.0
	*Changed some BlueprintFunction to use BlueprintPure
	*Add the missing bDaydream flag in UEDeployAndroid.cs
	#review-3384107

Change 3368975 on 2017/03/28 by Ryan.Vance

	CIS clean up
	#jira UE-43428, UE-43429, UE-43426, UE-43427

Change 3369028 on 2017/03/28 by Ryan.Vance

	This is not exacly 'correct', but it's at least what the code was trying to do.

Change 3370203 on 2017/03/29 by Ryan.Vance

	Adding gear vr controller component support.

Change 3370918 on 2017/03/29 by Ryan.Vance

	Merging 3370569 using Partner-Google-VR_to_DevVR

Change 3371030 on 2017/03/29 by Ryan.Vance

	Fixing linux build errors

	#jira UE-43426

Change 3371036 on 2017/03/29 by Ryan.Vance

	Oculus 4.16 integration.
	Not terribly happy with the use of std::string. They promised to clean this up for the next release.

Change 3373495 on 2017/03/30 by Jeff.Fisher

	Merging from Dev-Main, in preparation for 4.16

Change 3373578 on 2017/03/30 by Jeff.Fisher

	build break, one comma short

Change 3373870 on 2017/03/31 by Jeff.Fisher

	Include order fix.

Change 3374001 on 2017/03/31 by Keli.Hlodversson

	Use DefaultStereoLayers as base for Morpheus implementation.
	#jira UEVR-709 #jira UE-42919
	#rb: Jeff.Fisher

Change 3374004 on 2017/03/31 by Keli.Hlodversson

	Fix rendering for the default Stereo Layers implementation on mobile.
	Depth test was set to "Never" instead of "Always"
	Destination texture on GLES is flipped on the Y axis, the coordinates are reversed in the shade when compiled on the relevant platforms.

Change 3375125 on 2017/03/31 by Jeff.Fisher

	UE-43506 Ensure using VRPreview with GoogleVR
	-Removed the ensure, there is code in there to handle that case, and it works.
	#jira UE-43506

Change 3375294 on 2017/03/31 by nick.bullard

	Resaving Plugin content to resovle "saved with empty engine version"

	#jira UE-43537

Change 3375480 on 2017/03/31 by Jeff.Fisher

	UEVR-9 PSVR: Social Screen Support
	-Experimental social screen support for 4.16.
	-This does the basics of driving output through the Aux port in the proper format for display on the mirror monitor.
	-Only supports 30fps on the mirror monitor.  60fps will require the implementation of sony system dialogs to deal with incompatable system features (video streaming, remote play).
	-There is a project setting in Morpheus, under experiemental bEnableSocialScreenSeparateMode.  This must be set to true to use this feature.  When it is false we avoid allocating the back buffers.
	-MorpheusFunctionLibrary blueprints now have a node "SetSocialScreenMode" which can switch between SystemMirror (hardware supported mirroring), SeparateTest (alternates black and white), SeparateTexture (displays a texture, eg a render target, specified via blueprint), and SeparateMirror(puts the hmd render buffer on screen - which is both eyes, like a debug mode).
	-Also finally updated the bEnabled flag in project settings to tell people it's only for PC.
	#jira UEVR-9
	#review-3384107

Change 3375540 on 2017/03/31 by Ryan.Vance

	#jira UE-43504

	Fixing android build break when using a 64 bit isa.

Change 3375655 on 2017/03/31 by Jeff.Fisher

	Fixing missing RGBAToYUV shader problem
	-This at least unblocks our process.  Will revisit before zbr.

Change 3375820 on 2017/04/01 by Jeff.Fisher

	Fixing linux build warning about HAS_MORPHEUS

Change 3376050 on 2017/04/02 by Jeff.Fisher

	 UE-43515 Step 'UE4Editor Static Analysis Win64' - Module.OnlineSubsystemOculus.cpp Warnings
	-Temporary fix for static analysis annotation warnings in OnlineSubsytemOculus. Longer term plan is to eliminate the use of the headers that trigger the warnings.
	-Just wrap all standard headers in static analysis disables.

	#jira UE-43515

Change 3376609 on 2017/04/03 by Jeff.Fisher

	Fixing rgbatoyuvshader include.

Change 3377001 on 2017/04/03 by Jeff.Fisher

	UE-43547 Launch On PS4 fails during Run command - Missing global shader FRGBAToYUV420CS
	- shader c++ must be compiled so that it can be cooked for ps4.

	#jira UE-43547

Change 3379858 on 2017/04/04 by Jeff.Fisher

	Merging //UE4/Dev-Main to Dev-VR (//UE4/Dev-VR)
	pulling main this should get us ps4 sdk 4.508

Change 3379938 on 2017/04/04 by Ryan.Vance

	#jira UE-43548

	If stereo layers are not being used, don't setup overlay targets as we will never clear/initialize them.
	The clear happens as part of the default layers PostRenderView_RenderThread call which wont be called if layers aren't being used in the scene.

Change 3381519 on 2017/04/05 by Jeff.Fisher

	UEVR-733 PS4 sdk 4.500 hmd connection api changes break hmd connect.
	-Handling failure of sceHmdGetDeviceInformation if the hmd is powered off.  It now returns an error code about an invalid handle in that case, rather than reporting unready.  We just treat the error code like an unready status.
	#jira UEVR-733
	#review-3384107

Change 3382019 on 2017/04/05 by Ryan.Vance

	Linux: add Vulkan support from dev editor: 3381593

Change 3382021 on 2017/04/05 by Ryan.Vance

	SteamVR on Linux using Vulkan
	OpenVR rev to 1_0_6

	PR #3412: [GNUX] Initial support for SteamVR using Vulkan on GNUX platform. (Contributed by yaakuro)

Change 3382076 on 2017/04/05 by Ryan.Vance

	Fixing linux steamvr lib path. It changed to something less silly in 1.0.6
	Removing the steamvr plugin from the white list for linux. It's looking for a runtime that no one will have installed.

Change 3383237 on 2017/04/06 by Ryan.Vance

	#jira UE-43732
	Fixing Android compile issues. We can't wrap portions of a macro with a definie. This should probably be some sort of recursive macro thing since there's so much overlap. Good enough for now.

Change 3383353 on 2017/04/06 by Ryan.Vance

	Fixing include cycles.

Change 3383509 on 2017/04/06 by Jeff.Fisher

	Merging //UE4/Dev-Main to Dev-VR (//UE4/Dev-VR)
	merging the stuff from dev-mobile

[CL 3384106 by Ryan Vance in Main branch]
2017-04-06 22:03:51 -04:00

656 lines
25 KiB
Plaintext

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
MobileBasePassPixelShader.usf: Base pass pixel shader used with forward shading
=============================================================================*/
#include "Common.usf"
#include "MobileBasePassCommon.usf"
#include "Material.usf"
#include "VertexFactory.usf"
#include "ReflectionEnvironmentShared.usf"
#include "LightmapCommon.usf"
#include "BRDF.usf"
#include "SHCommon.usf"
#include "ShadowFilteringCommon.usf"
#include "DynamicLightingCommon.usf"
#include "PlanarReflectionShared.usf"
#if MAX_DYNAMIC_POINT_LIGHTS > 0
#if VARIABLE_NUM_DYNAMIC_POINT_LIGHTS
int NumDynamicPointLights;
#endif
float4 LightPositionAndInvRadius[MAX_DYNAMIC_POINT_LIGHTS];
float4 LightColorAndFalloffExponent[MAX_DYNAMIC_POINT_LIGHTS];
#endif
#ifndef MOBILE_QL_FORCE_FULLY_ROUGH
#define MOBILE_QL_FORCE_FULLY_ROUGH 0
#endif
#ifndef MOBILE_QL_FORCE_NONMETAL
#define MOBILE_QL_FORCE_NONMETAL 0
#endif
#ifndef MOBILE_QL_FORCE_LQ_REFLECTIONS
#define MOBILE_QL_FORCE_LQ_REFLECTIONS 0
#endif
#ifndef MOBILE_CSM_QUALITY
#define MOBILE_CSM_QUALITY 2
#endif
#define FULLY_ROUGH (MATERIAL_FULLY_ROUGH || MOBILE_QL_FORCE_FULLY_ROUGH)
#define NONMETAL (MATERIAL_NONMETAL || MOBILE_QL_FORCE_NONMETAL)
#define HQ_REFLECTIONS (MATERIAL_HQ_FORWARD_REFLECTIONS && !MOBILE_QL_FORCE_LQ_REFLECTIONS)
#define ALLOW_CUBE_REFLECTIONS 0
/** Prenormalized capture of the scene that's closest to the object being rendered. */
#if !FULLY_ROUGH
TextureCube ReflectionCubemap;
SamplerState ReflectionCubemapSampler;
float3 InvReflectionCubemapAverageBrightness;
#if HQ_REFLECTIONS
#define MAX_HQ_REFLECTIONS 3
TextureCube ReflectionCubemap1;
SamplerState ReflectionCubemapSampler1;
TextureCube ReflectionCubemap2;
SamplerState ReflectionCubemapSampler2;
float4 ReflectionPositionsAndRadii[MAX_HQ_REFLECTIONS];
#if ALLOW_CUBE_REFLECTIONS
float4x4 CaptureBoxTransformArray[MAX_HQ_REFLECTIONS];
float4 CaptureBoxScalesArray[MAX_HQ_REFLECTIONS];
#endif
#endif
#endif
half PhongApprox( half Roughness, half RoL )
{
half a = Roughness * Roughness; // 1 mul
//!! Ronin Hack?
a = max(a, 0.008); // avoid underflow in FP16, next sqr should be bigger than 6.1e-5
half a2 = a * a; // 1 mul
half rcp_a2 = rcp(a2); // 1 rcp
//half rcp_a2 = exp2( -6.88886882 * Roughness + 6.88886882 );
// Spherical Gaussian approximation: pow( x, n ) ~= exp( (n + 0.775) * (x - 1) )
// Phong: n = 0.5 / a2 - 0.5
// 0.5 / ln(2), 0.275 / ln(2)
half c = 0.72134752 * rcp_a2 + 0.39674113; // 1 mad
half p = rcp_a2 * exp2(c * RoL - c); // 2 mad, 1 exp2, 1 mul
// Total 7 instr
return min(p, rcp_a2); // Avoid overflow/underflow on Mali GPUs
}
#if !FULLY_ROUGH
#if HQ_REFLECTIONS
float4 GetSphereCaptureVector(float3 ReflectionVector, float3 WorldPosition, float4 CapturePositionAndRadius)
{
float4 ProjectedCaptureVector;
ProjectedCaptureVector.w = 0;
ProjectedCaptureVector.xyz = ReflectionVector;
float3 RayDirection = ReflectionVector;
float ProjectionSphereRadius = CapturePositionAndRadius.w * 1.2f;
float SphereRadiusSquared = ProjectionSphereRadius * ProjectionSphereRadius;
float3 ReceiverToSphereCenter = WorldPosition - CapturePositionAndRadius.xyz;
float ReceiverToSphereCenterSq = dot(ReceiverToSphereCenter, ReceiverToSphereCenter);
float3 CaptureVector = WorldPosition - CapturePositionAndRadius.xyz;
float CaptureVectorLength = sqrt(dot(CaptureVector, CaptureVector));
float NormalizedDistanceToCapture = saturate(CaptureVectorLength / CapturePositionAndRadius.w);
// Find the intersection between the ray along the reflection vector and the capture's sphere
float3 QuadraticCoef;
QuadraticCoef.x = 1;
QuadraticCoef.y = 2 * dot(RayDirection, ReceiverToSphereCenter);
QuadraticCoef.z = ReceiverToSphereCenterSq - SphereRadiusSquared;
float Determinant = QuadraticCoef.y * QuadraticCoef.y - 4 * QuadraticCoef.z;
BRANCH
// Only continue if the ray intersects the sphere
if (Determinant >= 0)
{
float FarIntersection = (sqrt(Determinant) - QuadraticCoef.y) * 0.5;
float3 IntersectPosition = WorldPosition + FarIntersection * RayDirection;
ProjectedCaptureVector.xyz = IntersectPosition - CapturePositionAndRadius.xyz;
// Fade out based on distance to capture
ProjectedCaptureVector.w = 1.0 - smoothstep(.6, 1, NormalizedDistanceToCapture);
}
return ProjectedCaptureVector;
}
#if ALLOW_CUBE_REFLECTIONS
float4 GetBoxCaptureVector(float3 ReflectionVector, float3 WorldPosition, float4 CapturePositionAndRadius, float4x4 CaptureBoxTransform, float4 CaptureBoxScales)
{
float4 ProjectedCaptureVector;
ProjectedCaptureVector.w = 0;
ProjectedCaptureVector.xyz = ReflectionVector;
float3 RayDirection = ReflectionVector * CapturePositionAndRadius.w * 2;
// Transform the ray into the local space of the box, where it is an AABB with mins at -1 and maxs at 1
float3 LocalRayStart = mul(float4(WorldPosition, 1), CaptureBoxTransform).xyz;
float3 LocalRayDirection = mul(RayDirection, (float3x3)CaptureBoxTransform);
// Intersections.y is the intersection with the far side of the box
float2 Intersections = LineBoxIntersect(LocalRayStart, LocalRayStart + LocalRayDirection, -1, 1);
{
// Compute the reprojected vector
float3 IntersectPosition = WorldPosition + Intersections.y * RayDirection;
ProjectedCaptureVector.xyz = IntersectPosition - CapturePositionAndRadius.xyz;
// Compute the distance from the receiving pixel to the box for masking
// Apply local to world scale to take scale into account without transforming back to world space
// Shrink the box by the transition distance (BoxScales.w) so that the fade happens inside the box influence area
float4 BoxScales = CaptureBoxScales;
float BoxDistance = ComputeDistanceFromBoxToPoint(-(BoxScales.xyz - .5f * BoxScales.w), BoxScales.xyz - .5f * BoxScales.w, LocalRayStart * BoxScales.xyz);
// Setup a fade based on receiver distance to the box, hides the box influence shape
float BoxDistanceAlpha = 1.0 - smoothstep(0, .7f * BoxScales.w, BoxDistance);
// Setup a fade based on reflection ray intersection distance, hides the discontinuity between rays that just barely
float RayDistanceAlpha = smoothstep(0, BoxScales.w, Intersections.y * CapturePositionAndRadius.w * 2);
ProjectedCaptureVector.w = BoxDistanceAlpha * RayDistanceAlpha;
}
return ProjectedCaptureVector;
}
#endif
half3 BlendReflectionCapture(FMaterialPixelParameters MaterialParameters, half Roughness, TextureCube ReflectionCube, SamplerState ReflectionSampler, half MipLevel, int ReflectionIndex, half InvReflectionCubemapAverageBrightness, inout half BlendFactor)
{
half4 ProjectedCaptureVector;
#if ALLOW_CUBE_REFLECTIONS
if (CaptureBoxScalesArray[ReflectionIndex].w > 0)
{
ProjectedCaptureVector = GetBoxCaptureVector(MaterialParameters.ReflectionVector, MaterialParameters.AbsoluteWorldPosition, ReflectionPositionsAndRadii[ReflectionIndex], CaptureBoxTransformArray[ReflectionIndex], CaptureBoxScalesArray[ReflectionIndex]);
}
else
#endif
{
ProjectedCaptureVector = GetSphereCaptureVector(MaterialParameters.ReflectionVector, MaterialParameters.AbsoluteWorldPosition, ReflectionPositionsAndRadii[ReflectionIndex]);
}
// Fetch from cubemap and convert to linear HDR
float4 Reflection = ReflectionCube.SampleLevel(ReflectionSampler, ProjectedCaptureVector.xyz, MipLevel);
half3 SpecularIBL = RGBMDecode(Reflection, 16.0f);
SpecularIBL = SpecularIBL * SpecularIBL * (InvReflectionCubemapAverageBrightness * ProjectedCaptureVector.w * BlendFactor);
BlendFactor = BlendFactor * (1.0 - ProjectedCaptureVector.w);
return SpecularIBL;
}
half3 BlendReflectionCaptures(FMaterialPixelParameters MaterialParameters, half Roughness)
{
// Compute fractional mip from roughness
half AbsoluteSpecularMip = ComputeReflectionCaptureMipFromRoughness(Roughness, ResolvedView.ReflectionCubemapMaxMip);
half3 SpecularIBL = half3(0, 0, 0);
half BlendFactor = 1;
SpecularIBL += BlendReflectionCapture(MaterialParameters, Roughness, ReflectionCubemap, ReflectionCubemapSampler, AbsoluteSpecularMip, 0, InvReflectionCubemapAverageBrightness.x, BlendFactor);
SpecularIBL += BlendReflectionCapture(MaterialParameters, Roughness, ReflectionCubemap1, ReflectionCubemapSampler1, AbsoluteSpecularMip, 1, InvReflectionCubemapAverageBrightness.y, BlendFactor);
SpecularIBL += BlendReflectionCapture(MaterialParameters, Roughness, ReflectionCubemap2, ReflectionCubemapSampler2, AbsoluteSpecularMip, 2, InvReflectionCubemapAverageBrightness.z, BlendFactor);
return SpecularIBL;
}
#endif // HQ_REFLECTIONS
float4 GetPlanarReflection(float3 WorldPosition, float3 WorldNormal, float Roughness)
{
float4 PlanarReflection = ComputePlanarReflections(WorldPosition, WorldNormal, Roughness, PlanarReflectionSampler);
#if OUTPUT_GAMMA_SPACE
// the capture will also be in gamma space, convert to linear:
PlanarReflection.rgb *= PlanarReflection.rgb;
#endif
return PlanarReflection;
}
half3 GetImageBasedReflectionLighting(FMaterialPixelParameters MaterialParameters, half Roughness)
{
#if HQ_REFLECTIONS
half3 SpecularIBL = BlendReflectionCaptures(MaterialParameters, Roughness);
#else
half3 ProjectedCaptureVector = MaterialParameters.ReflectionVector;
// Compute fractional mip from roughness
half AbsoluteSpecularMip = ComputeReflectionCaptureMipFromRoughness(Roughness, ResolvedView.ReflectionCubemapMaxMip);
// Fetch from cubemap and convert to linear HDR
half3 SpecularIBL = RGBMDecode(ReflectionCubemap.SampleLevel(ReflectionCubemapSampler, ProjectedCaptureVector, AbsoluteSpecularMip), 16.0f);
SpecularIBL = SpecularIBL * SpecularIBL * InvReflectionCubemapAverageBrightness.x;
#endif
#if WEBGL
// need a rgb swizzle instead of the existing rgba swizzle, we should add it if another use case comes up.
return SpecularIBL.bgr;
#else
return SpecularIBL;
#endif
}
#endif //!FULLY_ROUGH
#if USE_EDITOR_COMPOSITING
bool bEnableEditorPrimitiveDepthTest;
// depth in the red channel in DeviceZ
Texture2D FilteredSceneDepthTexture;
SamplerState FilteredSceneDepthTextureSampler;
#endif
#if USE_EDITOR_COMPOSITING && (MOBILE_EMULATION)
// @return 0:translucent..1:opaque
float ClipForEditorPrimitives(FMaterialPixelParameters MaterialParameters)
{
float Ret = 1;
// Depth test manually if compositing editor primitives since the depth buffer is different (MSAA only)
BRANCH
if (bEnableEditorPrimitiveDepthTest)
{
bool bIsPerspective = (ResolvedView.ViewToClip._m33 < 1.0f);
// dejitter the sample position and make a filtered lookup - for planes this allows to reconstruct a much less jittery depth comparison function, it however doesn't fix silhuetes
float DeviceZ = Texture2DSampleLevel(FilteredSceneDepthTexture, FilteredSceneDepthTextureSampler, (MaterialParameters.SvPosition.xy - ResolvedView.TemporalAAParams.zw) * ResolvedView.BufferSizeAndInvSize.zw, 0).r;
float PixelDeviceZ = MaterialParameters.SvPosition.z;
// Soft Bias with DeviceZ for best quality
const float DeviceDepthFade = 0.00005f;
// 0.5f is to bias around the actual value, 1 or 0 are another option
Ret = saturate(0.5f - (DeviceZ - PixelDeviceZ) / DeviceDepthFade);
}
// Note: multiple returns cause strange HLSL compiler error for CV_Coverage in later code
return Ret;
}
#endif
half3 FrameBufferBlendOp(half4 Source)
{
#if (COMPILER_GLSL_ES2)
half4 Dest = FramebufferFetchES2();
Dest = half4(RGBTDecode8BPC(Dest, DEFAULT_32BPPHDR_ENCODED_RANGE), 0.0f);
#else
half4 Dest = half4 (0,0,0,0);
#endif
#if MATERIALBLENDING_SOLID
return Source.rgb;
#elif MATERIALBLENDING_MASKED
return Source.rgb;
// AlphaComposite will set both MATERIALBLENDING_TRANSLUCENT and MATERIALBLENDING_ALPHACOMPOSITE defines
// so ensure MATERIALBLENDING_ALPHACOMPOSITE gets first in line
#elif MATERIALBLENDING_ALPHACOMPOSITE
return Source.rgb + (Dest.rgb*(1.0 - Source.a));
#elif MATERIALBLENDING_TRANSLUCENT
return (Source.rgb*Source.a) + (Dest.rgb*(1.0 - Source.a));
#elif MATERIALBLENDING_ADDITIVE
return Source.rgb + Dest.rgb;
#elif MATERIALBLENDING_MODULATE
return Source.rgb * Dest.rgb;
#endif
}
void Main(
FVertexFactoryInterpolantsVSToPS Interpolants
, FMobileBasePassInterpolantsVSToPS BasePassInterpolants
, in float4 SvPosition : SV_Position
OPTIONAL_IsFrontFace
, out half4 OutColor : SV_Target0
)
{
#if MOBILE_MULTI_VIEW
ResolvedView = ResolveView(uint(BasePassInterpolants.MultiViewId));
#else
ResolvedView = ResolveView();
#endif
#if USE_PS_CLIP_PLANE
clip(BasePassInterpolants.OutClipDistance);
#endif
#if PACK_INTERPOLANTS
float4 PackedInterpolants[NUM_VF_PACKED_INTERPOLANTS];
VertexFactoryUnpackInterpolants(Interpolants, PackedInterpolants);
#endif
#if (COMPILER_GLSL_ES2 || COMPILER_GLSL_ES3_1 || COMPILER_GLSL_ES3_1_EXT) && OUTPUT_GAMMA_SPACE && !MOBILE_EMULATION
// LDR ES2 needs screen vertical flipped
SvPosition.y = ResolvedView.BufferSizeAndInvSize.y - SvPosition.y - 1;
#endif
FMaterialPixelParameters MaterialParameters = GetMaterialPixelParameters(Interpolants, SvPosition);
FPixelMaterialInputs PixelMaterialInputs;
{
float4 ScreenPosition = SvPositionToResolvedScreenPosition(SvPosition);
float3 WorldPosition = BasePassInterpolants.PixelPosition;
float3 WorldPositionExcludingWPO = BasePassInterpolants.PixelPosition;
#if USE_WORLD_POSITION_EXCLUDING_SHADER_OFFSETS
WorldPositionExcludingWPO = BasePassInterpolants.PixelPositionExcludingWPO;
#endif
CalcMaterialParametersEx(MaterialParameters, PixelMaterialInputs, SvPosition, ScreenPosition, bIsFrontFace, WorldPosition, WorldPositionExcludingWPO);
}
//Clip if the blend mode requires it.
GetMaterialCoverageAndClipping(MaterialParameters, PixelMaterialInputs);
half Opacity = GetMaterialOpacity(PixelMaterialInputs);
// Store the results in local variables and reuse instead of calling the functions multiple times.
// Store the results in local variables and reuse instead of calling the functions multiple times.
half3 BaseColor = GetMaterialBaseColor(PixelMaterialInputs);
half Metallic = GetMaterialMetallic(PixelMaterialInputs);
half Specular = GetMaterialSpecular(PixelMaterialInputs);
#if NONMETAL
half3 DiffuseColor = BaseColor;
half SpecularColor = 0.04;
#else
half DielectricSpecular = 0.08 * Specular;
half3 DiffuseColor = BaseColor - BaseColor * Metallic; // 1 mad
half3 SpecularColor = (DielectricSpecular - DielectricSpecular * Metallic) + BaseColor * Metallic; // 2 mad
#endif
half Roughness = GetMaterialRoughness(PixelMaterialInputs);
#if FULLY_ROUGH
// Factors derived from EnvBRDFApprox( SpecularColor, 1, 1 ) == SpecularColor * 0.4524 - 0.0024
DiffuseColor += SpecularColor * 0.45;
SpecularColor = 0;
#else
half NoV = max( dot( MaterialParameters.WorldNormal, MaterialParameters.CameraVector ), 0 );
#if NONMETAL
// If nothing is hooked up to Metalic and Specular,
// then defaults are the same as a non-metal,
// so this define is safe.
SpecularColor = EnvBRDFApproxNonmetal( Roughness, NoV );
#else
SpecularColor = EnvBRDFApprox( SpecularColor, Roughness, NoV );
#endif
#endif
#if MOBILE_EMULATION
{
// this feature is only needed for development/editor - we can compile it out for a shipping build (see r.CompileShadersForDevelopment cvar help)
DiffuseColor = DiffuseColor * ResolvedView.DiffuseOverrideParameter.w + ResolvedView.DiffuseOverrideParameter.xyz;
SpecularColor = SpecularColor * ResolvedView.SpecularOverrideParameter.w + ResolvedView.SpecularOverrideParameter.xyz;
}
#endif
half3 Color = 0;
half IndirectIrradiance = 0;
#if LQ_TEXTURE_LIGHTMAP
float2 LightmapUV0, LightmapUV1;
GetLightMapCoordinates(Interpolants, LightmapUV0, LightmapUV1);
half4 LightmapColor = GetLightMapColorLQ( LightmapUV0, LightmapUV1, MaterialParameters.WorldNormal );
Color += LightmapColor.rgb * DiffuseColor;
IndirectIrradiance = LightmapColor.a;
#elif CACHED_POINT_INDIRECT_LIGHTING
#if MATERIALBLENDING_MASKED || MATERIALBLENDING_SOLID
// Take the normal into account for opaque
FThreeBandSHVectorRGB PointIndirectLighting;
PointIndirectLighting.R.V0 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[0];
PointIndirectLighting.R.V1 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients1[0];
PointIndirectLighting.R.V2 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients2[0];
PointIndirectLighting.G.V0 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[1];
PointIndirectLighting.G.V1 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients1[1];
PointIndirectLighting.G.V2 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients2[1];
PointIndirectLighting.B.V0 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients0[2];
PointIndirectLighting.B.V1 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients1[2];
PointIndirectLighting.B.V2 = PrecomputedLightingBuffer.IndirectLightingSHCoefficients2[2];
FThreeBandSHVector DiffuseTransferSH = CalcDiffuseTransferSH3(MaterialParameters.WorldNormal, 1);
// Compute diffuse lighting which takes the normal into account
half3 DiffuseGI = max(half3(0,0,0), DotSH3(PointIndirectLighting, DiffuseTransferSH));
IndirectIrradiance = Luminance(DiffuseGI);
Color += DiffuseColor * DiffuseGI;
#else
// Non-directional for translucency
// Ambient terms packed in xyz
// Already divided by PI and SH ambient on CPU
half3 PointIndirectLighting = PrecomputedLightingBuffer.IndirectLightingSHSingleCoefficient;
half3 DiffuseGI = PointIndirectLighting;
IndirectIrradiance = Luminance(DiffuseGI);
Color += DiffuseColor * DiffuseGI;
#endif
#endif
#if !MATERIAL_SHADINGMODEL_UNLIT
half MaterialAO = GetMaterialAmbientOcclusion(PixelMaterialInputs);
Color *= MaterialAO;
IndirectIrradiance *= MaterialAO;
#endif
#if !MATERIAL_SHADINGMODEL_UNLIT
half Shadow = GetPrimaryPrecomputedShadowMask(Interpolants).r;
#if DIRECTIONAL_LIGHT_CSM && !MOBILE_MULTI_VIEW
// Cascaded Shadow Map
{
FPCFSamplerSettings Settings;
Settings.ShadowDepthTexture = MobileDirectionalLight.DirectionalLightShadowTexture;
Settings.ShadowDepthTextureSampler = MobileDirectionalLight.DirectionalLightShadowSampler;
Settings.TransitionScale = MobileDirectionalLight.DirectionalLightShadowTransition;
Settings.ShadowBufferSize = MobileDirectionalLight.DirectionalLightShadowSize;
Settings.bSubsurface = false;
Settings.DensityMulConstant = 0;
Settings.ProjectionDepthBiasParameters = 0;
float4 ShadowPosition = float4(0,0,0,0);
for (int i = 0; i < MAX_MOBILE_SHADOWCASCADES; i++)
{
if (MaterialParameters.ScreenPosition.w < MobileDirectionalLight.DirectionalLightShadowDistances[i])
{
ShadowPosition = mul(float4(MaterialParameters.ScreenPosition.xyw, 1), MobileDirectionalLight.DirectionalLightScreenToShadow[i]);
break; // position found.
}
}
// Process CSM only when ShadowPosition is valid.
if (ShadowPosition.z > 0)
{
// Clamp pixel depth in light space for shadowing opaque, because areas of the shadow depth buffer that weren't rendered to will have been cleared to 1
// We want to force the shadow comparison to result in 'unshadowed' in that case, regardless of whether the pixel being shaded is in front or behind that plane
float LightSpacePixelDepthForOpaque = min(ShadowPosition.z, 0.99999f);
Settings.SceneDepth = LightSpacePixelDepthForOpaque;
#if MOBILE_CSM_QUALITY == 0
half ShadowMap = ManualNoFiltering(ShadowPosition.xy, Settings);
#elif MOBILE_CSM_QUALITY == 1
half ShadowMap = Manual1x1PCF(ShadowPosition.xy, Settings);
#elif MOBILE_CSM_QUALITY == 2
half ShadowMap = Manual2x2PCF(ShadowPosition.xy, Settings);
#else
#error Unsupported MOBILE_CSM_QUALITY value.
#endif
#if MOVABLE_DIRECTIONAL_LIGHT
Shadow = ShadowMap;
#else
Shadow = min(ShadowMap, Shadow);
#endif
}
}
#endif /* DIRECTIONAL_LIGHT_CSM */
float NoL = max(0, dot(float3(MaterialParameters.WorldNormal), float3(MobileDirectionalLight.DirectionalLightDirection)));
float RoL = max(0, dot(float3(MaterialParameters.ReflectionVector), float3(MobileDirectionalLight.DirectionalLightDirection)));
#if FULLY_ROUGH
Color += (Shadow * NoL) * MobileDirectionalLight.DirectionalLightColor.rgb * DiffuseColor;
#else
Color += (Shadow * NoL) * MobileDirectionalLight.DirectionalLightColor.rgb * (DiffuseColor + SpecularColor * PhongApprox(Roughness, RoL));
// Environment map has been prenormalized, scale by lightmap luminance
half3 SpecularIBL = GetImageBasedReflectionLighting(MaterialParameters, Roughness) * IndirectIrradiance;
#if MATERIAL_PLANAR_FORWARD_REFLECTIONS
BRANCH
if (abs(dot(ReflectionPlane.xyz, 1)) > .0001f)
{
half4 PlanarReflection = GetPlanarReflection(MaterialParameters.AbsoluteWorldPosition, MaterialParameters.WorldNormal, Roughness);
// Planar reflections win over reflection environment
SpecularIBL = lerp(SpecularIBL, PlanarReflection.rgb, PlanarReflection.a);
}
#endif
Color += SpecularIBL * SpecularColor;
#endif
#if ENABLE_SKY_LIGHT
//@mw todo
// TODO: Also need to do specular.
Color += GetSkySHDiffuseSimple(MaterialParameters.WorldNormal) * ResolvedView.SkyLightColor.rgb * DiffuseColor;
#endif
#if MAX_DYNAMIC_POINT_LIGHTS > 0
#if VARIABLE_NUM_DYNAMIC_POINT_LIGHTS
#if WEBGL || ES2_PROFILE
// webgl and ES2 needs a constant loop counter
UNROLL
for (int i = 0; i < MAX_DYNAMIC_POINT_LIGHTS; i++)
{
if(i >= NumDynamicPointLights)
{
break;
}
#else
for (int i = 0; i < NumDynamicPointLights; i++)
{
#endif
#else
for (int i = 0; i < NUM_DYNAMIC_POINT_LIGHTS; i++)
{
#endif
float3 ToLight = LightPositionAndInvRadius[i].xyz - MaterialParameters.AbsoluteWorldPosition;
float DistanceSqr = dot(ToLight, ToLight);
float3 L = ToLight * rsqrt(DistanceSqr);
float PointNoL = max(0, dot(MaterialParameters.WorldNormal, L));
float PointRoL = max(0, dot(MaterialParameters.ReflectionVector, L));
float Attenuation;
if (LightColorAndFalloffExponent[i].w == 0)
{
// Sphere falloff (technically just 1/d2 but this avoids inf)
Attenuation = 1 / ( DistanceSqr + 1 );
float LightRadiusMask = Square(saturate(1 - Square(DistanceSqr * (LightPositionAndInvRadius[i].w * LightPositionAndInvRadius[i].w))));
Attenuation *= LightRadiusMask;
}
else
{
Attenuation = RadialAttenuation(ToLight * LightPositionAndInvRadius[i].w, LightColorAndFalloffExponent[i].w);
}
#if !FULLY_ROUGH
Color += (Attenuation * PointNoL) * LightColorAndFalloffExponent[i].rgb * (DiffuseColor + SpecularColor * PhongApprox(Roughness, PointRoL));
#else
Color += (Attenuation * PointNoL) * LightColorAndFalloffExponent[i].rgb * DiffuseColor;
#endif
}
#endif
#endif /* !MATERIAL_SHADINGMODEL_UNLIT */
half3 Emissive = GetMaterialEmissive(PixelMaterialInputs);
Color += Emissive;
half4 VertexFog = half4(0, 0, 0, 1);
#if USE_VERTEX_FOG
#if PACK_INTERPOLANTS
VertexFog = PackedInterpolants[0];
#else
VertexFog = BasePassInterpolants.VertexFog;
#endif
#endif
#if !MATERIAL_SHADINGMODEL_UNLIT && MOBILE_EMULATION
Color = lerp(Color, DiffuseColor + SpecularColor, ResolvedView.UnlitViewmodeMask);
#endif
#if MATERIALBLENDING_ALPHACOMPOSITE
OutColor = half4(Color * VertexFog.a + VertexFog.rgb * Opacity, Opacity);
#elif MATERIALBLENDING_TRANSLUCENT
OutColor = half4(Color * VertexFog.a + VertexFog.rgb, Opacity);
#elif MATERIALBLENDING_ADDITIVE
OutColor = half4(Color * (VertexFog.a * Opacity.x), 0.0f);
#elif MATERIALBLENDING_MODULATE
half3 FoggedColor = lerp(half3(1, 1, 1), Color, VertexFog.aaa * VertexFog.aaa);
OutColor = half4(FoggedColor, Opacity);
#else
OutColor.rgb = Color * VertexFog.a + VertexFog.rgb;
// Scene color alpha is not used yet so we set it to 0
OutColor.a = 0.0;
#if !OUTPUT_GAMMA_SPACE
if (GetHDR32bppEncodeMode() == HDR_ENCODE_NONE)
{
// FP16 HDR stores Z in framebuffer alpha
OutColor.a = BasePassInterpolants.PixelPosition.w;
}
#endif
#endif
#if !MATERIALBLENDING_MODULATE
// 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.
OutColor.rgba *= ResolvedView.ExposureScale.xyzw;
#endif
#if USE_EDITOR_COMPOSITING && (MOBILE_EMULATION)
// Editor primitive depth testing
OutColor.a = 1.0;
#if MATERIALBLENDING_MASKED
// some material might have an opacity value
OutColor.a = GetMaterialMaskInputRaw(PixelMaterialInputs);
#endif
// we output premultiplied alpha to we have to darken all 4 channels
OutColor *= ClipForEditorPrimitives(MaterialParameters);
clip(OutColor.a - GetMaterialOpacityMaskClipValue());
#else
#if ES2_PROFILE && !OUTPUT_GAMMA_SPACE
half Mode = GetHDR32bppEncodeMode();
if (Mode == HDR_ENCODE_RGBA)
{
OutColor.rgb = FrameBufferBlendOp(OutColor);
OutColor = RGBTEncode8BPC(OutColor.rgb, DEFAULT_32BPPHDR_ENCODED_RANGE);
}
if (Mode == HDR_ENCODE_MOSAIC)
{
OutColor = half4(HdrMosaic(OutColor.rgb, SvPosition.xy), OutColor.a);
}
#endif
#if OUTPUT_GAMMA_SPACE
OutColor.rgb = sqrt(OutColor.rgb);
#endif
// We write to alpha here for mono far field mask computation
#if MONOSCOPIC_FAR_FIELD
#if MATERIALBLENDING_ANY_TRANSLUCENT
OutColor.a = Opacity;
#else
OutColor.a = 1.0;
#endif
#endif
#endif
}