Beispiel #1
0
        private void PostProcessingRendering(ScriptableRenderContext context, Camera camera, PostProcessLayer ppLayer)
        {
            var cullResults = context.Cull(ref _cullParam);

            context.SetupCameraProperties(camera);

            var cmdBuf = CommandBufferPool.Get(_ppRenderCmdName);

            cmdBuf.GetTemporaryRT(_colorNameId, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32);
            cmdBuf.GetTemporaryRT(_depthNameId, camera.pixelWidth, camera.pixelHeight, 24, FilterMode.Point, RenderTextureFormat.Depth);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            cmdBuf.SetRenderTarget(
                _colorNameId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,
                _depthNameId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store);
            cmdBuf.ClearRenderTarget(true, true, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            context.DrawRenderers(cullResults, ref _opaqueDrawing, ref _opaqueFiltering);
            context.DrawRenderers(cullResults, ref _transparentDrawing, ref _transparentFiltering);
#if UNITY_EDITOR
            if (CameraType.SceneView == camera.cameraType)
            {
                context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
                context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
            }
#endif

            _ppContext.Reset();
            _ppContext.camera       = camera;
            _ppContext.source       = _colorNameId;
            _ppContext.sourceFormat = RenderTextureFormat.ARGB32;
            _ppContext.destination  = BuiltinRenderTextureType.CameraTarget;
            _ppContext.command      = cmdBuf;
            _ppContext.flip         = true;
            ppLayer.Render(_ppContext);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            cmdBuf.ReleaseTemporaryRT(_colorNameId);
            cmdBuf.ReleaseTemporaryRT(_depthNameId);
            context.ExecuteCommandBuffer(cmdBuf);
            cmdBuf.Clear();

            context.Submit();
        }
Beispiel #2
0
        private void RenderPostProcess(ref ScriptableRenderContext renderContext, PostProcessLayer postProcessLayer)
        {
            var postProcessCommand = CommandBufferPool.Get("Post Processing");

            m_PostProcessRenderContext.Reset();
            m_PostProcessRenderContext.camera       = m_CurrCamera;
            m_PostProcessRenderContext.source       = BuiltinRenderTextureType.CurrentActive;
            m_PostProcessRenderContext.sourceFormat = m_ColorFormat;
            m_PostProcessRenderContext.destination  = BuiltinRenderTextureType.CameraTarget;
            m_PostProcessRenderContext.command      = postProcessCommand;
            m_PostProcessRenderContext.flip         = true;

            postProcessLayer.Render(m_PostProcessRenderContext);
            renderContext.ExecuteCommandBuffer(postProcessCommand);
            CommandBufferPool.Release(postProcessCommand);
        }
Beispiel #3
0
    private void RenderPostProcess(PostProcessLayer layer, CommandBuffer cmd, Camera camera)
    {
        var context = m_PostProcessRenderContext;

        context.Reset();
        context.source       = m_ColorBuffer;
        context.destination  = m_ColorBuffer;
        context.command      = cmd;
        context.camera       = camera;
        context.sourceFormat = RenderTextureFormat.ARGBHalf;
        context.flip         = false;
#if !UNITY_2019_1_OR_NEWER // Y-flip correction available in 2019.1
        context.flip = context.flip && (!hdcamera.camera.stereoEnabled);
#endif

        layer.Render(context);
    }
        public void RenderPostProcess(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier dest, bool opaqueOnly, Camera camera)
        {
            m_PostProcessRenderContext.Reset();
            m_PostProcessRenderContext.camera       = camera;
            m_PostProcessRenderContext.source       = source;
            m_PostProcessRenderContext.sourceFormat = m_ColorFormat;
            m_PostProcessRenderContext.destination  = dest;
            m_PostProcessRenderContext.command      = cmd;
            m_PostProcessRenderContext.flip         = true;

            if (opaqueOnly)
            {
                m_CameraPostProcessLayer.RenderOpaqueOnly(m_PostProcessRenderContext);
            }
            else
            {
                m_CameraPostProcessLayer.Render(m_PostProcessRenderContext);
            }
        }
Beispiel #5
0
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        BeginFrameRendering(context, cameras);

        foreach (Camera camera in cameras)
        {
            BeginCameraRendering(context, camera);

            //Culling
            ScriptableCullingParameters cullingParams;
            if (!camera.TryGetCullingParameters(out cullingParams))
            {
                continue;
            }
            CullingResults cull = context.Cull(ref cullingParams);

            //Camera setup some builtin variables e.g. camera projection matrices etc
            context.SetupCameraProperties(camera);

            //Get the setting from camera component
            bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false;
            bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true;
            bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false;

            //************************** Set TempRT ************************************

            CommandBuffer cmdTempId = new CommandBuffer();
            cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT";

            //Color
            m_ColorFormatActive = camera.allowHDR ? m_ColorFormatHDR : m_ColorFormat;
            RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            colorRTDesc.graphicsFormat    = m_ColorFormatActive;
            colorRTDesc.depthBufferBits   = depthBufferBits;
            colorRTDesc.sRGB              = (QualitySettings.activeColorSpace == ColorSpace.Linear);
            colorRTDesc.msaaSamples       = camera.allowMSAA ? QualitySettings.antiAliasing : 1;
            colorRTDesc.enableRandomWrite = false;
            cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear);

            //Depth
            RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            depthRTDesc.colorFormat     = RenderTextureFormat.Depth;
            depthRTDesc.depthBufferBits = depthBufferBits;
            cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear);
            context.ExecuteCommandBuffer(cmdTempId);
            cmdTempId.Release();

            //************************** Setup DrawSettings and FilterSettings ************************************

            var               sortingSettings   = new SortingSettings(camera);
            DrawingSettings   drawSettings      = new DrawingSettings(m_PassName, sortingSettings);
            FilteringSettings filterSettings    = new FilteringSettings(RenderQueueRange.all);
            DrawingSettings   drawSettingsDepth = new DrawingSettings(m_PassName, sortingSettings)
            {
                perObjectData             = PerObjectData.None,
                overrideMaterial          = depthOnlyMaterial,
                overrideMaterialPassIndex = 0
            };

            //************************** Rendering depth ************************************

            //Set RenderTarget & Camera clear flag
            CommandBuffer cmdDepth = new CommandBuffer();
            cmdDepth.name = "(" + camera.name + ")" + "Depth Clear Flag";
            cmdDepth.SetRenderTarget(m_DepthRT); //Set CameraTarget to the depth texture

            cmdDepth.ClearRenderTarget(true, true, Color.black);
            //MyDebug(camera,context,m_DepthRT,colorRTDesc,null);
            context.ExecuteCommandBuffer(cmdDepth);
            //MyDebug(camera,context,m_DepthRT,colorRTDesc,null);
            cmdDepth.Release();

            //Opaque objects
            sortingSettings.criteria          = SortingCriteria.CommonOpaque;
            drawSettingsDepth.sortingSettings = sortingSettings;
            filterSettings.renderQueueRange   = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettings);

            //To let shader has _CameraDepthTexture, to make Depth of Field work
            CommandBuffer cmdDepthTexture = new CommandBuffer();
            cmdDepthTexture.name = "(" + camera.name + ")" + "Depth Texture";
            cmdDepthTexture.SetGlobalTexture(m_DepthRTid, m_DepthRT);
            context.ExecuteCommandBuffer(cmdDepthTexture);
            //MyDebug(camera,context,m_DepthRT,colorRTDesc,null);
            cmdDepthTexture.Release();

            //************************** Rendering colors ************************************

            //Set RenderTarget & Camera clear flag
            CommandBuffer cmd = new CommandBuffer();
            cmd.name = "(" + camera.name + ")" + "Clear Flag";
            cmd.SetRenderTarget(m_ColorRT); //Set CameraTarget to the color texture
            cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmd);
            //MyDebug(camera,context,m_ColorRT,colorRTDesc,null);
            cmd.Release();

            //Skybox
            if (drawSkyBox)
            {
                context.DrawSkybox(camera);
            }

            AfterSkybox(camera, context);
            //************************** Rendering Opaque Objects ************************************

            sortingSettings.criteria        = SortingCriteria.CommonOpaque;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);
            AfterOpaqueObject(camera, context);
            //************************** SetUp Post-processing ************************************

            PostProcessLayer         m_CameraPostProcessLayer   = camera.GetComponent <PostProcessLayer>();
            bool                     hasPostProcessing          = m_CameraPostProcessLayer != null;
            bool                     usePostProcessing          = false;
            bool                     hasOpaqueOnlyEffects       = false;
            PostProcessRenderContext m_PostProcessRenderContext = null;
            if (hasPostProcessing)
            {
                m_PostProcessRenderContext = new PostProcessRenderContext();
                usePostProcessing          = m_CameraPostProcessLayer.enabled;
                hasOpaqueOnlyEffects       = m_CameraPostProcessLayer.HasOpaqueOnlyEffects(m_PostProcessRenderContext);
            }

            //************************** Opaque Post-processing ************************************
            //Ambient Occlusion, Screen-spaced reflection are generally not supported for SRP
            //So this part is only for custom opaque post-processing
            if (usePostProcessing)
            {
                CommandBuffer cmdpp = new CommandBuffer();
                cmdpp.name = "(" + camera.name + ")" + "Post-processing Opaque";

                m_PostProcessRenderContext.Reset();
                m_PostProcessRenderContext.camera       = camera;
                m_PostProcessRenderContext.source       = m_ColorRT;
                m_PostProcessRenderContext.sourceFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetRenderTextureFormat(m_ColorFormatActive);
                m_PostProcessRenderContext.destination  = m_ColorRT;
                m_PostProcessRenderContext.command      = cmdpp;
                m_PostProcessRenderContext.flip         = camera.targetTexture == null;//是否反转画面
                m_CameraPostProcessLayer.RenderOpaqueOnly(m_PostProcessRenderContext);

                context.ExecuteCommandBuffer(cmdpp);
                cmdpp.Release();
            }

            //************************** Rendering Transparent Objects ************************************

            sortingSettings.criteria        = SortingCriteria.CommonTransparent;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);
            AfterTransparentObject(camera, context, m_DepthRTid, depthRTDesc);
            //************************** Transparent Post-processing ************************************
            //Bloom, Vignette, Grain, ColorGrading, LensDistortion, Chromatic Aberration, Auto Exposure
            if (usePostProcessing)
            {
                CommandBuffer cmdpp = new CommandBuffer();
                cmdpp.name = "(" + camera.name + ")" + "Post-processing Transparent";

                m_PostProcessRenderContext.Reset();
                m_PostProcessRenderContext.camera       = camera;
                m_PostProcessRenderContext.source       = m_ColorRT;
                m_PostProcessRenderContext.sourceFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetRenderTextureFormat(m_ColorFormatActive);
                m_PostProcessRenderContext.destination  = BuiltinRenderTextureType.CameraTarget;
                m_PostProcessRenderContext.command      = cmdpp;
                m_PostProcessRenderContext.flip         = camera.targetTexture == null;
                m_CameraPostProcessLayer.Render(m_PostProcessRenderContext);

                context.ExecuteCommandBuffer(cmdpp);
                cmdpp.Release();
            }

            //************************** Make sure screen has the thing when Postprocessing is off ************************************
            if (!usePostProcessing)
            {
                CommandBuffer cmdBlitToCam = new CommandBuffer();
                cmdBlitToCam.name = "(" + camera.name + ")" + "Blit back to Camera";
                cmdBlitToCam.Blit(m_ColorRTid, BuiltinRenderTextureType.CameraTarget);
                //MDebug.MyDebug();
                context.ExecuteCommandBuffer(cmdBlitToCam);
                cmdBlitToCam.Release();
            }

            //************************** Clean Up ************************************
            CommandBuffer cmdclean = new CommandBuffer();
            cmdclean.name = "(" + camera.name + ")" + "Clean Up";
            cmdclean.ReleaseTemporaryRT(m_ColorRTid);
            cmdclean.ReleaseTemporaryRT(m_DepthRTid);
            context.ExecuteCommandBuffer(cmdclean);
            cmdclean.Release();

            context.Submit();

            EndCameraRendering(context, camera);
        }

        EndFrameRendering(context, cameras);
    }
