Advertisement
Guest User

overview

a guest
Jul 17th, 2018
555
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 116.34 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using UnityEngine.Rendering;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using UnityEngine.Rendering.PostProcessing;
  7. using UnityEngine.Experimental.GlobalIllumination;
  8. using UnityEngine.XR;
  9.  
  10. namespace UnityEngine.Experimental.Rendering.HDPipeline
  11. {
  12.     public class HDRenderPipeline : RenderPipeline
  13.     {
  14.         enum ForwardPass
  15.         {
  16.             Opaque,
  17.             PreRefraction,
  18.             Transparent
  19.         }
  20.  
  21.         static readonly string[] k_ForwardPassDebugName =
  22.         {
  23.             "Forward Opaque Debug",
  24.             "Forward PreRefraction Debug",
  25.             "Forward Transparent Debug"
  26.         };
  27.  
  28.         static readonly string[] k_ForwardPassName =
  29.         {
  30.             "Forward Opaque",
  31.             "Forward PreRefraction",
  32.             "Forward Transparent"
  33.         };
  34.  
  35.         readonly HDRenderPipelineAsset m_Asset;
  36.         public HDRenderPipelineAsset asset { get { return m_Asset; } }
  37.  
  38.         DiffusionProfileSettings m_InternalSSSAsset;
  39.         public DiffusionProfileSettings diffusionProfileSettings
  40.         {
  41.             get
  42.             {
  43.                 // If no SSS asset is set, build / reuse an internal one for simplicity
  44.                 var asset = m_Asset.diffusionProfileSettings;
  45.  
  46.                 if (asset == null)
  47.                 {
  48.                     if (m_InternalSSSAsset == null)
  49.                         m_InternalSSSAsset = ScriptableObject.CreateInstance<DiffusionProfileSettings>();
  50.  
  51.                     asset = m_InternalSSSAsset;
  52.                 }
  53.  
  54.                 return asset;
  55.             }
  56.         }
  57.         public RenderPipelineSettings renderPipelineSettings { get { return m_Asset.renderPipelineSettings; } }
  58.  
  59.         public bool IsInternalDiffusionProfile(DiffusionProfileSettings profile)
  60.         {
  61.             return m_InternalSSSAsset == profile;
  62.         }
  63.  
  64.         readonly RenderPipelineMaterial m_DeferredMaterial;
  65.         readonly List<RenderPipelineMaterial> m_MaterialList = new List<RenderPipelineMaterial>();
  66.  
  67.         readonly GBufferManager m_GbufferManager;
  68.         readonly DBufferManager m_DbufferManager;
  69.         readonly SubsurfaceScatteringManager m_SSSBufferManager = new SubsurfaceScatteringManager();
  70.         readonly NormalBufferManager m_NormalBufferManager = new NormalBufferManager();
  71.  
  72.         // Renderer Bake configuration can vary depends on if shadow mask is enabled or no
  73.         RendererConfiguration m_currentRendererConfigurationBakedLighting = HDUtils.k_RendererConfigurationBakedLighting;
  74.         Material m_CopyStencilForNoLighting;
  75.         Material m_CopyDepth;
  76.         GPUCopy m_GPUCopy;
  77.         BufferPyramid m_BufferPyramid;
  78.  
  79.         IBLFilterGGX m_IBLFilterGGX = null;
  80.  
  81.         ComputeShader m_applyDistortionCS { get { return m_Asset.renderPipelineResources.applyDistortionCS; } }
  82.         int m_applyDistortionKernel;
  83.  
  84.         Material m_CameraMotionVectorsMaterial;
  85.  
  86.         // Debug material
  87.         Material m_DebugViewMaterialGBuffer;
  88.         Material m_DebugViewMaterialGBufferShadowMask;
  89.         Material m_currentDebugViewMaterialGBuffer;
  90.         Material m_DebugDisplayLatlong;
  91.         Material m_DebugFullScreen;
  92.         Material m_DebugColorPicker;
  93.         Material m_Blit;
  94.         Material m_ErrorMaterial;
  95.  
  96.         RenderTargetIdentifier[] m_MRTCache2 = new RenderTargetIdentifier[2];
  97.  
  98.         // 'm_CameraColorBuffer' does not contain diffuse lighting of SSS materials until the SSS pass. It is stored within 'm_CameraSssDiffuseLightingBuffer'.
  99.         RTHandleSystem.RTHandle m_CameraColorBuffer;
  100.         RTHandleSystem.RTHandle m_CameraSssDiffuseLightingBuffer;
  101.  
  102.         RTHandleSystem.RTHandle m_CameraDepthStencilBuffer;
  103.         RTHandleSystem.RTHandle m_CameraDepthBufferCopy;
  104.         RTHandleSystem.RTHandle m_CameraStencilBufferCopy;
  105.  
  106.         RTHandleSystem.RTHandle m_VelocityBuffer;
  107.         RTHandleSystem.RTHandle m_DeferredShadowBuffer;
  108.         RTHandleSystem.RTHandle m_AmbientOcclusionBuffer;
  109.         RTHandleSystem.RTHandle m_DistortionBuffer;
  110.  
  111.         // The pass "SRPDefaultUnlit" is a fall back to legacy unlit rendering and is required to support unity 2d + unity UI that render in the scene.
  112.         ShaderPassName[] m_ForwardAndForwardOnlyPassNames = { HDShaderPassNames.s_ForwardOnlyName, HDShaderPassNames.s_ForwardName, HDShaderPassNames.s_SRPDefaultUnlitName };
  113.         ShaderPassName[] m_ForwardOnlyPassNames = { HDShaderPassNames.s_ForwardOnlyName, HDShaderPassNames.s_SRPDefaultUnlitName };
  114.  
  115.         ShaderPassName[] m_AllTransparentPassNames = {  HDShaderPassNames.s_TransparentBackfaceName,
  116.                                                         HDShaderPassNames.s_ForwardOnlyName,
  117.                                                         HDShaderPassNames.s_ForwardName,
  118.                                                         HDShaderPassNames.s_SRPDefaultUnlitName };
  119.  
  120.         ShaderPassName[] m_AllForwardOpaquePassNames = {    HDShaderPassNames.s_ForwardOnlyName,
  121.                                                             HDShaderPassNames.s_ForwardName,
  122.                                                             HDShaderPassNames.s_SRPDefaultUnlitName };
  123.  
  124.         ShaderPassName[] m_DepthOnlyAndDepthForwardOnlyPassNames = { HDShaderPassNames.s_DepthForwardOnlyName, HDShaderPassNames.s_DepthOnlyName };
  125.         ShaderPassName[] m_DepthForwardOnlyPassNames = { HDShaderPassNames.s_DepthForwardOnlyName };
  126.         ShaderPassName[] m_DepthOnlyPassNames = { HDShaderPassNames.s_DepthOnlyName };
  127.         ShaderPassName[] m_TransparentDepthPrepassNames = { HDShaderPassNames.s_TransparentDepthPrepassName };
  128.         ShaderPassName[] m_TransparentDepthPostpassNames = { HDShaderPassNames.s_TransparentDepthPostpassName };
  129.         ShaderPassName[] m_ForwardErrorPassNames = { HDShaderPassNames.s_AlwaysName, HDShaderPassNames.s_ForwardBaseName, HDShaderPassNames.s_DeferredName, HDShaderPassNames.s_PrepassBaseName, HDShaderPassNames.s_VertexName, HDShaderPassNames.s_VertexLMRGBMName, HDShaderPassNames.s_VertexLMName };
  130.         ShaderPassName[] m_SinglePassName = new ShaderPassName[1];
  131.  
  132.         // Stencil usage in HDRenderPipeline.
  133.         // Currently we use only 2 bits to identify the kind of lighting that is expected from the render pipeline
  134.         // Usage is define in LightDefinitions.cs
  135.         [Flags]
  136.         public enum StencilBitMask
  137.         {
  138.             Clear           = 0,             // 0x0
  139.             LightingMask    = 7,             // 0x7  - 3 bit
  140.             ObjectVelocity  = 128,           // 0x80 - 1 bit
  141.             All             = 255            // 0xFF - 8 bit
  142.         }
  143.  
  144.         RenderStateBlock m_DepthStateOpaque;
  145.  
  146.         // Detect when windows size is changing
  147.         int m_CurrentWidth;
  148.         int m_CurrentHeight;
  149.  
  150.         // Use to detect frame changes
  151.         uint  m_FrameCount;
  152.         float m_LastTime, m_Time;
  153.  
  154.         public int GetCurrentShadowCount() { return m_LightLoop.GetCurrentShadowCount(); }
  155.         public int GetShadowAtlasCount() { return m_LightLoop.GetShadowAtlasCount(); }
  156.         public int GetDecalAtlasMipCount()
  157.         {
  158.             int highestDim = Math.Max(renderPipelineSettings.decalSettings.atlasWidth, renderPipelineSettings.decalSettings.atlasHeight);
  159.             return (int)Math.Log(highestDim, 2);
  160.         }
  161.  
  162.         public int GetShadowSliceCount(uint atlasIndex) { return m_LightLoop.GetShadowSliceCount(atlasIndex); }
  163.  
  164.         readonly SkyManager m_SkyManager = new SkyManager();
  165.         readonly LightLoop m_LightLoop = new LightLoop();
  166.         readonly ShadowSettings m_ShadowSettings = new ShadowSettings();
  167.         readonly VolumetricLightingSystem m_VolumetricLightingSystem = new VolumetricLightingSystem();
  168.  
  169.         // Debugging
  170.         MaterialPropertyBlock m_SharedPropertyBlock = new MaterialPropertyBlock();
  171.         DebugDisplaySettings m_DebugDisplaySettings = new DebugDisplaySettings();
  172.         public DebugDisplaySettings debugDisplaySettings { get { return m_DebugDisplaySettings; } }
  173.         static DebugDisplaySettings s_NeutralDebugDisplaySettings = new DebugDisplaySettings();
  174.         DebugDisplaySettings m_CurrentDebugDisplaySettings;
  175.         RTHandleSystem.RTHandle         m_DebugColorPickerBuffer;
  176.         RTHandleSystem.RTHandle         m_DebugFullScreenTempBuffer;
  177.         bool                            m_FullScreenDebugPushed;
  178.         bool                            m_ValidAPI; // False by default mean we render normally, true mean we don't render anything
  179.  
  180.         public Material GetBlitMaterial() { return m_Blit; }
  181.  
  182.         ComputeBuffer m_DebugScreenSpaceTracingData = null;
  183.         ScreenSpaceTracingDebug[] m_DebugScreenSpaceTracingDataArray = new ScreenSpaceTracingDebug[1];
  184.  
  185.         public HDRenderPipeline(HDRenderPipelineAsset asset)
  186.         {
  187.             DebugManager.instance.RefreshEditor();
  188.  
  189.             m_ValidAPI = true;
  190.  
  191.             if (!SetRenderingFeatures())
  192.             {
  193.                 m_ValidAPI = false;
  194.  
  195.                 return;
  196.             }
  197.  
  198.             m_Asset = asset;
  199.  
  200.             // Initial state of the RTHandle system.
  201.             // Tells the system that we will require MSAA or not so that we can avoid wasteful render texture allocation.
  202.             // TODO: Might want to initialize to at least the window resolution to avoid un-necessary re-alloc in the player
  203.             RTHandles.Initialize(1, 1, m_Asset.renderPipelineSettings.supportMSAA, m_Asset.renderPipelineSettings.msaaSampleCount);
  204.  
  205.             m_GPUCopy = new GPUCopy(asset.renderPipelineResources.copyChannelCS);
  206.  
  207.             var bufferPyramidProcessor = new BufferPyramidProcessor(
  208.                     asset.renderPipelineResources.colorPyramidCS,
  209.                     asset.renderPipelineResources.depthPyramidCS,
  210.                     m_GPUCopy,
  211.                     new TexturePadding(asset.renderPipelineResources.texturePaddingCS)
  212.                     );
  213.             m_BufferPyramid = new BufferPyramid(bufferPyramidProcessor);
  214.  
  215.             EncodeBC6H.DefaultInstance = EncodeBC6H.DefaultInstance ?? new EncodeBC6H(asset.renderPipelineResources.encodeBC6HCS);
  216.  
  217.             m_ReflectionProbeCullResults = new ReflectionProbeCullResults(asset.reflectionSystemParameters);
  218.             ReflectionSystem.SetParameters(asset.reflectionSystemParameters);
  219.  
  220.             // Scan material list and assign it
  221.             m_MaterialList = HDUtils.GetRenderPipelineMaterialList();
  222.             // Find first material that have non 0 Gbuffer count and assign it as deferredMaterial
  223.             m_DeferredMaterial = null;
  224.             foreach (var material in m_MaterialList)
  225.             {
  226.                 if (material.GetMaterialGBufferCount() > 0)
  227.                     m_DeferredMaterial = material;
  228.             }
  229.  
  230.             // TODO: Handle the case of no Gbuffer material
  231.             // TODO: I comment the assert here because m_DeferredMaterial for whatever reasons contain the correct class but with a "null" in the name instead of the real name and then trigger the assert
  232.             // whereas it work. Don't know what is happening, DebugDisplay use the same code and name is correct there.
  233.             // Debug.Assert(m_DeferredMaterial != null);
  234.  
  235.             m_GbufferManager = new GBufferManager(m_DeferredMaterial, m_Asset.renderPipelineSettings.supportShadowMask);
  236.             m_DbufferManager = new DBufferManager();
  237.  
  238.             m_SSSBufferManager.Build(asset);
  239.             m_NormalBufferManager.Build(asset);
  240.  
  241.             // Initialize various compute shader resources
  242.             m_applyDistortionKernel = m_applyDistortionCS.FindKernel("KMain");
  243.  
  244.             // General material
  245.             m_CopyStencilForNoLighting = CoreUtils.CreateEngineMaterial(asset.renderPipelineResources.copyStencilBuffer);
  246.             m_CopyStencilForNoLighting.SetInt(HDShaderIDs._StencilRef, (int)StencilLightingUsage.NoLighting);
  247.             m_CopyStencilForNoLighting.SetInt(HDShaderIDs._StencilMask, (int)StencilBitMask.LightingMask);
  248.             m_CameraMotionVectorsMaterial = CoreUtils.CreateEngineMaterial(asset.renderPipelineResources.cameraMotionVectors);
  249.  
  250.             m_CopyDepth = CoreUtils.CreateEngineMaterial(asset.renderPipelineResources.copyDepthBuffer);
  251.  
  252.             InitializeDebugMaterials();
  253.  
  254.             m_MaterialList.ForEach(material => material.Build(asset));
  255.  
  256.             m_IBLFilterGGX = new IBLFilterGGX(asset.renderPipelineResources, bufferPyramidProcessor);
  257.  
  258.             m_LightLoop.Build(asset, m_ShadowSettings, m_IBLFilterGGX);
  259.  
  260.             m_SkyManager.Build(asset, m_IBLFilterGGX);
  261.  
  262.             m_VolumetricLightingSystem.Build(asset);
  263.  
  264.             m_DebugDisplaySettings.RegisterDebug();
  265. #if UNITY_EDITOR
  266.             // We don't need the debug of Scene View at runtime (each camera have its own debug settings)
  267.             FrameSettings.RegisterDebug("Scene View", m_Asset.GetFrameSettings());
  268. #endif
  269.             m_DebugScreenSpaceTracingData = new ComputeBuffer(1, System.Runtime.InteropServices.Marshal.SizeOf(typeof(ScreenSpaceTracingDebug)));
  270.  
  271.             InitializeRenderTextures();
  272.  
  273.             // For debugging
  274.             MousePositionDebug.instance.Build();
  275.  
  276.             InitializeRenderStateBlocks();
  277.         }
  278.  
  279.         void InitializeRenderTextures()
  280.         {
  281.             if (!m_Asset.renderPipelineSettings.supportOnlyForward)
  282.                 m_GbufferManager.CreateBuffers();
  283.  
  284.             if (m_Asset.renderPipelineSettings.supportDBuffer)
  285.                 m_DbufferManager.CreateBuffers();
  286.  
  287.             m_SSSBufferManager.InitSSSBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
  288.             m_NormalBufferManager.InitNormalBuffers(m_GbufferManager, m_Asset.renderPipelineSettings);
  289.  
  290.             m_CameraColorBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraColor");
  291.             m_CameraSssDiffuseLightingBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.RGB111110Float, sRGB: false, enableRandomWrite: true, enableMSAA: true, name: "CameraSSSDiffuseLighting");
  292.  
  293.             m_CameraDepthStencilBuffer = RTHandles.Alloc(Vector2.one, depthBufferBits: DepthBits.Depth24, colorFormat: RenderTextureFormat.Depth, filterMode: FilterMode.Point, bindTextureMS: true, enableMSAA: true, name: "CameraDepthStencil");
  294.  
  295.             if (NeedDepthBufferCopy())
  296.             {
  297.                 m_CameraDepthBufferCopy = RTHandles.Alloc(Vector2.one, depthBufferBits: DepthBits.Depth24, colorFormat: RenderTextureFormat.Depth, filterMode: FilterMode.Point, bindTextureMS: true, enableMSAA: true, name: "CameraDepthStencilCopy");
  298.             }
  299.  
  300.             // Technically we won't need this buffer in some cases, but nothing that we can determine at init time.
  301.             m_CameraStencilBufferCopy = RTHandles.Alloc(Vector2.one, depthBufferBits: DepthBits.None, colorFormat: RenderTextureFormat.R8, sRGB: false, filterMode: FilterMode.Point, enableMSAA: true, name: "CameraStencilCopy"); // DXGI_FORMAT_R8_UINT is not supported by Unity
  302.  
  303.             if (m_Asset.renderPipelineSettings.supportSSAO)
  304.             {
  305.                 m_AmbientOcclusionBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Bilinear, colorFormat: RenderTextureFormat.R8, sRGB: false, enableRandomWrite: true, name: "AmbientOcclusion");
  306.             }
  307.  
  308.             if (m_Asset.renderPipelineSettings.supportMotionVectors)
  309.             {
  310.                 m_VelocityBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: Builtin.GetVelocityBufferFormat(), sRGB: Builtin.GetVelocityBufferSRGBFlag(), enableMSAA: true, name: "Velocity");
  311.             }
  312.  
  313.             m_DistortionBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: Builtin.GetDistortionBufferFormat(), sRGB: Builtin.GetDistortionBufferSRGBFlag(), name: "Distortion");
  314.  
  315.             // TODO: For MSAA, we'll need to add a Draw path in order to support MSAA properly
  316.             m_DeferredShadowBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGB32, sRGB: false, enableRandomWrite: true, name: "DeferredShadow");
  317.  
  318.             if (Debug.isDebugBuild)
  319.             {
  320.                 m_DebugColorPickerBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, name: "DebugColorPicker");
  321.                 m_DebugFullScreenTempBuffer = RTHandles.Alloc(Vector2.one, filterMode: FilterMode.Point, colorFormat: RenderTextureFormat.ARGBHalf, sRGB: false, name: "DebugFullScreen");
  322.             }
  323.         }
  324.  
  325.         void DestroyRenderTextures()
  326.         {
  327.             m_GbufferManager.DestroyBuffers();
  328.             m_DbufferManager.DestroyBuffers();
  329.             m_BufferPyramid.DestroyBuffers();
  330.  
  331.             RTHandles.Release(m_CameraColorBuffer);
  332.             RTHandles.Release(m_CameraSssDiffuseLightingBuffer);
  333.  
  334.             RTHandles.Release(m_CameraDepthStencilBuffer);
  335.             RTHandles.Release(m_CameraDepthBufferCopy);
  336.             RTHandles.Release(m_CameraStencilBufferCopy);
  337.  
  338.             RTHandles.Release(m_AmbientOcclusionBuffer);
  339.             RTHandles.Release(m_VelocityBuffer);
  340.             RTHandles.Release(m_DistortionBuffer);
  341.             RTHandles.Release(m_DeferredShadowBuffer);
  342.  
  343.             RTHandles.Release(m_DebugColorPickerBuffer);
  344.             RTHandles.Release(m_DebugFullScreenTempBuffer);
  345.  
  346.             m_DebugScreenSpaceTracingData.Release();
  347.  
  348.             HDCamera.ClearAll();
  349.         }
  350.  
  351.         bool SetRenderingFeatures()
  352.         {
  353.             // Set subshader pipeline tag
  354.             Shader.globalRenderPipeline = "HDRenderPipeline";
  355.  
  356.             // HD use specific GraphicsSettings
  357.             GraphicsSettings.lightsUseLinearIntensity = true;
  358.             GraphicsSettings.lightsUseColorTemperature = true;
  359.             // HD should always use the new batcher - TODO once fix are backport in 2018.2/staging
  360.             //GraphicsSettings.useScriptableRenderPipelineBatching = true;
  361.  
  362.             SupportedRenderingFeatures.active = new SupportedRenderingFeatures()
  363.             {
  364.                 reflectionProbeSupportFlags = SupportedRenderingFeatures.ReflectionProbeSupportFlags.Rotation,
  365.                 defaultMixedLightingMode = SupportedRenderingFeatures.LightmapMixedBakeMode.IndirectOnly,
  366.                 supportedMixedLightingModes = SupportedRenderingFeatures.LightmapMixedBakeMode.IndirectOnly | SupportedRenderingFeatures.LightmapMixedBakeMode.Shadowmask,
  367.                 supportedLightmapBakeTypes = LightmapBakeType.Baked | LightmapBakeType.Mixed | LightmapBakeType.Realtime,
  368.                 supportedLightmapsModes = LightmapsMode.NonDirectional | LightmapsMode.CombinedDirectional,
  369.                 rendererSupportsLightProbeProxyVolumes = true,
  370.                 rendererSupportsMotionVectors = true,
  371.                 rendererSupportsReceiveShadows = false,
  372.                 rendererSupportsReflectionProbes = true
  373.             };
  374.  
  375.             Lightmapping.SetDelegate(GlobalIlluminationUtils.hdLightsDelegate);
  376.  
  377. #if UNITY_EDITOR
  378.             SceneViewDrawMode.SetupDrawMode();
  379.  
  380.             if (UnityEditor.PlayerSettings.colorSpace == ColorSpace.Gamma)
  381.             {
  382.                 Debug.LogError("High Definition Render Pipeline doesn't support Gamma mode, change to Linear mode");
  383.             }
  384. #endif
  385.  
  386.             if (!IsSupportedPlatform())
  387.             {
  388.                 CoreUtils.DisplayUnsupportedAPIMessage();
  389.  
  390.                 return false;
  391.             }
  392.  
  393. #if !UNITY_SWITCH
  394.             // VR is not supported currently in HD
  395.             if (XRSettings.isDeviceActive)
  396.             {
  397.                 CoreUtils.DisplayUnsupportedXRMessage();
  398.  
  399.                 return false;
  400.             }
  401. #endif
  402.  
  403.             return true;
  404.         }
  405.  
  406.         bool IsSupportedPlatform()
  407.         {
  408.             // Note: If you add new platform in this function, think about adding support when building the player to in HDRPCustomBuildProcessor.cs
  409.  
  410.             if (!SystemInfo.supportsComputeShaders)
  411.                 return false;
  412.  
  413.             if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11 ||
  414.                 SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12 ||
  415.                 SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 ||
  416.                 SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne ||
  417.                 SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12 ||
  418.                 SystemInfo.graphicsDeviceType == GraphicsDeviceType.Vulkan ||
  419.                 SystemInfo.graphicsDeviceType == (GraphicsDeviceType)22/*GraphicsDeviceType.Switch*/)
  420.             {
  421.                 return true;
  422.             }
  423.  
  424.             if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal)
  425.             {
  426.                 string os = SystemInfo.operatingSystem;
  427.  
  428.                 // Metal support depends on OS version:
  429.                 // macOS 10.11.x doesn't have tessellation / earlydepthstencil support, early driver versions were buggy in general
  430.                 // macOS 10.12.x should usually work with AMD, but issues with Intel/Nvidia GPUs. Regardless of the GPU, there are issues with MTLCompilerService crashing with some shaders
  431.                 // macOS 10.13.x is expected to work, and if it's a driver/shader compiler issue, there's still hope on getting it fixed to next shipping OS patch release
  432.                 //
  433.                 // Has worked experimentally with iOS in the past, but it's not currently supported
  434.                 //
  435.  
  436.                 if (os.StartsWith("Mac"))
  437.                 {
  438.                     // TODO: Expose in C# version number, for now assume "Mac OS X 10.10.4" format with version 10 at least
  439.                     int startIndex = os.LastIndexOf(" ");
  440.                     var parts = os.Substring(startIndex + 1).Split('.');
  441.                     int a = Convert.ToInt32(parts[0]);
  442.                     int b = Convert.ToInt32(parts[1]);
  443.                     // In case in the future there's a need to disable specific patch releases
  444.                     // int c = Convert.ToInt32(parts[2]);
  445.  
  446.                     if (a >= 10 && b >= 13)
  447.                         return true;
  448.                 }
  449.             }
  450.  
  451.             return false;
  452.         }
  453.  
  454.         void UnsetRenderingFeatures()
  455.         {
  456.             Shader.globalRenderPipeline = "";
  457.  
  458.             SupportedRenderingFeatures.active = new SupportedRenderingFeatures();
  459.  
  460.             Lightmapping.ResetDelegate();
  461.         }
  462.  
  463.         void InitializeDebugMaterials()
  464.         {
  465.             m_DebugViewMaterialGBuffer = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugViewMaterialGBufferShader);
  466.             m_DebugViewMaterialGBufferShadowMask = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugViewMaterialGBufferShader);
  467.             m_DebugViewMaterialGBufferShadowMask.EnableKeyword("SHADOWS_SHADOWMASK");
  468.             m_DebugDisplayLatlong = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugDisplayLatlongShader);
  469.             m_DebugFullScreen = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugFullScreenShader);
  470.             m_DebugColorPicker = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.debugColorPickerShader);
  471.             m_Blit = CoreUtils.CreateEngineMaterial(m_Asset.renderPipelineResources.blit);
  472.             m_ErrorMaterial = CoreUtils.CreateEngineMaterial("Hidden/InternalErrorShader");
  473.         }
  474.  
  475.         void InitializeRenderStateBlocks()
  476.         {
  477.             m_DepthStateOpaque = new RenderStateBlock
  478.             {
  479.                 depthState = new DepthState(true, CompareFunction.LessEqual),
  480.                 mask = RenderStateMask.Depth
  481.             };
  482.         }
  483.  
  484.         public void OnSceneLoad()
  485.         {
  486.             // Recreate the textures which went NULL
  487.             m_MaterialList.ForEach(material => material.Build(m_Asset));
  488.         }
  489.  
  490.         public override void Dispose()
  491.         {
  492.             UnsetRenderingFeatures();
  493.  
  494.             if (!m_ValidAPI)
  495.                 return;
  496.  
  497.             base.Dispose();
  498.  
  499.             m_DebugDisplaySettings.UnregisterDebug();
  500.  
  501.             m_LightLoop.Cleanup();
  502.  
  503.             // For debugging
  504.             MousePositionDebug.instance.Cleanup();
  505.  
  506.             DecalSystem.instance.Cleanup();
  507.  
  508.             m_MaterialList.ForEach(material => material.Cleanup());
  509.  
  510.             CoreUtils.Destroy(m_CopyStencilForNoLighting);
  511.             CoreUtils.Destroy(m_CameraMotionVectorsMaterial);
  512.  
  513.             CoreUtils.Destroy(m_DebugViewMaterialGBuffer);
  514.             CoreUtils.Destroy(m_DebugViewMaterialGBufferShadowMask);
  515.             CoreUtils.Destroy(m_DebugDisplayLatlong);
  516.             CoreUtils.Destroy(m_DebugFullScreen);
  517.             CoreUtils.Destroy(m_DebugColorPicker);
  518.             CoreUtils.Destroy(m_Blit);
  519.             CoreUtils.Destroy(m_CopyDepth);
  520.             CoreUtils.Destroy(m_ErrorMaterial);
  521.  
  522.             m_SSSBufferManager.Cleanup();
  523.             m_NormalBufferManager.Cleanup();
  524.             m_SkyManager.Cleanup();
  525.             m_VolumetricLightingSystem.Cleanup();
  526.             m_IBLFilterGGX.Cleanup();
  527.  
  528.             HDCamera.ClearAll();
  529.  
  530.             DestroyRenderTextures();
  531.  
  532. #if UNITY_EDITOR
  533.             SceneViewDrawMode.ResetDrawMode();
  534.             FrameSettings.UnRegisterDebug("Scene View");
  535. #endif
  536.         }
  537.  
  538.         void Resize(HDCamera hdCamera)
  539.         {
  540.             bool resolutionChanged = (hdCamera.actualWidth != m_CurrentWidth) || (hdCamera.actualHeight != m_CurrentHeight);
  541.  
  542.             if (resolutionChanged || m_LightLoop.NeedResize())
  543.             {
  544.                 if (m_CurrentWidth > 0 && m_CurrentHeight > 0)
  545.                     m_LightLoop.ReleaseResolutionDependentBuffers();
  546.  
  547.                 m_LightLoop.AllocResolutionDependentBuffers((int)hdCamera.screenSize.x, (int)hdCamera.screenSize.y, hdCamera.frameSettings.enableStereo);
  548.             }
  549.  
  550.             // update recorded window resolution
  551.             m_CurrentWidth = hdCamera.actualWidth;
  552.             m_CurrentHeight = hdCamera.actualHeight;
  553.         }
  554.  
  555.         public void PushGlobalParams(HDCamera hdCamera, CommandBuffer cmd, DiffusionProfileSettings sssParameters)
  556.         {
  557.             using (new ProfilingSample(cmd, "Push Global Parameters", CustomSamplerId.PushGlobalParameters.GetSampler()))
  558.             {
  559.                 // Set up UnityPerFrame CBuffer.
  560.                 m_SSSBufferManager.PushGlobalParams(hdCamera, cmd, sssParameters);
  561.  
  562.                 m_DbufferManager.PushGlobalParams(hdCamera, cmd);
  563.  
  564.                 m_VolumetricLightingSystem.PushGlobalParams(hdCamera, cmd, m_FrameCount);
  565.  
  566.                 var ssRefraction = VolumeManager.instance.stack.GetComponent<ScreenSpaceRefraction>()
  567.                     ?? ScreenSpaceRefraction.@default;
  568.                 ssRefraction.PushShaderParameters(cmd);
  569.                 var ssReflection = VolumeManager.instance.stack.GetComponent<ScreenSpaceReflection>()
  570.                     ?? ScreenSpaceReflection.@default;
  571.                 ssReflection.PushShaderParameters(cmd);
  572.  
  573.                 // Set up UnityPerView CBuffer.
  574.                 hdCamera.SetupGlobalParams(cmd, m_Time, m_LastTime, m_FrameCount);
  575.                 if (hdCamera.frameSettings.enableStereo)
  576.                     hdCamera.SetupGlobalStereoParams(cmd);
  577.  
  578.                 cmd.SetGlobalInt(HDShaderIDs._SSReflectionEnabled, hdCamera.frameSettings.enableSSR ? 1 : 0);
  579.  
  580.                 PushGlobalRTHandle(
  581.                     cmd,
  582.                     hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.DepthPyramid),
  583.                     HDShaderIDs._DepthPyramidTexture,
  584.                     HDShaderIDs._DepthPyramidSize,
  585.                     HDShaderIDs._DepthPyramidScale
  586.                 );
  587.                 PushGlobalRTHandle(
  588.                     cmd,
  589.                     hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ColorPyramid),
  590.                     HDShaderIDs._ColorPyramidTexture,
  591.                     HDShaderIDs._ColorPyramidSize,
  592.                     HDShaderIDs._ColorPyramidScale
  593.                 );
  594.                 PushGlobalRTHandle(
  595.                     cmd,
  596.                     m_VelocityBuffer,
  597.                     HDShaderIDs._CameraMotionVectorsTexture,
  598.                     HDShaderIDs._CameraMotionVectorsSize,
  599.                     HDShaderIDs._CameraMotionVectorsScale
  600.                 );
  601.  
  602.                 cmd.SetGlobalBuffer(HDShaderIDs._DebugScreenSpaceTracingData, m_DebugScreenSpaceTracingData);
  603.             }
  604.         }
  605.  
  606.         bool IsConsolePlatform()
  607.         {
  608.             return SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 ||
  609.                 SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne ||
  610.                 SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12;
  611.         }
  612.  
  613.         bool NeedDepthBufferCopy()
  614.         {
  615.             // For now we consider all console to be able to read from a bound depth buffer.
  616.             return !IsConsolePlatform();
  617.         }
  618.  
  619.         bool NeedStencilBufferCopy()
  620.         {
  621.             // Currently, Unity does not offer a way to bind the stencil buffer as a texture in a compute shader.
  622.             // Therefore, it's manually copied using a pixel shader.
  623.             return m_LightLoop.GetFeatureVariantsEnabled();
  624.         }
  625.  
  626.         RTHandleSystem.RTHandle GetDepthTexture()
  627.         {
  628.             return NeedDepthBufferCopy() ? m_CameraDepthBufferCopy : m_CameraDepthStencilBuffer;
  629.         }
  630.  
  631.         void CopyDepthBufferIfNeeded(CommandBuffer cmd)
  632.         {
  633.             using (new ProfilingSample(cmd, NeedDepthBufferCopy() ? "Copy DepthBuffer" : "Set DepthBuffer", CustomSamplerId.CopySetDepthBuffer.GetSampler()))
  634.             {
  635.                 if (NeedDepthBufferCopy())
  636.                 {
  637.                     using (new ProfilingSample(cmd, "Copy depth-stencil buffer", CustomSamplerId.CopyDepthStencilbuffer.GetSampler()))
  638.                     {
  639.                         cmd.CopyTexture(m_CameraDepthStencilBuffer, m_CameraDepthBufferCopy);
  640.                     }
  641.                 }
  642.             }
  643.         }
  644.  
  645.         public void UpdateShadowSettings(HDCamera hdCamera)
  646.         {
  647.             var shadowSettings = VolumeManager.instance.stack.GetComponent<HDShadowSettings>();
  648.  
  649.             m_ShadowSettings.maxShadowDistance = shadowSettings.maxShadowDistance;
  650.             //m_ShadowSettings.directionalLightNearPlaneOffset = commonSettings.shadowNearPlaneOffset;
  651.  
  652.             m_ShadowSettings.enabled = hdCamera.frameSettings.enableShadow;
  653.         }
  654.  
  655.         public void ConfigureForShadowMask(bool enableBakeShadowMask, CommandBuffer cmd)
  656.         {
  657.             // Globally enable (for GBuffer shader and forward lit (opaque and transparent) the keyword SHADOWS_SHADOWMASK
  658.             CoreUtils.SetKeyword(cmd, "SHADOWS_SHADOWMASK", enableBakeShadowMask);
  659.  
  660.             // Configure material to use depends on shadow mask option
  661.             m_currentRendererConfigurationBakedLighting = enableBakeShadowMask ? HDUtils.k_RendererConfigurationBakedLightingWithShadowMask : HDUtils.k_RendererConfigurationBakedLighting;
  662.             m_currentDebugViewMaterialGBuffer = enableBakeShadowMask ? m_DebugViewMaterialGBufferShadowMask : m_DebugViewMaterialGBuffer;
  663.         }
  664.  
  665.         CullResults m_CullResults;
  666.         ReflectionProbeCullResults m_ReflectionProbeCullResults;
  667.         public override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
  668.         {
  669.             if (!m_ValidAPI)
  670.                 return;
  671.  
  672.             base.Render(renderContext, cameras);
  673.             RenderPipeline.BeginFrameRendering(cameras);
  674.  
  675.             {
  676.                 // SRP.Render() can be called several times per frame.
  677.                 // Also, most Time variables do not consistently update in the Scene View.
  678.                 // This makes reliable detection of the start of the new frame VERY hard.
  679.                 // One of the exceptions is 'Time.realtimeSinceStartup'.
  680.                 // Therefore, outside of the Play Mode we update the time at 60 fps,
  681.                 // and in the Play Mode we rely on 'Time.frameCount'.
  682.                 float t = Time.realtimeSinceStartup;
  683.                 uint  c = (uint)Time.frameCount;
  684.  
  685.                 bool newFrame;
  686.  
  687.                 if (Application.isPlaying)
  688.                 {
  689.                     newFrame = m_FrameCount != c;
  690.  
  691.                     m_FrameCount = c;
  692.                 }
  693.                 else
  694.                 {
  695.                     newFrame = (t - m_Time) > 0.0166f;
  696.  
  697.                     if (newFrame) m_FrameCount++;
  698.                 }
  699.  
  700.                 if (newFrame)
  701.                 {
  702.                     HDCamera.CleanUnused();
  703.  
  704.                     // Make sure both are never 0.
  705.                     m_LastTime = (m_Time > 0) ? m_Time : t;
  706.                     m_Time  = t;
  707.                 }
  708.             }
  709.  
  710.             // TODO: Render only visible probes
  711.             var isReflection = cameras.Any(c => c.cameraType == CameraType.Reflection);
  712.             if (!isReflection)
  713.                 ReflectionSystem.RenderAllRealtimeProbes(ReflectionProbeType.PlanarReflection);
  714.  
  715.             // We first update the state of asset frame settings as they can be use by various camera
  716.             // but we keep the dirty state to correctly reset other camera that use RenderingPath.Default.
  717.             bool assetFrameSettingsIsDirty = m_Asset.frameSettingsIsDirty;
  718.             m_Asset.UpdateDirtyFrameSettings();
  719.  
  720.             foreach (var camera in cameras)
  721.             {
  722.                 if (camera == null)
  723.                     continue;
  724.  
  725.                 RenderPipeline.BeginCameraRendering(camera);
  726.  
  727.                 // First, get aggregate of frame settings base on global settings, camera frame settings and debug settings
  728.                 // Note: the SceneView camera will never have additionalCameraData
  729.                 var additionalCameraData = camera.GetComponent<HDAdditionalCameraData>();
  730.  
  731.                 // Init effective frame settings of each camera
  732.                 // Each camera have its own debug frame settings control from the debug windows
  733.                 // debug frame settings can't be aggregate with frame settings (i.e we can't aggregate forward only control for example)
  734.                 // so debug settings (when use) are the effective frame settings
  735.                 // To be able to have this behavior we init effective frame settings with serialized frame settings and copy
  736.                 // debug settings change on top of it. Each time frame settings are change in the editor, we reset all debug settings
  737.                 // to stay in sync. The loop below allow to update all frame settings correctly and is required because
  738.                 // camera can rely on default frame settings from the HDRendeRPipelineAsset
  739.                 FrameSettings srcFrameSettings;
  740.                 if (additionalCameraData)
  741.                 {
  742.                     additionalCameraData.UpdateDirtyFrameSettings(assetFrameSettingsIsDirty, m_Asset.GetFrameSettings());
  743.                     srcFrameSettings = additionalCameraData.GetFrameSettings();
  744.                 }
  745.                 else
  746.                 {
  747.                     srcFrameSettings = m_Asset.GetFrameSettings();
  748.                 }
  749.  
  750.                 FrameSettings currentFrameSettings = new FrameSettings();
  751.                 // Get the effective frame settings for this camera taking into account the global setting and camera type
  752.                 FrameSettings.InitializeFrameSettings(camera, m_Asset.GetRenderPipelineSettings(), srcFrameSettings, ref currentFrameSettings);
  753.  
  754.                 // This is the main command buffer used for the frame.
  755.                 var cmd = CommandBufferPool.Get("");
  756.  
  757.                 // Specific pass to simply display the content of the camera buffer if users have fill it themselves (like video player)
  758.                 if (additionalCameraData && additionalCameraData.renderingPath == HDAdditionalCameraData.RenderingPath.FullscreenPassthrough)
  759.                 {
  760.                     renderContext.ExecuteCommandBuffer(cmd);
  761.                     CommandBufferPool.Release(cmd);
  762.                     renderContext.Submit();
  763.                     continue;
  764.                 }
  765.  
  766.                 // Don't render reflection in Preview, it prevent them to display
  767.                 if (camera.cameraType != CameraType.Reflection && camera.cameraType != CameraType.Preview
  768.                     // Planar probes rendering is not currently supported for orthographic camera
  769.                     // Avoid rendering to prevent error log spamming
  770.                     && !camera.orthographic)
  771.                     // TODO: Render only visible probes
  772.                     ReflectionSystem.RenderAllRealtimeViewerDependentProbesFor(ReflectionProbeType.PlanarReflection, camera);
  773.  
  774.                 // Init material if needed
  775.                 // TODO: this should be move outside of the camera loop but we have no command buffer, ask details to Tim or Julien to do this
  776.                 if (!m_IBLFilterGGX.IsInitialized())
  777.                     m_IBLFilterGGX.Initialize(cmd);
  778.  
  779.                 foreach (var material in m_MaterialList)
  780.                     material.RenderInit(cmd);
  781.  
  782.                 using (new ProfilingSample(cmd, "HDRenderPipeline::Render", CustomSamplerId.HDRenderPipelineRender.GetSampler()))
  783.                 {
  784.                     // Do anything we need to do upon a new frame.
  785.                     m_LightLoop.NewFrame(currentFrameSettings);
  786.  
  787.                     // If we render a reflection view or a preview we should not display any debug information
  788.                     // This need to be call before ApplyDebugDisplaySettings()
  789.                     if (camera.cameraType == CameraType.Reflection || camera.cameraType == CameraType.Preview)
  790.                     {
  791.                         // Neutral allow to disable all debug settings
  792.                         m_CurrentDebugDisplaySettings = s_NeutralDebugDisplaySettings;
  793.                     }
  794.                     else
  795.                     {
  796.                         m_CurrentDebugDisplaySettings = m_DebugDisplaySettings;
  797.                     }
  798.  
  799.                     using (new ProfilingSample(cmd, "Volume Update", CustomSamplerId.VolumeUpdate.GetSampler()))
  800.                     {
  801.                         LayerMask layerMask = -1;
  802.                         if (additionalCameraData != null)
  803.                         {
  804.                             layerMask = additionalCameraData.volumeLayerMask;
  805.                         }
  806.                         else
  807.                         {
  808.                             // Temporary hack:
  809.                             // For scene view, by default, we use the "main" camera volume layer mask if it exists
  810.                             // Otherwise we just remove the lighting override layers in the current sky to avoid conflicts
  811.                             // This is arbitrary and should be editable in the scene view somehow.
  812.                             if (camera.cameraType == CameraType.SceneView)
  813.                             {
  814.                                 var mainCamera = Camera.main;
  815.                                 bool needFallback = true;
  816.                                 if (mainCamera != null)
  817.                                 {
  818.                                     var mainCamAdditionalData = mainCamera.GetComponent<HDAdditionalCameraData>();
  819.                                     if (mainCamAdditionalData != null)
  820.                                     {
  821.                                         layerMask = mainCamAdditionalData.volumeLayerMask;
  822.                                         needFallback = false;
  823.                                     }
  824.                                 }
  825.  
  826.                                 if (needFallback)
  827.                                 {
  828.                                     // If the override layer is "Everything", we fall-back to "Everything" for the current layer mask to avoid issues by having no current layer
  829.                                     // In practice we should never have "Everything" as an override mask as it does not make sense (a warning is issued in the UI)
  830.                                     if (m_Asset.renderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask == -1)
  831.                                         layerMask = -1;
  832.                                     else
  833.                                         layerMask = (-1 & ~m_Asset.renderPipelineSettings.lightLoopSettings.skyLightingOverrideLayerMask);
  834.                                 }
  835.                             }
  836.                         }
  837.                         VolumeManager.instance.Update(camera.transform, layerMask);
  838.                     }
  839.  
  840.                     var postProcessLayer = camera.GetComponent<PostProcessLayer>();
  841.  
  842.                     // Disable post process if we enable debug mode or if the post process layer is disabled
  843.                     if (m_CurrentDebugDisplaySettings.IsDebugDisplayRemovePostprocess() || !HDUtils.IsPostProcessingActive(postProcessLayer))
  844.                     {
  845.                         currentFrameSettings.enablePostprocess = false;
  846.                     }
  847.  
  848.                     var hdCamera = HDCamera.Get(camera);
  849.  
  850.                     if (hdCamera == null)
  851.                     {
  852.                         hdCamera = HDCamera.Create(camera, m_VolumetricLightingSystem);
  853.                     }
  854.  
  855.                     // From this point, we should only use frame settings from the camera
  856.                     hdCamera.Update(currentFrameSettings, postProcessLayer, m_VolumetricLightingSystem);
  857.  
  858.                     Resize(hdCamera);
  859.  
  860.                     ApplyDebugDisplaySettings(hdCamera, cmd);
  861.                     UpdateShadowSettings(hdCamera);
  862.                     m_SkyManager.UpdateCurrentSkySettings(hdCamera);
  863.  
  864.                     ScriptableCullingParameters cullingParams;
  865.                     if (!CullResults.GetCullingParameters(camera, hdCamera.frameSettings.enableStereo, out cullingParams))
  866.                     {
  867.                         renderContext.Submit();
  868.                         continue;
  869.                     }
  870.  
  871.                     m_LightLoop.UpdateCullingParameters(ref cullingParams);
  872.                     hdCamera.UpdateStereoDependentState(ref cullingParams);
  873.  
  874. #if UNITY_EDITOR
  875.                     // emit scene view UI
  876.                     if (camera.cameraType == CameraType.SceneView)
  877.                     {
  878.                         ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
  879.                     }
  880. #endif
  881.  
  882.                     if (hdCamera.frameSettings.enableDBuffer)
  883.                     {
  884.                         // decal system needs to be updated with current camera, it needs it to set up culling and light list generation parameters
  885.                         DecalSystem.instance.CurrentCamera = camera;
  886.                         DecalSystem.instance.BeginCull();
  887.                     }
  888.  
  889.                     ReflectionSystem.PrepareCull(camera, m_ReflectionProbeCullResults);
  890.  
  891.                     using (new ProfilingSample(cmd, "CullResults.Cull", CustomSamplerId.CullResultsCull.GetSampler()))
  892.                     {
  893.                         CullResults.Cull(ref cullingParams, renderContext, ref m_CullResults);
  894.                     }
  895.  
  896.                     m_ReflectionProbeCullResults.Cull();
  897.  
  898.                     m_DbufferManager.EnableDBUffer = false;
  899.                     using (new ProfilingSample(cmd, "DBufferPrepareDrawData", CustomSamplerId.DBufferPrepareDrawData.GetSampler()))
  900.                     {
  901.                         if (hdCamera.frameSettings.enableDBuffer)
  902.                         {
  903.                             DecalSystem.instance.EndCull();
  904.                             m_DbufferManager.EnableDBUffer = true;              // mesh decals are renderers managed by c++ runtime and we have no way to query if any are visible, so set to true
  905.                             DecalSystem.instance.UpdateCachedMaterialData();    // textures, alpha or fade distances could've changed
  906.                             DecalSystem.instance.CreateDrawData();              // prepare data is separate from draw
  907.                             DecalSystem.instance.UpdateTextureAtlas(cmd);       // as this is only used for transparent pass, would've been nice not to have to do this if no transparent renderers are visible, needs to happen after CreateDrawData
  908.                         }
  909.                     }
  910.                     renderContext.SetupCameraProperties(camera, hdCamera.frameSettings.enableStereo);
  911.  
  912.                     PushGlobalParams(hdCamera, cmd, diffusionProfileSettings);
  913.  
  914.                     // TODO: Find a correct place to bind these material textures
  915.                     // We have to bind the material specific global parameters in this mode
  916.                     m_MaterialList.ForEach(material => material.Bind());
  917.  
  918.                     // Frustum cull density volumes on the CPU. Can be performed as soon as the camera is set up.
  919.                     DensityVolumeList densityVolumes = m_VolumetricLightingSystem.PrepareVisibleDensityVolumeList(hdCamera, cmd, m_Time);
  920.  
  921.                     // Note: Legacy Unity behave like this for ShadowMask
  922.                     // When you select ShadowMask in Lighting panel it recompile shaders on the fly with the SHADOW_MASK keyword.
  923.                     // However there is no C# function that we can query to know what mode have been select in Lighting Panel and it will be wrong anyway. Lighting Panel setup what will be the next bake mode. But until light is bake, it is wrong.
  924.                     // Currently to know if you need shadow mask you need to go through all visible lights (of CullResult), check the LightBakingOutput struct and look at lightmapBakeType/mixedLightingMode. If one light have shadow mask bake mode, then you need shadow mask features (i.e extra Gbuffer).
  925.                     // It mean that when we build a standalone player, if we detect a light with bake shadow mask, we generate all shader variant (with and without shadow mask) and at runtime, when a bake shadow mask light is visible, we dynamically allocate an extra GBuffer and switch the shader.
  926.                     // So the first thing to do is to go through all the light: PrepareLightsForGPU
  927.                     bool enableBakeShadowMask;
  928.                     using (new ProfilingSample(cmd, "TP_PrepareLightsForGPU", CustomSamplerId.TPPrepareLightsForGPU.GetSampler()))
  929.                     {
  930.                         enableBakeShadowMask = m_LightLoop.PrepareLightsForGPU(cmd, hdCamera, m_ShadowSettings, m_CullResults, m_ReflectionProbeCullResults, densityVolumes);
  931.                     }
  932.                     ConfigureForShadowMask(enableBakeShadowMask, cmd);
  933.  
  934.                     StartStereoRendering(renderContext, hdCamera);
  935.  
  936.                     ClearBuffers(hdCamera, cmd);
  937.  
  938.                     // TODO: Add stereo occlusion mask
  939.                     RenderDepthPrepass(m_CullResults, hdCamera, renderContext, cmd);
  940.  
  941.                     // This will bind the depth buffer if needed for DBuffer)
  942.                     RenderDBuffer(hdCamera, cmd, renderContext, m_CullResults);
  943.  
  944.                     RenderGBuffer(m_CullResults, hdCamera, enableBakeShadowMask, renderContext, cmd);
  945.  
  946.                     // We can now bind the normal buffer to be use by any effect
  947.                     m_NormalBufferManager.BindNormalBuffers(cmd);
  948.  
  949.                     // In both forward and deferred, everything opaque should have been rendered at this point so we can safely copy the depth buffer for later processing.
  950.                     CopyDepthBufferIfNeeded(cmd);
  951.                     RenderDepthPyramid(hdCamera, cmd, renderContext, FullScreenDebugMode.DepthPyramid);
  952.  
  953.                     // TODO: In the future we will render object velocity at the same time as depth prepass (we need C++ modification for this)
  954.                     // Once the C++ change is here we will first render all object without motion vector then motion vector object
  955.                     // We can't currently render object velocity after depth prepass because if there is no depth prepass we can have motion vector write that should have been rejected
  956.                     RenderObjectsVelocity(m_CullResults, hdCamera, renderContext, cmd);
  957.                     RenderCameraVelocity(m_CullResults, hdCamera, renderContext, cmd);
  958.  
  959.                     // Depth texture is now ready, bind it (Depth buffer could have been bind before if DBuffer is enable)
  960.                     cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, GetDepthTexture());
  961.  
  962.                     // Caution: We require sun light here as some skies use the sun light to render, it means that UpdateSkyEnvironment must be called after PrepareLightsForGPU.
  963.                     // TODO: Try to arrange code so we can trigger this call earlier and use async compute here to run sky convolution during other passes (once we move convolution shader to compute).
  964.                     UpdateSkyEnvironment(hdCamera, cmd);
  965.  
  966.                     StopStereoRendering(renderContext, hdCamera);
  967.  
  968.                     if (m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled())
  969.                     {
  970.                         RenderDebugViewMaterial(m_CullResults, hdCamera, renderContext, cmd);
  971.  
  972.                         PushColorPickerDebugTexture(cmd, m_CameraColorBuffer, hdCamera);
  973.                     }
  974.                     else
  975.                     {
  976.                         StartStereoRendering(renderContext, hdCamera);
  977.  
  978.                         using (new ProfilingSample(cmd, "Render SSAO", CustomSamplerId.RenderSSAO.GetSampler()))
  979.                         {
  980.                             // TODO: Everything here (SSAO, Shadow, Build light list, deferred shadow, material and light classification can be parallelize with Async compute)
  981.                             RenderSSAO(cmd, hdCamera, renderContext, postProcessLayer);
  982.                         }
  983.  
  984.                         // Clear and copy the stencil texture needs to be moved to before we invoke the async light list build,
  985.                         // otherwise the async compute queue can end up using that texture before the graphics queue is done with it.
  986.                         // TODO: Move this code inside LightLoop
  987.                         if (m_LightLoop.GetFeatureVariantsEnabled())
  988.                         {
  989.                             // For material classification we use compute shader and so can't read into the stencil, so prepare it.
  990.                             using (new ProfilingSample(cmd, "Clear and copy stencil texture", CustomSamplerId.ClearAndCopyStencilTexture.GetSampler()))
  991.                             {
  992.                                 HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraStencilBufferCopy, ClearFlag.Color, CoreUtils.clearColorAllBlack);
  993.  
  994.                                 // In the material classification shader we will simply test is we are no lighting
  995.                                 // Use ShaderPassID 1 => "Pass 1 - Write 1 if value different from stencilRef to output"
  996.                                 HDUtils.DrawFullScreen(cmd, hdCamera, m_CopyStencilForNoLighting, m_CameraStencilBufferCopy, m_CameraDepthStencilBuffer, null, 1);
  997.                             }
  998.                         }
  999.  
  1000.                         StopStereoRendering(renderContext, hdCamera);
  1001.  
  1002.                         GPUFence buildGPULightListsCompleteFence = new GPUFence();
  1003.                         if (hdCamera.frameSettings.enableAsyncCompute)
  1004.                         {
  1005.                             GPUFence startFence = cmd.CreateGPUFence();
  1006.                             renderContext.ExecuteCommandBuffer(cmd);
  1007.                             cmd.Clear();
  1008.  
  1009.                             buildGPULightListsCompleteFence = m_LightLoop.BuildGPULightListsAsyncBegin(hdCamera, renderContext, m_CameraDepthStencilBuffer, m_CameraStencilBufferCopy, startFence, m_SkyManager.IsLightingSkyValid());
  1010.                         }
  1011.  
  1012.                         using (new ProfilingSample(cmd, "Render shadows", CustomSamplerId.RenderShadows.GetSampler()))
  1013.                         {
  1014.                             // This call overwrites camera properties passed to the shader system.
  1015.                             m_LightLoop.RenderShadows(renderContext, cmd, m_CullResults);
  1016.  
  1017.                             // Overwrite camera properties set during the shadow pass with the original camera properties.
  1018.                             renderContext.SetupCameraProperties(camera, hdCamera.frameSettings.enableStereo);
  1019.                             hdCamera.SetupGlobalParams(cmd, m_Time, m_LastTime, m_FrameCount);
  1020.                             if (hdCamera.frameSettings.enableStereo)
  1021.                                 hdCamera.SetupGlobalStereoParams(cmd);
  1022.                         }
  1023.  
  1024.                         using (new ProfilingSample(cmd, "Deferred directional shadows", CustomSamplerId.RenderDeferredDirectionalShadow.GetSampler()))
  1025.                         {
  1026.                             // When debug is enabled we need to clear otherwise we may see non-shadows areas with stale values.
  1027.                             if (m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.DeferredShadows)
  1028.                             {
  1029.                                 HDUtils.SetRenderTarget(cmd, hdCamera, m_DeferredShadowBuffer, ClearFlag.Color, CoreUtils.clearColorAllBlack);
  1030.                             }
  1031.  
  1032.                             m_LightLoop.RenderDeferredDirectionalShadow(hdCamera, m_DeferredShadowBuffer, GetDepthTexture(), cmd);
  1033.                             PushFullScreenDebugTexture(hdCamera, cmd, m_DeferredShadowBuffer, FullScreenDebugMode.DeferredShadows);
  1034.                         }
  1035.  
  1036.                         if (hdCamera.frameSettings.enableAsyncCompute)
  1037.                         {
  1038.                             m_LightLoop.BuildGPULightListAsyncEnd(hdCamera, cmd, buildGPULightListsCompleteFence);
  1039.                         }
  1040.                         else
  1041.                         {
  1042.                             using (new ProfilingSample(cmd, "Build Light list", CustomSamplerId.BuildLightList.GetSampler()))
  1043.                             {
  1044.                                 m_LightLoop.BuildGPULightLists(hdCamera, cmd, m_CameraDepthStencilBuffer, m_CameraStencilBufferCopy, m_SkyManager.IsLightingSkyValid());
  1045.                             }
  1046.                         }
  1047.  
  1048.                         {
  1049.                             // Set fog parameters for volumetric lighting.
  1050.                             var visualEnv = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();
  1051.                             visualEnv.PushFogShaderParameters(hdCamera, cmd);
  1052.                         }
  1053.  
  1054.                         // Perform the voxelization step which fills the density 3D texture.
  1055.                         // Requires the clustered lighting data structure to be built, and can run async.
  1056.                         m_VolumetricLightingSystem.VolumeVoxelizationPass(hdCamera, cmd, m_FrameCount, densityVolumes);
  1057.  
  1058.                         // Render the volumetric lighting.
  1059.                         // The pass requires the volume properties, the light list and the shadows, and can run async.
  1060.                         m_VolumetricLightingSystem.VolumetricLightingPass(hdCamera, cmd, m_FrameCount);
  1061.  
  1062.                         RenderDeferredLighting(hdCamera, cmd);
  1063.  
  1064.                         // Might float this higher if we enable stereo w/ deferred
  1065.                         StartStereoRendering(renderContext, hdCamera);
  1066.  
  1067.                         RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.Opaque);
  1068.  
  1069.                         // SSS pass here handle both SSS material from deferred and forward
  1070.                         m_SSSBufferManager.SubsurfaceScatteringPass(hdCamera, cmd, diffusionProfileSettings,
  1071.                             m_CameraColorBuffer, m_CameraSssDiffuseLightingBuffer, m_CameraDepthStencilBuffer, GetDepthTexture());
  1072.  
  1073.                         RenderSky(hdCamera, cmd);
  1074.  
  1075.                         // Render pre refraction objects
  1076.                         RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.PreRefraction);
  1077.  
  1078.                         RenderColorPyramid(hdCamera, cmd, renderContext, true);
  1079.  
  1080.                         // Render all type of transparent forward (unlit, lit, complex (hair...)) to keep the sorting between transparent objects.
  1081.                         RenderForward(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.Transparent);
  1082.  
  1083.                         // Render All forward error
  1084.                         RenderForwardError(m_CullResults, hdCamera, renderContext, cmd);
  1085.  
  1086.                         // Fill depth buffer to reduce artifact for transparent object during postprocess
  1087.                         RenderTransparentDepthPostpass(m_CullResults, hdCamera, renderContext, cmd, ForwardPass.Transparent);
  1088.  
  1089.                         RenderColorPyramid(hdCamera, cmd, renderContext, false);
  1090.  
  1091.                         AccumulateDistortion(m_CullResults, hdCamera, renderContext, cmd);
  1092.                         RenderDistortion(hdCamera, cmd, m_Asset.renderPipelineResources);
  1093.  
  1094.                         StopStereoRendering(renderContext, hdCamera);
  1095.  
  1096.                         PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.NanTracker);
  1097.                         PushColorPickerDebugTexture(hdCamera, cmd, m_CameraColorBuffer);
  1098.  
  1099.                         // The final pass either postprocess of Blit will flip the screen (as it is reverse by default due to Unity openGL legacy)
  1100.                         // Postprocess system (that doesn't use cmd.Blit) handle it with configuration (and do not flip in SceneView) or it is automatically done in Blit
  1101.  
  1102.                         StartStereoRendering(renderContext, hdCamera);
  1103.  
  1104.                         // Final blit
  1105.                         if (hdCamera.frameSettings.enablePostprocess)
  1106.                         {
  1107.                             RenderPostProcess(hdCamera, cmd, postProcessLayer);
  1108.                         }
  1109.                         else
  1110.                         {
  1111.                             using (new ProfilingSample(cmd, "Blit to final RT", CustomSamplerId.BlitToFinalRT.GetSampler()))
  1112.                             {
  1113.                                 // This Blit will flip the screen on anything other than openGL
  1114.                                 HDUtils.BlitCameraTexture(cmd, hdCamera, m_CameraColorBuffer, BuiltinRenderTextureType.CameraTarget);
  1115.                             }
  1116.                         }
  1117.  
  1118.                         StopStereoRendering(renderContext, hdCamera);
  1119.                         // Pushes to XR headset and/or display mirror
  1120.                         if (hdCamera.frameSettings.enableStereo)
  1121.                             renderContext.StereoEndRender(hdCamera.camera);
  1122.                     }
  1123.  
  1124.  
  1125. #if UNITY_EDITOR
  1126.                     // During rendering we use our own depth buffer instead of the one provided by the scene view (because we need to be able to control its life cycle)
  1127.                     // In order for scene view gizmos/icons etc to be depth test correctly, we need to copy the content of our own depth buffer into the scene view depth buffer.
  1128.                     // On subtlety here is that our buffer can be bigger than the camera one so we need to copy only the corresponding portion
  1129.                     // (it's handled automatically by the copy shader because it uses a load in pixel coordinates based on the target).
  1130.                     // This copy will also have the effect of re-binding this depth buffer correctly for subsequent editor rendering.
  1131.  
  1132.                     // NOTE: This needs to be done before the call to RenderDebug because debug overlays need to update the depth for the scene view as well.
  1133.                     // Make sure RenderDebug does not change the current Render Target
  1134.                     if (camera.cameraType == CameraType.SceneView)
  1135.                     {
  1136.                         using (new ProfilingSample(cmd, "Copy Depth For SceneView", CustomSamplerId.CopyDepthForSceneView.GetSampler()))
  1137.                         {
  1138.                             m_CopyDepth.SetTexture(HDShaderIDs._InputDepth, m_CameraDepthStencilBuffer);
  1139.                             cmd.Blit(null, BuiltinRenderTextureType.CameraTarget, m_CopyDepth);
  1140.                         }
  1141.                     }
  1142. #endif
  1143.                     PushFullScreenDebugTexture(hdCamera, cmd, m_CameraColorBuffer, FullScreenDebugMode.ScreenSpaceTracing);
  1144.                     // Caution: RenderDebug need to take into account that we have flip the screen (so anything capture before the flip will be flipped)
  1145.                     RenderDebug(hdCamera, cmd);
  1146.  
  1147. #if UNITY_EDITOR
  1148.                     // We need to make sure the viewport is correctly set for the editor rendering. It might have been changed by debug overlay rendering just before.
  1149.                     cmd.SetViewport(new Rect(0.0f, 0.0f, hdCamera.actualWidth, hdCamera.actualHeight));
  1150. #endif
  1151.                 }
  1152.  
  1153.                 // Caution: ExecuteCommandBuffer must be outside of the profiling bracket
  1154.                 renderContext.ExecuteCommandBuffer(cmd);
  1155.  
  1156.                 CommandBufferPool.Release(cmd);
  1157.                 renderContext.Submit();
  1158.  
  1159.                 if (m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.ScreenSpaceTracing)
  1160.                 {
  1161.                     m_DebugScreenSpaceTracingData.GetData(m_DebugScreenSpaceTracingDataArray);
  1162.                     var data = m_DebugScreenSpaceTracingDataArray[0];
  1163.                     m_CurrentDebugDisplaySettings.screenSpaceTracingDebugData = data;
  1164.  
  1165.                     // Assign -1 in tracing model to notifiy we took the data.
  1166.                     // When debugging in forward, we want only the first time the pixel is drawn
  1167.                     data.tracingModel = (Lit.ProjectionModel)(-1);
  1168.                     m_DebugScreenSpaceTracingDataArray[0] = data;
  1169.                     m_DebugScreenSpaceTracingData.SetData(m_DebugScreenSpaceTracingDataArray);
  1170.                 }
  1171.  
  1172.             } // For each camera
  1173.         }
  1174.  
  1175.         void RenderOpaqueRenderList(CullResults cull,
  1176.             HDCamera hdCamera,
  1177.             ScriptableRenderContext renderContext,
  1178.             CommandBuffer cmd,
  1179.             ShaderPassName passName,
  1180.             RendererConfiguration rendererConfiguration = 0,
  1181.             RenderQueueRange? inRenderQueueRange = null,
  1182.             RenderStateBlock? stateBlock = null,
  1183.             Material overrideMaterial = null)
  1184.         {
  1185.             m_SinglePassName[0] = passName;
  1186.             RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_SinglePassName, rendererConfiguration, inRenderQueueRange, stateBlock, overrideMaterial);
  1187.         }
  1188.  
  1189.         void RenderOpaqueRenderList(CullResults cull,
  1190.             HDCamera hdCamera,
  1191.             ScriptableRenderContext renderContext,
  1192.             CommandBuffer cmd,
  1193.             ShaderPassName[] passNames,
  1194.             RendererConfiguration rendererConfiguration = 0,
  1195.             RenderQueueRange? inRenderQueueRange = null,
  1196.             RenderStateBlock? stateBlock = null,
  1197.             Material overrideMaterial = null)
  1198.         {
  1199.             if (!hdCamera.frameSettings.enableOpaqueObjects)
  1200.                 return;
  1201.  
  1202.             // This is done here because DrawRenderers API lives outside command buffers so we need to make call this before doing any DrawRenders
  1203.             renderContext.ExecuteCommandBuffer(cmd);
  1204.             cmd.Clear();
  1205.  
  1206.             var drawSettings = new DrawRendererSettings(hdCamera.camera, HDShaderPassNames.s_EmptyName)
  1207.             {
  1208.                 rendererConfiguration = rendererConfiguration,
  1209.                 sorting = { flags = SortFlags.CommonOpaque }
  1210.             };
  1211.  
  1212.             for (int i = 0; i < passNames.Length; ++i)
  1213.             {
  1214.                 drawSettings.SetShaderPassName(i, passNames[i]);
  1215.             }
  1216.  
  1217.             if (overrideMaterial != null)
  1218.                 drawSettings.SetOverrideMaterial(overrideMaterial, 0);
  1219.  
  1220.             var filterSettings = new FilterRenderersSettings(true)
  1221.             {
  1222.                 renderQueueRange = inRenderQueueRange == null ? HDRenderQueue.k_RenderQueue_AllOpaque : inRenderQueueRange.Value
  1223.             };
  1224.  
  1225.             if (stateBlock == null)
  1226.                 renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
  1227.             else
  1228.                 renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, stateBlock.Value);
  1229.         }
  1230.  
  1231.         void RenderTransparentRenderList(CullResults cull,
  1232.             HDCamera hdCamera,
  1233.             ScriptableRenderContext renderContext,
  1234.             CommandBuffer cmd,
  1235.             ShaderPassName passName,
  1236.             RendererConfiguration rendererConfiguration = 0,
  1237.             RenderQueueRange? inRenderQueueRange = null,
  1238.             RenderStateBlock? stateBlock = null,
  1239.             Material overrideMaterial = null)
  1240.         {
  1241.             m_SinglePassName[0] = passName;
  1242.             RenderTransparentRenderList(cull, hdCamera, renderContext, cmd, m_SinglePassName,
  1243.                 rendererConfiguration, inRenderQueueRange, stateBlock, overrideMaterial);
  1244.         }
  1245.  
  1246.         void RenderTransparentRenderList(CullResults cull,
  1247.             HDCamera hdCamera,
  1248.             ScriptableRenderContext renderContext,
  1249.             CommandBuffer cmd,
  1250.             ShaderPassName[] passNames,
  1251.             RendererConfiguration rendererConfiguration = 0,
  1252.             RenderQueueRange? inRenderQueueRange = null,
  1253.             RenderStateBlock? stateBlock = null,
  1254.             Material overrideMaterial = null
  1255.             )
  1256.         {
  1257.             if (!hdCamera.frameSettings.enableTransparentObjects)
  1258.                 return;
  1259.  
  1260.             // This is done here because DrawRenderers API lives outside command buffers so we need to make call this before doing any DrawRenders
  1261.             renderContext.ExecuteCommandBuffer(cmd);
  1262.             cmd.Clear();
  1263.  
  1264.             var drawSettings = new DrawRendererSettings(hdCamera.camera, HDShaderPassNames.s_EmptyName)
  1265.             {
  1266.                 rendererConfiguration = rendererConfiguration,
  1267.                 sorting = { flags = SortFlags.CommonTransparent }
  1268.             };
  1269.  
  1270.             for (int i = 0; i < passNames.Length; ++i)
  1271.             {
  1272.                 drawSettings.SetShaderPassName(i, passNames[i]);
  1273.             }
  1274.  
  1275.             if (overrideMaterial != null)
  1276.                 drawSettings.SetOverrideMaterial(overrideMaterial, 0);
  1277.  
  1278.             var filterSettings = new FilterRenderersSettings(true)
  1279.             {
  1280.                 renderQueueRange = inRenderQueueRange == null ? HDRenderQueue.k_RenderQueue_AllTransparent : inRenderQueueRange.Value
  1281.             };
  1282.  
  1283.             if (stateBlock == null)
  1284.                 renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings);
  1285.             else
  1286.                 renderContext.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings, stateBlock.Value);
  1287.         }
  1288.  
  1289.         void AccumulateDistortion(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
  1290.         {
  1291.             if (!hdCamera.frameSettings.enableDistortion)
  1292.                 return;
  1293.  
  1294.             using (new ProfilingSample(cmd, "Distortion", CustomSamplerId.Distortion.GetSampler()))
  1295.             {
  1296.                 HDUtils.SetRenderTarget(cmd, hdCamera, m_DistortionBuffer, m_CameraDepthStencilBuffer, ClearFlag.Color, Color.clear);
  1297.  
  1298.                 // Only transparent object can render distortion vectors
  1299.                 RenderTransparentRenderList(cullResults, hdCamera, renderContext, cmd, HDShaderPassNames.s_DistortionVectorsName);
  1300.             }
  1301.         }
  1302.  
  1303.         void RenderDistortion(HDCamera hdCamera, CommandBuffer cmd, RenderPipelineResources resources)
  1304.         {
  1305.             if (!hdCamera.frameSettings.enableDistortion)
  1306.                 return;
  1307.  
  1308.             using (new ProfilingSample(cmd, "ApplyDistortion", CustomSamplerId.ApplyDistortion.GetSampler()))
  1309.             {
  1310.                 var colorPyramidRT = hdCamera.GetPreviousFrameRT((int)HDCameraFrameHistoryType.ColorPyramid);
  1311.                 var pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera, colorPyramidRT);
  1312.  
  1313.                 // Need to account for the fact that the gaussian pyramid is actually rendered inside the camera viewport in a square texture so we mutiply by the PyramidToScreen scale
  1314.                 var size = new Vector4(hdCamera.screenSize.x, hdCamera.screenSize.y, pyramidScale.x / hdCamera.screenSize.x, pyramidScale.y / hdCamera.screenSize.y);
  1315.                 uint x, y, z;
  1316.                 m_applyDistortionCS.GetKernelThreadGroupSizes(m_applyDistortionKernel, out x, out y, out z);
  1317.                 cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._DistortionTexture, m_DistortionBuffer);
  1318.                 cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._ColorPyramidTexture, colorPyramidRT);
  1319.                 cmd.SetComputeTextureParam(m_applyDistortionCS, m_applyDistortionKernel, HDShaderIDs._CameraColorTexture, m_CameraColorBuffer);
  1320.                 cmd.SetComputeVectorParam(m_applyDistortionCS, HDShaderIDs._Size, size);
  1321.  
  1322.                 cmd.DispatchCompute(m_applyDistortionCS, m_applyDistortionKernel, Mathf.CeilToInt(size.x / x), Mathf.CeilToInt(size.y / y), 1);
  1323.             }
  1324.         }
  1325.  
  1326.         // RenderDepthPrepass render both opaque and opaque alpha tested based on engine configuration.
  1327.         // Forward only renderer: We always render everything
  1328.         // Deferred renderer: We always render depth prepass for alpha tested (optimization), other object are render based on engine configuration.
  1329.         // Forward opaque with deferred renderer (DepthForwardOnly pass): We always render everything
  1330.         void RenderDepthPrepass(CullResults cull, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
  1331.         {
  1332.             // In case of deferred renderer, we can have forward opaque material. These materials need to be render in the depth buffer to correctly build the light list.
  1333.             // And they will tag the stencil to not be lit during the deferred lighting pass.
  1334.  
  1335.             // Guidelines: In deferred by default there is no opaque in forward. However it is possible to force an opaque material to render in forward
  1336.             // by using the pass "ForwardOnly". In this case the .shader should not have "Forward" but only a "ForwardOnly" pass.
  1337.             // It must also have a "DepthForwardOnly" and no "DepthOnly" pass as forward material (either deferred or forward only rendering) have always a depth pass.
  1338.             // If a forward material have no depth prepass, then lighting can be incorrect (deferred sahdowing, SSAO), this may be acceptable depends on usage
  1339.  
  1340.             // Whatever the configuration we always render first the opaque object as opaque alpha tested are more costly to render and could be reject by early-z
  1341.             // (but not Hi-z as it is disable with clip instruction). This is handled automatically with the RenderQueue value (OpaqueAlphaTested have a different value and thus are sorted after Opaque)
  1342.  
  1343.             // Forward material always output normal buffer (unless they don't participate to shading)
  1344.             // Deferred material never output normal buffer
  1345.  
  1346.             // Note: Unlit object use a ForwardOnly pass and don't have normal, they will write 0 in the normal buffer. This should be safe
  1347.             // as they will not use the result of lighting anyway. However take care of effect that will try to filter normal buffer.
  1348.             // TODO: maybe we can use a stencil to tag when Forward unlit touch normal buffer
  1349.             if (hdCamera.frameSettings.enableForwardRenderingOnly)
  1350.             {
  1351.                 using (new ProfilingSample(cmd, "Depth Prepass (forward)", CustomSamplerId.DepthPrepass.GetSampler()))
  1352.                 {
  1353.                     cmd.EnableShaderKeyword("WRITE_NORMAL_BUFFER");
  1354.  
  1355.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
  1356.  
  1357.                     // Full forward: Output normal buffer for both forward and forwardOnly
  1358.                     RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthOnlyAndDepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
  1359.                 }
  1360.             }
  1361.             // If we enable DBuffer, we need a full depth prepass
  1362.             else if (hdCamera.frameSettings.enableDepthPrepassWithDeferredRendering || m_DbufferManager.EnableDBUffer)
  1363.             {
  1364.                 using (new ProfilingSample(cmd, m_DbufferManager.EnableDBUffer ? "Depth Prepass (deferred) force by DBuffer" : "Depth Prepass (deferred)", CustomSamplerId.DepthPrepass.GetSampler()))
  1365.                 {
  1366.                     cmd.DisableShaderKeyword("WRITE_NORMAL_BUFFER"); // Note: This only disable the output of normal buffer for Lit shader, not the other shader that don't use multicompile
  1367.  
  1368.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
  1369.  
  1370.                     // First deferred material
  1371.                     RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
  1372.  
  1373.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
  1374.  
  1375.                     // Then forward only material that output normal buffer
  1376.                     RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
  1377.                 }
  1378.             }
  1379.             else // Deferred with partial depth prepass
  1380.             {
  1381.                 using (new ProfilingSample(cmd, "Depth Prepass (deferred incomplete)", CustomSamplerId.DepthPrepass.GetSampler()))
  1382.                 {
  1383.                     cmd.DisableShaderKeyword("WRITE_NORMAL_BUFFER");
  1384.  
  1385.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
  1386.  
  1387.                     // First deferred alpha tested materials. Alpha tested object have always a prepass even if enableDepthPrepassWithDeferredRendering is disabled
  1388.                     var renderQueueRange = new RenderQueueRange { min = (int)RenderQueue.AlphaTest, max = (int)RenderQueue.GeometryLast - 1 };
  1389.                     RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthOnlyPassNames, 0, renderQueueRange);
  1390.  
  1391.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_NormalBufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer);
  1392.  
  1393.                     // Then forward only material that output normal buffer
  1394.                     RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_DepthForwardOnlyPassNames, 0, HDRenderQueue.k_RenderQueue_AllOpaque);
  1395.                 }
  1396.             }
  1397.  
  1398.             if (hdCamera.frameSettings.enableTransparentPrepass)
  1399.             {
  1400.                 // Render transparent depth prepass after opaque one
  1401.                 using (new ProfilingSample(cmd, "Transparent Depth Prepass", CustomSamplerId.TransparentDepthPrepass.GetSampler()))
  1402.                 {
  1403.                     RenderTransparentRenderList(cull, hdCamera, renderContext, cmd, m_TransparentDepthPrepassNames);
  1404.                 }
  1405.             }
  1406.         }
  1407.  
  1408.         // RenderGBuffer do the gbuffer pass. This is solely call with deferred. If we use a depth prepass, then the depth prepass will perform the alpha testing for opaque apha tested and we don't need to do it anymore
  1409.         // during Gbuffer pass. This is handled in the shader and the depth test (equal and no depth write) is done here.
  1410.         void RenderGBuffer(CullResults cull, HDCamera hdCamera, bool enableShadowMask, ScriptableRenderContext renderContext, CommandBuffer cmd)
  1411.         {
  1412.             if (hdCamera.frameSettings.enableForwardRenderingOnly)
  1413.                 return;
  1414.  
  1415.             using (new ProfilingSample(cmd, m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ? "GBuffer Debug" : "GBuffer", CustomSamplerId.GBuffer.GetSampler()))
  1416.             {
  1417.                 // setup GBuffer for rendering
  1418.                 HDUtils.SetRenderTarget(cmd, hdCamera, m_GbufferManager.GetBuffersRTI(enableShadowMask), m_CameraDepthStencilBuffer);
  1419.                 RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, HDShaderPassNames.s_GBufferName, m_currentRendererConfigurationBakedLighting, HDRenderQueue.k_RenderQueue_AllOpaque);
  1420.  
  1421.                 m_GbufferManager.BindBufferAsTextures(cmd);
  1422.             }
  1423.         }
  1424.  
  1425.         void RenderDBuffer(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, CullResults cullResults)
  1426.         {
  1427.             if (!hdCamera.frameSettings.enableDBuffer)
  1428.                 return;
  1429.  
  1430.             using (new ProfilingSample(cmd, "DBufferRender", CustomSamplerId.DBufferRender.GetSampler()))
  1431.             {
  1432.                 // We need to copy depth buffer texture if we want to bind it at this stage
  1433.                 CopyDepthBufferIfNeeded(cmd);
  1434.  
  1435.                 // Depth texture is now ready, bind it.
  1436.                 cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, GetDepthTexture());
  1437.                 m_DbufferManager.ClearTargets(cmd, hdCamera);
  1438.                 HDUtils.SetRenderTarget(cmd, hdCamera, m_DbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer); // do not clear anymore
  1439.                 m_DbufferManager.SetHTile(m_DbufferManager.bufferCount, cmd);
  1440.                 renderContext.ExecuteCommandBuffer(cmd);
  1441.                 cmd.Clear();
  1442.  
  1443.                 DrawRendererSettings drawSettings = new DrawRendererSettings(hdCamera.camera, HDShaderPassNames.s_EmptyName)
  1444.                 {
  1445.                     rendererConfiguration = 0,
  1446.                     sorting = { flags = SortFlags.CommonOpaque }
  1447.                 };
  1448.                 drawSettings.SetShaderPassName(0, HDShaderPassNames.s_MeshDecalsName);
  1449.                 FilterRenderersSettings filterRenderersSettings = new FilterRenderersSettings(true)
  1450.                 {
  1451.                     renderQueueRange = HDRenderQueue.k_RenderQueue_AllOpaque
  1452.                 };
  1453.                 renderContext.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, filterRenderersSettings);
  1454.  
  1455.                 DecalSystem.instance.RenderIntoDBuffer(cmd);
  1456.                 m_DbufferManager.UnSetHTile(cmd);
  1457.                 m_DbufferManager.SetHTileTexture(cmd);  // mask per 8x8 tile used for optimization when looking up dbuffer values
  1458.             }
  1459.         }
  1460.  
  1461.         void RenderDebugViewMaterial(CullResults cull, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
  1462.         {
  1463.             using (new ProfilingSample(cmd, "DisplayDebug ViewMaterial", CustomSamplerId.DisplayDebugViewMaterial.GetSampler()))
  1464.             {
  1465.                 if (m_CurrentDebugDisplaySettings.materialDebugSettings.IsDebugGBufferEnabled() && !hdCamera.frameSettings.enableForwardRenderingOnly)
  1466.                 {
  1467.                     using (new ProfilingSample(cmd, "DebugViewMaterialGBuffer", CustomSamplerId.DebugViewMaterialGBuffer.GetSampler()))
  1468.                     {
  1469.                         HDUtils.DrawFullScreen(cmd, hdCamera, m_currentDebugViewMaterialGBuffer, m_CameraColorBuffer);
  1470.                     }
  1471.                 }
  1472.                 else
  1473.                 {
  1474.                     // When rendering debug material we shouldn't rely on a depth prepass for optimizing the alpha clip test. As it is control on the material inspector side
  1475.                     // we must override the state here.
  1476.  
  1477.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer, ClearFlag.All, CoreUtils.clearColorAllBlack);
  1478.                     // Render Opaque forward
  1479.                     RenderOpaqueRenderList(cull, hdCamera, renderContext, cmd, m_AllForwardOpaquePassNames, m_currentRendererConfigurationBakedLighting, stateBlock: m_DepthStateOpaque);
  1480.  
  1481.                     // Render forward transparent
  1482.                     RenderTransparentRenderList(cull, hdCamera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, stateBlock: m_DepthStateOpaque);
  1483.                 }
  1484.             }
  1485.  
  1486.             // Last blit
  1487.             {
  1488.                 using (new ProfilingSample(cmd, "Blit DebugView Material Debug", CustomSamplerId.BlitDebugViewMaterialDebug.GetSampler()))
  1489.                 {
  1490.                     // This Blit will flip the screen anything other than openGL
  1491.                     HDUtils.BlitCameraTexture(cmd, hdCamera, m_CameraColorBuffer, BuiltinRenderTextureType.CameraTarget);
  1492.                 }
  1493.             }
  1494.         }
  1495.  
  1496.         void RenderSSAO(CommandBuffer cmd, HDCamera hdCamera, ScriptableRenderContext renderContext, PostProcessLayer postProcessLayer)
  1497.         {
  1498.             var camera = hdCamera.camera;
  1499.  
  1500.             // Apply SSAO from PostProcessLayer
  1501.             if (hdCamera.frameSettings.enableSSAO && postProcessLayer != null && postProcessLayer.enabled)
  1502.             {
  1503.                 var settings = postProcessLayer.GetSettings<AmbientOcclusion>();
  1504.  
  1505.                 if (settings.IsEnabledAndSupported(null))
  1506.                 {
  1507.                     postProcessLayer.BakeMSVOMap(cmd, camera, m_AmbientOcclusionBuffer, GetDepthTexture(), true);
  1508.  
  1509.                     cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, m_AmbientOcclusionBuffer);
  1510.                     cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, new Vector4(settings.color.value.r, settings.color.value.g, settings.color.value.b, settings.directLightingStrength.value));
  1511.                     PushFullScreenDebugTexture(hdCamera, cmd, m_AmbientOcclusionBuffer, FullScreenDebugMode.SSAO);
  1512.                     return;
  1513.                 }
  1514.             }
  1515.  
  1516.             // No AO applied - neutral is black, see the comment in the shaders
  1517.             cmd.SetGlobalTexture(HDShaderIDs._AmbientOcclusionTexture, RuntimeUtilities.blackTexture);
  1518.             cmd.SetGlobalVector(HDShaderIDs._AmbientOcclusionParam, Vector4.zero);
  1519.         }
  1520.  
  1521.         void RenderDeferredLighting(HDCamera hdCamera, CommandBuffer cmd)
  1522.         {
  1523.             if (hdCamera.frameSettings.enableForwardRenderingOnly)
  1524.                 return;
  1525.  
  1526.             m_MRTCache2[0] = m_CameraColorBuffer;
  1527.             m_MRTCache2[1] = m_CameraSssDiffuseLightingBuffer;
  1528.             var depthTexture = GetDepthTexture();
  1529.  
  1530.             var options = new LightLoop.LightingPassOptions();
  1531.  
  1532.             if (hdCamera.frameSettings.enableSubsurfaceScattering)
  1533.             {
  1534.                 // Output split lighting for materials asking for it (masked in the stencil buffer)
  1535.                 options.outputSplitLighting = true;
  1536.  
  1537.                 m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBuffer, depthTexture, options, m_DebugScreenSpaceTracingData);
  1538.             }
  1539.  
  1540.             // Output combined lighting for all the other materials.
  1541.             options.outputSplitLighting = false;
  1542.  
  1543.             m_LightLoop.RenderDeferredLighting(hdCamera, cmd, m_CurrentDebugDisplaySettings, m_MRTCache2, m_CameraDepthStencilBuffer, depthTexture, options, m_DebugScreenSpaceTracingData);
  1544.         }
  1545.  
  1546.         void UpdateSkyEnvironment(HDCamera hdCamera, CommandBuffer cmd)
  1547.         {
  1548.             m_SkyManager.UpdateEnvironment(hdCamera, m_LightLoop.GetCurrentSunLight(), cmd);
  1549.         }
  1550.  
  1551.         void RenderSky(HDCamera hdCamera, CommandBuffer cmd)
  1552.         {
  1553.             var visualEnv = VolumeManager.instance.stack.GetComponent<VisualEnvironment>();
  1554.  
  1555.             m_SkyManager.RenderSky(hdCamera, m_LightLoop.GetCurrentSunLight(), m_CameraColorBuffer, m_CameraDepthStencilBuffer, m_CurrentDebugDisplaySettings, cmd);
  1556.  
  1557.             if (visualEnv.fogType != FogType.None)
  1558.                 m_SkyManager.RenderOpaqueAtmosphericScattering(cmd);
  1559.         }
  1560.  
  1561.         public Texture2D ExportSkyToTexture()
  1562.         {
  1563.             return m_SkyManager.ExportSkyToTexture();
  1564.         }
  1565.  
  1566.         // Render forward is use for both transparent and opaque objects. In case of deferred we can still render opaque object in forward.
  1567.         void RenderForward(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd, ForwardPass pass)
  1568.         {
  1569.             // Guidelines: In deferred by default there is no opaque in forward. However it is possible to force an opaque material to render in forward
  1570.             // by using the pass "ForwardOnly". In this case the .shader should not have "Forward" but only a "ForwardOnly" pass.
  1571.             // It must also have a "DepthForwardOnly" and no "DepthOnly" pass as forward material (either deferred or forward only rendering) have always a depth pass.
  1572.             // The RenderForward pass will render the appropriate pass depends on the engine settings. In case of forward only rendering, both "Forward" pass and "ForwardOnly" pass
  1573.             // material will be render for both transparent and opaque. In case of deferred, both path are used for transparent but only "ForwardOnly" is use for opaque.
  1574.             // (Thus why "Forward" and "ForwardOnly" are exclusive, else they will render two times"
  1575.  
  1576.             string profileName;
  1577.             if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
  1578.             {
  1579.                 profileName = k_ForwardPassDebugName[(int)pass];
  1580.             }
  1581.             else
  1582.             {
  1583.                 profileName = k_ForwardPassName[(int)pass];
  1584.             }
  1585.  
  1586.             using (new ProfilingSample(cmd, profileName, CustomSamplerId.ForwardPassName.GetSampler()))
  1587.             {
  1588.                 var camera = hdCamera.camera;
  1589.  
  1590.                 m_LightLoop.RenderForward(camera, cmd, pass == ForwardPass.Opaque);
  1591.                 var debugScreenSpaceTracing = m_CurrentDebugDisplaySettings.fullScreenDebugMode == FullScreenDebugMode.ScreenSpaceTracing;
  1592.  
  1593.                 if (pass == ForwardPass.Opaque)
  1594.                 {
  1595.                     // In case of forward SSS we will bind all the required target. It is up to the shader to write into it or not.
  1596.                     if (hdCamera.frameSettings.enableSubsurfaceScattering)
  1597.                     {
  1598.                         RenderTargetIdentifier[] m_MRTWithSSS = new RenderTargetIdentifier[2 + m_SSSBufferManager.sssBufferCount];
  1599.                         m_MRTWithSSS[0] = m_CameraColorBuffer; // Store the specular color
  1600.                         m_MRTWithSSS[1] = m_CameraSssDiffuseLightingBuffer;
  1601.                         for (int i = 0; i < m_SSSBufferManager.sssBufferCount; ++i)
  1602.                         {
  1603.                             m_MRTWithSSS[i + 2] = m_SSSBufferManager.GetSSSBuffer(i);
  1604.                         }
  1605.  
  1606.                         HDUtils.SetRenderTarget(cmd, hdCamera, m_MRTWithSSS, m_CameraDepthStencilBuffer);
  1607.                     }
  1608.                     else
  1609.                     {
  1610.                         HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
  1611.                     }
  1612.  
  1613.                     var passNames = hdCamera.frameSettings.enableForwardRenderingOnly
  1614.                         ? m_ForwardAndForwardOnlyPassNames
  1615.                         : m_ForwardOnlyPassNames;
  1616.                     var debugSSTThisPass = debugScreenSpaceTracing && (m_CurrentDebugDisplaySettings.lightingDebugSettings.debugLightingMode == DebugLightingMode.ScreenSpaceTracingReflection);
  1617.                     if (debugSSTThisPass)
  1618.                         cmd.SetRandomWriteTarget(7, m_DebugScreenSpaceTracingData);
  1619.                     RenderOpaqueRenderList(cullResults, hdCamera, renderContext, cmd, passNames, m_currentRendererConfigurationBakedLighting);
  1620.                     if (debugSSTThisPass)
  1621.                         cmd.ClearRandomWriteTargets();
  1622.                 }
  1623.                 else
  1624.                 {
  1625.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
  1626.                     if ((hdCamera.frameSettings.enableDBuffer) && (DecalSystem.m_DecalDatasCount > 0)) // enable d-buffer flag value is being interpreted more like enable decals in general now that we have clustered
  1627.                                                                                                        // decal datas count is 0 if no decals affect transparency
  1628.                     {
  1629.                         DecalSystem.instance.SetAtlas(cmd); // for clustered decals
  1630.                     }
  1631.  
  1632.                     var debugSSTThisPass = debugScreenSpaceTracing && (m_CurrentDebugDisplaySettings.lightingDebugSettings.debugLightingMode == DebugLightingMode.ScreenSpaceTracingRefraction);
  1633.                     if (debugSSTThisPass)
  1634.                         cmd.SetRandomWriteTarget(7, m_DebugScreenSpaceTracingData);
  1635.                     RenderTransparentRenderList(cullResults, hdCamera, renderContext, cmd, m_AllTransparentPassNames, m_currentRendererConfigurationBakedLighting, pass == ForwardPass.PreRefraction ? HDRenderQueue.k_RenderQueue_PreRefraction : HDRenderQueue.k_RenderQueue_Transparent);
  1636.                     if (debugSSTThisPass)
  1637.                         cmd.ClearRandomWriteTargets();
  1638.                 }
  1639.             }
  1640.         }
  1641.  
  1642.         // This is use to Display legacy shader with an error shader
  1643.         [Conditional("DEVELOPMENT_BUILD"), Conditional("UNITY_EDITOR")]
  1644.         void RenderForwardError(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
  1645.         {
  1646.             using (new ProfilingSample(cmd, "Render Forward Error", CustomSamplerId.RenderForwardError.GetSampler()))
  1647.             {
  1648.                 HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer);
  1649.                 RenderOpaqueRenderList(cullResults, hdCamera, renderContext, cmd, m_ForwardErrorPassNames, 0, RenderQueueRange.all, null, m_ErrorMaterial);
  1650.             }
  1651.         }
  1652.  
  1653.         void RenderTransparentDepthPostpass(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd, ForwardPass pass)
  1654.         {
  1655.             if (!hdCamera.frameSettings.enableTransparentPostpass)
  1656.                 return;
  1657.  
  1658.             using (new ProfilingSample(cmd, "Render Transparent Depth Post ", CustomSamplerId.TransparentDepthPostpass.GetSampler()))
  1659.             {
  1660.                 HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraDepthStencilBuffer);
  1661.                 RenderTransparentRenderList(cullResults, hdCamera, renderContext, cmd, m_TransparentDepthPostpassNames);
  1662.             }
  1663.         }
  1664.  
  1665.         void RenderObjectsVelocity(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
  1666.         {
  1667.             if (!hdCamera.frameSettings.enableMotionVectors || !hdCamera.frameSettings.enableObjectMotionVectors)
  1668.                 return;
  1669.  
  1670.             using (new ProfilingSample(cmd, "Objects Velocity", CustomSamplerId.ObjectsVelocity.GetSampler()))
  1671.             {
  1672.                 // These flags are still required in SRP or the engine won't compute previous model matrices...
  1673.                 // If the flag hasn't been set yet on this camera, motion vectors will skip a frame.
  1674.                 hdCamera.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;
  1675.  
  1676.                 HDUtils.SetRenderTarget(cmd, hdCamera, m_VelocityBuffer, m_CameraDepthStencilBuffer);
  1677.                 RenderOpaqueRenderList(cullResults, hdCamera, renderContext, cmd, HDShaderPassNames.s_MotionVectorsName, RendererConfiguration.PerObjectMotionVectors);
  1678.             }
  1679.         }
  1680.  
  1681.         void RenderCameraVelocity(CullResults cullResults, HDCamera hdCamera, ScriptableRenderContext renderContext, CommandBuffer cmd)
  1682.         {
  1683.             if (!hdCamera.frameSettings.enableMotionVectors)
  1684.                 return;
  1685.  
  1686.             using (new ProfilingSample(cmd, "Camera Velocity", CustomSamplerId.CameraVelocity.GetSampler()))
  1687.             {
  1688.                 // These flags are still required in SRP or the engine won't compute previous model matrices...
  1689.                 // If the flag hasn't been set yet on this camera, motion vectors will skip a frame.
  1690.                 hdCamera.camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;
  1691.  
  1692.                 HDUtils.DrawFullScreen(cmd, hdCamera, m_CameraMotionVectorsMaterial, m_VelocityBuffer, m_CameraDepthStencilBuffer, null, 0);
  1693.                 PushFullScreenDebugTexture(hdCamera, cmd, m_VelocityBuffer, FullScreenDebugMode.MotionVectors);
  1694.  
  1695. #if UNITY_EDITOR
  1696.                 // In scene view there is no motion vector, so we clear the RT to black
  1697.                 if (hdCamera.camera.cameraType == CameraType.SceneView)
  1698.                 {
  1699.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_VelocityBuffer, m_CameraDepthStencilBuffer, ClearFlag.Color, CoreUtils.clearColorAllBlack);
  1700.                 }
  1701. #endif
  1702.             }
  1703.         }
  1704.  
  1705.         void RenderColorPyramid(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, bool isPreRefraction)
  1706.         {
  1707.             if (isPreRefraction)
  1708.             {
  1709.                 if (!hdCamera.frameSettings.enableRoughRefraction)
  1710.                     return;
  1711.             }
  1712.             else
  1713.             {
  1714.                 // TODO: This final Gaussian pyramid can be reuse by Bloom and SSR in the future, so disable it only if there is no postprocess AND no distortion
  1715.                 if (!hdCamera.frameSettings.enableDistortion && !hdCamera.frameSettings.enablePostprocess && !hdCamera.frameSettings.enableSSR)
  1716.                     return;
  1717.             }
  1718.  
  1719.             // TODO: Move allocation in separate method call in start of the render loop
  1720.             var cameraRT = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.ColorPyramid)
  1721.                 ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.ColorPyramid, m_BufferPyramid.AllocColorRT);
  1722.  
  1723.             using (new ProfilingSample(cmd, "Color Pyramid", CustomSamplerId.ColorPyramid.GetSampler()))
  1724.                 m_BufferPyramid.RenderColorPyramid(hdCamera, cmd, renderContext, m_CameraColorBuffer, cameraRT);
  1725.  
  1726.             Vector2 pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera, cameraRT);
  1727.             PushFullScreenDebugTextureMip(hdCamera, cmd, cameraRT, m_BufferPyramid.GetPyramidLodCount(new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight)), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), isPreRefraction ? FullScreenDebugMode.PreRefractionColorPyramid : FullScreenDebugMode.FinalColorPyramid);
  1728.         }
  1729.  
  1730.         void RenderDepthPyramid(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, FullScreenDebugMode debugMode)
  1731.         {
  1732.             if (!hdCamera.frameSettings.enableRoughRefraction)
  1733.                 return;
  1734.  
  1735.             // TODO: Move allocation in separate method call in start of the render loop
  1736.             var cameraRT = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.DepthPyramid)
  1737.                 ?? hdCamera.AllocHistoryFrameRT((int)HDCameraFrameHistoryType.DepthPyramid, m_BufferPyramid.AllocDepthRT);
  1738.  
  1739.             using (new ProfilingSample(cmd, "Depth Pyramid", CustomSamplerId.DepthPyramid.GetSampler()))
  1740.                 m_BufferPyramid.RenderDepthPyramid(hdCamera, cmd, renderContext, GetDepthTexture(), cameraRT);
  1741.  
  1742.             Vector2 pyramidScale = m_BufferPyramid.GetPyramidToScreenScale(hdCamera, cameraRT);
  1743.             PushFullScreenDebugTextureMip(hdCamera, cmd, cameraRT, m_BufferPyramid.GetPyramidLodCount(new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight)), new Vector4(pyramidScale.x, pyramidScale.y, 0.0f, 0.0f), debugMode);
  1744.         }
  1745.  
  1746.         void RenderPostProcess(HDCamera hdcamera, CommandBuffer cmd, PostProcessLayer layer)
  1747.         {
  1748.             using (new ProfilingSample(cmd, "Post-processing", CustomSamplerId.PostProcessing.GetSampler()))
  1749.             {
  1750.                 RenderTargetIdentifier source = m_CameraColorBuffer;
  1751.  
  1752.                 // For console we are not allowed to resize the windows, so don't use our hack.
  1753.                 bool tempHACK = !IsConsolePlatform();
  1754.  
  1755.                 if (tempHACK)
  1756.                 {
  1757.                     // TEMPORARY:
  1758.                     // Since we don't render to the full render textures, we need to feed the post processing stack with the right scale/bias.
  1759.                     // This feature not being implemented yet, we'll just copy the relevant buffers into an appropriately sized RT.
  1760.                     cmd.ReleaseTemporaryRT(HDShaderIDs._CameraDepthTexture);
  1761.                     cmd.ReleaseTemporaryRT(HDShaderIDs._CameraMotionVectorsTexture);
  1762.                     cmd.ReleaseTemporaryRT(HDShaderIDs._CameraColorTexture);
  1763.  
  1764.                     cmd.GetTemporaryRT(HDShaderIDs._CameraDepthTexture, hdcamera.actualWidth, hdcamera.actualHeight, m_CameraDepthStencilBuffer.rt.depth, FilterMode.Point, m_CameraDepthStencilBuffer.rt.format);
  1765.                     m_CopyDepth.SetTexture(HDShaderIDs._InputDepth, m_CameraDepthStencilBuffer);
  1766.                     cmd.Blit(null, HDShaderIDs._CameraDepthTexture, m_CopyDepth);
  1767.                     if (m_VelocityBuffer != null)
  1768.                     {
  1769.                         cmd.GetTemporaryRT(HDShaderIDs._CameraMotionVectorsTexture, hdcamera.actualWidth, hdcamera.actualHeight, 0, FilterMode.Point, m_VelocityBuffer.rt.format);
  1770.                         HDUtils.BlitCameraTexture(cmd, hdcamera, m_VelocityBuffer, HDShaderIDs._CameraMotionVectorsTexture);
  1771.                     }
  1772.                     cmd.GetTemporaryRT(HDShaderIDs._CameraColorTexture, hdcamera.actualWidth, hdcamera.actualHeight, 0, FilterMode.Point, m_CameraColorBuffer.rt.format);
  1773.                     HDUtils.BlitCameraTexture(cmd, hdcamera, m_CameraColorBuffer, HDShaderIDs._CameraColorTexture);
  1774.                     source = HDShaderIDs._CameraColorTexture;
  1775.                 }
  1776.                 else
  1777.                 {
  1778.                     // Note: Here we don't use GetDepthTexture() to get the depth texture but m_CameraDepthStencilBuffer as the Forward transparent pass can
  1779.                     // write extra data to deal with DOF/MB
  1780.                     cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, m_CameraDepthStencilBuffer);
  1781.                     cmd.SetGlobalTexture(HDShaderIDs._CameraMotionVectorsTexture, m_VelocityBuffer);
  1782.                 }
  1783.  
  1784.                 var context = hdcamera.postprocessRenderContext;
  1785.                 context.Reset();
  1786.                 context.source = source;
  1787.                 context.destination = BuiltinRenderTextureType.CameraTarget;
  1788.                 context.command = cmd;
  1789.                 context.camera = hdcamera.camera;
  1790.                 context.sourceFormat = RenderTextureFormat.ARGBHalf;
  1791.                 context.flip = hdcamera.camera.targetTexture == null;
  1792.  
  1793.                 layer.Render(context);
  1794.             }
  1795.         }
  1796.  
  1797.         public void ApplyDebugDisplaySettings(HDCamera hdCamera, CommandBuffer cmd)
  1798.         {
  1799.             if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() ||
  1800.                 m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None)
  1801.             {
  1802.                 // enable globally the keyword DEBUG_DISPLAY on shader that support it with multicompile
  1803.                 cmd.EnableShaderKeyword("DEBUG_DISPLAY");
  1804.  
  1805.                 // This is for texture streaming
  1806.                 m_CurrentDebugDisplaySettings.UpdateMaterials();
  1807.  
  1808.                 var lightingDebugSettings = m_CurrentDebugDisplaySettings.lightingDebugSettings;
  1809.                 var debugAlbedo = new Vector4(lightingDebugSettings.overrideAlbedo ? 1.0f : 0.0f, lightingDebugSettings.overrideAlbedoValue.r, lightingDebugSettings.overrideAlbedoValue.g, lightingDebugSettings.overrideAlbedoValue.b);
  1810.                 var debugSmoothness = new Vector4(lightingDebugSettings.overrideSmoothness ? 1.0f : 0.0f, lightingDebugSettings.overrideSmoothnessValue, 0.0f, 0.0f);
  1811.                 var debugNormal = new Vector4(lightingDebugSettings.overrideNormal ? 1.0f : 0.0f, 0.0f, 0.0f, 0.0f);
  1812.                 var debugSpecularColor = new Vector4(lightingDebugSettings.overrideSpecularColor ? 1.0f : 0.0f, lightingDebugSettings.overrideSpecularColorValue.r, lightingDebugSettings.overrideSpecularColorValue.g, lightingDebugSettings.overrideSpecularColorValue.b);
  1813.  
  1814.                 cmd.SetGlobalInt(HDShaderIDs._DebugViewMaterial, (int)m_CurrentDebugDisplaySettings.GetDebugMaterialIndex());
  1815.                 cmd.SetGlobalInt(HDShaderIDs._DebugLightingMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingMode());
  1816.                 cmd.SetGlobalInt(HDShaderIDs._DebugLightingSubMode, (int)m_CurrentDebugDisplaySettings.GetDebugLightingSubMode());
  1817.                 cmd.SetGlobalInt(HDShaderIDs._DebugMipMapMode, (int)m_CurrentDebugDisplaySettings.GetDebugMipMapMode());
  1818.                 cmd.SetGlobalInt(HDShaderIDs._ColorPickerMode, (int)m_CurrentDebugDisplaySettings.GetDebugColorPickerMode());
  1819.  
  1820.                 cmd.SetGlobalVector(HDShaderIDs._DebugLightingAlbedo, debugAlbedo);
  1821.                 cmd.SetGlobalVector(HDShaderIDs._DebugLightingSmoothness, debugSmoothness);
  1822.                 cmd.SetGlobalVector(HDShaderIDs._DebugLightingNormal, debugNormal);
  1823.                 cmd.SetGlobalVector(HDShaderIDs._DebugLightingSpecularColor, debugSpecularColor);
  1824.  
  1825.                 cmd.SetGlobalVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(hdCamera));
  1826.                 cmd.SetGlobalVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(hdCamera));
  1827.                 cmd.SetGlobalTexture(HDShaderIDs._DebugFont, m_Asset.renderPipelineResources.debugFontTexture);
  1828.                 cmd.SetGlobalInt(HDShaderIDs._DebugStep, HDUtils.debugStep);
  1829.                 cmd.SetGlobalInt(HDShaderIDs._ShowGrid, m_CurrentDebugDisplaySettings.showSSRayGrid ? 1 : 0);
  1830.                 cmd.SetGlobalInt(HDShaderIDs._ShowDepthPyramidDebug, m_CurrentDebugDisplaySettings.showSSRayDepthPyramid ? 1 : 0);
  1831.                 cmd.SetGlobalInt(HDShaderIDs._ShowSSRaySampledColor, m_CurrentDebugDisplaySettings.showSSSampledColor ? 1 : 0);
  1832.  
  1833.                 // The DebugNeedsExposure test allows us to set a neutral value if exposure is not needed. This way we don't need to make various tests inside shaders but only in this function.
  1834.                 cmd.SetGlobalFloat(HDShaderIDs._DebugExposure, m_CurrentDebugDisplaySettings.DebugNeedsExposure() ? lightingDebugSettings.debugExposure : 0.0f);
  1835.             }
  1836.             else
  1837.             {
  1838.                 // TODO: Be sure that if there is no change in the state of this keyword, it doesn't imply any work on CPU side! else we will need to save the sate somewher
  1839.                 cmd.DisableShaderKeyword("DEBUG_DISPLAY");
  1840.             }
  1841.         }
  1842.  
  1843.         public void PushColorPickerDebugTexture(CommandBuffer cmd, RTHandleSystem.RTHandle textureID, HDCamera hdCamera)
  1844.         {
  1845.             if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_DebugDisplaySettings.falseColorDebugSettings.falseColor)
  1846.             {
  1847.                 using (new ProfilingSample(cmd, "Push To Color Picker"))
  1848.                 {
  1849.                     HDUtils.BlitCameraTexture(cmd, hdCamera, textureID, m_DebugColorPickerBuffer);
  1850.                 }
  1851.             }
  1852.         }
  1853.  
  1854.         // TODO TEMP: Not sure I want to keep this special case. Gotta see how to get rid of it (not sure it will work correctly for non-full viewports.
  1855.         public void PushColorPickerDebugTexture(HDCamera hdCamera, CommandBuffer cmd, RenderTargetIdentifier textureID)
  1856.         {
  1857.             if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_DebugDisplaySettings.falseColorDebugSettings.falseColor)
  1858.             {
  1859.                 using (new ProfilingSample(cmd, "Push To Color Picker"))
  1860.                 {
  1861.                     HDUtils.BlitCameraTexture(cmd, hdCamera, textureID, m_DebugColorPickerBuffer);
  1862.                 }
  1863.             }
  1864.         }
  1865.  
  1866.         public void PushFullScreenDebugTexture(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle textureID, FullScreenDebugMode debugMode)
  1867.         {
  1868.             if (debugMode == m_CurrentDebugDisplaySettings.fullScreenDebugMode)
  1869.             {
  1870.                 m_FullScreenDebugPushed = true; // We need this flag because otherwise if no full screen debug is pushed (like for example if the corresponding pass is disabled), when we render the result in RenderDebug m_DebugFullScreenTempBuffer will contain potential garbage
  1871.                 HDUtils.BlitCameraTexture(cmd, hdCamera, textureID, m_DebugFullScreenTempBuffer);
  1872.             }
  1873.         }
  1874.  
  1875.         void PushFullScreenDebugTextureMip(HDCamera hdCamera, CommandBuffer cmd, RTHandleSystem.RTHandle texture, int lodCount, Vector4 scaleBias, FullScreenDebugMode debugMode)
  1876.         {
  1877.             if (debugMode == m_CurrentDebugDisplaySettings.fullScreenDebugMode)
  1878.             {
  1879.                 var mipIndex = Mathf.FloorToInt(m_CurrentDebugDisplaySettings.fullscreenDebugMip * (lodCount));
  1880.  
  1881.                 m_FullScreenDebugPushed = true; // We need this flag because otherwise if no full screen debug is pushed (like for example if the corresponding pass is disabled), when we render the result in RenderDebug m_DebugFullScreenTempBuffer will contain potential garbage
  1882.                 HDUtils.BlitCameraTexture(cmd, hdCamera, texture, m_DebugFullScreenTempBuffer, scaleBias, mipIndex);
  1883.             }
  1884.         }
  1885.  
  1886.         void RenderDebug(HDCamera hdCamera, CommandBuffer cmd)
  1887.         {
  1888.             // We don't want any overlay for these kind of rendering
  1889.             if (hdCamera.camera.cameraType == CameraType.Reflection || hdCamera.camera.cameraType == CameraType.Preview)
  1890.                 return;
  1891.  
  1892.             using (new ProfilingSample(cmd, "Render Debug", CustomSamplerId.RenderDebug.GetSampler()))
  1893.             {
  1894.                 // First render full screen debug texture
  1895.                 if (m_CurrentDebugDisplaySettings.fullScreenDebugMode != FullScreenDebugMode.None && m_FullScreenDebugPushed)
  1896.                 {
  1897.                     m_FullScreenDebugPushed = false;
  1898.                     cmd.SetGlobalTexture(HDShaderIDs._DebugFullScreenTexture, m_DebugFullScreenTempBuffer);
  1899.                     // TODO: Replace with command buffer call when available
  1900.                     m_DebugFullScreen.SetFloat(HDShaderIDs._FullScreenDebugMode, (float)m_CurrentDebugDisplaySettings.fullScreenDebugMode);
  1901.                     // Everything we have capture is flipped (as it happen before FinalPass/postprocess/Blit. So if we are not in SceneView
  1902.                     // (i.e. we have perform a flip, we need to flip the input texture)
  1903.                     m_DebugFullScreen.SetFloat(HDShaderIDs._RequireToFlipInputTexture, hdCamera.camera.cameraType != CameraType.SceneView ? 1.0f : 0.0f);
  1904.                     m_DebugFullScreen.SetBuffer(HDShaderIDs._DebugScreenSpaceTracingData, m_DebugScreenSpaceTracingData);
  1905.                     HDUtils.DrawFullScreen(cmd, hdCamera, m_DebugFullScreen, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
  1906.  
  1907.                     PushColorPickerDebugTexture(hdCamera, cmd, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
  1908.                 }
  1909.  
  1910.                 // Then overlays
  1911.                 float x = 0;
  1912.                 float overlayRatio = m_CurrentDebugDisplaySettings.debugOverlayRatio;
  1913.                 float overlaySize = Math.Min(hdCamera.actualHeight, hdCamera.actualWidth) * overlayRatio;
  1914.                 float y = hdCamera.actualHeight - overlaySize;
  1915.  
  1916.                 var lightingDebug = m_CurrentDebugDisplaySettings.lightingDebugSettings;
  1917.  
  1918.                 if (lightingDebug.displaySkyReflection)
  1919.                 {
  1920.                     var skyReflection = m_SkyManager.skyReflection;
  1921.                     m_SharedPropertyBlock.SetTexture(HDShaderIDs._InputCubemap, skyReflection);
  1922.                     m_SharedPropertyBlock.SetFloat(HDShaderIDs._Mipmap, lightingDebug.skyReflectionMipmap);
  1923.                     m_SharedPropertyBlock.SetFloat(HDShaderIDs._RequireToFlipInputTexture, hdCamera.camera.cameraType != CameraType.SceneView ? 1.0f : 0.0f);
  1924.                     m_SharedPropertyBlock.SetFloat(HDShaderIDs._DebugExposure, lightingDebug.debugExposure);
  1925.                     cmd.SetViewport(new Rect(x, y, overlaySize, overlaySize));
  1926.                     cmd.DrawProcedural(Matrix4x4.identity, m_DebugDisplayLatlong, 0, MeshTopology.Triangles, 3, 1, m_SharedPropertyBlock);
  1927.                     HDUtils.NextOverlayCoord(ref x, ref y, overlaySize, overlaySize, hdCamera.actualWidth);
  1928.                 }
  1929.  
  1930.                 m_LightLoop.RenderDebugOverlay(hdCamera, cmd, m_CurrentDebugDisplaySettings, ref x, ref y, overlaySize, hdCamera.actualWidth);
  1931.  
  1932.                 DecalSystem.instance.RenderDebugOverlay(hdCamera, cmd, m_CurrentDebugDisplaySettings, ref x, ref y, overlaySize, hdCamera.actualWidth);
  1933.  
  1934.                 if (m_CurrentDebugDisplaySettings.colorPickerDebugSettings.colorPickerMode != ColorPickerDebugMode.None || m_CurrentDebugDisplaySettings.falseColorDebugSettings.falseColor)
  1935.                 {
  1936.                     ColorPickerDebugSettings colorPickerDebugSettings = m_CurrentDebugDisplaySettings.colorPickerDebugSettings;
  1937.                     FalseColorDebugSettings falseColorDebugSettings = m_CurrentDebugDisplaySettings.falseColorDebugSettings;
  1938.                     var falseColorThresholds = new Vector4(falseColorDebugSettings.colorThreshold0, falseColorDebugSettings.colorThreshold1, falseColorDebugSettings.colorThreshold2, falseColorDebugSettings.colorThreshold3);
  1939.  
  1940.                     // Here we have three cases:
  1941.                     // - Material debug is enabled, this is the buffer we display
  1942.                     // - Otherwise we display the HDR buffer before postprocess and distortion
  1943.                     // - If fullscreen debug is enabled we always use it
  1944.  
  1945.                     cmd.SetGlobalTexture(HDShaderIDs._DebugColorPickerTexture, m_DebugColorPickerBuffer); // No SetTexture with RenderTarget identifier... so use SetGlobalTexture
  1946.                     // TODO: Replace with command buffer call when available
  1947.                     m_DebugColorPicker.SetColor(HDShaderIDs._ColorPickerFontColor, colorPickerDebugSettings.fontColor);
  1948.                     m_DebugColorPicker.SetInt(HDShaderIDs._FalseColorEnabled, falseColorDebugSettings.falseColor ? 1 : 0);
  1949.                     m_DebugColorPicker.SetVector(HDShaderIDs._FalseColorThresholds, falseColorThresholds);
  1950.                     // The material display debug perform sRGBToLinear conversion as the final blit currently hardcode a linearToSrgb conversion. As when we read with color picker this is not done,
  1951.                     // we perform it inside the color picker shader. But we shouldn't do it for HDR buffer.
  1952.                     m_DebugColorPicker.SetFloat(HDShaderIDs._ApplyLinearToSRGB, m_CurrentDebugDisplaySettings.IsDebugMaterialDisplayEnabled() ? 1.0f : 0.0f);
  1953.                     // Everything we have capture is flipped (as it happen before FinalPass/postprocess/Blit. So if we are not in SceneView
  1954.                     // (i.e. we have perform a flip, we need to flip the input texture) + we need to handle the case were we debug a fullscreen pass that have already perform the flip
  1955.                     m_DebugColorPicker.SetFloat(HDShaderIDs._RequireToFlipInputTexture, hdCamera.camera.cameraType != CameraType.SceneView ? 1.0f : 0.0f);
  1956.                     HDUtils.DrawFullScreen(cmd, hdCamera, m_DebugColorPicker, (RenderTargetIdentifier)BuiltinRenderTextureType.CameraTarget);
  1957.                 }
  1958.             }
  1959.         }
  1960.  
  1961.         void ClearBuffers(HDCamera hdCamera, CommandBuffer cmd)
  1962.         {
  1963.             using (new ProfilingSample(cmd, "ClearBuffers", CustomSamplerId.ClearBuffers.GetSampler()))
  1964.             {
  1965.                 // We clear only the depth buffer, no need to clear the various color buffer as we overwrite them.
  1966.                 // Clear depth/stencil and init buffers
  1967.                 using (new ProfilingSample(cmd, "Clear Depth/Stencil", CustomSamplerId.ClearDepthStencil.GetSampler()))
  1968.                 {
  1969.                     if (hdCamera.clearDepth)
  1970.                     {
  1971.                         HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer, ClearFlag.Depth);
  1972.                     }
  1973.                 }
  1974.  
  1975.                 // Clear the HDR target
  1976.                 using (new ProfilingSample(cmd, "Clear HDR target", CustomSamplerId.ClearHDRTarget.GetSampler()))
  1977.                 {
  1978.                     if (hdCamera.clearColorMode == HDAdditionalCameraData.ClearColorMode.BackgroundColor ||
  1979.                         // If we want the sky but the sky don't exist, still clear with background color
  1980.                         (hdCamera.clearColorMode == HDAdditionalCameraData.ClearColorMode.Sky && !m_SkyManager.IsVisualSkyValid()) ||
  1981.                         // Special handling for Preview we force to clear with background color (i.e black)
  1982.                         // Note that the sky use in this case is the last one setup. If there is no scene or game, there is no sky use as reflection in the preview
  1983.                         HDUtils.IsRegularPreviewCamera(hdCamera.camera)
  1984.                         )
  1985.                     {
  1986.                         Color clearColor = hdCamera.backgroundColorHDR;
  1987.                         HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraColorBuffer, m_CameraDepthStencilBuffer, ClearFlag.Color, clearColor);
  1988.                     }
  1989.                 }
  1990.  
  1991.                 // Clear the diffuse SSS lighting target
  1992.                 using (new ProfilingSample(cmd, "Clear SSS diffuse target", CustomSamplerId.ClearSSSDiffuseTarget.GetSampler()))
  1993.                 {
  1994.                     HDUtils.SetRenderTarget(cmd, hdCamera, m_CameraSssDiffuseLightingBuffer, ClearFlag.Color, CoreUtils.clearColorAllBlack);
  1995.                 }
  1996.  
  1997.                 // We don't need to clear the GBuffers as scene is rewrite and we are suppose to only access valid data (invalid data are tagged with stencil as StencilLightingUsage.NoLighting),
  1998.                 // This is to save some performance
  1999.                 if (!hdCamera.frameSettings.enableForwardRenderingOnly)
  2000.                 {
  2001.                     // We still clear in case of debug mode
  2002.                     if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled())
  2003.                     {
  2004.                         using (new ProfilingSample(cmd, "Clear GBuffer", CustomSamplerId.ClearGBuffer.GetSampler()))
  2005.                         {
  2006.                             HDUtils.SetRenderTarget(cmd, hdCamera, m_GbufferManager.GetBuffersRTI(), m_CameraDepthStencilBuffer, ClearFlag.Color, CoreUtils.clearColorAllBlack);
  2007.                         }
  2008.                     }
  2009.                 }
  2010.             }
  2011.         }
  2012.  
  2013.         void StartStereoRendering(ScriptableRenderContext renderContext, HDCamera hdCamera)
  2014.         {
  2015.             if (hdCamera.frameSettings.enableStereo)
  2016.                 renderContext.StartMultiEye(hdCamera.camera);
  2017.         }
  2018.  
  2019.         void StopStereoRendering(ScriptableRenderContext renderContext, HDCamera hdCamera)
  2020.         {
  2021.             if (hdCamera.frameSettings.enableStereo)
  2022.                 renderContext.StopMultiEye(hdCamera.camera);
  2023.         }
  2024.  
  2025.         /// <summary>
  2026.         /// Push a RenderTexture handled by a RTHandle in global parameters.
  2027.         /// </summary>
  2028.         /// <param name="cmd">Command buffer to queue commands</param>
  2029.         /// <param name="rth">RTHandle handling the RenderTexture</param>
  2030.         /// <param name="textureID">TextureID to use for texture binding.</param>
  2031.         /// <param name="sizeID">Property ID to store RTHandle size ((x,y) = Actual Pixel Size, (z,w) = 1 / Actual Pixel Size).</param>
  2032.         /// <param name="scaleID">PropertyID to store RTHandle scale ((x,y) = Screen Scale, z = lod count, w = unused).</param>
  2033.         void PushGlobalRTHandle(CommandBuffer cmd, RTHandleSystem.RTHandle rth, int textureID, int sizeID, int scaleID)
  2034.         {
  2035.             if (rth != null)
  2036.             {
  2037.                 cmd.SetGlobalTexture(textureID, rth);
  2038.                 cmd.SetGlobalVector(
  2039.                     sizeID,
  2040.                     new Vector4(
  2041.                     rth.referenceSize.x,
  2042.                     rth.referenceSize.y,
  2043.                     1f / rth.referenceSize.x,
  2044.                     1f / rth.referenceSize.y
  2045.                     )
  2046.                 );
  2047.                 cmd.SetGlobalVector(
  2048.                     scaleID,
  2049.                     new Vector4(
  2050.                     rth.referenceSize.x / (float)rth.rt.width,
  2051.                     rth.referenceSize.y / (float)rth.rt.height,
  2052.                     Mathf.Log(Mathf.Min(rth.rt.width, rth.rt.height), 2),
  2053.                     0.0f
  2054.                     )
  2055.                 );
  2056.             }
  2057.             else
  2058.             {
  2059.                 cmd.SetGlobalTexture(textureID, Texture2D.blackTexture);
  2060.                 cmd.SetGlobalVector(sizeID, Vector4.one);
  2061.                 cmd.SetGlobalVector(scaleID, Vector4.one);
  2062.             }
  2063.         }
  2064.     }
  2065. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement