using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Assertions;
using UnityEngine.Experimental.GlobalIllumination;
using UnityEngine.Experimental.Rendering;
using Lightmapping = UnityEngine.Experimental.GlobalIllumination.Lightmapping;
namespace UnityEngine.Rendering.Universal
{
static class NativeArrayExtensions
{
///
/// IMPORTANT: Make sure you do not write to the value! There are no checks for this!
///
public static unsafe ref T UnsafeElementAt(this NativeArray array, int index) where T : struct
{
return ref UnsafeUtility.ArrayElementAsRef(array.GetUnsafeReadOnlyPtr(), index);
}
public static unsafe ref T UnsafeElementAtMutable(this NativeArray array, int index) where T : struct
{
return ref UnsafeUtility.ArrayElementAsRef(array.GetUnsafePtr(), index);
}
}
///
/// Options for mixed lighting setup.
///
public enum MixedLightingSetup
{
///
/// Use this to disable mixed lighting.
///
None,
///
/// Use this to select shadow mask.
///
ShadowMask,
///
/// Use this to select subtractive.
///
Subtractive,
};
///
/// Enumeration that indicates what kind of image scaling is occurring if any
///
internal enum ImageScalingMode
{
/// No scaling
None,
/// Upscaling to a larger image
Upscaling,
/// Downscaling to a smaller image
Downscaling
}
///
/// Enumeration that indicates what kind of upscaling filter is being used
///
internal enum ImageUpscalingFilter
{
/// Bilinear filtering
Linear,
/// Nearest-Neighbor filtering
Point,
/// FidelityFX Super Resolution
FSR,
/// Spatial-Temporal Post-Processing
STP
}
///
/// Struct that flattens several rendering settings used to render a camera stack.
/// URP builds the RenderingData settings from several places, including the pipeline asset, camera and light settings.
/// The settings also might vary on different platforms and depending on if Adaptive Performance is used.
///
public struct RenderingData
{
internal ContextContainer frameData;
internal RenderingData(ContextContainer frameData)
{
this.frameData = frameData;
cameraData = new CameraData(frameData);
lightData = new LightData(frameData);
shadowData = new ShadowData(frameData);
postProcessingData = new PostProcessingData(frameData);
}
internal UniversalRenderingData universalRenderingData => frameData.Get();
// Non-rendergraph path only. Do NOT use with rendergraph!
internal ref CommandBuffer commandBuffer
{
get
{
ref var cmd = ref frameData.Get().m_CommandBuffer;
if (cmd == null)
Debug.LogError("RenderingData.commandBuffer is null. RenderGraph does not support this property. Please use the command buffer provided by the RenderGraphContext.");
return ref cmd;
}
}
///
/// Returns culling results that exposes handles to visible objects, lights and probes.
/// You can use this to draw objects with ScriptableRenderContext.DrawRenderers
///
///
///
public ref CullingResults cullResults => ref frameData.Get().cullResults;
///
/// Holds several rendering settings related to camera.
///
///
public CameraData cameraData;
///
/// Holds several rendering settings related to lights.
///
///
public LightData lightData;
///
/// Holds several rendering settings related to shadows.
///
///
public ShadowData shadowData;
///
/// Holds several rendering settings and resources related to the integrated post-processing stack.
///
///
public PostProcessingData postProcessingData;
///
/// True if the pipeline supports dynamic batching.
/// This settings doesn't apply when drawing shadow casters. Dynamic batching is always disabled when drawing shadow casters.
///
public ref bool supportsDynamicBatching => ref frameData.Get().supportsDynamicBatching;
///
/// Holds per-object data that are requested when drawing
///
///
public ref PerObjectData perObjectData => ref frameData.Get().perObjectData;
///
/// True if post-processing effect is enabled while rendering the camera stack.
///
public ref bool postProcessingEnabled => ref frameData.Get().isEnabled;
}
///
/// Struct that holds settings related to lights.
///
public struct LightData
{
ContextContainer frameData;
internal LightData(ContextContainer frameData)
{
this.frameData = frameData;
}
internal UniversalLightData universalLightData => frameData.Get();
///
/// Holds the main light index from the VisibleLight list returned by culling. If there's no main light in the scene, mainLightIndex is set to -1.
/// The main light is the directional light assigned as Sun source in light settings or the brightest directional light.
///
///
public ref int mainLightIndex => ref frameData.Get().mainLightIndex;
///
/// The number of additional lights visible by the camera.
///
public ref int additionalLightsCount => ref frameData.Get().additionalLightsCount;
///
/// Maximum amount of lights that can be shaded per-object. This value only affects forward rendering.
///
public ref int maxPerObjectAdditionalLightsCount => ref frameData.Get().maxPerObjectAdditionalLightsCount;
///
/// List of visible lights returned by culling.
///
public ref NativeArray visibleLights => ref frameData.Get().visibleLights;
///
/// True if additional lights should be shaded in vertex shader, otherwise additional lights will be shaded per pixel.
///
public ref bool shadeAdditionalLightsPerVertex => ref frameData.Get().shadeAdditionalLightsPerVertex;
///
/// True if mixed lighting is supported.
///
public ref bool supportsMixedLighting => ref frameData.Get().supportsMixedLighting;
///
/// True if box projection is enabled for reflection probes.
///
public ref bool reflectionProbeBoxProjection => ref frameData.Get().reflectionProbeBoxProjection;
///
/// True if blending is enabled for reflection probes.
///
public ref bool reflectionProbeBlending => ref frameData.Get().reflectionProbeBlending;
///
/// True if light layers are enabled.
///
public ref bool supportsLightLayers => ref frameData.Get().supportsLightLayers;
///
/// True if additional lights enabled.
///
public ref bool supportsAdditionalLights => ref frameData.Get().supportsAdditionalLights;
}
///
/// Struct that holds settings related to camera.
///
public struct CameraData
{
ContextContainer frameData;
internal CameraData(ContextContainer frameData)
{
this.frameData = frameData;
}
internal UniversalCameraData universalCameraData => frameData.Get();
internal void SetViewAndProjectionMatrix(Matrix4x4 viewMatrix, Matrix4x4 projectionMatrix)
{
frameData.Get().SetViewAndProjectionMatrix(viewMatrix, projectionMatrix);
}
internal void SetViewProjectionAndJitterMatrix(Matrix4x4 viewMatrix, Matrix4x4 projectionMatrix, Matrix4x4 jitterMatrix)
{
frameData.Get().SetViewProjectionAndJitterMatrix(viewMatrix, projectionMatrix, jitterMatrix);
}
// Helper function to populate builtin stereo matricies as well as URP stereo matricies
internal void PushBuiltinShaderConstantsXR(RasterCommandBuffer cmd, bool renderIntoTexture)
{
frameData.Get().PushBuiltinShaderConstantsXR(cmd, renderIntoTexture);
}
///
/// Returns the camera view matrix.
///
/// View index in case of stereo rendering. By default viewIndex is set to 0.
/// The camera view matrix.
public Matrix4x4 GetViewMatrix(int viewIndex = 0)
{
return frameData.Get().GetViewMatrix(viewIndex);
}
///
/// Returns the camera projection matrix. Might be jittered for temporal features.
///
/// View index in case of stereo rendering. By default viewIndex is set to 0.
/// The camera projection matrix.
public Matrix4x4 GetProjectionMatrix(int viewIndex = 0)
{
return frameData.Get().GetProjectionMatrix(viewIndex);
}
internal Matrix4x4 GetProjectionMatrixNoJitter(int viewIndex = 0)
{
return frameData.Get().GetProjectionMatrixNoJitter(viewIndex);
}
///
/// Returns the camera GPU projection matrix. This contains platform specific changes to handle y-flip and reverse z. Includes camera jitter if required by active features.
/// Similar to GL.GetGPUProjectionMatrix but queries URP internal state to know if the pipeline is rendering to render texture.
/// For more info on platform differences regarding camera projection check: https://docs.unity3d.com/Manual/SL-PlatformDifferences.html
///
/// View index in case of stereo rendering. By default viewIndex is set to 0.
///
///
public Matrix4x4 GetGPUProjectionMatrix(int viewIndex = 0)
{
return frameData.Get().GetGPUProjectionMatrix(viewIndex);
}
///
/// Returns the camera GPU projection matrix. This contains platform specific changes to handle y-flip and reverse z. Does not include any camera jitter.
/// Similar to GL.GetGPUProjectionMatrix but queries URP internal state to know if the pipeline is rendering to render texture.
/// For more info on platform differences regarding camera projection check: https://docs.unity3d.com/Manual/SL-PlatformDifferences.html
///
/// View index in case of stereo rendering. By default viewIndex is set to 0.
///
///
public Matrix4x4 GetGPUProjectionMatrixNoJitter(int viewIndex = 0)
{
return frameData.Get().GetGPUProjectionMatrixNoJitter(viewIndex);
}
internal Matrix4x4 GetGPUProjectionMatrix(bool renderIntoTexture, int viewIndex = 0)
{
return frameData.Get().GetGPUProjectionMatrix(renderIntoTexture, viewIndex);
}
///
/// The camera component.
///
public ref Camera camera => ref frameData.Get().camera;
///
/// The camera history texture manager. Used to access camera history from a ScriptableRenderPass.
///
///
public ref UniversalCameraHistory historyManager => ref frameData.Get().m_HistoryManager;
///
/// The camera render type used for camera stacking.
///
///
public ref CameraRenderType renderType => ref frameData.Get().renderType;
///
/// Controls the final target texture for a camera. If null camera will resolve rendering to screen.
///
public ref RenderTexture targetTexture => ref frameData.Get().targetTexture;
///
/// Render texture settings used to create intermediate camera textures for rendering.
///
public ref RenderTextureDescriptor cameraTargetDescriptor => ref frameData.Get().cameraTargetDescriptor;
internal ref Rect pixelRect => ref frameData.Get().pixelRect;
internal ref bool useScreenCoordOverride => ref frameData.Get().useScreenCoordOverride;
internal ref Vector4 screenSizeOverride => ref frameData.Get().screenSizeOverride;
internal ref Vector4 screenCoordScaleBias => ref frameData.Get().screenCoordScaleBias;
internal ref int pixelWidth => ref frameData.Get().pixelWidth;
internal ref int pixelHeight => ref frameData.Get().pixelHeight;
internal ref float aspectRatio => ref frameData.Get().aspectRatio;
///
/// Render scale to apply when creating camera textures. Scaled extents are rounded down to integers.
///
public ref float renderScale => ref frameData.Get().renderScale;
internal ref ImageScalingMode imageScalingMode => ref frameData.Get().imageScalingMode;
internal ref ImageUpscalingFilter upscalingFilter => ref frameData.Get().upscalingFilter;
internal ref bool fsrOverrideSharpness => ref frameData.Get().fsrOverrideSharpness;
internal ref float fsrSharpness => ref frameData.Get().fsrSharpness;
internal ref HDRColorBufferPrecision hdrColorBufferPrecision => ref frameData.Get().hdrColorBufferPrecision;
///
/// True if this camera should clear depth buffer. This setting only applies to cameras of type CameraRenderType.Overlay
///
///
public ref bool clearDepth => ref frameData.Get().clearDepth;
///
/// The camera type.
///
///
public ref CameraType cameraType => ref frameData.Get().cameraType;
///
/// True if this camera is drawing to a viewport that maps to the entire screen.
///
public ref bool isDefaultViewport => ref frameData.Get().isDefaultViewport;
///
/// True if this camera should render to high dynamic range color targets.
///
public ref bool isHdrEnabled => ref frameData.Get().isHdrEnabled;
///
/// True if this camera allow color conversion and encoding for high dynamic range displays.
///
public ref bool allowHDROutput => ref frameData.Get().allowHDROutput;
///
/// True if this camera writes the alpha channel. Requires to color target to have an alpha channel.
///
public ref bool isAlphaOutputEnabled => ref frameData.Get().isAlphaOutputEnabled;
///
/// True if this camera requires to write _CameraDepthTexture.
///
public ref bool requiresDepthTexture => ref frameData.Get().requiresDepthTexture;
///
/// True if this camera requires to copy camera color texture to _CameraOpaqueTexture.
///
public ref bool requiresOpaqueTexture => ref frameData.Get().requiresOpaqueTexture;
///
/// Returns true if post processing passes require depth texture.
///
public ref bool postProcessingRequiresDepthTexture => ref frameData.Get().postProcessingRequiresDepthTexture;
///
/// Returns true if XR rendering is enabled.
///
public ref bool xrRendering => ref frameData.Get().xrRendering;
internal bool requireSrgbConversion => frameData.Get().requireSrgbConversion;
///
/// True if the camera rendering is for the scene window in the editor.
///
public bool isSceneViewCamera => frameData.Get().isSceneViewCamera;
///
/// True if the camera rendering is for the preview window in the editor.
///
public bool isPreviewCamera => frameData.Get().isPreviewCamera;
internal bool isRenderPassSupportedCamera => frameData.Get().isRenderPassSupportedCamera;
internal bool resolveToScreen => frameData.Get().resolveToScreen;
///
/// True if the Camera should output to an HDR display.
///
public bool isHDROutputActive => frameData.Get().isHDROutputActive;
///
/// HDR Display information about the current display this camera is rendering to.
///
public HDROutputUtils.HDRDisplayInformation hdrDisplayInformation => frameData.Get().hdrDisplayInformation;
///
/// HDR Display Color Gamut
///
public ColorGamut hdrDisplayColorGamut => frameData.Get().hdrDisplayColorGamut;
///
/// True if the Camera should render overlay UI.
///
public bool rendersOverlayUI => frameData.Get().rendersOverlayUI;
///
/// True is the handle has its content flipped on the y axis.
/// This happens only with certain rendering APIs.
/// On those platforms, any handle will have its content flipped unless rendering to a backbuffer, however,
/// the scene view will always be flipped.
/// When transitioning from a flipped space to a non-flipped space - or vice-versa - the content must be flipped
/// in the shader:
/// shouldPerformYFlip = IsHandleYFlipped(source) != IsHandleYFlipped(target)
///
/// Handle to check the flipped status on.
/// True is the content is flipped in y.
public bool IsHandleYFlipped(RTHandle handle)
{
return frameData.Get().IsHandleYFlipped(handle);
}
///
/// True if the camera device projection matrix is flipped. This happens when the pipeline is rendering
/// to a render texture in non OpenGL platforms. If you are doing a custom Blit pass to copy camera textures
/// (_CameraColorTexture, _CameraDepthAttachment) you need to check this flag to know if you should flip the
/// matrix when rendering with for cmd.Draw* and reading from camera textures.
///
/// True if the camera device projection matrix is flipped.
[Obsolete(DeprecationMessage.CompatibilityScriptingAPIObsolete, false)]
public bool IsCameraProjectionMatrixFlipped()
{
return frameData.Get().IsCameraProjectionMatrixFlipped();
}
///
/// True if the render target's projection matrix is flipped. This happens when the pipeline is rendering
/// to a render texture in non OpenGL platforms. If you are doing a custom Blit pass to copy camera textures
/// (_CameraColorTexture, _CameraDepthAttachment) you need to check this flag to know if you should flip the
/// matrix when rendering with for cmd.Draw* and reading from camera textures.
///
/// Color render target to check whether the matrix is flipped.
/// Depth render target which is used if color is null. By default depth is set to null.
/// True if the render target's projection matrix is flipped.
public bool IsRenderTargetProjectionMatrixFlipped(RTHandle color, RTHandle depth = null)
{
return frameData.Get().IsRenderTargetProjectionMatrixFlipped(color, depth);
}
internal bool IsTemporalAAEnabled()
{
return frameData.Get().IsTemporalAAEnabled();
}
///
/// The sorting criteria used when drawing opaque objects by the internal URP render passes.
/// When a GPU supports hidden surface removal, URP will rely on that information to avoid sorting opaque objects front to back and
/// benefit for more optimal static batching.
///
///
public ref SortingCriteria defaultOpaqueSortFlags => ref frameData.Get().defaultOpaqueSortFlags;
///
/// XRPass holds the render target information and a list of XRView.
/// XRView contains the parameters required to render (projection and view matrices, viewport, etc)
///
public XRPass xr
{
get => frameData.Get().xr;
internal set => frameData.Get().xr = value;
}
internal XRPassUniversal xrUniversal => frameData.Get().xrUniversal;
///
/// Maximum shadow distance visible to the camera. When set to zero shadows will be disable for that camera.
///
public ref float maxShadowDistance => ref frameData.Get().maxShadowDistance;
///
/// True if post-processing is enabled for this camera.
///
public ref bool postProcessEnabled => ref frameData.Get().postProcessEnabled;
///
/// Provides set actions to the renderer to be triggered at the end of the render loop for camera capture.
///
public ref IEnumerator> captureActions => ref frameData.Get().captureActions;
///
/// The camera volume layer mask.
///
public ref LayerMask volumeLayerMask => ref frameData.Get().volumeLayerMask;
///
/// The camera volume trigger.
///
public ref Transform volumeTrigger => ref frameData.Get().volumeTrigger;
///
/// If set to true, the integrated post-processing stack will replace any NaNs generated by render passes prior to post-processing with black/zero.
/// Enabling this option will cause a noticeable performance impact. It should be used while in development mode to identify NaN issues.
///
public ref bool isStopNaNEnabled => ref frameData.Get().isStopNaNEnabled;
///
/// If set to true a final post-processing pass will be applied to apply dithering.
/// This can be combined with post-processing antialiasing.
///
///
public ref bool isDitheringEnabled => ref frameData.Get().isDitheringEnabled;
///
/// Controls the anti-alising mode used by the integrated post-processing stack.
/// When any other value other than AntialiasingMode.None is chosen, a final post-processing pass will be applied to apply anti-aliasing.
/// This pass can be combined with dithering.
///
///
///
public ref AntialiasingMode antialiasing => ref frameData.Get().antialiasing;
///
/// Controls the anti-alising quality of the anti-aliasing mode.
///
///
///
public ref AntialiasingQuality antialiasingQuality => ref frameData.Get().antialiasingQuality;
///
/// Returns the current renderer used by this camera.
///
///
public ref ScriptableRenderer renderer => ref frameData.Get().renderer;
///
/// True if this camera is resolving rendering to the final camera render target.
/// When rendering a stack of cameras only the last camera in the stack will resolve to camera target.
///
public ref bool resolveFinalTarget => ref frameData.Get().resolveFinalTarget;
///
/// Camera position in world space.
///
public ref Vector3 worldSpaceCameraPos => ref frameData.Get().worldSpaceCameraPos;
///
/// Final background color in the active color space.
///
public ref Color backgroundColor => ref frameData.Get().backgroundColor;
///
/// Persistent TAA data, primarily for the accumulation texture.
///
internal ref TaaHistory taaHistory => ref frameData.Get().taaHistory;
// TAA settings.
internal ref TemporalAA.Settings taaSettings => ref frameData.Get().taaSettings;
// Post-process history reset has been triggered for this camera.
internal bool resetHistory => frameData.Get().resetHistory;
///
/// Camera at the top of the overlay camera stack
///
public ref Camera baseCamera => ref frameData.Get().baseCamera;
}
///
/// Container struct for various data used for shadows in URP.
///
public struct ShadowData
{
ContextContainer frameData;
internal ShadowData(ContextContainer frameData)
{
this.frameData = frameData;
}
internal UniversalShadowData universalShadowData => frameData.Get();
///
/// True if main light shadows are enabled.
///
public ref bool supportsMainLightShadows => ref frameData.Get().supportsMainLightShadows;
///
/// True if additional lights shadows are enabled in the URP Asset
///
internal ref bool mainLightShadowsEnabled => ref frameData.Get().mainLightShadowsEnabled;
///
/// The width of the main light shadow map.
///
public ref int mainLightShadowmapWidth => ref frameData.Get().mainLightShadowmapWidth;
///
/// The height of the main light shadow map.
///
public ref int mainLightShadowmapHeight => ref frameData.Get().mainLightShadowmapHeight;
///
/// The number of shadow cascades.
///
public ref int mainLightShadowCascadesCount => ref frameData.Get().mainLightShadowCascadesCount;
///
/// The split between cascades.
///
public ref Vector3 mainLightShadowCascadesSplit => ref frameData.Get().mainLightShadowCascadesSplit;
///
/// Main light last cascade shadow fade border.
/// Value represents the width of shadow fade that ranges from 0 to 1.
/// Where value 0 is used for no shadow fade.
///
public ref float mainLightShadowCascadeBorder => ref frameData.Get().mainLightShadowCascadeBorder;
///
/// True if additional lights shadows are enabled.
///
public ref bool supportsAdditionalLightShadows => ref frameData.Get().supportsAdditionalLightShadows;
///
/// True if additional lights shadows are enabled in the URP Asset
///
internal ref bool additionalLightShadowsEnabled => ref frameData.Get().additionalLightShadowsEnabled;
///
/// The width of the additional light shadow map.
///
public ref int additionalLightsShadowmapWidth => ref frameData.Get().additionalLightsShadowmapWidth;
///
/// The height of the additional light shadow map.
///
public ref int additionalLightsShadowmapHeight => ref frameData.Get().additionalLightsShadowmapHeight;
///
/// True if soft shadows are enabled.
///
public ref bool supportsSoftShadows => ref frameData.Get().supportsSoftShadows;
///
/// The number of bits used.
///
public ref int shadowmapDepthBufferBits => ref frameData.Get().shadowmapDepthBufferBits;
///
/// A list of shadow bias.
///
public ref List bias => ref frameData.Get().bias;
///
/// A list of resolution for the shadow maps.
///
public ref List resolution => ref frameData.Get().resolution;
internal ref bool isKeywordAdditionalLightShadowsEnabled => ref frameData.Get().isKeywordAdditionalLightShadowsEnabled;
internal ref bool isKeywordSoftShadowsEnabled => ref frameData.Get().isKeywordSoftShadowsEnabled;
internal ref int mainLightShadowResolution => ref frameData.Get().mainLightShadowResolution;
internal ref int mainLightRenderTargetWidth => ref frameData.Get().mainLightRenderTargetWidth;
internal ref int mainLightRenderTargetHeight => ref frameData.Get().mainLightRenderTargetHeight;
internal ref NativeArray visibleLightsShadowCullingInfos => ref frameData.Get().visibleLightsShadowCullingInfos;
internal ref AdditionalLightsShadowAtlasLayout shadowAtlasLayout => ref frameData.Get().shadowAtlasLayout;
}
///
/// Precomputed tile data.
/// Tile left, right, bottom and top plane equations in view space.
/// Normals are pointing out.
///
public struct PreTile
{
///
/// The left plane.
///
public Unity.Mathematics.float4 planeLeft;
///
/// The right plane.
///
public Unity.Mathematics.float4 planeRight;
///
/// The bottom plane.
///
public Unity.Mathematics.float4 planeBottom;
///
/// The top plane.
///
public Unity.Mathematics.float4 planeTop;
}
///
/// The tile data passed to the deferred shaders.
///
public struct TileData
{
///
/// The tile ID.
///
public uint tileID; // 2x 16 bits
///
/// The list bit mask.
///
public uint listBitMask; // 32 bits
///
/// The relative light offset.
///
public uint relLightOffset; // 16 bits is enough
///
/// Unused variable.
///
public uint unused;
}
///
/// The point/spot light data passed to the deferred shaders.
///
public struct PunctualLightData
{
///
/// The world position.
///
public Vector3 wsPos;
///
/// The radius of the light.
///
public float radius; // TODO remove? included in attenuation
///
/// The color of the light.
///
public Vector4 color;
///
/// The attenuation of the light.
///
public Vector4 attenuation; // .xy are used by DistanceAttenuation - .zw are used by AngleAttenuation (for SpotLights)
///
/// The direction for spot lights.
///
public Vector3 spotDirection; // for spotLights
///
/// The flags used.
///
public int flags;
///
/// The occlusion probe info.
///
public Vector4 occlusionProbeInfo;
///
/// The layer mask used.
///
public uint layerMask;
}
internal static class ShaderPropertyId
{
public static readonly int glossyEnvironmentColor = Shader.PropertyToID("_GlossyEnvironmentColor");
public static readonly int subtractiveShadowColor = Shader.PropertyToID("_SubtractiveShadowColor");
public static readonly int glossyEnvironmentCubeMap = Shader.PropertyToID("_GlossyEnvironmentCubeMap");
public static readonly int glossyEnvironmentCubeMapHDR = Shader.PropertyToID("_GlossyEnvironmentCubeMap_HDR");
public static readonly int ambientSkyColor = Shader.PropertyToID("unity_AmbientSky");
public static readonly int ambientEquatorColor = Shader.PropertyToID("unity_AmbientEquator");
public static readonly int ambientGroundColor = Shader.PropertyToID("unity_AmbientGround");
public static readonly int time = Shader.PropertyToID("_Time");
public static readonly int sinTime = Shader.PropertyToID("_SinTime");
public static readonly int cosTime = Shader.PropertyToID("_CosTime");
public static readonly int deltaTime = Shader.PropertyToID("unity_DeltaTime");
public static readonly int timeParameters = Shader.PropertyToID("_TimeParameters");
public static readonly int lastTimeParameters = Shader.PropertyToID("_LastTimeParameters");
public static readonly int scaledScreenParams = Shader.PropertyToID("_ScaledScreenParams");
public static readonly int worldSpaceCameraPos = Shader.PropertyToID("_WorldSpaceCameraPos");
public static readonly int screenParams = Shader.PropertyToID("_ScreenParams");
public static readonly int alphaToMaskAvailable = Shader.PropertyToID("_AlphaToMaskAvailable");
public static readonly int projectionParams = Shader.PropertyToID("_ProjectionParams");
public static readonly int zBufferParams = Shader.PropertyToID("_ZBufferParams");
public static readonly int orthoParams = Shader.PropertyToID("unity_OrthoParams");
public static readonly int globalMipBias = Shader.PropertyToID("_GlobalMipBias");
public static readonly int screenSize = Shader.PropertyToID("_ScreenSize");
public static readonly int screenCoordScaleBias = Shader.PropertyToID("_ScreenCoordScaleBias");
public static readonly int screenSizeOverride = Shader.PropertyToID("_ScreenSizeOverride");
public static readonly int viewMatrix = Shader.PropertyToID("unity_MatrixV");
public static readonly int projectionMatrix = Shader.PropertyToID("glstate_matrix_projection");
public static readonly int viewAndProjectionMatrix = Shader.PropertyToID("unity_MatrixVP");
public static readonly int inverseViewMatrix = Shader.PropertyToID("unity_MatrixInvV");
public static readonly int inverseProjectionMatrix = Shader.PropertyToID("unity_MatrixInvP");
public static readonly int inverseViewAndProjectionMatrix = Shader.PropertyToID("unity_MatrixInvVP");
public static readonly int cameraProjectionMatrix = Shader.PropertyToID("unity_CameraProjection");
public static readonly int inverseCameraProjectionMatrix = Shader.PropertyToID("unity_CameraInvProjection");
public static readonly int worldToCameraMatrix = Shader.PropertyToID("unity_WorldToCamera");
public static readonly int cameraToWorldMatrix = Shader.PropertyToID("unity_CameraToWorld");
public static readonly int shadowBias = Shader.PropertyToID("_ShadowBias");
public static readonly int lightDirection = Shader.PropertyToID("_LightDirection");
public static readonly int lightPosition = Shader.PropertyToID("_LightPosition");
public static readonly int cameraWorldClipPlanes = Shader.PropertyToID("unity_CameraWorldClipPlanes");
public static readonly int billboardNormal = Shader.PropertyToID("unity_BillboardNormal");
public static readonly int billboardTangent = Shader.PropertyToID("unity_BillboardTangent");
public static readonly int billboardCameraParams = Shader.PropertyToID("unity_BillboardCameraParams");
public static readonly int previousViewProjectionNoJitter = Shader.PropertyToID("_PrevViewProjMatrix");
public static readonly int viewProjectionNoJitter = Shader.PropertyToID("_NonJitteredViewProjMatrix");
#if ENABLE_VR && ENABLE_XR_MODULE
public static readonly int previousViewProjectionNoJitterStereo = Shader.PropertyToID("_PrevViewProjMatrixStereo");
public static readonly int viewProjectionNoJitterStereo = Shader.PropertyToID("_NonJitteredViewProjMatrixStereo");
#endif
public static readonly int blitTexture = Shader.PropertyToID("_BlitTexture");
public static readonly int blitScaleBias = Shader.PropertyToID("_BlitScaleBias");
public static readonly int sourceTex = Shader.PropertyToID("_SourceTex");
public static readonly int scaleBias = Shader.PropertyToID("_ScaleBias");
public static readonly int scaleBiasRt = Shader.PropertyToID("_ScaleBiasRt");
// This uniform is specific to the RTHandle system
public static readonly int rtHandleScale = Shader.PropertyToID("_RTHandleScale");
// Required for 2D Unlit Shadergraph master node as it doesn't currently support hidden properties.
public static readonly int rendererColor = Shader.PropertyToID("_RendererColor");
public static readonly int ditheringTexture = Shader.PropertyToID("_DitheringTexture");
public static readonly int ditheringTextureInvSize = Shader.PropertyToID("_DitheringTextureInvSize");
public static readonly int renderingLayerMaxInt = Shader.PropertyToID("_RenderingLayerMaxInt");
public static readonly int renderingLayerRcpMaxInt = Shader.PropertyToID("_RenderingLayerRcpMaxInt");
public static readonly int overlayUITexture = Shader.PropertyToID("_OverlayUITexture");
public static readonly int hdrOutputLuminanceParams = Shader.PropertyToID("_HDROutputLuminanceParams");
public static readonly int hdrOutputGradingParams = Shader.PropertyToID("_HDROutputGradingParams");
}
///
/// Settings used for Post Processing.
///
public struct PostProcessingData
{
ContextContainer frameData;
internal PostProcessingData(ContextContainer frameData)
{
this.frameData = frameData;
}
internal UniversalPostProcessingData universalPostProcessingData => frameData.Get();
///
/// The ColorGradingMode to use.
///
///
public ref ColorGradingMode gradingMode => ref frameData.Get().gradingMode;
///
/// The size of the Look Up Table (LUT)
///
public ref int lutSize => ref frameData.Get().lutSize;
///
/// True if fast approximation functions are used when converting between the sRGB and Linear color spaces, false otherwise.
///
public ref bool useFastSRGBLinearConversion => ref frameData.Get().useFastSRGBLinearConversion;
///
/// Returns true if Screen Space Lens Flare are supported by this asset, false otherwise.
///
public ref bool supportScreenSpaceLensFlare => ref frameData.Get().supportScreenSpaceLensFlare;
///
/// Returns true if Data Driven Lens Flare are supported by this asset, false otherwise.
///
public ref bool supportDataDrivenLensFlare => ref frameData.Get().supportDataDrivenLensFlare;
}
internal static class ShaderGlobalKeywords
{
public static GlobalKeyword MainLightShadows;
public static GlobalKeyword MainLightShadowCascades;
public static GlobalKeyword MainLightShadowScreen;
public static GlobalKeyword CastingPunctualLightShadow;
public static GlobalKeyword AdditionalLightsVertex;
public static GlobalKeyword AdditionalLightsPixel;
public static GlobalKeyword ForwardPlus;
public static GlobalKeyword AdditionalLightShadows;
public static GlobalKeyword ReflectionProbeBoxProjection;
public static GlobalKeyword ReflectionProbeBlending;
public static GlobalKeyword SoftShadows;
public static GlobalKeyword SoftShadowsLow;
public static GlobalKeyword SoftShadowsMedium;
public static GlobalKeyword SoftShadowsHigh;
public static GlobalKeyword MixedLightingSubtractive; // Backward compatibility
public static GlobalKeyword LightmapShadowMixing;
public static GlobalKeyword ShadowsShadowMask;
public static GlobalKeyword LightLayers;
public static GlobalKeyword RenderPassEnabled;
public static GlobalKeyword BillboardFaceCameraPos;
public static GlobalKeyword LightCookies;
public static GlobalKeyword DepthNoMsaa;
public static GlobalKeyword DepthMsaa2;
public static GlobalKeyword DepthMsaa4;
public static GlobalKeyword DepthMsaa8;
public static GlobalKeyword DBufferMRT1;
public static GlobalKeyword DBufferMRT2;
public static GlobalKeyword DBufferMRT3;
public static GlobalKeyword DecalNormalBlendLow;
public static GlobalKeyword DecalNormalBlendMedium;
public static GlobalKeyword DecalNormalBlendHigh;
public static GlobalKeyword DecalLayers;
public static GlobalKeyword WriteRenderingLayers;
public static GlobalKeyword ScreenSpaceOcclusion;
public static GlobalKeyword _SPOT;
public static GlobalKeyword _DIRECTIONAL;
public static GlobalKeyword _POINT;
public static GlobalKeyword _DEFERRED_STENCIL;
public static GlobalKeyword _DEFERRED_FIRST_LIGHT;
public static GlobalKeyword _DEFERRED_MAIN_LIGHT;
public static GlobalKeyword _GBUFFER_NORMALS_OCT;
public static GlobalKeyword _DEFERRED_MIXED_LIGHTING;
public static GlobalKeyword LIGHTMAP_ON;
public static GlobalKeyword DYNAMICLIGHTMAP_ON;
public static GlobalKeyword _ALPHATEST_ON;
public static GlobalKeyword DIRLIGHTMAP_COMBINED;
public static GlobalKeyword _DETAIL_MULX2;
public static GlobalKeyword _DETAIL_SCALED;
public static GlobalKeyword _CLEARCOAT;
public static GlobalKeyword _CLEARCOATMAP;
public static GlobalKeyword DEBUG_DISPLAY;
public static GlobalKeyword LOD_FADE_CROSSFADE;
public static GlobalKeyword USE_UNITY_CROSSFADE;
public static GlobalKeyword _EMISSION;
public static GlobalKeyword _RECEIVE_SHADOWS_OFF;
public static GlobalKeyword _SURFACE_TYPE_TRANSPARENT;
public static GlobalKeyword _ALPHAPREMULTIPLY_ON;
public static GlobalKeyword _ALPHAMODULATE_ON;
public static GlobalKeyword _NORMALMAP;
public static GlobalKeyword _ADD_PRECOMPUTED_VELOCITY;
public static GlobalKeyword EDITOR_VISUALIZATION;
public static GlobalKeyword FoveatedRenderingNonUniformRaster;
public static GlobalKeyword DisableTexture2DXArray;
public static GlobalKeyword BlitSingleSlice;
public static GlobalKeyword XROcclusionMeshCombined;
public static GlobalKeyword SCREEN_COORD_OVERRIDE;
public static GlobalKeyword DOWNSAMPLING_SIZE_2;
public static GlobalKeyword DOWNSAMPLING_SIZE_4;
public static GlobalKeyword DOWNSAMPLING_SIZE_8;
public static GlobalKeyword DOWNSAMPLING_SIZE_16;
public static GlobalKeyword EVALUATE_SH_MIXED;
public static GlobalKeyword EVALUATE_SH_VERTEX;
public static GlobalKeyword ProbeVolumeL1;
public static GlobalKeyword ProbeVolumeL2;
public static GlobalKeyword _OUTPUT_DEPTH;
public static GlobalKeyword LinearToSRGBConversion;
public static GlobalKeyword _ENABLE_ALPHA_OUTPUT;
// TODO: Move following keywords to Local keywords?
// https://docs.unity3d.com/ScriptReference/Rendering.LocalKeyword.html
//public static GlobalKeyword TonemapACES;
//public static GlobalKeyword TonemapNeutral;
//public static GlobalKeyword UseFastSRGBLinearConversion;
//public static GlobalKeyword SmaaLow;
//public static GlobalKeyword SmaaMedium;
//public static GlobalKeyword SmaaHigh;
//public static GlobalKeyword PaniniGeneric;
//public static GlobalKeyword PaniniUnitDistance;
//public static GlobalKeyword HighQualitySampling;
//public static GlobalKeyword BloomLQ;
//public static GlobalKeyword BloomHQ;
//public static GlobalKeyword BloomLQDirt;
//public static GlobalKeyword BloomHQDirt;
//public static GlobalKeyword UseRGBM;
//public static GlobalKeyword Distortion;
//public static GlobalKeyword ChromaticAberration;
//public static GlobalKeyword HDRGrading;
//public static GlobalKeyword FilmGrain;
//public static GlobalKeyword Fxaa;
//public static GlobalKeyword Dithering;
//public static GlobalKeyword Rcas;
//public static GlobalKeyword EasuRcasAndHDRInput;
//public static GlobalKeyword Gamma20;
//public static GlobalKeyword Gamma20AndHDRInput;
//public static GlobalKeyword PointSampling;
public static void InitializeShaderGlobalKeywords()
{
// Init all keywords upfront
ShaderGlobalKeywords.MainLightShadows = GlobalKeyword.Create(ShaderKeywordStrings.MainLightShadows);
ShaderGlobalKeywords.MainLightShadowCascades = GlobalKeyword.Create(ShaderKeywordStrings.MainLightShadowCascades);
ShaderGlobalKeywords.MainLightShadowScreen = GlobalKeyword.Create(ShaderKeywordStrings.MainLightShadowScreen);
ShaderGlobalKeywords.CastingPunctualLightShadow = GlobalKeyword.Create(ShaderKeywordStrings.CastingPunctualLightShadow);
ShaderGlobalKeywords.AdditionalLightsVertex = GlobalKeyword.Create(ShaderKeywordStrings.AdditionalLightsVertex);
ShaderGlobalKeywords.AdditionalLightsPixel = GlobalKeyword.Create(ShaderKeywordStrings.AdditionalLightsPixel);
ShaderGlobalKeywords.ForwardPlus = GlobalKeyword.Create(ShaderKeywordStrings.ForwardPlus);
ShaderGlobalKeywords.AdditionalLightShadows = GlobalKeyword.Create(ShaderKeywordStrings.AdditionalLightShadows);
ShaderGlobalKeywords.ReflectionProbeBoxProjection = GlobalKeyword.Create(ShaderKeywordStrings.ReflectionProbeBoxProjection);
ShaderGlobalKeywords.ReflectionProbeBlending = GlobalKeyword.Create(ShaderKeywordStrings.ReflectionProbeBlending);
ShaderGlobalKeywords.SoftShadows = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadows);
ShaderGlobalKeywords.SoftShadowsLow = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadowsLow);
ShaderGlobalKeywords.SoftShadowsMedium = GlobalKeyword.Create(ShaderKeywordStrings.SoftShadowsMedium);
ShaderGlobalKeywords.MixedLightingSubtractive = GlobalKeyword.Create(ShaderKeywordStrings.MixedLightingSubtractive);
ShaderGlobalKeywords.LightmapShadowMixing = GlobalKeyword.Create(ShaderKeywordStrings.LightmapShadowMixing);
ShaderGlobalKeywords.ShadowsShadowMask = GlobalKeyword.Create(ShaderKeywordStrings.ShadowsShadowMask);
ShaderGlobalKeywords.LightLayers = GlobalKeyword.Create(ShaderKeywordStrings.LightLayers);
ShaderGlobalKeywords.RenderPassEnabled = GlobalKeyword.Create(ShaderKeywordStrings.RenderPassEnabled);
ShaderGlobalKeywords.BillboardFaceCameraPos = GlobalKeyword.Create(ShaderKeywordStrings.BillboardFaceCameraPos);
ShaderGlobalKeywords.LightCookies = GlobalKeyword.Create(ShaderKeywordStrings.LightCookies);
ShaderGlobalKeywords.DepthNoMsaa = GlobalKeyword.Create(ShaderKeywordStrings.DepthNoMsaa);
ShaderGlobalKeywords.DepthMsaa2 = GlobalKeyword.Create(ShaderKeywordStrings.DepthMsaa2);
ShaderGlobalKeywords.DepthMsaa4 = GlobalKeyword.Create(ShaderKeywordStrings.DepthMsaa4);
ShaderGlobalKeywords.DepthMsaa8 = GlobalKeyword.Create(ShaderKeywordStrings.DepthMsaa8);
ShaderGlobalKeywords.DBufferMRT1 = GlobalKeyword.Create(ShaderKeywordStrings.DBufferMRT1);
ShaderGlobalKeywords.DBufferMRT2 = GlobalKeyword.Create(ShaderKeywordStrings.DBufferMRT2);
ShaderGlobalKeywords.DBufferMRT3 = GlobalKeyword.Create(ShaderKeywordStrings.DBufferMRT3);
ShaderGlobalKeywords.DecalNormalBlendLow = GlobalKeyword.Create(ShaderKeywordStrings.DecalNormalBlendLow);
ShaderGlobalKeywords.DecalNormalBlendMedium = GlobalKeyword.Create(ShaderKeywordStrings.DecalNormalBlendMedium);
ShaderGlobalKeywords.DecalNormalBlendHigh = GlobalKeyword.Create(ShaderKeywordStrings.DecalNormalBlendHigh);
ShaderGlobalKeywords.DecalLayers = GlobalKeyword.Create(ShaderKeywordStrings.DecalLayers);
ShaderGlobalKeywords.WriteRenderingLayers = GlobalKeyword.Create(ShaderKeywordStrings.WriteRenderingLayers);
ShaderGlobalKeywords.ScreenSpaceOcclusion = GlobalKeyword.Create(ShaderKeywordStrings.ScreenSpaceOcclusion);
ShaderGlobalKeywords._SPOT = GlobalKeyword.Create(ShaderKeywordStrings._SPOT);
ShaderGlobalKeywords._DIRECTIONAL = GlobalKeyword.Create(ShaderKeywordStrings._DIRECTIONAL);
ShaderGlobalKeywords._POINT = GlobalKeyword.Create(ShaderKeywordStrings._POINT);
ShaderGlobalKeywords._DEFERRED_STENCIL = GlobalKeyword.Create(ShaderKeywordStrings._DEFERRED_STENCIL);
ShaderGlobalKeywords._DEFERRED_FIRST_LIGHT = GlobalKeyword.Create(ShaderKeywordStrings._DEFERRED_FIRST_LIGHT);
ShaderGlobalKeywords._DEFERRED_MAIN_LIGHT = GlobalKeyword.Create(ShaderKeywordStrings._DEFERRED_MAIN_LIGHT);
ShaderGlobalKeywords._GBUFFER_NORMALS_OCT = GlobalKeyword.Create(ShaderKeywordStrings._GBUFFER_NORMALS_OCT);
ShaderGlobalKeywords._DEFERRED_MIXED_LIGHTING = GlobalKeyword.Create(ShaderKeywordStrings._DEFERRED_MIXED_LIGHTING);
ShaderGlobalKeywords.LIGHTMAP_ON = GlobalKeyword.Create(ShaderKeywordStrings.LIGHTMAP_ON);
ShaderGlobalKeywords.DYNAMICLIGHTMAP_ON = GlobalKeyword.Create(ShaderKeywordStrings.DYNAMICLIGHTMAP_ON);
ShaderGlobalKeywords._ALPHATEST_ON = GlobalKeyword.Create(ShaderKeywordStrings._ALPHATEST_ON);
ShaderGlobalKeywords.DIRLIGHTMAP_COMBINED = GlobalKeyword.Create(ShaderKeywordStrings.DIRLIGHTMAP_COMBINED);
ShaderGlobalKeywords._DETAIL_MULX2 = GlobalKeyword.Create(ShaderKeywordStrings._DETAIL_MULX2);
ShaderGlobalKeywords._DETAIL_SCALED = GlobalKeyword.Create(ShaderKeywordStrings._DETAIL_SCALED);
ShaderGlobalKeywords._CLEARCOAT = GlobalKeyword.Create(ShaderKeywordStrings._CLEARCOAT);
ShaderGlobalKeywords._CLEARCOATMAP = GlobalKeyword.Create(ShaderKeywordStrings._CLEARCOATMAP);
ShaderGlobalKeywords.DEBUG_DISPLAY = GlobalKeyword.Create(ShaderKeywordStrings.DEBUG_DISPLAY);
ShaderGlobalKeywords.LOD_FADE_CROSSFADE = GlobalKeyword.Create(ShaderKeywordStrings.LOD_FADE_CROSSFADE);
ShaderGlobalKeywords.USE_UNITY_CROSSFADE = GlobalKeyword.Create(ShaderKeywordStrings.USE_UNITY_CROSSFADE);
ShaderGlobalKeywords._EMISSION = GlobalKeyword.Create(ShaderKeywordStrings._EMISSION);
ShaderGlobalKeywords._RECEIVE_SHADOWS_OFF = GlobalKeyword.Create(ShaderKeywordStrings._RECEIVE_SHADOWS_OFF);
ShaderGlobalKeywords._SURFACE_TYPE_TRANSPARENT = GlobalKeyword.Create(ShaderKeywordStrings._SURFACE_TYPE_TRANSPARENT);
ShaderGlobalKeywords._ALPHAPREMULTIPLY_ON = GlobalKeyword.Create(ShaderKeywordStrings._ALPHAPREMULTIPLY_ON);
ShaderGlobalKeywords._ALPHAMODULATE_ON = GlobalKeyword.Create(ShaderKeywordStrings._ALPHAMODULATE_ON);
ShaderGlobalKeywords._NORMALMAP = GlobalKeyword.Create(ShaderKeywordStrings._NORMALMAP);
ShaderGlobalKeywords._ADD_PRECOMPUTED_VELOCITY = GlobalKeyword.Create(ShaderKeywordStrings._ADD_PRECOMPUTED_VELOCITY);
ShaderGlobalKeywords.EDITOR_VISUALIZATION = GlobalKeyword.Create(ShaderKeywordStrings.EDITOR_VISUALIZATION);
ShaderGlobalKeywords.FoveatedRenderingNonUniformRaster = GlobalKeyword.Create(ShaderKeywordStrings.FoveatedRenderingNonUniformRaster);
ShaderGlobalKeywords.DisableTexture2DXArray = GlobalKeyword.Create(ShaderKeywordStrings.DisableTexture2DXArray);
ShaderGlobalKeywords.BlitSingleSlice = GlobalKeyword.Create(ShaderKeywordStrings.BlitSingleSlice);
ShaderGlobalKeywords.XROcclusionMeshCombined = GlobalKeyword.Create(ShaderKeywordStrings.XROcclusionMeshCombined);
ShaderGlobalKeywords.SCREEN_COORD_OVERRIDE = GlobalKeyword.Create(ShaderKeywordStrings.SCREEN_COORD_OVERRIDE);
ShaderGlobalKeywords.DOWNSAMPLING_SIZE_2 = GlobalKeyword.Create(ShaderKeywordStrings.DOWNSAMPLING_SIZE_2);
ShaderGlobalKeywords.DOWNSAMPLING_SIZE_4 = GlobalKeyword.Create(ShaderKeywordStrings.DOWNSAMPLING_SIZE_4);
ShaderGlobalKeywords.DOWNSAMPLING_SIZE_8 = GlobalKeyword.Create(ShaderKeywordStrings.DOWNSAMPLING_SIZE_8);
ShaderGlobalKeywords.DOWNSAMPLING_SIZE_16 = GlobalKeyword.Create(ShaderKeywordStrings.DOWNSAMPLING_SIZE_16);
ShaderGlobalKeywords.EVALUATE_SH_MIXED = GlobalKeyword.Create(ShaderKeywordStrings.EVALUATE_SH_MIXED);
ShaderGlobalKeywords.EVALUATE_SH_VERTEX = GlobalKeyword.Create(ShaderKeywordStrings.EVALUATE_SH_VERTEX);
ShaderGlobalKeywords.ProbeVolumeL1 = GlobalKeyword.Create(ShaderKeywordStrings.ProbeVolumeL1);
ShaderGlobalKeywords.ProbeVolumeL2 = GlobalKeyword.Create(ShaderKeywordStrings.ProbeVolumeL2);
ShaderGlobalKeywords._OUTPUT_DEPTH = GlobalKeyword.Create(ShaderKeywordStrings._OUTPUT_DEPTH);
ShaderGlobalKeywords.LinearToSRGBConversion = GlobalKeyword.Create(ShaderKeywordStrings.LinearToSRGBConversion);
ShaderGlobalKeywords._ENABLE_ALPHA_OUTPUT = GlobalKeyword.Create(ShaderKeywordStrings._ENABLE_ALPHA_OUTPUT);
}
}
///
/// Container class for keywords used in URP shaders.
///
public static class ShaderKeywordStrings
{
/// Keyword used for shadows without cascades.
public const string MainLightShadows = "_MAIN_LIGHT_SHADOWS";
/// Keyword used for shadows with cascades.
public const string MainLightShadowCascades = "_MAIN_LIGHT_SHADOWS_CASCADE";
/// Keyword used for screen space shadows.
public const string MainLightShadowScreen = "_MAIN_LIGHT_SHADOWS_SCREEN";
/// Keyword used during shadow map generation to differentiate between directional and punctual light shadows, as they use different formulas to apply Normal Bias.
public const string CastingPunctualLightShadow = "_CASTING_PUNCTUAL_LIGHT_SHADOW";
/// Keyword used for per vertex additional lights.
public const string AdditionalLightsVertex = "_ADDITIONAL_LIGHTS_VERTEX";
/// Keyword used for per pixel additional lights.
public const string AdditionalLightsPixel = "_ADDITIONAL_LIGHTS";
/// Keyword used for Forward+.
internal const string ForwardPlus = "_FORWARD_PLUS";
/// Keyword used for shadows on additional lights.
public const string AdditionalLightShadows = "_ADDITIONAL_LIGHT_SHADOWS";
/// Keyword used for Box Projection with Reflection Probes.
public const string ReflectionProbeBoxProjection = "_REFLECTION_PROBE_BOX_PROJECTION";
/// Keyword used for Reflection probe blending.
public const string ReflectionProbeBlending = "_REFLECTION_PROBE_BLENDING";
/// Keyword used for soft shadows.
public const string SoftShadows = "_SHADOWS_SOFT";
/// Keyword used for low quality soft shadows.
public const string SoftShadowsLow = "_SHADOWS_SOFT_LOW";
/// Keyword used for medium quality soft shadows.
public const string SoftShadowsMedium = "_SHADOWS_SOFT_MEDIUM";
/// Keyword used for high quality soft shadows.
public const string SoftShadowsHigh = "_SHADOWS_SOFT_HIGH";
/// Keyword used for Mixed Lights in Subtractive lighting mode.
public const string MixedLightingSubtractive = "_MIXED_LIGHTING_SUBTRACTIVE"; // Backward compatibility
/// Keyword used for mixing lightmap shadows.
public const string LightmapShadowMixing = "LIGHTMAP_SHADOW_MIXING";
/// Keyword used for Shadowmask.
public const string ShadowsShadowMask = "SHADOWS_SHADOWMASK";
/// Keyword used for Light Layers.
public const string LightLayers = "_LIGHT_LAYERS";
/// Keyword used for RenderPass.
public const string RenderPassEnabled = "_RENDER_PASS_ENABLED";
/// Keyword used for Billboard cameras.
public const string BillboardFaceCameraPos = "BILLBOARD_FACE_CAMERA_POS";
/// Keyword used for Light Cookies.
public const string LightCookies = "_LIGHT_COOKIES";
/// Keyword used for no Multi Sampling Anti-Aliasing (MSAA).
public const string DepthNoMsaa = "_DEPTH_NO_MSAA";
/// Keyword used for Multi Sampling Anti-Aliasing (MSAA) with 2 per pixel sample count.
public const string DepthMsaa2 = "_DEPTH_MSAA_2";
/// Keyword used for Multi Sampling Anti-Aliasing (MSAA) with 4 per pixel sample count.
public const string DepthMsaa4 = "_DEPTH_MSAA_4";
/// Keyword used for Multi Sampling Anti-Aliasing (MSAA) with 8 per pixel sample count.
public const string DepthMsaa8 = "_DEPTH_MSAA_8";
/// Keyword used for Linear to SRGB conversions.
public const string LinearToSRGBConversion = "_LINEAR_TO_SRGB_CONVERSION";
/// Keyword used for less expensive Linear to SRGB conversions.
internal const string UseFastSRGBLinearConversion = "_USE_FAST_SRGB_LINEAR_CONVERSION";
/// Keyword used for first target in the DBuffer.
public const string DBufferMRT1 = "_DBUFFER_MRT1";
/// Keyword used for second target in the DBuffer.
public const string DBufferMRT2 = "_DBUFFER_MRT2";
/// Keyword used for third target in the DBuffer.
public const string DBufferMRT3 = "_DBUFFER_MRT3";
/// Keyword used for low quality normal reconstruction in Decals.
public const string DecalNormalBlendLow = "_DECAL_NORMAL_BLEND_LOW";
/// Keyword used for medium quality normal reconstruction in Decals.
public const string DecalNormalBlendMedium = "_DECAL_NORMAL_BLEND_MEDIUM";
/// Keyword used for high quality normal reconstruction in Decals.
public const string DecalNormalBlendHigh = "_DECAL_NORMAL_BLEND_HIGH";
/// Keyword used for Decal Layers.
public const string DecalLayers = "_DECAL_LAYERS";
/// Keyword used for writing Rendering Layers.
public const string WriteRenderingLayers = "_WRITE_RENDERING_LAYERS";
/// Keyword used for low quality Subpixel Morphological Anti-aliasing (SMAA).
public const string SmaaLow = "_SMAA_PRESET_LOW";
/// Keyword used for medium quality Subpixel Morphological Anti-aliasing (SMAA).
public const string SmaaMedium = "_SMAA_PRESET_MEDIUM";
/// Keyword used for high quality Subpixel Morphological Anti-aliasing (SMAA).
public const string SmaaHigh = "_SMAA_PRESET_HIGH";
/// Keyword used for generic Panini Projection.
public const string PaniniGeneric = "_GENERIC";
/// Keyword used for unit distance Panini Projection.
public const string PaniniUnitDistance = "_UNIT_DISTANCE";
/// Keyword used for low quality Bloom.
public const string BloomLQ = "_BLOOM_LQ";
/// Keyword used for high quality Bloom.
public const string BloomHQ = "_BLOOM_HQ";
/// Keyword used for low quality Bloom dirt.
public const string BloomLQDirt = "_BLOOM_LQ_DIRT";
/// Keyword used for high quality Bloom dirt.
public const string BloomHQDirt = "_BLOOM_HQ_DIRT";
/// Keyword used for Distortion.
public const string Distortion = "_DISTORTION";
/// Keyword used for Chromatic Aberration.
public const string ChromaticAberration = "_CHROMATIC_ABERRATION";
/// Keyword used for HDR Color Grading.
public const string HDRGrading = "_HDR_GRADING";
/// Keyword used for HDR UI Overlay compositing.
public const string HDROverlay = "_HDR_OVERLAY";
/// Keyword used for ACES Tonemapping.
public const string TonemapACES = "_TONEMAP_ACES";
/// Keyword used for Neutral Tonemapping.
public const string TonemapNeutral = "_TONEMAP_NEUTRAL";
/// Keyword used for Film Grain.
public const string FilmGrain = "_FILM_GRAIN";
/// Keyword used for Fast Approximate Anti-aliasing (FXAA).
public const string Fxaa = "_FXAA";
/// Keyword used for Dithering.
public const string Dithering = "_DITHERING";
/// Keyword used for Screen Space Occlusion, such as Screen Space Ambient Occlusion (SSAO).
public const string ScreenSpaceOcclusion = "_SCREEN_SPACE_OCCLUSION";
/// Keyword used for Point sampling when doing upsampling.
public const string PointSampling = "_POINT_SAMPLING";
/// Keyword used for Robust Contrast-Adaptive Sharpening (RCAS) when doing upsampling.
public const string Rcas = "_RCAS";
/// Keyword used for Robust Contrast-Adaptive Sharpening (RCAS) when doing upsampling, after EASU has ran and with HDR Dsiplay output.
public const string EasuRcasAndHDRInput = "_EASU_RCAS_AND_HDR_INPUT";
/// Keyword used for Gamma 2.0.
public const string Gamma20 = "_GAMMA_20";
/// Keyword used for Gamma 2.0 with HDR_INPUT.
public const string Gamma20AndHDRInput = "_GAMMA_20_AND_HDR_INPUT";
/// Keyword used for high quality sampling for Depth Of Field.
public const string HighQualitySampling = "_HIGH_QUALITY_SAMPLING";
/// Keyword used for Spot lights.
public const string _SPOT = "_SPOT";
/// Keyword used for Directional lights.
public const string _DIRECTIONAL = "_DIRECTIONAL";
/// Keyword used for Point lights.
public const string _POINT = "_POINT";
/// Keyword used for stencils when rendering with the Deferred rendering path.
public const string _DEFERRED_STENCIL = "_DEFERRED_STENCIL";
/// Keyword used for the first light when rendering with the Deferred rendering path.
public const string _DEFERRED_FIRST_LIGHT = "_DEFERRED_FIRST_LIGHT";
/// Keyword used for the main light when rendering with the Deferred rendering path.
public const string _DEFERRED_MAIN_LIGHT = "_DEFERRED_MAIN_LIGHT";
/// Keyword used for Accurate G-buffer normals when rendering with the Deferred rendering path.
public const string _GBUFFER_NORMALS_OCT = "_GBUFFER_NORMALS_OCT";
/// Keyword used for Mixed Lighting when rendering with the Deferred rendering path.
public const string _DEFERRED_MIXED_LIGHTING = "_DEFERRED_MIXED_LIGHTING";
/// Keyword used for Lightmaps.
public const string LIGHTMAP_ON = "LIGHTMAP_ON";
/// Keyword used for dynamic Lightmaps.
public const string DYNAMICLIGHTMAP_ON = "DYNAMICLIGHTMAP_ON";
/// Keyword used for Alpha testing.
public const string _ALPHATEST_ON = "_ALPHATEST_ON";
/// Keyword used for combined directional Lightmaps.
public const string DIRLIGHTMAP_COMBINED = "DIRLIGHTMAP_COMBINED";
/// Keyword used for 2x detail mapping.
public const string _DETAIL_MULX2 = "_DETAIL_MULX2";
/// Keyword used for scaled detail mapping.
public const string _DETAIL_SCALED = "_DETAIL_SCALED";
/// Keyword used for Clear Coat.
public const string _CLEARCOAT = "_CLEARCOAT";
/// Keyword used for Clear Coat maps.
public const string _CLEARCOATMAP = "_CLEARCOATMAP";
/// Keyword used for Debug Display.
public const string DEBUG_DISPLAY = "DEBUG_DISPLAY";
/// Keyword used for LOD Crossfade.
public const string LOD_FADE_CROSSFADE = "LOD_FADE_CROSSFADE";
/// Keyword used for LOD Crossfade with ShaderGraph shaders.
public const string USE_UNITY_CROSSFADE = "USE_UNITY_CROSSFADE";
/// Keyword used for Emission.
public const string _EMISSION = "_EMISSION";
/// Keyword used for receiving shadows.
public const string _RECEIVE_SHADOWS_OFF = "_RECEIVE_SHADOWS_OFF";
/// Keyword used for opaque or transparent surface types.
public const string _SURFACE_TYPE_TRANSPARENT = "_SURFACE_TYPE_TRANSPARENT";
/// Keyword used for Alpha premultiply.
public const string _ALPHAPREMULTIPLY_ON = "_ALPHAPREMULTIPLY_ON";
/// Keyword used for Alpha modulate.
public const string _ALPHAMODULATE_ON = "_ALPHAMODULATE_ON";
/// Keyword used for Normal maps.
public const string _NORMALMAP = "_NORMALMAP";
/// Keyword used for Alembic precomputed velocity.
public const string _ADD_PRECOMPUTED_VELOCITY = "_ADD_PRECOMPUTED_VELOCITY";
/// Keyword used for editor visualization.
public const string EDITOR_VISUALIZATION = "EDITOR_VISUALIZATION";
/// Keyword used for foveated rendering.
public const string FoveatedRenderingNonUniformRaster = "_FOVEATED_RENDERING_NON_UNIFORM_RASTER";
/// Keyword used for disabling Texture 2D Arrays.
public const string DisableTexture2DXArray = "DISABLE_TEXTURE2D_X_ARRAY";
/// Keyword used for Single Slice Blits.
public const string BlitSingleSlice = "BLIT_SINGLE_SLICE";
/// Keyword used for rendering a combined mesh for XR.
public const string XROcclusionMeshCombined = "XR_OCCLUSION_MESH_COMBINED";
/// Keyword used for applying scale and bias.
public const string SCREEN_COORD_OVERRIDE = "SCREEN_COORD_OVERRIDE";
/// Keyword used for half size downsampling.
public const string DOWNSAMPLING_SIZE_2 = "DOWNSAMPLING_SIZE_2";
/// Keyword used for quarter size downsampling.
public const string DOWNSAMPLING_SIZE_4 = "DOWNSAMPLING_SIZE_4";
/// Keyword used for eighth size downsampling.
public const string DOWNSAMPLING_SIZE_8 = "DOWNSAMPLING_SIZE_8";
/// Keyword used for sixteenth size downsampling.
public const string DOWNSAMPLING_SIZE_16 = "DOWNSAMPLING_SIZE_16";
/// Keyword used for mixed Spherical Harmonic (SH) evaluation in URP Lit shaders.
public const string EVALUATE_SH_MIXED = "EVALUATE_SH_MIXED";
/// Keyword used for vertex Spherical Harmonic (SH) evaluation in URP Lit shaders.
public const string EVALUATE_SH_VERTEX = "EVALUATE_SH_VERTEX";
/// Keyword used for APV with SH L1
public const string ProbeVolumeL1 = "PROBE_VOLUMES_L1";
/// Keyword used for APV with SH L2
public const string ProbeVolumeL2 = "PROBE_VOLUMES_L2";
/// Keyword used for opting out of lightmap texture arrays, when using BatchRendererGroup.
public const string USE_LEGACY_LIGHTMAPS = "USE_LEGACY_LIGHTMAPS";
/// Keyword used for CopyDepth pass.
public const string _OUTPUT_DEPTH = "_OUTPUT_DEPTH";
/// Keyword used for enable alpha output. Used in post processing.
public const string _ENABLE_ALPHA_OUTPUT = "_ENABLE_ALPHA_OUTPUT";
}
public sealed partial class UniversalRenderPipeline
{
// Holds light direction for directional lights or position for punctual lights.
// When w is set to 1.0, it means it's a punctual light.
static Vector4 k_DefaultLightPosition = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
static Vector4 k_DefaultLightColor = Color.black;
// Default light attenuation is setup in a particular way that it causes
// directional lights to return 1.0 for both distance and angle attenuation
static Vector4 k_DefaultLightAttenuation = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
static Vector4 k_DefaultLightSpotDirection = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
static Vector4 k_DefaultLightsProbeChannel = new Vector4(0.0f, 0.0f, 0.0f, 0.0f);
static List m_ShadowBiasData = new List();
static List m_ShadowResolutionData = new List();
///
/// Checks if a camera is a game camera.
///
/// Camera to check state from.
/// true if given camera is a game camera, false otherwise.
public static bool IsGameCamera(Camera camera)
{
if (camera == null)
throw new ArgumentNullException("camera");
return camera.cameraType == CameraType.Game || camera.cameraType == CameraType.VR;
}
///
/// Returns the current render pipeline asset for the current quality setting.
/// If no render pipeline asset is assigned in QualitySettings, then returns the one assigned in GraphicsSettings.
///
public static UniversalRenderPipelineAsset asset
{
get => GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
}
Comparison cameraComparison = (camera1, camera2) => { return (int)camera1.depth - (int)camera2.depth; };
#if UNITY_2021_1_OR_NEWER
void SortCameras(List cameras)
{
if (cameras.Count > 1)
cameras.Sort(cameraComparison);
}
#else
void SortCameras(Camera[] cameras)
{
if (cameras.Length > 1)
Array.Sort(cameras, cameraComparison);
}
#endif
internal static GraphicsFormat MakeRenderTextureGraphicsFormat(bool isHdrEnabled, HDRColorBufferPrecision requestHDRColorBufferPrecision, bool needsAlpha)
{
if (isHdrEnabled)
{
// TODO: we need a proper format scoring system. Score formats, sort, pick first or pick first supported (if not in score).
// UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend`
// For now, we keep checking for `Blend` until the performance hit of doing the correct checks is evaluated
if (!needsAlpha && requestHDRColorBufferPrecision != HDRColorBufferPrecision._64Bits && SystemInfo.IsFormatSupported(GraphicsFormat.B10G11R11_UFloatPack32, GraphicsFormatUsage.Blend))
return GraphicsFormat.B10G11R11_UFloatPack32;
if (SystemInfo.IsFormatSupported(GraphicsFormat.R16G16B16A16_SFloat, GraphicsFormatUsage.Blend))
return GraphicsFormat.R16G16B16A16_SFloat;
return SystemInfo.GetGraphicsFormat(DefaultFormat.HDR); // This might actually be a LDR format on old devices.
}
return SystemInfo.GetGraphicsFormat(DefaultFormat.LDR);
}
// Returns a UNORM based render texture format
// When supported by the device, this function will prefer formats with higher precision, but the same bit-depth
// NOTE: This function does not guarantee that the returned format will contain an alpha channel.
internal static GraphicsFormat MakeUnormRenderTextureGraphicsFormat()
{
// UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend`
// For now, we keep checking for `Blend` until the performance hit of doing the correct checks is evaluated
if (SystemInfo.IsFormatSupported(GraphicsFormat.A2B10G10R10_UNormPack32, GraphicsFormatUsage.Blend))
return GraphicsFormat.A2B10G10R10_UNormPack32;
else
return GraphicsFormat.R8G8B8A8_UNorm;
}
internal static RenderTextureDescriptor CreateRenderTextureDescriptor(Camera camera, UniversalCameraData cameraData,
bool isHdrEnabled, HDRColorBufferPrecision requestHDRColorBufferPrecision, int msaaSamples, bool needsAlpha, bool requiresOpaqueTexture)
{
RenderTextureDescriptor desc;
if (camera.targetTexture == null)
{
desc = new RenderTextureDescriptor(cameraData.scaledWidth, cameraData.scaledHeight);
desc.graphicsFormat = MakeRenderTextureGraphicsFormat(isHdrEnabled, requestHDRColorBufferPrecision, needsAlpha);
desc.depthStencilFormat = SystemInfo.GetGraphicsFormat(DefaultFormat.DepthStencil);
desc.msaaSamples = msaaSamples;
desc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear);
}
else
{
desc = camera.targetTexture.descriptor;
desc.msaaSamples = msaaSamples;
desc.width = cameraData.scaledWidth;
desc.height = cameraData.scaledHeight;
if (camera.cameraType == CameraType.SceneView && !isHdrEnabled)
{
desc.graphicsFormat = SystemInfo.GetGraphicsFormat(DefaultFormat.LDR);
}
// SystemInfo.SupportsRenderTextureFormat(camera.targetTexture.descriptor.colorFormat)
// will assert on R8_SINT since it isn't a valid value of RenderTextureFormat.
// If this is fixed then we can implement debug statement to the user explaining why some
// RenderTextureFormats available resolves in a black render texture when no warning or error
// is given.
}
desc.enableRandomWrite = false;
desc.bindMS = false;
desc.useDynamicScale = camera.allowDynamicResolution;
// check that the requested MSAA samples count is supported by the current platform. If it's not supported,
// replace the requested desc.msaaSamples value with the actual value the engine falls back to
desc.msaaSamples = SystemInfo.GetRenderTextureSupportedMSAASampleCount(desc);
// if the target platform doesn't support storing multisampled RTs and we are doing any offscreen passes, using a Load load action on the subsequent passes
// will result in loading Resolved data, which on some platforms is discarded, resulting in losing the results of the previous passes.
// As a workaround we disable MSAA to make sure that the results of previous passes are stored. (fix for Case 1247423).
if (!SystemInfo.supportsStoreAndResolveAction)
desc.msaaSamples = 1;
return desc;
}
private static Lightmapping.RequestLightsDelegate lightsDelegate = (Light[] requests, NativeArray lightsOutput) =>
{
LightDataGI lightData = new LightDataGI();
#if UNITY_EDITOR
// Always extract lights in the Editor.
for (int i = 0; i < requests.Length; i++)
{
Light light = requests[i];
var additionalLightData = light.GetUniversalAdditionalLightData();
LightmapperUtils.Extract(light, out Cookie cookie);
switch (light.type)
{
case LightType.Directional:
DirectionalLight directionalLight = new DirectionalLight();
LightmapperUtils.Extract(light, ref directionalLight);
if (light.cookie != null)
{
// Size == 1 / Scale
cookie.sizes = additionalLightData.lightCookieSize;
// Offset, Map cookie UV offset to light position on along local axes.
if (additionalLightData.lightCookieOffset != Vector2.zero)
{
var r = light.transform.right * additionalLightData.lightCookieOffset.x;
var u = light.transform.up * additionalLightData.lightCookieOffset.y;
var offset = r + u;
directionalLight.position += offset;
}
}
lightData.Init(ref directionalLight, ref cookie);
break;
case LightType.Point:
PointLight pointLight = new PointLight();
LightmapperUtils.Extract(light, ref pointLight);
lightData.Init(ref pointLight, ref cookie);
break;
case LightType.Spot:
SpotLight spotLight = new SpotLight();
LightmapperUtils.Extract(light, ref spotLight);
spotLight.innerConeAngle = light.innerSpotAngle * Mathf.Deg2Rad;
spotLight.angularFalloff = AngularFalloffType.AnalyticAndInnerAngle;
lightData.Init(ref spotLight, ref cookie);
break;
case LightType.Rectangle:
RectangleLight rectangleLight = new RectangleLight();
LightmapperUtils.Extract(light, ref rectangleLight);
rectangleLight.mode = LightMode.Baked;
lightData.Init(ref rectangleLight);
break;
case LightType.Disc:
DiscLight discLight = new DiscLight();
LightmapperUtils.Extract(light, ref discLight);
discLight.mode = LightMode.Baked;
lightData.Init(ref discLight);
break;
default:
lightData.InitNoBake(light.GetInstanceID());
break;
}
lightData.falloff = FalloffType.InverseSquared;
lightsOutput[i] = lightData;
}
#else
// If Enlighten realtime GI isn't active, we don't extract lights.
if (SupportedRenderingFeatures.active.enlighten == false || ((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) == 0)
{
for (int i = 0; i < requests.Length; i++)
{
Light light = requests[i];
lightData.InitNoBake(light.GetInstanceID());
lightsOutput[i] = lightData;
}
}
else
{
for (int i = 0; i < requests.Length; i++)
{
Light light = requests[i];
switch (light.type)
{
case LightType.Directional:
DirectionalLight directionalLight = new DirectionalLight();
LightmapperUtils.Extract(light, ref directionalLight);
lightData.Init(ref directionalLight);
break;
case LightType.Point:
PointLight pointLight = new PointLight();
LightmapperUtils.Extract(light, ref pointLight);
lightData.Init(ref pointLight);
break;
case LightType.Spot:
SpotLight spotLight = new SpotLight();
LightmapperUtils.Extract(light, ref spotLight);
spotLight.innerConeAngle = light.innerSpotAngle * Mathf.Deg2Rad;
spotLight.angularFalloff = AngularFalloffType.AnalyticAndInnerAngle;
lightData.Init(ref spotLight);
break;
case LightType.Rectangle:
// Rect area light is baked only in URP.
lightData.InitNoBake(light.GetInstanceID());
break;
case LightType.Disc:
// Disc light is baked only.
lightData.InitNoBake(light.GetInstanceID());
break;
default:
lightData.InitNoBake(light.GetInstanceID());
break;
}
lightData.falloff = FalloffType.InverseSquared;
lightsOutput[i] = lightData;
}
}
#endif
};
// Called from DeferredLights.cs too
///
/// Calculates the attenuation for a given light and also direction for spot lights.
///
/// The type of light.
/// The range of the light.
/// The local to world light matrix.
/// The spotlight angle.
/// The spotlight inner angle.
/// The light attenuation.
/// The spot light direction.
public static void GetLightAttenuationAndSpotDirection(
LightType lightType, float lightRange, Matrix4x4 lightLocalToWorldMatrix,
float spotAngle, float? innerSpotAngle,
out Vector4 lightAttenuation, out Vector4 lightSpotDir)
{
// Default is directional
lightAttenuation = k_DefaultLightAttenuation;
lightSpotDir = k_DefaultLightSpotDirection;
if (lightType != LightType.Directional)
{
GetPunctualLightDistanceAttenuation(lightRange, ref lightAttenuation);
if (lightType == LightType.Spot)
{
GetSpotDirection(ref lightLocalToWorldMatrix, out lightSpotDir);
GetSpotAngleAttenuation(spotAngle, innerSpotAngle, ref lightAttenuation);
}
}
}
internal static void GetPunctualLightDistanceAttenuation(float lightRange, ref Vector4 lightAttenuation)
{
// Light attenuation in universal matches the unity vanilla one (HINT_NICE_QUALITY).
// attenuation = 1.0 / distanceToLightSqr
// The smoothing factor makes sure that the light intensity is zero at the light range limit.
// (We used to offer two different smoothing factors.)
// The current smoothing factor matches the one used in the Unity lightmapper.
// smoothFactor = (1.0 - saturate((distanceSqr * 1.0 / lightRangeSqr)^2))^2
float lightRangeSqr = lightRange * lightRange;
float fadeStartDistanceSqr = 0.8f * 0.8f * lightRangeSqr;
float fadeRangeSqr = (fadeStartDistanceSqr - lightRangeSqr);
float lightRangeSqrOverFadeRangeSqr = -lightRangeSqr / fadeRangeSqr;
float oneOverLightRangeSqr = 1.0f / Mathf.Max(0.0001f, lightRangeSqr);
// On all devices: Use the smoothing factor that matches the GI.
lightAttenuation.x = oneOverLightRangeSqr;
lightAttenuation.y = lightRangeSqrOverFadeRangeSqr;
}
internal static void GetSpotAngleAttenuation(
float spotAngle, float? innerSpotAngle,
ref Vector4 lightAttenuation)
{
// Spot Attenuation with a linear falloff can be defined as
// (SdotL - cosOuterAngle) / (cosInnerAngle - cosOuterAngle)
// This can be rewritten as
// invAngleRange = 1.0 / (cosInnerAngle - cosOuterAngle)
// SdotL * invAngleRange + (-cosOuterAngle * invAngleRange)
// If we precompute the terms in a MAD instruction
float cosOuterAngle = Mathf.Cos(Mathf.Deg2Rad * spotAngle * 0.5f);
// We need to do a null check for particle lights
// This should be changed in the future
// Particle lights will use an inline function
float cosInnerAngle;
if (innerSpotAngle.HasValue)
cosInnerAngle = Mathf.Cos(innerSpotAngle.Value * Mathf.Deg2Rad * 0.5f);
else
cosInnerAngle = Mathf.Cos((2.0f * Mathf.Atan(Mathf.Tan(spotAngle * 0.5f * Mathf.Deg2Rad) * (64.0f - 18.0f) / 64.0f)) * 0.5f);
float smoothAngleRange = Mathf.Max(0.001f, cosInnerAngle - cosOuterAngle);
float invAngleRange = 1.0f / smoothAngleRange;
float add = -cosOuterAngle * invAngleRange;
lightAttenuation.z = invAngleRange;
lightAttenuation.w = add;
}
internal static void GetSpotDirection(ref Matrix4x4 lightLocalToWorldMatrix, out Vector4 lightSpotDir)
{
Vector4 dir = lightLocalToWorldMatrix.GetColumn(2);
lightSpotDir = new Vector4(-dir.x, -dir.y, -dir.z, 0.0f);
}
///
/// Initializes common light constants.
///
/// List of lights to iterate.
/// The index of the light.
/// The position of the light.
/// The color of the light.
/// The attenuation of the light.
/// The direction of the light.
/// The occlusion probe channel for the light.
public static void InitializeLightConstants_Common(NativeArray lights, int lightIndex, out Vector4 lightPos, out Vector4 lightColor, out Vector4 lightAttenuation, out Vector4 lightSpotDir, out Vector4 lightOcclusionProbeChannel)
{
lightPos = k_DefaultLightPosition;
lightColor = k_DefaultLightColor;
lightOcclusionProbeChannel = k_DefaultLightsProbeChannel;
lightAttenuation = k_DefaultLightAttenuation; // Directional by default.
lightSpotDir = k_DefaultLightSpotDirection;
// When no lights are visible, main light will be set to -1.
// In this case we initialize it to default values and return
if (lightIndex < 0)
return;
// Avoid memcpys. Pass by ref and locals for multiple uses.
ref VisibleLight lightData = ref lights.UnsafeElementAtMutable(lightIndex);
var light = lightData.light;
var lightLocalToWorld = lightData.localToWorldMatrix;
var lightType = lightData.lightType;
if (lightType == LightType.Directional)
{
Vector4 dir = -lightLocalToWorld.GetColumn(2);
lightPos = new Vector4(dir.x, dir.y, dir.z, 0.0f);
}
else
{
Vector4 pos = lightLocalToWorld.GetColumn(3);
lightPos = new Vector4(pos.x, pos.y, pos.z, 1.0f);
GetPunctualLightDistanceAttenuation(lightData.range, ref lightAttenuation);
if (lightType == LightType.Spot)
{
GetSpotAngleAttenuation(lightData.spotAngle, light?.innerSpotAngle, ref lightAttenuation);
GetSpotDirection(ref lightLocalToWorld, out lightSpotDir);
}
}
// VisibleLight.finalColor already returns color in active color space
lightColor = lightData.finalColor;
if (light != null && light.bakingOutput.lightmapBakeType == LightmapBakeType.Mixed &&
0 <= light.bakingOutput.occlusionMaskChannel &&
light.bakingOutput.occlusionMaskChannel < 4)
{
lightOcclusionProbeChannel[light.bakingOutput.occlusionMaskChannel] = 1.0f;
}
}
}
// URP Profile Id
// - Scopes using this enum are automatically picked up by the performance testing framework.
// - You can use [HideInDebugUI] attribute to hide a given id from the Detailed Stats section of Rendering Debugger.
internal enum URPProfileId
{
// CPU
UniversalRenderTotal,
UpdateVolumeFramework,
RenderCameraStack,
// GPU
AdditionalLightsShadow,
ColorGradingLUT,
CopyColor,
CopyDepth,
DrawDepthNormalPrepass,
DepthPrepass,
UpdateReflectionProbeAtlas,
// DrawObjectsPass
DrawOpaqueObjects,
DrawTransparentObjects,
DrawScreenSpaceUI,
//Full Record Render Graph
RecordRenderGraph,
// RenderObjectsPass
//RenderObjects,
LightCookies,
MainLightShadow,
ResolveShadows,
SSAO,
// PostProcessPass
StopNaNs,
SMAA,
GaussianDepthOfField,
BokehDepthOfField,
TemporalAA,
MotionBlur,
PaniniProjection,
UberPostProcess,
Bloom,
LensFlareDataDrivenComputeOcclusion,
LensFlareDataDriven,
LensFlareScreenSpace,
DrawMotionVectors,
DrawFullscreen,
// PostProcessPass RenderGraph
[HideInDebugUI] RG_SetupPostFX,
[HideInDebugUI] RG_StopNaNs,
[HideInDebugUI] RG_SMAAMaterialSetup,
[HideInDebugUI] RG_SMAAEdgeDetection,
[HideInDebugUI] RG_SMAABlendWeight,
[HideInDebugUI] RG_SMAANeighborhoodBlend,
[HideInDebugUI] RG_SetupDoF,
[HideInDebugUI] RG_DOFComputeCOC,
[HideInDebugUI] RG_DOFDownscalePrefilter,
[HideInDebugUI] RG_DOFBlurH,
[HideInDebugUI] RG_DOFBlurV,
[HideInDebugUI] RG_DOFBlurBokeh,
[HideInDebugUI] RG_DOFPostFilter,
[HideInDebugUI] RG_DOFComposite,
[HideInDebugUI] RG_TAA,
[HideInDebugUI] RG_TAACopyHistory,
[HideInDebugUI] RG_MotionBlur,
[HideInDebugUI] RG_BloomSetup,
[HideInDebugUI] RG_BloomPrefilter,
[HideInDebugUI] RG_BloomDownsample,
[HideInDebugUI] RG_BloomUpsample,
[HideInDebugUI] RG_UberPostSetupBloomPass,
[HideInDebugUI] RG_UberPost,
[HideInDebugUI] RG_FinalSetup,
[HideInDebugUI] RG_FinalFSRScale,
[HideInDebugUI] RG_FinalBlit,
BlitFinalToBackBuffer,
DrawSkybox
}
// Internal class to detect and cache runtime platform information.
// TODO: refine the logic to provide platform abstraction. Eg, we should divide platforms based on capabilities and perf budget.
// TODO: isXRMobile is a bad category. Alignment and refactor needed.
// TODO: Compress all the query data into "isXRMobile" style booleans and enums.
internal static class PlatformAutoDetect
{
///
/// Detect and cache runtime platform information. This function should only be called once when creating the URP.
///
internal static void Initialize()
{
bool isRunningMobile = false;
#if ENABLE_VR && ENABLE_VR_MODULE
#if PLATFORM_WINRT || PLATFORM_ANDROID
isRunningMobile = IsRunningXRMobile();
#endif
#endif
isXRMobile = isRunningMobile;
isShaderAPIMobileDefined = GraphicsSettings.HasShaderDefine(BuiltinShaderDefine.SHADER_API_MOBILE);
isSwitch = Application.platform == RuntimePlatform.Switch;
}
#if ENABLE_VR && ENABLE_VR_MODULE
#if PLATFORM_WINRT || PLATFORM_ANDROID
// XR mobile platforms are not treated as dedicated mobile platforms in Core. Handle them specially here. (Quest and HL).
private static List displaySubsystemList = new List();
private static bool IsRunningXRMobile()
{
var platform = Application.platform;
if (platform == RuntimePlatform.WSAPlayerX86 || platform == RuntimePlatform.WSAPlayerARM || platform == RuntimePlatform.WSAPlayerX64 || platform == RuntimePlatform.Android)
{
XR.XRDisplaySubsystem display = null;
SubsystemManager.GetSubsystems(displaySubsystemList);
if (displaySubsystemList.Count > 0)
display = displaySubsystemList[0];
if (display != null)
return true;
}
return false;
}
#endif
#endif
///
/// If true, the runtime platform is an XR mobile platform.
///
internal static bool isXRMobile { get; private set; } = false;
///
/// If true, then SHADER_API_MOBILE has been defined in URP Shaders.
///
internal static bool isShaderAPIMobileDefined { get; private set; } = false;
///
/// If true, then the runtime platform is set to Switch.
///
internal static bool isSwitch { get; private set; } = false;
///
/// Gives the SH evaluation mode when set to automatically detect.
///
/// The current SH evaluation mode.
/// Returns the SH evaluation mode to use.
internal static ShEvalMode ShAutoDetect(ShEvalMode mode)
{
if (mode == ShEvalMode.Auto)
{
if (isXRMobile || isShaderAPIMobileDefined || isSwitch)
return ShEvalMode.PerVertex;
else
return ShEvalMode.PerPixel;
}
return mode;
}
internal static bool isRunningOnPowerVRGPU = SystemInfo.graphicsDeviceName.Contains("PowerVR");
}
}