Beispiel #6
0
    protected override void Render(ScriptableRenderContext context, Camera[] cameras)
    {
        BeginFrameRendering(context, cameras);

        foreach (Camera camera in cameras)
        {
            BeginCameraRendering(context, camera);

            //Culling
            ScriptableCullingParameters cullingParams;
            if (!camera.TryGetCullingParameters(out cullingParams))
            {
                continue;
            }
            CullingResults cull = context.Cull(ref cullingParams);

            //Camera setup some builtin variables e.g. camera projection matrices etc
            context.SetupCameraProperties(camera);

            //Get the setting from camera component
            bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false;
            bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true;
            bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false;

            //************************** Set TempRT ************************************

            CommandBuffer cmdTempId = new CommandBuffer();
            cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT";

            //Color
            m_ColorFormatActive = camera.allowHDR ? m_ColorFormatHDR : m_ColorFormat;
            RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            colorRTDesc.graphicsFormat  = m_ColorFormatActive;
            colorRTDesc.depthBufferBits = depthBufferBits;
            //colorRTDesc.sRGB = ;
            colorRTDesc.msaaSamples       = camera.allowMSAA ? QualitySettings.antiAliasing : 1;
            colorRTDesc.enableRandomWrite = false;
            cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear);

            //Depth
            RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            depthRTDesc.colorFormat     = RenderTextureFormat.Depth;
            depthRTDesc.depthBufferBits = depthBufferBits;
            cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear);

            //MotionVector
            RenderTextureDescriptor motionvectorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            motionvectorRTDesc.graphicsFormat  = UnityEngine.Experimental.Rendering.GraphicsFormat.R16G16_SFloat;
            motionvectorRTDesc.depthBufferBits = depthBufferBits;
            //colorRTDesc.sRGB = ;
            motionvectorRTDesc.msaaSamples       = 1;
            motionvectorRTDesc.enableRandomWrite = false;
            cmdTempId.GetTemporaryRT(m_MotionVectorRTid, motionvectorRTDesc, FilterMode.Bilinear);

            context.ExecuteCommandBuffer(cmdTempId);

            cmdTempId.Release();

            //************************** Setup DrawSettings and FilterSettings ************************************

            camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth;

            var sortingSettings = new SortingSettings(camera);

            DrawingSettings   drawSettings   = new DrawingSettings(m_PassName, sortingSettings);
            FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all);

            DrawingSettings drawSettingsMotionVector = new DrawingSettings(m_PassName, sortingSettings)
            {
                perObjectData             = PerObjectData.MotionVectors,
                overrideMaterial          = motionVectorMaterial,
                overrideMaterialPassIndex = 0
            };
            FilteringSettings filterSettingsMotionVector = new FilteringSettings(RenderQueueRange.all)
            {
                excludeMotionVectorObjects = false
            };

            DrawingSettings drawSettingsDepth = new DrawingSettings(m_PassName, sortingSettings)
            {
                //perObjectData = PerObjectData.None,
                overrideMaterial          = depthOnlyMaterial,
                overrideMaterialPassIndex = 0,
            };
            FilteringSettings filterSettingsDepth = new FilteringSettings(RenderQueueRange.all);

            //************************** Rendering depth ************************************

            //Set RenderTarget & Camera clear flag
            CommandBuffer cmdDepth = new CommandBuffer();
            cmdDepth.name = "(" + camera.name + ")" + "Depth Clear Flag";
            cmdDepth.SetRenderTarget(m_DepthRT); //Set CameraTarget to the depth texture
            cmdDepth.ClearRenderTarget(true, true, Color.black);
            context.ExecuteCommandBuffer(cmdDepth);
            cmdDepth.Release();

            //Opaque objects
            sortingSettings.criteria             = SortingCriteria.CommonOpaque;
            drawSettingsDepth.sortingSettings    = sortingSettings;
            filterSettingsDepth.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettingsDepth);

            //To let shader has _CameraDepthTexture
            CommandBuffer cmdDepthTexture = new CommandBuffer();
            cmdDepthTexture.name = "(" + camera.name + ")" + "Depth Texture";
            cmdDepthTexture.SetGlobalTexture(m_DepthRTid, m_DepthRT);
            context.ExecuteCommandBuffer(cmdDepthTexture);
            cmdDepthTexture.Release();

            //************************** Rendering motion vectors ************************************

            //Camera clear flag
            CommandBuffer cmdMotionvector = new CommandBuffer();
            cmdMotionvector.SetRenderTarget(m_MotionVectorRT); //Set CameraTarget to the motion vector texture
            cmdMotionvector.ClearRenderTarget(true, true, Color.black);
            context.ExecuteCommandBuffer(cmdMotionvector);
            cmdMotionvector.Release();

            //Opaque objects
            sortingSettings.criteria = SortingCriteria.CommonOpaque;
            drawSettingsMotionVector.sortingSettings    = sortingSettings;
            filterSettingsMotionVector.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettingsMotionVector, ref filterSettingsMotionVector);

            //Camera motion vector
            CommandBuffer cmdCameraMotionVector = new CommandBuffer();
            cmdCameraMotionVector.name = "(" + camera.name + ")" + "Camera MotionVector";
            _NonJitteredVP             = camera.nonJitteredProjectionMatrix * camera.worldToCameraMatrix;
            cmdCameraMotionVector.SetGlobalMatrix("_CamPrevViewProjMatrix", _PreviousVP);
            cmdCameraMotionVector.SetGlobalMatrix("_CamNonJitteredViewProjMatrix", _NonJitteredVP);
            cmdCameraMotionVector.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity);
            cmdCameraMotionVector.DrawMesh(fullscreenMesh, Matrix4x4.identity, motionVectorMaterial, 0, 1, null);  // draw full screen quad to make Camera motion
            cmdCameraMotionVector.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix);
            context.ExecuteCommandBuffer(cmdCameraMotionVector);
            cmdCameraMotionVector.Release();

            //To let shader has MotionVectorTexture
            CommandBuffer cmdMotionVectorTexture = new CommandBuffer();
            cmdMotionVectorTexture.name = "(" + camera.name + ")" + "MotionVector Texture";
            cmdMotionVectorTexture.SetGlobalTexture(m_MotionVectorRTid, m_MotionVectorRT);
            context.ExecuteCommandBuffer(cmdMotionVectorTexture);
            cmdMotionVectorTexture.Release();

            //************************** Rendering color ************************************

            //Camera clear flag
            CommandBuffer cmd = new CommandBuffer();
            cmd.SetRenderTarget(m_ColorRT); //Set CameraTarget to the color texture
            cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor);
            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            //Skybox
            if (drawSkyBox)
            {
                context.DrawSkybox(camera);
            }

            //Opaque objects
            sortingSettings.criteria        = SortingCriteria.CommonOpaque;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //************************** SetUp Post-processing ************************************

            PostProcessLayer m_CameraPostProcessLayer = camera.GetComponent <PostProcessLayer>();
            bool             hasPostProcessing        = m_CameraPostProcessLayer != null;
            bool             usePostProcessing        = false;
            //bool hasOpaqueOnlyEffects = false;
            PostProcessRenderContext m_PostProcessRenderContext = null;
            if (hasPostProcessing)
            {
                m_PostProcessRenderContext = new PostProcessRenderContext();
                usePostProcessing          = m_CameraPostProcessLayer.enabled;
                //hasOpaqueOnlyEffects = m_CameraPostProcessLayer.HasOpaqueOnlyEffects(m_PostProcessRenderContext);
            }

            //************************** Opaque Post-processing ************************************
            //Ambient Occlusion, Screen-spaced reflection are generally not supported for SRP
            //So this part is only for custom opaque post-processing
            // if(usePostProcessing)
            // {
            //     CommandBuffer cmdpp = new CommandBuffer();
            //     cmdpp.name = "("+camera.name+")"+ "Post-processing Opaque";

            //     m_PostProcessRenderContext.Reset();
            //     m_PostProcessRenderContext.camera = camera;
            //     m_PostProcessRenderContext.source = m_ColorRT;
            //     m_PostProcessRenderContext.sourceFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetRenderTextureFormat(m_ColorFormatActive);
            //     m_PostProcessRenderContext.destination = m_ColorRT;
            //     m_PostProcessRenderContext.command = cmdpp;
            //     m_PostProcessRenderContext.flip = camera.targetTexture == null;
            //     m_CameraPostProcessLayer.RenderOpaqueOnly(m_PostProcessRenderContext);

            //     context.ExecuteCommandBuffer(cmdpp);
            //     cmdpp.Release();
            // }

            //************************** Rendering Transparent Objects ************************************

            sortingSettings.criteria        = SortingCriteria.CommonTransparent;
            drawSettings.sortingSettings    = sortingSettings;
            filterSettings.renderQueueRange = RenderQueueRange.transparent;
            context.DrawRenderers(cull, ref drawSettings, ref filterSettings);

            //************************** Transparent Post-processing ************************************
            //Bloom, Vignette, Grain, ColorGrading, LensDistortion, Chromatic Aberration, Auto Exposure, Motion Blur
            if (usePostProcessing)
            {
                CommandBuffer cmdpp = new CommandBuffer();
                cmdpp.name = "(" + camera.name + ")" + "Post-processing Transparent";

                m_PostProcessRenderContext.Reset();
                m_PostProcessRenderContext.camera       = camera;
                m_PostProcessRenderContext.source       = m_ColorRT;
                m_PostProcessRenderContext.sourceFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetRenderTextureFormat(m_ColorFormatActive);
                m_PostProcessRenderContext.destination  = BuiltinRenderTextureType.CameraTarget;
                m_PostProcessRenderContext.command      = cmdpp;
                m_PostProcessRenderContext.flip         = camera.targetTexture == null;
                m_CameraPostProcessLayer.Render(m_PostProcessRenderContext);

                context.ExecuteCommandBuffer(cmdpp);
                cmdpp.Release();
            }
            else
            {
                //Make sure screen has the thing when Postprocessing is off
                CommandBuffer cmdBlitToCam = new CommandBuffer();
                cmdBlitToCam.name = "(" + camera.name + ")" + "Blit back to Camera";
                cmdBlitToCam.Blit(m_ColorRTid, BuiltinRenderTextureType.CameraTarget);
                context.ExecuteCommandBuffer(cmdBlitToCam);
                cmdBlitToCam.Release();
            }

            //************************** Debug ************************************

            if (_motionVectorDebug)
            {
                CommandBuffer cmdDebug = new CommandBuffer();
                RenderTexture rt;
                rt = new RenderTexture(colorRTDesc);
                cmdDebug.Blit(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CameraTarget, motionVectorDebugMaterial);
                cmdDebug.Blit(BuiltinRenderTextureType.CameraTarget, rt, motionVectorDebugMaterial);
                //MyDebug(camera, context, rt, colorRTDesc, cmdDebug);
                context.ExecuteCommandBuffer(cmdDebug);
                cmdDebug.Release();
                rt.Release();
            }

            //************************** Clean Up ************************************

            CommandBuffer cmdclean = new CommandBuffer();
            cmdclean.name = "(" + camera.name + ")" + "Clean Up";
            cmdclean.ReleaseTemporaryRT(m_ColorRTid);
            cmdclean.ReleaseTemporaryRT(m_DepthRTid);
            cmdclean.ReleaseTemporaryRT(m_MotionVectorRTid);
            context.ExecuteCommandBuffer(cmdclean);
            cmdclean.Release();

            context.Submit();

            //For camera motion vector
            _PreviousVP = _NonJitteredVP;

            EndCameraRendering(context, camera);
        }

        EndFrameRendering(context, cameras);
    }
Beispiel #7
0
    //Starts Rendering Part
    public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras)
    {
        //For shadowmapping, the matrices from the light's point of view
        Matrix4x4 view             = Matrix4x4.identity;
        Matrix4x4 proj             = Matrix4x4.identity;
        bool      successShadowMap = false;

        foreach (Camera camera in cameras)
        {
            bool isSceneViewCam = camera.cameraType == CameraType.SceneView;
            //************************** UGUI Geometry on scene view *************************
            #if UNITY_EDITOR
            if (isSceneViewCam)
            {
                ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
            }
            #endif

            //************************** Culling ****************************************
            ScriptableCullingParameters cullingParams;
            if (!CullResults.GetCullingParameters(camera, out cullingParams))
            {
                continue;
            }
            CullResults cull = new CullResults();
            CullResults.Cull(ref cullingParams, context, ref cull);

            //************************** Lighting Variables *****************************
            CommandBuffer cmdLighting = new CommandBuffer();
            cmdLighting.name = "(" + camera.name + ")" + "Lighting variable";
            int   mainLightIndex = -1;
            Light mainLight      = null;

            Vector4[] lightPositions = new Vector4[8];
            Vector4[] lightColors    = new Vector4[8];
            Vector4[] lightAttn      = new Vector4[8];
            Vector4[] lightSpotDir   = new Vector4[8];

            //Initialise values
            for (int i = 0; i < 8; i++)
            {
                lightPositions[i] = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
                lightColors[i]    = Color.black;
                lightAttn[i]      = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
                lightSpotDir[i]   = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
            }

            for (int i = 0; i < cull.visibleLights.Count; i++)
            {
                VisibleLight light = cull.visibleLights[i];

                if (mainLightIndex == -1) //Directional light
                {
                    if (light.lightType == LightType.Directional)
                    {
                        Vector4 dir = light.localToWorld.GetColumn(2);
                        lightPositions[0] = new Vector4(-dir.x, -dir.y, -dir.z, 0);
                        lightColors[0]    = light.light.color;

                        float lightRangeSqr                 = light.range * light.range;
                        float fadeStartDistanceSqr          = 0.8f * 0.8f * lightRangeSqr;
                        float fadeRangeSqr                  = (fadeStartDistanceSqr - lightRangeSqr);
                        float oneOverFadeRangeSqr           = 1.0f / fadeRangeSqr;
                        float lightRangeSqrOverFadeRangeSqr = -lightRangeSqr / fadeRangeSqr;
                        float quadAtten = 25.0f / lightRangeSqr;
                        lightAttn[0] = new Vector4(quadAtten, oneOverFadeRangeSqr, lightRangeSqrOverFadeRangeSqr, 1.0f);

                        cmdLighting.SetGlobalVector("_LightColor0", lightColors[0]);
                        cmdLighting.SetGlobalVector("_WorldSpaceLightPos0", lightPositions[0]);

                        mainLight      = light.light;
                        mainLightIndex = i;
                    }
                }
                else
                {
                    continue;//so far just do only 1 directional light
                }
            }

            cmdLighting.SetGlobalVectorArray("unity_LightPosition", lightPositions);
            cmdLighting.SetGlobalVectorArray("unity_LightColor", lightColors);
            cmdLighting.SetGlobalVectorArray("unity_LightAtten", lightAttn);
            cmdLighting.SetGlobalVectorArray("unity_SpotDirection", lightSpotDir);

            context.ExecuteCommandBuffer(cmdLighting);
            cmdLighting.Release();

            //************************** Draw Settings ************************************
            FilterRenderersSettings filterSettings = new FilterRenderersSettings(true);

            DrawRendererSettings drawSettingsDefault = new DrawRendererSettings(camera, passNameDefault);
            drawSettingsDefault.rendererConfiguration = renderConfig;
            drawSettingsDefault.flags = DrawRendererFlags.EnableDynamicBatching;
            drawSettingsDefault.SetShaderPassName(5, m_UnlitPassName);

            DrawRendererSettings drawSettingsBase = new DrawRendererSettings(camera, passNameBase);
            drawSettingsBase.flags = DrawRendererFlags.EnableDynamicBatching;
            drawSettingsBase.rendererConfiguration = renderConfig;

            DrawRendererSettings drawSettingsAdd = new DrawRendererSettings(camera, passNameAdd);
            drawSettingsAdd.flags = DrawRendererFlags.EnableDynamicBatching;
            drawSettingsAdd.rendererConfiguration = renderConfig;

            DrawRendererSettings drawSettingsDepth = new DrawRendererSettings(camera, passNameShadow);
            drawSettingsDepth.flags = DrawRendererFlags.EnableDynamicBatching;
            //drawSettingsBase.rendererConfiguration = renderConfig;

            //************************** Set TempRT ************************************
            CommandBuffer cmdTempId = new CommandBuffer();
            cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT";

            //Depth
            RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            depthRTDesc.colorFormat     = m_DepthFormat;
            depthRTDesc.depthBufferBits = depthBufferBits;
            cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear);

            //Color
            RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            colorRTDesc.colorFormat       = m_ColorFormat;
            colorRTDesc.depthBufferBits   = depthBufferBits; //have depth because we don't want to ruin the _CameraDepthTexture
            colorRTDesc.sRGB              = true;
            colorRTDesc.msaaSamples       = 1;
            colorRTDesc.enableRandomWrite = false;
            cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear);

            //Shadow
            RenderTextureDescriptor shadowRTDesc = new RenderTextureDescriptor(m_ShadowRes, m_ShadowRes);
            shadowRTDesc.colorFormat       = m_ShadowFormat;
            shadowRTDesc.depthBufferBits   = depthBufferBits; //have depth because it is also a depth texture
            shadowRTDesc.msaaSamples       = 1;
            shadowRTDesc.enableRandomWrite = false;
            cmdTempId.GetTemporaryRT(m_ShadowMapLightid, shadowRTDesc, FilterMode.Bilinear);//depth per light

            //ScreenSpaceShadowMap
            RenderTextureDescriptor shadowMapRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
            shadowMapRTDesc.colorFormat       = m_ShadowMapFormat;
            shadowMapRTDesc.depthBufferBits   = 0;
            shadowMapRTDesc.msaaSamples       = 1;
            shadowMapRTDesc.enableRandomWrite = false;
            cmdTempId.GetTemporaryRT(m_ShadowMapid, shadowMapRTDesc, FilterMode.Bilinear);//screen space shadow

            context.ExecuteCommandBuffer(cmdTempId);
            cmdTempId.Release();

            //************************** Do shadow? ************************************
            Bounds bounds;
            bool   doShadow = cull.GetShadowCasterBounds(mainLightIndex, out bounds);

            //************************** Shadow Mapping ************************************
            if (doShadow && !isSceneViewCam)
            {
                DrawShadowsSettings shadowSettings = new DrawShadowsSettings(cull, mainLightIndex);

                successShadowMap = cull.ComputeDirectionalShadowMatricesAndCullingPrimitives(mainLightIndex,
                                                                                             0, 1, new Vector3(1, 0, 0),
                                                                                             m_ShadowRes, mainLight.shadowNearPlane, out view, out proj,
                                                                                             out shadowSettings.splitData);

                CommandBuffer cmdShadow = new CommandBuffer();
                cmdShadow.name = "(" + camera.name + ")" + "Shadow Mapping";

                cmdShadow.SetRenderTarget(m_ShadowMapLight);
                cmdShadow.ClearRenderTarget(true, true, Color.black);

                //Change the view to light's point of view
                cmdShadow.SetViewport(new Rect(0, 0, m_ShadowRes, m_ShadowRes));
                cmdShadow.EnableScissorRect(new Rect(4, 4, m_ShadowRes - 8, m_ShadowRes - 8));
                cmdShadow.SetViewProjectionMatrices(view, proj);

                context.ExecuteCommandBuffer(cmdShadow);
                cmdShadow.Clear();

                //Render Shadowmap
                context.DrawShadows(ref shadowSettings);

                cmdShadow.DisableScissorRect();
                cmdShadow.SetGlobalTexture(m_ShadowMapLightid, m_ShadowMapLight);
                context.ExecuteCommandBuffer(cmdShadow);
                cmdShadow.Clear();
                cmdShadow.Release();
            }

            //************************** Camera Parameters ************************************
            context.SetupCameraProperties(camera);

            //************************** Depth (for CameraDepthTexture) ************************************
            CommandBuffer cmdDepthOpaque = new CommandBuffer();
            cmdDepthOpaque.name = "(" + camera.name + ")" + "Make CameraDepthTexture";

            cmdDepthOpaque.SetRenderTarget(m_DepthRT);
            cmdDepthOpaque.ClearRenderTarget(true, true, Color.black);
            context.ExecuteCommandBuffer(cmdDepthOpaque);
            cmdDepthOpaque.Clear();

            filterSettings.renderQueueRange = RenderQueueRange.opaque;
            drawSettingsDepth.sorting.flags = SortFlags.CommonOpaque;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDepth, filterSettings);

            cmdDepthOpaque.SetGlobalTexture(m_DepthRTid, m_DepthRT);
            context.ExecuteCommandBuffer(cmdDepthOpaque);
            cmdDepthOpaque.Release();

            //************************** Screen Space Shadow ************************************
            if (doShadow)
            {
                CommandBuffer cmdShadow2 = new CommandBuffer();
                cmdShadow2.name = "(" + camera.name + ")" + "Screen Space Shadow";

                //Bias
                if (mainLight != null)
                {
                    float sign = (SystemInfo.usesReversedZBuffer) ? 1.0f : -1.0f;
                    if (isSceneViewCam)
                    {
                        sign = -sign * 0.01f;
                    }
                    float bias = mainLight.shadowBias * proj.m22 * sign;

                    cmdShadow2.SetGlobalFloat("_ShadowBias", bias);
                }

                //Shadow Transform
                if (successShadowMap)
                {
                    cmdShadow2.EnableShaderKeyword("SHADOWS_SCREEN");
                    cmdShadow2.EnableShaderKeyword("LIGHTMAP_SHADOW_MIXING");

                    if (SystemInfo.usesReversedZBuffer)
                    {
                        proj.m20 = -proj.m20;
                        proj.m21 = -proj.m21;
                        proj.m22 = -proj.m22;
                        proj.m23 = -proj.m23;
                    }

                    Matrix4x4 WorldToShadow = proj * view;

                    float f = 0.5f;

                    var textureScaleAndBias = Matrix4x4.identity;
                    textureScaleAndBias.m00 = f;
                    textureScaleAndBias.m11 = f;
                    textureScaleAndBias.m22 = f;
                    textureScaleAndBias.m03 = f;
                    textureScaleAndBias.m23 = f;
                    textureScaleAndBias.m13 = f;

                    WorldToShadow = textureScaleAndBias * WorldToShadow;

                    cmdShadow2.SetGlobalMatrix("_WorldToShadow", WorldToShadow);
                    cmdShadow2.SetGlobalFloat("_ShadowStrength", mainLight.shadowStrength);
                }

                //Render the screen-space shadow
                cmdShadow2.Blit(m_ShadowMap, m_ShadowMap, m_ScreenSpaceShadowsMaterial);
                cmdShadow2.SetGlobalTexture(m_ShadowMapid, m_ShadowMap);

                context.ExecuteCommandBuffer(cmdShadow2);
                cmdShadow2.Release();
            }

            //************************** Clear ************************************
            CommandBuffer cmd = new CommandBuffer();
            cmd.name = "(" + camera.name + ")" + "Clear Flag";

            cmd.SetRenderTarget(m_ColorRT);
            ClearFlag(cmd, camera, camera.backgroundColor);

            context.ExecuteCommandBuffer(cmd);
            cmd.Release();

            //************************** Skybox ************************************
            if (camera.clearFlags == CameraClearFlags.Skybox)
            {
                context.DrawSkybox(camera);
            }

            //************************** Opaque ************************************
            filterSettings.renderQueueRange = RenderQueueRange.opaque;

            // DEFAULT pass, draw shaders without a pass name
            drawSettingsDefault.sorting.flags = SortFlags.CommonOpaque;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDefault, filterSettings);

            // BASE pass
            drawSettingsBase.sorting.flags = SortFlags.CommonOpaque;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettingsBase, filterSettings);

            // ADD pass
            drawSettingsAdd.sorting.flags = SortFlags.CommonOpaque;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettingsAdd, filterSettings);

            //************************** Blit to Camera Target ************************************
            // so that reflection probes will work + screen view buttons
            CommandBuffer cmdColorOpaque = new CommandBuffer();
            cmdColorOpaque.name = "(" + camera.name + ")" + "After opaque";

            //This blit is necessary for Windows...It makes sure the Z is correct for transparent objects
            cmdColorOpaque.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget);
            cmdColorOpaque.SetRenderTarget(m_ColorRT);

            //"Grab" pass
            cmdColorOpaque.SetGlobalTexture(m_GrabOpaqueRTid, m_ColorRT);

            context.ExecuteCommandBuffer(cmdColorOpaque);
            cmdColorOpaque.Release();

            //************************** Transparent ************************************
            filterSettings.renderQueueRange = RenderQueueRange.transparent;

            // DEFAULT pass
            drawSettingsDefault.sorting.flags = SortFlags.CommonTransparent;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDefault, filterSettings);

            // BASE pass
            drawSettingsBase.sorting.flags = SortFlags.CommonTransparent;
            context.DrawRenderers(cull.visibleRenderers, ref drawSettingsBase, filterSettings);

            //************************** Blit to Camera Target ************************************
            // so that reflection probes will work + screen view buttons
            CommandBuffer cmdColor = new CommandBuffer();
            cmdColor.name = "(" + camera.name + ")" + "After transparent";
            cmdColor.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget);
            cmdColor.SetRenderTarget(m_ColorRT);
            context.ExecuteCommandBuffer(cmdColor);
            cmdColor.Release();

            //************************** Post-processing ************************************
            m_CameraPostProcessLayer = camera.GetComponent <PostProcessLayer>();
            if (m_CameraPostProcessLayer != null && m_CameraPostProcessLayer.enabled)
            {
                CommandBuffer cmdpp = new CommandBuffer();
                cmdpp.name = "(" + camera.name + ")" + "Post-processing";

                m_PostProcessRenderContext.Reset();
                m_PostProcessRenderContext.camera       = camera;
                m_PostProcessRenderContext.source       = m_ColorRT;
                m_PostProcessRenderContext.sourceFormat = m_ColorFormat;
                m_PostProcessRenderContext.destination  = BuiltinRenderTextureType.CameraTarget;
                m_PostProcessRenderContext.command      = cmdpp;
                m_PostProcessRenderContext.flip         = camera.targetTexture == null;
                m_CameraPostProcessLayer.Render(m_PostProcessRenderContext);

                //Target is already CameraTarget

                context.ExecuteCommandBuffer(cmdpp);
                cmdpp.Release();
            }

            //************************** Scene View Fix ************************************
            #if UNITY_EDITOR
            if (isSceneViewCam)     //Copy depth to backbuffer's depth buffer
            {
                CommandBuffer cmdSceneDepth = new CommandBuffer();
                cmdSceneDepth.name = "(" + camera.name + ")" + "Copy Depth to CameraTarget";
                cmdSceneDepth.Blit(m_DepthRT, BuiltinRenderTextureType.CameraTarget, m_CopyDepthMaterial);
                context.ExecuteCommandBuffer(cmdSceneDepth);
                cmdSceneDepth.Release();
            }
            #endif

            //************************** Clean Up ************************************
            CommandBuffer cmdclean = new CommandBuffer();
            cmdclean.name = "(" + camera.name + ")" + "Clean Up";
            cmdclean.ReleaseTemporaryRT(m_ColorRTid);
            cmdclean.ReleaseTemporaryRT(m_DepthRTid);
            cmdclean.ReleaseTemporaryRT(m_ShadowMapid);
            cmdclean.ReleaseTemporaryRT(m_ShadowMapLightid);
            context.ExecuteCommandBuffer(cmdclean);
            cmdclean.Release();

            context.Submit();
        }
    }
Beispiel #8
0
    void OnGUI()
    {
        //minSize = new Vector2(kPreviewWidth, kPreviewHeight);
        //maxSize = new Vector2(kPreviewWidth, kPreviewHeight);

        curWindowSize.x = position.width;
        curWindowSize.y = position.height;
#if USING_MWU_HDRP
        GUILayout.BeginHorizontal();
        {
            if (GUILayout.Button("Converge", GUILayout.Height(STANDARDBUTTONHEIGHT)))
            {
                //Recreate preview buffer on resolution change.
                if (m_RenderCamera.pixelWidth != m_RenderView.width ||
                    m_RenderCamera.pixelHeight != m_RenderView.height)
                {
                    CreatePreviewBuffer();
                }

                //Request the final picture RT frame.
                RenderTexture convertedFrameRT = FilmicMotionBlurManager.Converge();

                //Blit RT to presentation buffer.
                Graphics.Blit(convertedFrameRT, m_RenderView);

                //Destory RT
                RenderTexture.DestroyImmediate(convertedFrameRT);

                // Hack: Currently the final converged from does not include bloom/final grading. Run it through post here...
                PostProcessLayer postProcessing = FilmicMotionBlurManager.GetPostLayer();

                //Supply Depth for DoF.
                CommandBuffer cmd = new CommandBuffer()
                {
                    name = "Render Window"
                };
                cmd.SetGlobalTexture(HDShaderIDs._CameraDepthTexture, HDRPColorDepthCapture.instance.DepthTexture); //Hack: Ask VFX script for depth...

                HDCamera hdCamera = HDCamera.Get(m_RenderCamera);
                var      postProcessRenderContext = hdCamera.postprocessRenderContext;
                postProcessRenderContext.Reset();
                postProcessRenderContext.source           = m_RenderView;
                postProcessRenderContext.destination      = m_RenderView;
                postProcessRenderContext.command          = cmd;
                postProcessRenderContext.camera           = Camera.main;
                postProcessRenderContext.sourceFormat     = RenderTextureFormat.ARGBHalf;
                postProcessRenderContext.flip             = false;
                postProcessRenderContext.skipDepthOfField = true;
                postProcessing.Render(postProcessRenderContext);

                Graphics.ExecuteCommandBuffer(cmd);
                cmd.Dispose();
            }

            if (GUILayout.Button("Save", GUILayout.Height(STANDARDBUTTONHEIGHT)))
            {
                string path = EditorUtility.SaveFilePanel("Save Render Preview", "", "RenderPreview", "png");

                int       w = m_RenderView.width;
                int       h = m_RenderView.height;
                Texture2D t = new Texture2D(w, h, TextureFormat.RGB24, false);

                RenderTexture pRT = RenderTexture.active;
                RenderTexture.active = m_RenderView;
                t.ReadPixels(new Rect(0, 0, w, h), 0, 0);
                RenderTexture.active = pRT;

                //Brute-force Gamma Correct
                for (int x = 0; x < w; x++)
                {
                    for (int y = 0; y < h; ++y)
                    {
                        Color currentColor = t.GetPixel(x, y);
                        t.SetPixel(x, y, currentColor.gamma);
                    }
                }

                byte[] bytes = t.EncodeToPNG();
                CoreUtils.Destroy(t);

                File.WriteAllBytes(path, bytes);
            }

            //if (GUILayout.Button("Close", GUILayout.Height(STANDARDBUTTONHEIGHT)))
            //{
            //    Close();
            //    return;
            //}
        }
        GUILayout.EndHorizontal();

        //Present final picture
        EditorGUI.DrawPreviewTexture(GUILayoutUtility.GetRect(curWindowSize.x, curWindowSize.y), m_RenderView, m_RenderWindowMaterial, ScaleMode.ScaleToFit, 0f);
#else
        GUILayout.Label("Render Window requires Sherman Custom HDRP package. If you have it installed already, add the #USING_MWU_HDRP define in your player defines", EditorStyles.helpBox);
#endif
    }