public override void FrameUpdate(PipelineCamera cam, ref PipelineCommandData data) { CommandBuffer buffer = data.buffer; RenderClusterOptions options = new RenderClusterOptions { command = buffer, frustumPlanes = proper.frustumPlanes, cullingShader = data.resources.shaders.gpuFrustumCulling, terrainCompute = data.resources.shaders.terrainCompute }; FilteringSettings alphaTestFilter = new FilteringSettings { layerMask = cam.cam.cullingMask, renderingLayerMask = 1, renderQueueRange = new RenderQueueRange(2450, 2499) }; FilteringSettings opaqueFilter = new FilteringSettings { layerMask = cam.cam.cullingMask, renderingLayerMask = 1, renderQueueRange = new RenderQueueRange(2000, 2449) }; FilteringSettings mvFilter = new FilteringSettings { layerMask = cam.cam.cullingMask, renderingLayerMask = 1, renderQueueRange = RenderQueueRange.opaque }; DrawingSettings depthAlphaTestDrawSettings = new DrawingSettings(new ShaderTagId("Depth"), new SortingSettings(cam.cam) { criteria = SortingCriteria.QuantizedFrontToBack | SortingCriteria.OptimizeStateChanges }) { perObjectData = UnityEngine.Rendering.PerObjectData.None, enableDynamicBatching = false, enableInstancing = false }; DrawingSettings depthOpaqueDrawSettings = new DrawingSettings(new ShaderTagId("Depth"), new SortingSettings(cam.cam) { criteria = SortingCriteria.QuantizedFrontToBack }) { perObjectData = UnityEngine.Rendering.PerObjectData.None, enableDynamicBatching = false, enableInstancing = false, overrideMaterial = proper.overrideOpaqueMaterial, overrideMaterialPassIndex = 1 }; DrawingSettings drawSettings = new DrawingSettings(new ShaderTagId("GBuffer"), new SortingSettings(cam.cam) { criteria = SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges }) { perObjectData = UnityEngine.Rendering.PerObjectData.Lightmaps, enableDynamicBatching = false, enableInstancing = false }; DrawingSettings mvDraw = new DrawingSettings(new ShaderTagId("MotionVector"), new SortingSettings { criteria = SortingCriteria.OptimizeStateChanges }) { perObjectData = UnityEngine.Rendering.PerObjectData.None, enableDynamicBatching = false, enableInstancing = false }; //Draw Depth Prepass data.buffer.SetRenderTarget(ShaderIDs._DepthBufferTexture); data.buffer.ClearRenderTarget(true, false, Color.black); cullHandle.Complete(); var lst = CustomDrawRequest.allEvents; foreach (var i in gbufferCullResults) { lst[i].DrawDepthPrepass(buffer); } SceneController.RenderScene(ref data, ref opaqueFilter, ref depthOpaqueDrawSettings, ref proper.cullResults); data.context.DrawRenderers(proper.cullResults, ref depthAlphaTestDrawSettings, ref alphaTestFilter); decalEvt.FrameUpdate(cam, ref data); //Draw GBuffer data.buffer.SetRenderTarget(colors: cam.targets.gbufferIdentifier, depth: ShaderIDs._DepthBufferTexture); data.buffer.ClearRenderTarget(false, true, Color.black); HizOcclusionData hizOccData; if (useHiZ) { hizOccData = IPerCameraData.GetProperty(cam, () => new HizOcclusionData()); SceneController.DrawCluster_LastFrameDepthHiZ(ref options, hizOccData, clusterMat, cam, proper.frustumMinPoint, proper.frustumMaxPoint); } foreach (var i in gbufferCullResults) { lst[i].DrawGBuffer(buffer); } SceneController.RenderScene(ref data, ref opaqueFilter, ref drawSettings, ref proper.cullResults); if (useHiZ) { SceneController.DrawCluster_RecheckHiz(ref options, ref hizDepth, hizOccData, clusterMat, linearMat, cam); } if (MTerrain.current) { MTerrain.current.DrawTerrain(buffer, 0, proper.frustumPlanes); } //Draw AlphaTest /* SortingSettings st = drawSettings.sortingSettings; * st.criteria = SortingCriteria.SortingLayer | SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges; * drawSettings.sortingSettings = st;*/ SceneController.RenderScene(ref data, ref alphaTestFilter, ref drawSettings, ref proper.cullResults); //Draw Depth data.buffer.Blit(ShaderIDs._DepthBufferTexture, ShaderIDs._CameraDepthTexture); //Draw Motion Vector data.buffer.SetRenderTarget(color: ShaderIDs._CameraMotionVectorsTexture, depth: ShaderIDs._DepthBufferTexture); foreach (var i in gbufferCullResults) { lst[i].DrawMotionVector(buffer); } SceneController.RenderScene(ref data, ref mvFilter, ref mvDraw, ref proper.cullResults); //Draw Static Global Motion Vector data.buffer.DrawMesh(GraphicsUtility.mesh, Matrix4x4.identity, motionVecMat, 0, 0); }
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { SortingCriteria sortingCriteria = (renderQueueType == RenderQueueType.Transparent) ? SortingCriteria.CommonTransparent : renderingData.cameraData.defaultOpaqueSortFlags; DrawingSettings drawingSettings = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortingCriteria); drawingSettings.overrideMaterial = overrideMaterial; drawingSettings.overrideMaterialPassIndex = overrideMaterialPassIndex; Camera camera = renderingData.cameraData.camera; float cameraAspect = (float)camera.pixelWidth / (float)camera.pixelHeight; CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag); using (new ProfilingSample(cmd, m_ProfilerTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); cmd.BeginSample("Copy Depth"); cmd.SetGlobalTexture("_CameraDepthAttachment", "_CameraDepthTexture"); // Copy the source depth buffer to the target render texture if (destination.Identifier() != source) { Blit(cmd, source, destination.Identifier(), m_CopyDepthMaterial); } cmd.EndSample("Copy Depth"); context.ExecuteCommandBuffer(cmd); cmd.Clear(); if (m_CameraSettings.overrideCamera) { Matrix4x4 projectionMatrix = Matrix4x4.Perspective(m_CameraSettings.cameraFieldOfView, cameraAspect, camera.nearClipPlane, camera.farClipPlane); Matrix4x4 viewMatrix = camera.worldToCameraMatrix; Vector4 cameraTranslation = viewMatrix.GetColumn(3); viewMatrix.SetColumn(3, cameraTranslation + m_CameraSettings.offset); cmd.SetViewProjectionMatrices(viewMatrix, projectionMatrix); context.ExecuteCommandBuffer(cmd); } context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref m_FilteringSettings, ref m_RenderStateBlock); if (m_CameraSettings.overrideCamera && m_CameraSettings.restoreCamera) { Matrix4x4 projectionMatrix = Matrix4x4.Perspective(camera.fieldOfView, cameraAspect, camera.nearClipPlane, camera.farClipPlane); cmd.Clear(); cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, projectionMatrix); } } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
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; //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //filterSettings.layerMask = 1; //only draws objects marked with UI layer filterSettings.renderingLayerMask = 1 << 4; //only draws renderers that has RenderingLayerMask Layer5 ********************************** //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); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
public override void Execute(ScriptableRenderContext context, ref UnityEngine.Rendering.Universal.RenderingData renderingData) { SortingCriteria sortingCriteria = (renderQueueType == RenderQueueType.Transparent) ? SortingCriteria.CommonTransparent : renderingData.cameraData.defaultOpaqueSortFlags; DrawingSettings drawingSettings = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortingCriteria); drawingSettings.overrideMaterial = overrideMaterial; drawingSettings.overrideMaterialPassIndex = overrideMaterialPassIndex; GraphicsFence portalsRenderedFence; Camera camera = renderingData.cameraData.camera; float cameraAspect = (float)camera.pixelWidth / (float)camera.pixelHeight; CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag); using (new ProfilingSample(cmd, m_ProfilerTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); cmd.SetRandomWriteTarget(1, portalRenderContext.computeBuffer); if (m_CameraSettings.overrideCamera) { //Matrix4x4 projectionMatrix = Matrix4x4.Perspective(m_CameraSettings.cameraFieldOfView, cameraAspect, // camera.nearClipPlane, camera.farClipPlane); //Matrix4x4 viewMatrix = camera.worldToCameraMatrix; //Vector4 cameraTranslation = viewMatrix.GetColumn(3); //viewMatrix.SetColumn(3, cameraTranslation + m_CameraSettings.offset); //cmd.SetViewProjectionMatrices(viewMatrix, projectionMatrix); portalRenderContext.exitPortal = GameObject.FindGameObjectWithTag("ExitPortal"); Camera exitCam = portalRenderContext.exitPortal.GetComponentInChildren <Camera>(); GameObject entryGO = GameObject.FindGameObjectWithTag("EntryPortal"); //Vector3 normal = exitCam.transform.forward; //Vector3 pos = exitCam.transform.position; //Vector4 clipPlaneWorldSpace = new Vector4(normal.x, normal.y, normal.z, -Vector3.Dot(normal, pos)); //Vector4 clipPlaneCameraSpace = exitCam.worldToCameraMatrix * clipPlaneWorldSpace; Matrix4x4 projectionMatrix = camera.projectionMatrix;//exitCam.CalculateObliqueMatrix(clipPlaneCameraSpace); Matrix4x4 destView = camera.worldToCameraMatrix * entryGO.transform.localToWorldMatrix * Matrix4x4.Rotate(entryGO.transform.rotation) * exitCam.transform.localToWorldMatrix.inverse; //* glm::rotate(glm::mat4(1.0f), 180.0f, glm::vec3(0.0f, 1.0f, 0.0f) * portal.orientation()) //* glm::inverse(portal.destination()->modelMat()); projectionMatrix = clippedProjMat(destView, projectionMatrix, entryGO.transform.position, entryGO.transform.rotation); //cmd.Clear(); cmd.SetViewProjectionMatrices(destView, projectionMatrix); context.ExecuteCommandBuffer(cmd); cmd.Clear(); } context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref m_FilteringSettings, ref m_RenderStateBlock); //ScriptableCullingParameters param; //context.Cull() if (m_CameraSettings.overrideCamera && m_CameraSettings.restoreCamera) { Matrix4x4 projectionMatrix = Matrix4x4.Perspective(camera.fieldOfView, cameraAspect, camera.nearClipPlane, camera.farClipPlane); cmd.Clear(); cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, projectionMatrix); } //portalsRenderedFence = cmd.CreateGraphicsFence(GraphicsFenceType.CPUSynchronisation, // SynchronisationStageFlags.PixelProcessing); //if (PortalDebugRenderOverlay.Instance?.renderTarget) //{ // PortalDebugRenderOverlay.Instance?.renderTarget = new RenderTexture(depthAttachment) //} //PortalDebugRenderOverlay.Instance?.fullscreenOverlay?.mainTexture = this.depthAttachment; } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); context.Submit(); //Debug.Log("Fence support:"+ SystemInfo.supportsGraphicsFence); //while (!portalsRenderedFence.passed) ; //Int32[] perPortalPixelCount = new Int32[255]; //portalRenderContext.computeBuffer.GetData(perPortalPixelCount, 0, 0, 255); //for (int i = 0; i < 5; i++) //{ // Debug.Log(i + "Portal count: " + perPortalPixelCount[i]); //} //portalRenderContext.computeBuffer.SetData(new Int32[255]); }
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; //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Define positions positions.Clear(); Vector4 pos = Vector4.zero; int splitRow = 5; for (int i = 0; i < m_PipelineAsset.count; i++) { pos.x = i % splitRow; pos.y = Mathf.FloorToInt(i / splitRow); pos.z = 0; pos.w = 1; positions.Add(pos); } //SetUp Position Computebuffers Data positionBuffer = new ComputeBuffer(m_PipelineAsset.count, 16); //4*4 bytes for Vector4 positionBuffer.SetData(positions); m_MaterialPropertyBlock.SetBuffer("positionBuffer", positionBuffer); //SetUp Args Computebuffers Data argsBuffer = new ComputeBuffer(1, args.Length * sizeof(uint), ComputeBufferType.IndirectArguments); args[0] = (uint)m_PipelineAsset.mesh.GetIndexCount(0); args[1] = (uint)m_PipelineAsset.count; args[2] = (uint)m_PipelineAsset.mesh.GetIndexStart(0); args[3] = (uint)m_PipelineAsset.mesh.GetBaseVertex(0); argsBuffer.SetData(args); //Draw Commands CommandBuffer cmdDraw = new CommandBuffer(); cmdDraw.DrawMeshInstancedIndirect(m_PipelineAsset.mesh, 0, m_PipelineAsset.mat, 0, argsBuffer, 0, m_MaterialPropertyBlock); context.ExecuteCommandBuffer(cmdDraw); cmdDraw.Release(); context.Submit(); //CleanUp after rendering this cam if (positionBuffer != null) { positionBuffer.Release(); positionBuffer = null; } if (argsBuffer != null) { argsBuffer.Release(); argsBuffer = null; } EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { bool isLitView = true; #if UNITY_EDITOR if (renderingData.cameraData.isSceneViewCamera) { isLitView = UnityEditor.SceneView.currentDrawingSceneView.sceneLighting; } if (renderingData.cameraData.camera.cameraType == CameraType.Preview) { isLitView = false; } if (!Application.isPlaying) { s_SortingLayers = SortingLayer.layers; } #endif Camera camera = renderingData.cameraData.camera; FilteringSettings filterSettings = new FilteringSettings(); filterSettings.renderQueueRange = RenderQueueRange.all; filterSettings.layerMask = -1; filterSettings.renderingLayerMask = 0xFFFFFFFF; filterSettings.sortingLayerRange = SortingLayerRange.all; bool isSceneLit = Light2D.IsSceneLit(camera); if (isSceneLit) { m_Renderer2DData.InitializeTransient(); CommandBuffer cmd = CommandBufferPool.Get(); cmd.Clear(); using (new ProfilingScope(cmd, m_ProfilingSampler)) { this.CreateNormalMapRenderTexture(renderingData, cmd); cmd.SetGlobalFloat("_HDREmulationScale", m_Renderer2DData.hdrEmulationScale); cmd.SetGlobalFloat("_InverseHDREmulationScale", 1.0f / m_Renderer2DData.hdrEmulationScale); cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f); cmd.SetGlobalColor("_RendererColor", Color.white); this.SetShapeLightShaderGlobals(cmd); context.ExecuteCommandBuffer(cmd); DrawingSettings combinedDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent); DrawingSettings normalsDrawSettings = CreateDrawingSettings(k_NormalsRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent); SortingSettings sortSettings = combinedDrawSettings.sortingSettings; GetTransparencySortingMode(camera, ref sortSettings); combinedDrawSettings.sortingSettings = sortSettings; normalsDrawSettings.sortingSettings = sortSettings; var blendStylesCount = m_Renderer2DData.lightBlendStyles.Length; for (var i = 0; i < s_SortingLayers.Length;) { var layerToRender = s_SortingLayers[i].id; var lightStats = Light2D.GetLightStatsByLayer(layerToRender, camera); cmd.Clear(); for (int blendStyleIndex = 0; blendStyleIndex < blendStylesCount; blendStyleIndex++) { uint blendStyleMask = (uint)(1 << blendStyleIndex); bool blendStyleUsed = (lightStats.blendStylesUsed & blendStyleMask) > 0; if (blendStyleUsed && !m_Renderer2DData.lightBlendStyles[blendStyleIndex].hasRenderTarget) { this.CreateBlendStyleRenderTexture(renderingData, cmd, blendStyleIndex); } RendererLighting.EnableBlendStyle(cmd, blendStyleIndex, blendStyleUsed); } context.ExecuteCommandBuffer(cmd); // find the highest layer that share the same set of lights as this layer var upperLayerInBatch = FindUpperBoundInBatch(i); // Some renderers override their sorting layer value with short.MinValue or short.MaxValue. // When drawing the first sorting layer, we should include the range from short.MinValue to layerValue. // Similarly, when drawing the last sorting layer, include the range from layerValue to short.MaxValue. var startLayerValue = (short)s_SortingLayers[i].value; var lowerBound = (i == 0) ? short.MinValue : startLayerValue; var endLayerValue = (short)s_SortingLayers[upperLayerInBatch].value; var upperBound = (upperLayerInBatch == s_SortingLayers.Length - 1) ? short.MaxValue : endLayerValue; // renderer within this range share the same set of lights so they should be rendered together filterSettings.sortingLayerRange = new SortingLayerRange(lowerBound, upperBound); // Start Rendering if (lightStats.totalNormalMapUsage > 0) { this.RenderNormals(context, renderingData.cullResults, normalsDrawSettings, filterSettings, depthAttachment); } cmd.Clear(); if (lightStats.totalLights > 0) { this.RenderLights(renderingData, cmd, layerToRender, lightStats.blendStylesUsed); } else { this.ClearDirtyLighting(cmd, lightStats.blendStylesUsed); } CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white); context.ExecuteCommandBuffer(cmd); Profiler.BeginSample("RenderSpritesWithLighting - Draw Transparent Renderers"); context.DrawRenderers(renderingData.cullResults, ref combinedDrawSettings, ref filterSettings); Profiler.EndSample(); if (lightStats.totalVolumetricUsage > 0) { cmd.Clear(); this.RenderLightVolumes(renderingData, cmd, layerToRender, colorAttachment, depthAttachment, lightStats.blendStylesUsed); context.ExecuteCommandBuffer(cmd); cmd.Clear(); } // move on to the next one i = upperLayerInBatch + 1; } cmd.Clear(); Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures"); this.ReleaseRenderTextures(cmd); Profiler.EndSample(); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); filterSettings.sortingLayerRange = SortingLayerRange.all; RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None); } else { DrawingSettings unlitDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent); CommandBuffer cmd = CommandBufferPool.Get(); using (new ProfilingScope(cmd, m_ProfilingSamplerUnlit)) { CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white); cmd.SetGlobalTexture("_ShapeLightTexture0", Texture2D.blackTexture); cmd.SetGlobalTexture("_ShapeLightTexture1", Texture2D.blackTexture); cmd.SetGlobalTexture("_ShapeLightTexture2", Texture2D.blackTexture); cmd.SetGlobalTexture("_ShapeLightTexture3", Texture2D.blackTexture); cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f); cmd.SetGlobalColor("_RendererColor", Color.white); cmd.EnableShaderKeyword("USE_SHAPE_LIGHT_TYPE_0"); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); Profiler.BeginSample("Render Sprites Unlit"); context.DrawRenderers(renderingData.cullResults, ref unlitDrawSettings, ref filterSettings); Profiler.EndSample(); RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None); } }
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; //************************** Start Set TempRT ************************************ CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; //Color RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); colorRTDesc.graphicsFormat = camera.allowHDR ? m_ColorFormatHDR : m_ColorFormat; 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); debugRTDesc = colorRTDesc; context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //************************** End Set TempRT ************************************ //Set RenderTarget & Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.SetRenderTarget(m_ColorRT); //Set CameraTarget to the color texture cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); MyDebug(camera, context, m_ColorRT, debugRTDesc, null); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } AfterSkybox(camera, context); //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Callback AfterOpaqueObject(camera, context); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Blit the content back to screen CommandBuffer cmdBlitToCam = new CommandBuffer(); cmdBlitToCam.name = "(" + camera.name + ")" + "Blit back to Camera"; cmdBlitToCam.Blit(m_ColorRTid, BuiltinRenderTextureType.CameraTarget); //Callback AfterTransparentObject(camera, context, m_ColorRT, debugRTDesc); context.ExecuteCommandBuffer(cmdBlitToCam); cmdBlitToCam.Release(); //************************** Clean Up ************************************ CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_ColorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
private void TestMetric(double value, string expected, int precision) { Assert.Equal(expected, DrawingSettings.FormatUnits(value, UnitFormat.Metric, precision)); }
private void TestArch(double value, string expected, int precision) { Assert.Equal(expected, DrawingSettings.FormatUnits(value, UnitFormat.Architectural, precision)); }
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { #if UNITY_EDITOR if (!Application.isPlaying) { s_SortingLayers = SortingLayer.layers; } #endif Camera camera = renderingData.cameraData.camera; RendererLighting.Setup(m_RendererData); CommandBuffer cmd = CommandBufferPool.Get("Render 2D Lighting"); Profiler.BeginSample("RenderSpritesWithLighting - Create Render Textures"); RendererLighting.CreateRenderTextures(cmd, camera); Profiler.EndSample(); cmd.SetGlobalFloat("_LightIntensityScale", m_RendererData.lightIntensityScale); cmd.SetGlobalFloat("_InverseLightIntensityScale", 1.0f / m_RendererData.lightIntensityScale); RendererLighting.SetShapeLightShaderGlobals(cmd); context.ExecuteCommandBuffer(cmd); Profiler.BeginSample("RenderSpritesWithLighting - Prepare"); DrawingSettings drawSettings = CreateDrawingSettings(k_CombinedRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent); FilteringSettings filterSettings = new FilteringSettings(); filterSettings.renderQueueRange = RenderQueueRange.all; filterSettings.layerMask = -1; filterSettings.renderingLayerMask = 0xFFFFFFFF; filterSettings.sortingLayerRange = SortingLayerRange.all; Profiler.EndSample(); bool cleared = false; for (int i = 0; i < s_SortingLayers.Length; i++) { short layerValue = (short)s_SortingLayers[i].value; filterSettings.sortingLayerRange = new SortingLayerRange(layerValue, layerValue); RendererLighting.RenderNormals(context, renderingData.cullResults, drawSettings, filterSettings); cmd.Clear(); int layerToRender = s_SortingLayers[i].id; RendererLighting.RenderLights(camera, cmd, layerToRender); // This should have an optimization where I can determine if this needs to be called. // And the clear is only needed if no previous pass has cleared the camera RT yet. var clearFlag = cleared ? ClearFlag.None : ClearFlag.All; var clearColor = renderingData.cameraData.camera.backgroundColor; cleared = true; SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, clearFlag, clearColor, TextureDimension.Tex2D); context.ExecuteCommandBuffer(cmd); Profiler.BeginSample("RenderSpritesWithLighting - Draw Renderers"); context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings); Profiler.EndSample(); cmd.Clear(); RendererLighting.RenderLightVolumes(camera, cmd, layerToRender); context.ExecuteCommandBuffer(cmd); cmd.Clear(); } Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures"); RendererLighting.ReleaseRenderTextures(cmd); Profiler.EndSample(); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); filterSettings.sortingLayerRange = SortingLayerRange.all; RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None); }
//完整的基本的兰伯特光照脚本 protected void Render_mutil_light(ScriptableRenderContext renderContext, Camera[] cameras) { //渲染开始后,创建CommandBuffer; if (myCommandBuffer == null) { myCommandBuffer = new CommandBuffer() { name = "SRP Study CB" } } ; //将shader中需要的属性参数映射为ID,加速传参 var D_LightDir = Shader.PropertyToID("_DLightDir"); var D_LightColor = Shader.PropertyToID("_DLightColor"); //在设置灯光参数ID下面增加相机参数ID: var _CameraPos = Shader.PropertyToID("_CameraPos"); var _PLightPos = Shader.PropertyToID("_PLightPos"); var _PLightColor = Shader.PropertyToID("_PLightColor"); //所有相机开始逐次渲染 foreach (var camera in cameras) { myCommandBuffer.BeginSample("Render " + camera.name); //设置渲染相关相机参数,包含相机的各个矩阵和剪裁平面等 renderContext.SetupCameraProperties(camera); //清理myCommandBuffer,设置渲染目标的颜色为摄像机背景 var flags = camera.clearFlags; //myCommandBuffer.ClearRenderTarget(true,true,camera.backgroundColor); myCommandBuffer.ClearRenderTarget((flags & CameraClearFlags.Depth) != 0, (flags & CameraClearFlags.Color) != 0, camera.backgroundColor); #if UNITY_EDITOR //为了在场景视图中看到UI //尽管Unity帮我们适配了UI在游戏窗口中显示,但不会在场景窗口显示。 //UI始终存在于场景窗口中的世界空间中,但是我们必须手动将其注入场景中。 //通过调用static ScriptableRenderContext.EmitWorldGeometryForSceneView方法(以当前摄像机为参数)来添加UI 。 //必须在cull之前完成此操作。 //为了避免游戏窗口中第二次添加UI。我们仅在渲染场景窗口时才发出UI几何。 //cameraType相机的等于时就是这种情况CameraType.SceneView。 if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif //剔除:拿到场景中的所有渲染器,然后剔除那些在摄像机视锥范围之外的渲染器。 //渲染器:它是附着在游戏对象上的组件,可将它们转变为可以渲染的东西。通常是一个MeshRenderer组件。 ScriptableCullingParameters cullParam = new ScriptableCullingParameters(); camera.TryGetCullingParameters(out cullParam); cullParam.isOrthographic = false; //TODO:避免没有任何可渲染的物体时,往下渲染 CullingResults cullResults = renderContext.Cull(ref cullParam); renderContext.DrawSkybox(camera); //在剪裁结果中获取灯光并进行参数获取 var lights = cullResults.visibleLights; int dLightIndex = 0; int pLightIndex = 0; foreach (var light in lights) { //判断灯光类型 if (light.lightType == LightType.Directional) { //在限定的灯光数量下,获取参数 if (dLightIndex < maxDirectionalLights) { //获取灯光参数,平行光朝向即为灯光Z轴方向。矩阵第一到三列分别为xyz轴项,第四列为位置。 Vector4 lightpos = light.localToWorldMatrix.GetColumn(2); //这边获取的灯光的finalColor是灯光颜色乘上强度之后的值,也正好是shader需要的值 DLightColors[dLightIndex] = light.finalColor; DLightDirections[dLightIndex] = -lightpos; DLightDirections[dLightIndex].w = 0;//方向光的第四个值(W值)为0,点为1. dLightIndex++; } } else { if (light.lightType != LightType.Point) { //其他类型光源部分 continue; } else { if (pLightIndex < maxPointLights) { PLightColors[pLightIndex] = light.finalColor; //将点光源的距离设置塞到颜色的A通道 PLightColors[pLightIndex].w = light.range; //矩阵第4列为位置 PLightPos[pLightIndex] = light.localToWorldMatrix.GetColumn(3); pLightIndex++; } } } } //传入相机参数。注意是世界空间位置。 Vector4 cameraPos = camera.transform.position; myCommandBuffer.SetGlobalVector(_CameraPos, cameraPos); //利用CommandBuffer进将灯光参数组传入Shader myCommandBuffer.SetGlobalVectorArray(D_LightColor, DLightColors); myCommandBuffer.SetGlobalVectorArray(D_LightDir, DLightDirections); myCommandBuffer.SetGlobalVectorArray(_PLightColor, PLightColors); myCommandBuffer.SetGlobalVectorArray(_PLightPos, PLightPos); myCommandBuffer.EndSample("Render " + camera.name); //执行CommandBuffer中的指令 renderContext.ExecuteCommandBuffer(myCommandBuffer); myCommandBuffer.Clear(); //过滤:决定使用哪些渲染器 FilteringSettings filtSet = new FilteringSettings(RenderQueueRange.opaque, -1); //filtSet.renderQueueRange = RenderQueueRange.opaque; //filtSet.layerMask = -1; //相机用于设置排序和剔除层,而DrawingSettings控制使用哪个着色器过程进行渲染。 //决定使用何种渲染排序顺序 对应shader里的 Tags{ "Queue" = "Geometry" } 这属性(不是这个单一属性) //opaque涵盖了从0到2500(包括2500)之间的渲染队列。 SortingSettings sortSet = new SortingSettings(camera) { criteria = SortingCriteria.CommonOpaque }; //决定使用何种light mode,对应shader的pass的tag中的LightMode DrawingSettings drawSet = new DrawingSettings(new ShaderTagId("BaseLit"), sortSet); //1.绘制不透明物体 renderContext.DrawRenderers(cullResults, ref drawSet, ref filtSet); //2.绘制天空球,在不透明物体之后绘制。early-z避免不必要的overdraw。 renderContext.DrawSkybox(camera); //3.绘制透明物体 //,RenderQueueRange.transparent在渲染天空盒之后,将队列范围更改为从2501到5000,包括5000,然后再次渲染。 filtSet.renderQueueRange = RenderQueueRange.transparent; sortSet.criteria = SortingCriteria.CommonTransparent; //由于我们仅在管道中支持未照明的材质,因此我们将使用Unity的默认未照明通道,该通道由SRPDefaultUnlit标识。 drawSet = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), sortSet); renderContext.DrawRenderers(cullResults, ref drawSet, ref filtSet); //绘制错误 //由于我们的管道仅支持未着色的着色器,因此不会渲染使用不同着色器的对象,从而使它们不可见。尽管这是正确的, //但它掩盖了某些对象使用错误着色器的事实。如果我们使用Unity的错误着色器可视化这些对象,那将是很好的, //因此它们显示为明显不正确的洋红色形状。让我们DrawDefaultPipeline为此添加一个专用方法,其中包含一个上下文和一个camera参数。 //在绘制透明形状之后,我们将在最后调用它。 DrawErrorShaderObject(cullResults, renderContext, camera); //开始执行渲染内容 renderContext.Submit(); } } RenderTexture shadowMap; //void RenderShadows(ScriptableRenderContext context) //{ // shadowMap = RenderTexture.GetTemporary(512, 512, 16, RenderTextureFormat.Shadowmap); // shadowMap.filterMode = FilterMode.Bilinear; // shadowMap.wrapMode = TextureWrapMode.Clamp; // CoreUtils.SetRenderTarget(shadowBuffer, shadowMap, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.Depth); // shadowBuffer.BeginSample("Render Shadows"); // context.ExecuteCommandBuffer(shadowBuffer); // shadowBuffer.Clear(); // shadowBuffer.EndSample("Render shadows"); // context.ExecuteCommandBuffer(shadowBuffer); // shadowBuffer.Clear(); //} }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(cameras); foreach (Camera camera in cameras) { BeginCameraRendering(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); camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth; //Setup sort, filter, draw settings var sortingSettings = new SortingSettings(camera); var drawSettings = new DrawingSettings(m_PassName, sortingSettings); drawSettings.perObjectData |= PerObjectData.MotionVectors; var filterSettings = new FilteringSettings(RenderQueueRange.all); filterSettings.excludeMotionVectorObjects = false; InitializeFrameSettings(); #if true int iterations = Application.isPlaying && m_AccumulationMode == StochasticRasterizer.AccumulationMode.Finite ? m_AccumulationIterations : 1; for (int i = 0; i < iterations; ++i) { //Clear ClearBuffers(context); //Sky DrawSkybox(camera, context); //Shader Inputs PushShadingConstants(camera, context, i); //Opacity Accumulation //RenderOpacity(sortingSettings, drawSettings, filterSettings, cull, context); //Stochastic RenderStochasticForward(sortingSettings, drawSettings, filterSettings, cull, context); //Final Pass RenderFinalPass(context, i, camera); } PresentAccumulation(context); #endif // Gather Shutter-Open information. var gpuView = camera.worldToCameraMatrix; var gpuProj = GL.GetGPUProjectionMatrix(camera.projectionMatrix, true); bool isSceneCam = camera.name == "SceneCamera"; if (isSceneCam) { m_ShutterOpenViewMatrix_scene = gpuView; m_ShutterOpenProjectionMatrix_scene = gpuProj; } else { m_ShutterOpenViewMatrix_game = gpuView; m_ShutterOpenProjectionMatrix_game = gpuProj; } //Get the world matrix of an object's transform on shutter close to demonstrate object motion blur var hack = camera.GetComponent <StochasticMaterialDebugger>(); if (hack != null) { m_ObjectShutterOpenMatrix = hack.FirstObjectMatrix; } context.Submit(); } }
private void Render(ScriptableRenderContext context, CommandBuffer cmd, ref RenderingData renderingData, ref FilteringSettings filterSettings, DrawingSettings drawSettings, bool debugRender) { if (debugRender) { foreach (DebugRenderSetup debugRenderSetup in DebugHandler.CreateDebugRenderSetupEnumerable(context, cmd)) { DrawingSettings debugDrawSettings = debugRenderSetup.CreateDrawingSettings(ref renderingData, drawSettings); if (debugRenderSetup.GetRenderStateBlock(out RenderStateBlock renderStateBlock)) { context.DrawRenderers(renderingData.cullResults, ref debugDrawSettings, ref filterSettings, ref renderStateBlock); } else { context.DrawRenderers(renderingData.cullResults, ref debugDrawSettings, ref filterSettings); } } } else { context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings); } }
public DrawingArgs(DrawingSettings drawingSetting) : base() { DrawingSetting = drawingSetting; }
/// <inheritdoc/> public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { // NOTE: Do NOT mix ProfilingScope with named CommandBuffers i.e. CommandBufferPool.Get("name"). // Currently there's an issue which results in mismatched markers. CommandBuffer cmd = CommandBufferPool.Get(); using (new ProfilingScope(cmd, m_ProfilingSampler)) { // Global render pass data containing various settings. // x,y,z are currently unused // w is used for knowing whether the object is opaque(1) or alpha blended(0) Vector4 drawObjectPassData = new Vector4(0.0f, 0.0f, 0.0f, (m_IsOpaque) ? 1.0f : 0.0f); cmd.SetGlobalVector(s_DrawObjectPassDataPropID, drawObjectPassData); // scaleBias.x = flipSign // scaleBias.y = scale // scaleBias.z = bias // scaleBias.w = unused float flipSign = (renderingData.cameraData.IsCameraProjectionMatrixFlipped()) ? -1.0f : 1.0f; Vector4 scaleBias = (flipSign < 0.0f) ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f) : new Vector4(flipSign, 0.0f, 1.0f, 1.0f); cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBias); context.ExecuteCommandBuffer(cmd); cmd.Clear(); Camera camera = renderingData.cameraData.camera; var sortFlags = (m_IsOpaque) ? renderingData.cameraData.defaultOpaqueSortFlags : SortingCriteria.CommonTransparent; if (renderingData.cameraData.renderer.useDepthPriming && m_IsOpaque && (renderingData.cameraData.renderType == CameraRenderType.Base || renderingData.cameraData.clearDepth)) { sortFlags = SortingCriteria.SortingLayer | SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges | SortingCriteria.CanvasOrder; } var filterSettings = m_FilteringSettings; #if UNITY_EDITOR // When rendering the preview camera, we want the layer mask to be forced to Everything if (renderingData.cameraData.isPreviewCamera) { filterSettings.layerMask = -1; } #endif DrawingSettings drawSettings = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortFlags); var activeDebugHandler = GetActiveDebugHandler(renderingData); if (activeDebugHandler != null) { activeDebugHandler.DrawWithDebugRenderState(context, cmd, ref renderingData, ref drawSettings, ref filterSettings, ref m_RenderStateBlock, (ScriptableRenderContext ctx, ref RenderingData data, ref DrawingSettings ds, ref FilteringSettings fs, ref RenderStateBlock rsb) => { ctx.DrawRenderers(data.cullResults, ref ds, ref fs, ref rsb); }); } else { context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings, ref m_RenderStateBlock); // Render objects that did not match any shader pass with error shader RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None); } } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
private void ParseFail(string text) { double temp; Assert.False(DrawingSettings.TryParseUnits(text, out temp)); }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(out cullingParameters)) { return; } // cull cullingResults = context.Cull(ref cullingParameters); context.SetupCameraProperties(camera); // clear CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.BeginSample("Render Camera"); cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); // shadow RenderShadows(context); // light constans ConfigureLights(); cameraBuffer.SetGlobalVectorArray(visibleLightColorsId, visibleLightColors); cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions); cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsId, visisbleLightAtenuations); cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionsId, visisbleLightSpotDirections); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // draw oqaque mesh var sortingSettings = new SortingSettings(camera); var drawSettings = new DrawingSettings(unlitShaderTagId, sortingSettings) { enableDynamicBatching = enableDynamicBatching, enableInstancing = enableInstancing, perObjectData = PerObjectData.LightProbe | PerObjectData.ReflectionProbes | PerObjectData.Lightmaps | PerObjectData.ShadowMask | PerObjectData.LightProbeProxyVolume | PerObjectData.OcclusionProbe | PerObjectData.LightData | PerObjectData.LightIndices, }; for (int i = 0; i < legacyShaderTagIds.Length; i++) { drawSettings.SetShaderPassName(i + 1, legacyShaderTagIds[i]); } var filterSettings = new FilteringSettings(RenderQueueRange.opaque); context.DrawRenderers(cullingResults, ref drawSettings, ref filterSettings); // draw skybox context.DrawSkybox(camera); // draw transparent mesh filterSettings = new FilteringSettings(RenderQueueRange.transparent); context.DrawRenderers(cullingResults, ref drawSettings, ref filterSettings); cameraBuffer.EndSample("Render Camera"); // commit context.Submit(); // release if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } }
public override void FrameUpdate(PipelineCamera cam, ref PipelineCommandData data) { CommandBuffer buffer = data.buffer; RenderClusterOptions options = new RenderClusterOptions { command = buffer, frustumPlanes = proper.frustumPlanes, cullingShader = data.resources.shaders.gpuFrustumCulling, terrainCompute = data.resources.shaders.terrainCompute }; FilteringSettings alphaTestFilter = new FilteringSettings { layerMask = cam.cam.cullingMask, renderingLayerMask = 1, renderQueueRange = new RenderQueueRange(2450, 2499) }; FilteringSettings opaqueFilter = new FilteringSettings { layerMask = cam.cam.cullingMask, renderingLayerMask = 1, renderQueueRange = new RenderQueueRange(2000, 2449) }; FilteringSettings mvFilter = new FilteringSettings { layerMask = cam.cam.cullingMask, renderingLayerMask = 1, renderQueueRange = RenderQueueRange.opaque }; DrawingSettings depthAlphaTestDrawSettings = new DrawingSettings(new ShaderTagId("Depth"), new SortingSettings(cam.cam) { criteria = SortingCriteria.QuantizedFrontToBack }) { perObjectData = UnityEngine.Rendering.PerObjectData.None, enableDynamicBatching = false, enableInstancing = false }; DrawingSettings depthOpaqueDrawSettings = new DrawingSettings(new ShaderTagId("Depth"), new SortingSettings(cam.cam) { criteria = SortingCriteria.QuantizedFrontToBack }) { perObjectData = UnityEngine.Rendering.PerObjectData.None, enableDynamicBatching = false, enableInstancing = false, overrideMaterial = proper.overrideOpaqueMaterial, overrideMaterialPassIndex = 1 }; DrawingSettings drawSettings = new DrawingSettings(new ShaderTagId("GBuffer"), new SortingSettings(cam.cam) { criteria = SortingCriteria.SortingLayer | SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges }) { perObjectData = UnityEngine.Rendering.PerObjectData.Lightmaps, enableDynamicBatching = false, enableInstancing = false }; DrawingSettings mvDraw = new DrawingSettings(new ShaderTagId("MotionVector"), new SortingSettings { criteria = SortingCriteria.None }) { perObjectData = UnityEngine.Rendering.PerObjectData.None, enableDynamicBatching = false, enableInstancing = false }; //Draw Depth Prepass data.buffer.SetRenderTarget(ShaderIDs._DepthBufferTexture); data.buffer.ClearRenderTarget(true, false, Color.black); cullHandle.Complete(); var lst = CustomDrawRequest.allEvents; foreach (var i in gbufferCullResults) { lst[i].DrawDepthPrepass(buffer); } SceneController.RenderScene(ref data, ref opaqueFilter, ref depthOpaqueDrawSettings, ref proper.cullResults); data.context.DrawRenderers(proper.cullResults, ref depthAlphaTestDrawSettings, ref alphaTestFilter); //Draw GBuffer data.buffer.SetRenderTarget(colors: cam.targets.gbufferIdentifier, depth: ShaderIDs._DepthBufferTexture); data.buffer.ClearRenderTarget(false, true, Color.black); HizOcclusionData hizOccData; if (useHiZ) { hizOccData = IPerCameraData.GetProperty(cam, () => new HizOcclusionData()); SceneController.DrawCluster_LastFrameDepthHiZ(ref options, hizOccData, clusterMat, cam); } foreach (var i in gbufferCullResults) { lst[i].DrawGBuffer(buffer); } SceneController.RenderScene(ref data, ref opaqueFilter, ref drawSettings, ref proper.cullResults); if (useHiZ) { SceneController.DrawCluster_RecheckHiz(ref options, ref hizDepth, hizOccData, clusterMat, linearMat, cam); } //Draw AlphaTest /* SortingSettings st = drawSettings.sortingSettings; * st.criteria = SortingCriteria.SortingLayer | SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges; * drawSettings.sortingSettings = st;*/ SceneController.RenderScene(ref data, ref alphaTestFilter, ref drawSettings, ref proper.cullResults); //Draw Depth data.buffer.Blit(ShaderIDs._DepthBufferTexture, ShaderIDs._CameraDepthTexture); //Draw Motion Vector data.buffer.SetRenderTarget(color: ShaderIDs._CameraMotionVectorsTexture, depth: ShaderIDs._DepthBufferTexture); foreach (var i in gbufferCullResults) { lst[i].DrawMotionVector(buffer); } SceneController.RenderScene(ref data, ref mvFilter, ref mvDraw, ref proper.cullResults); //Draw Static Global Motion Vector data.buffer.DrawMesh(GraphicsUtility.mesh, Matrix4x4.identity, motionVecMat, 0, 0); //Generate DownSampled GBuffer if ((ao != null && ao.Enabled) || (reflection != null && reflection.Enabled && reflection.ssrEvents.enabled)) { int2 res = int2(cam.cam.pixelWidth, cam.cam.pixelHeight) / 2; data.buffer.GetTemporaryRT(ShaderIDs._DownSampledGBuffer1, res.x, res.y, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1, false); data.buffer.GetTemporaryRT(ShaderIDs._DownSampledGBuffer2, res.x, res.y, 0, FilterMode.Point, RenderTextureFormat.ARGB2101010, RenderTextureReadWrite.Linear, 1, false); data.buffer.GetTemporaryRT(ShaderIDs._DownSampledDepthTexture, res.x, res.y, 0, FilterMode.Point, RenderTextureFormat.RHalf, RenderTextureReadWrite.Linear, 1, false); downSampledGBuffers[0] = ShaderIDs._DownSampledDepthTexture; downSampledGBuffers[1] = ShaderIDs._DownSampledGBuffer1; downSampledGBuffers[2] = ShaderIDs._DownSampledGBuffer2; data.buffer.SetRenderTarget(colors: downSampledGBuffers, depth: downSampledGBuffers[0]); data.buffer.DrawMesh(GraphicsUtility.mesh, Matrix4x4.identity, downSampleMat, 0, 0); RenderPipeline.ReleaseRTAfterFrame(ShaderIDs._DownSampledGBuffer1); RenderPipeline.ReleaseRTAfterFrame(ShaderIDs._DownSampledGBuffer2); RenderPipeline.ReleaseRTAfterFrame(ShaderIDs._DownSampledDepthTexture); //TODO } }
static public void RenderNormals(ScriptableRenderContext renderContext, CullingResults cullResults, DrawingSettings drawSettings, FilteringSettings filterSettings) { var cmd = CommandBufferPool.Get("Clear Normals"); cmd.SetRenderTarget(s_NormalsTarget.Identifier()); cmd.ClearRenderTarget(true, true, k_NormalClearColor); renderContext.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); drawSettings.SetShaderPassName(0, k_NormalsRenderingPassName); renderContext.DrawRenderers(cullResults, ref drawSettings, ref filterSettings); }
public static void RenderNormals(this IRenderPass2D pass, ScriptableRenderContext context, RenderingData renderingData, DrawingSettings drawSettings, FilteringSettings filterSettings, RenderTargetIdentifier depthTarget, CommandBuffer cmd, LightStats lightStats) { using (new ProfilingScope(cmd, m_ProfilingSampler)) { // figure out the scale var normalRTScale = 0.0f; if (depthTarget != BuiltinRenderTextureType.None) { normalRTScale = 1.0f; } else { normalRTScale = Mathf.Clamp(pass.rendererData.lightRenderTextureScale, 0.01f, 1.0f); } pass.CreateNormalMapRenderTexture(renderingData, cmd, normalRTScale); var msaaEnabled = renderingData.cameraData.cameraTargetDescriptor.msaaSamples > 1; var storeAction = msaaEnabled ? RenderBufferStoreAction.Resolve : RenderBufferStoreAction.Store; var clearFlag = pass.rendererData.useDepthStencilBuffer ? ClearFlag.All : ClearFlag.Color; if (depthTarget != BuiltinRenderTextureType.None) { CoreUtils.SetRenderTarget(cmd, pass.rendererData.normalsRenderTarget, RenderBufferLoadAction.DontCare, storeAction, depthTarget, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, clearFlag, k_NormalClearColor); } else { CoreUtils.SetRenderTarget(cmd, pass.rendererData.normalsRenderTarget, RenderBufferLoadAction.DontCare, storeAction, clearFlag, k_NormalClearColor); } context.ExecuteCommandBuffer(cmd); cmd.Clear(); drawSettings.SetShaderPassName(0, k_NormalsRenderingPassName); context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings); } }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(context, cameras); foreach (Camera camera in cameras) { #if UNITY_EDITOR bool isSceneViewCam = camera.cameraType == CameraType.SceneView; if (isSceneViewCam) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); //This makes the UI Canvas geometry appear on scene view } #endif 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; //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.name = "Cam:" + camera.name + " ClearFlag"; 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); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //SceneView fix, so that it draws the gizmos on scene view #if UNITY_EDITOR if (isSceneViewCam) { context.DrawGizmos(camera, GizmoSubset.PostImageEffects); } #endif context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
private void Render(ScriptableRenderContext context, Camera camera) { /* Attempt to cull the current camera. * If it fails to cull, don't render anything to this camera. */ ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(out cullingParameters)) { return; } #if UNITY_EDITOR // For rendering UI in the scene view if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif cullingResults = context.Cull(ref cullingParameters); // Setup properties for a specific camera. context.SetupCameraProperties(camera); /* Creates a graphics command buffer. * This particular one is told to clear the depth buffer, not the colour, and to set the clear colour to transparent. * It finally releases the memory it has, as the commands have been sent to the internal buffer of the rendering context. */ //var buffer = new CommandBuffer(); //buffer.ClearRenderTarget(true, false, Color.clear); //context.ExecuteCommandBuffer(buffer); //buffer.Release(); /* Creates a graphics command buffer. * This particular one is told to clear the depth buffer, not the colour, and to set the clear colour to transparent. * It finally releases the memory it has, as the commands have been sent to the internal buffer of the rendering context. */ CameraClearFlags clearFlags = camera.clearFlags; buffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); buffer.BeginSample("Render Camera"); // Start nested grouping for command buffer (For Frame Debugger) context.ExecuteCommandBuffer(buffer); //buffer.Release(); buffer.Clear(); // Once culling and clearing have been completed we can draw the appropriate renderers. var drawSettings = new DrawingSettings(new ShaderTagId("SRPDefaultUnlit"), new SortingSettings(camera)); var filterSettings = FilteringSettings.defaultValue; // Only render the opaque objects first. To avoid transparent objects being drawn behind the skybox. filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cullingResults, ref drawSettings, ref filterSettings); // Check for any problems drawing objects with custom pipeline. DrawDefaultPipeline(context, camera); // Draws a skybox to the specified camera. context.DrawSkybox(camera); // After all the opaque objects have been drawn, draw the transparent objects. filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cullingResults, ref drawSettings, ref filterSettings); // End nested grouping for command buffer (For Frame Debugger) buffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(buffer); buffer.Clear(); // Commands sent to the rendering context are just buffered. They are only excuted once we submit them. context.Submit(); }
// Here you can implement the rendering logic. // Use <c>ScriptableRenderContext</c> to issue drawing commands or execute command buffers // https://docs.unity3d.com/ScriptReference/Rendering.ScriptableRenderContext.html // You don't have to call ScriptableRenderContext.submit, the render pipeline will call it at specific points in the pipeline. public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { CommandBuffer cb = CommandBufferPool.Get("SSPR"); int dispatchThreadGroupXCount = GetRTWidth() / SHADER_NUMTHREAD_X; //divide by shader's numthreads.x int dispatchThreadGroupYCount = GetRTHeight() / SHADER_NUMTHREAD_Y; //divide by shader's numthreads.y int dispatchThreadGroupZCount = 1; //divide by shader's numthreads.z if (settings.ShouldRenderSSPR) { cb.SetComputeVectorParam(cs, Shader.PropertyToID("_RTSize"), new Vector2(GetRTWidth(), GetRTHeight())); cb.SetComputeFloatParam(cs, Shader.PropertyToID("_HorizontalPlaneHeightWS"), settings.HorizontalReflectionPlaneHeightWS); cb.SetComputeFloatParam(cs, Shader.PropertyToID("_FadeOutScreenBorderWidthVerticle"), settings.FadeOutScreenBorderWidthVerticle); cb.SetComputeFloatParam(cs, Shader.PropertyToID("_FadeOutScreenBorderWidthHorizontal"), settings.FadeOutScreenBorderWidthHorizontal); cb.SetComputeVectorParam(cs, Shader.PropertyToID("_CameraDirection"), renderingData.cameraData.camera.transform.forward); cb.SetComputeFloatParam(cs, Shader.PropertyToID("_ScreenLRStretchIntensity"), settings.ScreenLRStretchIntensity); cb.SetComputeFloatParam(cs, Shader.PropertyToID("_ScreenLRStretchThreshold"), settings.ScreenLRStretchThreshold); cb.SetComputeVectorParam(cs, Shader.PropertyToID("_FinalTintColor"), settings.TintColor); if (ShouldUseSinglePassUnsafeAllowFlickeringDirectResolve()) { //////////////////////////////////////////////// //Android Path //////////////////////////////////////////////// //kernel MobilePathsinglePassColorRTDirectResolve int kernel_MobilePathSinglePassColorRTDirectResolve = cs.FindKernel("MobilePathSinglePassColorRTDirectResolve"); cb.SetComputeTextureParam(cs, kernel_MobilePathSinglePassColorRTDirectResolve, "ColorRT", _SSPR_ColorRT_rti); cb.SetComputeTextureParam(cs, kernel_MobilePathSinglePassColorRTDirectResolve, "PosWSyRT", _SSPR_PosWSyRT_rti); cb.SetComputeTextureParam(cs, kernel_MobilePathSinglePassColorRTDirectResolve, "_CameraOpaqueTexture", new RenderTargetIdentifier("_CameraOpaqueTexture")); cb.SetComputeTextureParam(cs, kernel_MobilePathSinglePassColorRTDirectResolve, "_CameraDepthTexture", new RenderTargetIdentifier("_CameraDepthTexture")); cb.DispatchCompute(cs, kernel_MobilePathSinglePassColorRTDirectResolve, dispatchThreadGroupXCount, dispatchThreadGroupYCount, dispatchThreadGroupZCount); } else { //////////////////////////////////////////////// //Non-Android Path (PC/console..) //////////////////////////////////////////////// //kernel NonMobilePathClear int kernel_NonMobilePathClear = cs.FindKernel("NonMobilePathClear"); cb.SetComputeTextureParam(cs, kernel_NonMobilePathClear, "HashRT", _SSPR_PackedDataRT_rti); cb.SetComputeTextureParam(cs, kernel_NonMobilePathClear, "ColorRT", _SSPR_ColorRT_rti); cb.DispatchCompute(cs, kernel_NonMobilePathClear, dispatchThreadGroupXCount, dispatchThreadGroupYCount, dispatchThreadGroupZCount); //kernel NonMobilePathRenderHashRT int kernel_NonMobilePathRenderHashRT = cs.FindKernel("NonMobilePathRenderHashRT"); cb.SetComputeTextureParam(cs, kernel_NonMobilePathRenderHashRT, "HashRT", _SSPR_PackedDataRT_rti); cb.SetComputeTextureParam(cs, kernel_NonMobilePathRenderHashRT, "_CameraDepthTexture", new RenderTargetIdentifier("_CameraDepthTexture")); cb.DispatchCompute(cs, kernel_NonMobilePathRenderHashRT, dispatchThreadGroupXCount, dispatchThreadGroupYCount, dispatchThreadGroupZCount); //resolve to ColorRT int kernel_NonMobilePathResolveColorRT = cs.FindKernel("NonMobilePathResolveColorRT"); cb.SetComputeTextureParam(cs, kernel_NonMobilePathResolveColorRT, "_CameraOpaqueTexture", new RenderTargetIdentifier("_CameraOpaqueTexture")); cb.SetComputeTextureParam(cs, kernel_NonMobilePathResolveColorRT, "ColorRT", _SSPR_ColorRT_rti); cb.SetComputeTextureParam(cs, kernel_NonMobilePathResolveColorRT, "HashRT", _SSPR_PackedDataRT_rti); cb.DispatchCompute(cs, kernel_NonMobilePathResolveColorRT, dispatchThreadGroupXCount, dispatchThreadGroupYCount, dispatchThreadGroupZCount); } //optional shared pass to improve result only: fill RT hole if (settings.ApplyFillHoleFix) { int kernel_FillHoles = cs.FindKernel("FillHoles"); cb.SetComputeTextureParam(cs, kernel_FillHoles, "ColorRT", _SSPR_ColorRT_rti); cb.SetComputeTextureParam(cs, kernel_FillHoles, "PackedDataRT", _SSPR_PackedDataRT_rti); cb.DispatchCompute(cs, kernel_FillHoles, Mathf.CeilToInt(dispatchThreadGroupXCount / 2f), Mathf.CeilToInt(dispatchThreadGroupYCount / 2f), dispatchThreadGroupZCount); } //send out to global, for user's shader to sample reflection result RT (_MobileSSPR_ColorRT) //where _MobileSSPR_ColorRT's rgb is reflection color, a is reflection usage 0~1 for user's shader to lerp with fallback reflection probe's rgb cb.SetGlobalTexture(_SSPR_ColorRT_pid, _SSPR_ColorRT_rti); cb.EnableShaderKeyword("_MobileSSPR"); } else { //allow user to skip SSPR related code if disabled cb.DisableShaderKeyword("_MobileSSPR"); } context.ExecuteCommandBuffer(cb); CommandBufferPool.Release(cb); //====================================================================== //draw objects(e.g. reflective wet ground plane) with lightmode "MobileSSPR", which will sample _MobileSSPR_ColorRT DrawingSettings drawingSettings = CreateDrawingSettings(lightMode_SSPR_sti, ref renderingData, SortingCriteria.CommonOpaque); FilteringSettings filteringSettings = new FilteringSettings(RenderQueueRange.all); context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings); }
public static void RenderScene(ref PipelineCommandData data, ref FilteringSettings filterSettings, ref DrawingSettings drawSettings, ref CullingResults cullResults) { data.ExecuteCommandBuffer(); data.context.DrawRenderers(cullResults, ref drawSettings, ref filterSettings); }
private void Render(ScriptableRenderContext context, CommandBuffer cmd, ref RenderingData renderingData, ref FilteringSettings filterSettings, DrawingSettings drawSettings) { var activeDebugHandler = GetActiveDebugHandler(renderingData); if (activeDebugHandler != null) { RenderStateBlock renderStateBlock = new RenderStateBlock(); activeDebugHandler.DrawWithDebugRenderState(context, cmd, ref renderingData, ref drawSettings, ref filterSettings, ref renderStateBlock, (ScriptableRenderContext ctx, ref RenderingData data, ref DrawingSettings ds, ref FilteringSettings fs, ref RenderStateBlock rsb) => { ctx.DrawRenderers(data.cullResults, ref ds, ref fs, ref rsb); }); } else { context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings); } }
public void PipelineUpdate(ref PipelineCommandData data) { if (renderingCommand.Length <= 0) { return; } CommandBuffer buffer = data.buffer; for (int i = 0; i < renderingCommand.Length; ++i) { ref CameraState orthoCam = ref renderingCommand[i]; ScriptableCullingParameters cullParam; bool rendering = orthoCam.cullingMask != 0; if (rendering) { transform.position = orthoCam.position; transform.rotation = orthoCam.rotation; cam.orthographicSize = orthoCam.size; cam.nearClipPlane = orthoCam.nearClipPlane; cam.farClipPlane = orthoCam.farClipPlane; cam.cullingMask = orthoCam.cullingMask; rendering = cam.TryGetCullingParameters(out cullParam); if (rendering) { data.context.SetupCameraProperties(cam); cullParam.cullingMask = (uint)orthoCam.cullingMask; cullParam.cullingOptions = CullingOptions.ForceEvenIfCameraIsNotActive; CullingResults result = data.context.Cull(ref cullParam); FilteringSettings filter = new FilteringSettings { layerMask = orthoCam.cullingMask, renderingLayerMask = 1, renderQueueRange = new RenderQueueRange(1000, 5000) }; SortingSettings sort = new SortingSettings(cam) { criteria = SortingCriteria.RenderQueue }; DrawingSettings drawS = new DrawingSettings(new ShaderTagId("TerrainDecal"), sort) { perObjectData = UnityEngine.Rendering.PerObjectData.None }; DrawingSettings drawH = new DrawingSettings(new ShaderTagId("TerrainDisplacement"), sort) { perObjectData = UnityEngine.Rendering.PerObjectData.None }; ComputeShader copyShader = data.resources.shaders.texCopyShader; buffer.SetGlobalVector(ShaderIDs._MaskScaleOffset, float4(orthoCam.maskScaleOffset, (float)(1.0 / MTerrain.current.terrainData.displacementScale))); buffer.SetGlobalInt(ShaderIDs._OffsetIndex, orthoCam.heightIndex); var terrainData = MTerrain.current.terrainData; buffer.SetGlobalVector(ShaderIDs._HeightScaleOffset, (float4)double4(terrainData.heightScale, terrainData.heightOffset, 1, 1)); buffer.GetTemporaryRT(RenderTargets.gbufferIndex[0], MTerrain.COLOR_RESOLUTION, MTerrain.COLOR_RESOLUTION, 16, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1, true); buffer.GetTemporaryRT(RenderTargets.gbufferIndex[2], MTerrain.COLOR_RESOLUTION, MTerrain.COLOR_RESOLUTION, 0, FilterMode.Point, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear, 1, true); buffer.GetTemporaryRT(RenderTargets.gbufferIndex[1], MTerrain.COLOR_RESOLUTION, MTerrain.COLOR_RESOLUTION, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1, true); idfs[0] = RenderTargets.gbufferIndex[0]; idfs[1] = RenderTargets.gbufferIndex[2]; idfs[2] = RenderTargets.gbufferIndex[1]; buffer.SetComputeIntParam(copyShader, ShaderIDs._Count, orthoCam.depthSlice); buffer.SetComputeTextureParam(copyShader, 7, ShaderIDs._VirtualMainTex, orthoCam.albedoRT); buffer.SetComputeTextureParam(copyShader, 7, ShaderIDs._VirtualBumpMap, orthoCam.normalRT); buffer.SetComputeTextureParam(copyShader, 7, ShaderIDs._VirtualSMO, orthoCam.smoRT); buffer.SetComputeTextureParam(copyShader, 7, RenderTargets.gbufferIndex[0], RenderTargets.gbufferIndex[0]); buffer.SetComputeTextureParam(copyShader, 7, RenderTargets.gbufferIndex[1], RenderTargets.gbufferIndex[1]); buffer.SetComputeTextureParam(copyShader, 7, RenderTargets.gbufferIndex[2], RenderTargets.gbufferIndex[2]); const int disp = MTerrain.COLOR_RESOLUTION / 8; buffer.DispatchCompute(copyShader, 7, disp, disp, 1); buffer.SetRenderTarget(colors: idfs, depth: idfs[0]); buffer.ClearRenderTarget(true, false, new Color(0, 0, 0, 0)); data.ExecuteCommandBuffer(); data.context.DrawRenderers(result, ref drawS, ref filter); buffer.SetComputeTextureParam(copyShader, 6, ShaderIDs._VirtualMainTex, orthoCam.albedoRT); buffer.SetComputeTextureParam(copyShader, 6, ShaderIDs._VirtualBumpMap, orthoCam.normalRT); buffer.SetComputeTextureParam(copyShader, 6, ShaderIDs._VirtualSMO, orthoCam.smoRT); buffer.SetComputeTextureParam(copyShader, 6, RenderTargets.gbufferIndex[0], RenderTargets.gbufferIndex[0]); buffer.SetComputeTextureParam(copyShader, 6, RenderTargets.gbufferIndex[1], RenderTargets.gbufferIndex[1]); buffer.SetComputeTextureParam(copyShader, 6, RenderTargets.gbufferIndex[2], RenderTargets.gbufferIndex[2]); buffer.DispatchCompute(copyShader, 6, disp, disp, 1); buffer.ReleaseTemporaryRT(RenderTargets.gbufferIndex[1]); buffer.ReleaseTemporaryRT(RenderTargets.gbufferIndex[2]); buffer.ReleaseTemporaryRT(RenderTargets.gbufferIndex[0]); buffer.SetRenderTarget(color: heightTempTex.colorBuffer, depth: heightTempTex.depthBuffer, 0); buffer.ClearRenderTarget(true, true, Color.black); data.ExecuteCommandBuffer(); data.context.DrawRenderers(result, ref drawH, ref filter); buffer.GenerateMips(heightTempTex); buffer.CopyTexture(heightTempTex, 0, 2, orthoCam.heightRT, orthoCam.depthSlice, 0); } } if (!rendering) { buffer.SetRenderTarget(orthoCam.heightRT, mipLevel: 0, cubemapFace: CubemapFace.Unknown, depthSlice: orthoCam.depthSlice); buffer.ClearRenderTarget(false, true, Color.black); } MTerrain.current.GenerateMips(orthoCam.depthSlice, buffer); data.ExecuteCommandBuffer(); data.context.Submit(); }
/// <summary> /// 绘制场景 /// </summary> private void drawVisibleGeometry() { //渲染不透明物体 var sortingSettings = new SortingSettings(m_camera) { criteria = SortingCriteria.CommonOpaque }; var drawingSettings = new DrawingSettings(s_unlitShaderTagId, sortingSettings); var filteringSettings = new FilteringSettings(RenderQueueRange.opaque); //设置单个物体输入灯光数据 if (m_cullingResults.visibleLights.Length > 0) { drawingSettings.perObjectData = PerObjectData.LightData | PerObjectData.LightIndices; } //设置启用反射探针 drawingSettings.perObjectData |= PerObjectData.ReflectionProbes; //是否开启动态批处理 drawingSettings.enableDynamicBatching = m_params.bDynamicBatching; //是否开启GPU Instancing drawingSettings.enableInstancing = m_params.bInsancing; //提交绘制命令 m_context.DrawRenderers(m_cullingResults, ref drawingSettings, ref filteringSettings); //处理不透明物体的后处理 if (m_activeStack) { if (m_needsDepthOnlyPass) { //单独渲染一次深度纹理 var sortSetting = new SortingSettings(m_camera); var depthOnlyDrawSettings = new DrawingSettings(new ShaderTagId("DepthOnly"), sortSetting); var depthOnlyFilterSettings = new FilteringSettings(); depthOnlyFilterSettings.renderQueueRange = RenderQueueRange.opaque; m_cameraBuffer.SetRenderTarget(s_cameraDepthTextureId, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); m_cameraBuffer.ClearRenderTarget(true, false, Color.clear); executeBuffer(m_cameraBuffer); m_context.DrawRenderers(m_cullingResults, ref depthOnlyDrawSettings, ref depthOnlyFilterSettings); } SPostProcessingParam p = new SPostProcessingParam { cb = m_postProcessingBuffer, cameraColorId = s_cameraColorTextureId, cameraDepthId = s_cameraDepthTextureId, width = m_renderSize.x, height = m_renderSize.y, samples = m_renderSamples, format = m_format }; //调用不透明后处理 m_activeStack.RenderAfterOpaque(p); executeBuffer(m_postProcessingBuffer); //设置相机渲染纹理 if (m_needsDirectDepth) { m_cameraBuffer.SetRenderTarget(s_cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, s_cameraDepthTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); } else { m_cameraBuffer.SetRenderTarget(s_cameraColorTextureId, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); } executeBuffer(m_cameraBuffer); } //渲染天空盒 m_context.DrawSkybox(m_camera); //渲染不透明物体 sortingSettings.criteria = SortingCriteria.CommonTransparent; drawingSettings.sortingSettings = sortingSettings; filteringSettings.renderQueueRange = RenderQueueRange.transparent; m_context.DrawRenderers(m_cullingResults, ref drawingSettings, ref filteringSettings); //进行不透明后处理 if (m_renderToTexture) { //进行后处理 if (m_activeStack) { m_activeStack.RenderAfterTransparent(); executeBuffer(m_postProcessingBuffer); } else { m_cameraBuffer.Blit(s_cameraColorTextureId, BuiltinRenderTextureType.CameraTarget); } //释放掉相机纹理 m_cameraBuffer.ReleaseTemporaryRT(s_cameraColorTextureId); if (m_needsDepth) { m_cameraBuffer.ReleaseTemporaryRT(s_cameraDepthTextureId); } } }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(cameras); foreach (Camera camera in cameras) { BeginCameraRendering(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; //Color Texture Descriptor RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); colorRTDesc.graphicsFormat = m_ColorFormat; colorRTDesc.depthBufferBits = depthBufferBits; colorRTDesc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); colorRTDesc.msaaSamples = 1; colorRTDesc.enableRandomWrite = true; //For compute //Depth Texture Descriptor RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); depthRTDesc.colorFormat = RenderTextureFormat.Depth; depthRTDesc.depthBufferBits = depthBufferBits; //Set texture temp RT CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); 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 }; //Clear Depth Texture 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(); //Draw Depth with Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettingsDepth.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettings); //Draw Depth with Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettingsDepth.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettings); //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(); //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.SetRenderTarget(m_ColorRT); //Remember to set target 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); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Run Compute shader if (m_PipelineAsset.computeShader != null) { CommandBuffer cmdCompute = new CommandBuffer(); cmdCompute.name = "(" + camera.name + ")" + "Compute"; cmdCompute.SetComputeIntParam(m_PipelineAsset.computeShader, "range", m_PipelineAsset.detectRange); cmdCompute.SetComputeFloatParam(m_PipelineAsset.computeShader, "detect", m_PipelineAsset.edgeDetect); cmdCompute.SetComputeTextureParam(m_PipelineAsset.computeShader, _kernel, m_ColorRTid, m_ColorRT); cmdCompute.SetComputeTextureParam(m_PipelineAsset.computeShader, _kernel, m_DepthRTid, m_DepthRT); cmdCompute.DispatchCompute(m_PipelineAsset.computeShader, _kernel, camera.pixelWidth / 8 + 1, camera.pixelHeight / 8 + 1, 1); context.ExecuteCommandBuffer(cmdCompute); cmdCompute.Release(); } //Blit the content back to screen CommandBuffer cmdBlitToCam = new CommandBuffer(); cmdBlitToCam.name = "(" + camera.name + ")" + "Blit back to Camera"; cmdBlitToCam.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmdBlitToCam); cmdBlitToCam.Release(); //Clean Up CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_DepthRTid); cmdclean.ReleaseTemporaryRT(m_ColorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); } }
public override void FrameUpdate(PipelineCamera cam, ref PipelineCommandData data) { CommandBuffer buffer = data.buffer; RenderClusterOptions options = new RenderClusterOptions { command = buffer, frustumPlanes = proper.frustumPlanes, cullingShader = data.resources.shaders.gpuFrustumCulling, terrainCompute = data.resources.shaders.terrainCompute }; FilteringSettings alphaTestFilter = new FilteringSettings { layerMask = cam.cam.cullingMask, renderingLayerMask = 1, renderQueueRange = new RenderQueueRange(2450, 2499) }; FilteringSettings opaqueFilter = new FilteringSettings { layerMask = cam.cam.cullingMask, renderingLayerMask = 1, renderQueueRange = new RenderQueueRange(2000, 2449) }; DrawingSettings depthAlphaTestDrawSettings = new DrawingSettings(new ShaderTagId("Depth"), new SortingSettings(cam.cam) { criteria = SortingCriteria.OptimizeStateChanges } ) { perObjectData = UnityEngine.Rendering.PerObjectData.None, enableDynamicBatching = true, enableInstancing = false }; DrawingSettings depthOpaqueDrawSettings = new DrawingSettings(new ShaderTagId("Depth"), new SortingSettings(cam.cam) { criteria = SortingCriteria.None }) { perObjectData = UnityEngine.Rendering.PerObjectData.None, enableDynamicBatching = true, enableInstancing = false, overrideMaterial = proper.overrideOpaqueMaterial, overrideMaterialPassIndex = 1 }; DrawingSettings drawSettings = new DrawingSettings(new ShaderTagId("GBuffer"), new SortingSettings(cam.cam) { criteria = SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges }) { perObjectData = UnityEngine.Rendering.PerObjectData.Lightmaps, enableDynamicBatching = true, enableInstancing = false }; //Draw Depth Prepass data.buffer.SetRenderTarget(ShaderIDs._DepthBufferTexture); data.buffer.ClearRenderTarget(true, false, Color.black); cullHandle.Complete(); var lst = CustomDrawRequest.allEvents; foreach (var i in gbufferCullResults) { lst[i].DrawDepthPrepass(buffer); } HizOcclusionData hizOccData = null; PipelineFunctions.UpdateFrustumMinMaxPoint(buffer, proper.frustumMinPoint, proper.frustumMaxPoint); if (useHiZ && SceneController.gpurpEnabled) { #if UNITY_EDITOR if (Application.isPlaying) { #endif hizOccData = IPerCameraData.GetProperty(cam, (c) => new HizOcclusionData(c.cam.pixelWidth)); hizOccData.UpdateWidth(cam.cam.pixelWidth); SceneController.CullCluster_LastFrameDepthHiZ(ref options, hizOccData, cam); buffer.DrawProceduralIndirect(Matrix4x4.identity, clusterMat, 2, MeshTopology.Triangles, SceneController.baseBuffer.instanceCountBuffer, 0); #if UNITY_EDITOR } #endif } RenderStateBlock depthBlock = new RenderStateBlock { depthState = new DepthState(true, CompareFunction.Less), mask = RenderStateMask.Depth }; SceneController.RenderScene(ref data, ref opaqueFilter, ref depthOpaqueDrawSettings, ref proper.cullResults, ref depthBlock); data.context.DrawRenderers(proper.cullResults, ref depthAlphaTestDrawSettings, ref alphaTestFilter); decalEvt.FrameUpdate(cam, ref data); //Draw GBuffer data.buffer.SetRenderTarget(colors: cam.targets.gbufferIdentifier, depth: ShaderIDs._DepthBufferTexture); data.buffer.ClearRenderTarget(false, true, Color.black); foreach (var i in gbufferCullResults) { lst[i].DrawGBuffer(buffer); } if (useHiZ && SceneController.gpurpEnabled) { #if UNITY_EDITOR if (Application.isPlaying) { #endif buffer.SetGlobalBuffer(ShaderIDs._MaterialBuffer, data.resources.clusterResources.vmManager.materialBuffer); buffer.SetGlobalBuffer(ShaderIDs._TriangleMaterialBuffer, SceneController.baseBuffer.triangleMaterialBuffer); buffer.SetGlobalTexture(ShaderIDs._GPURPMainTex, data.resources.clusterResources.rgbaPool.rt); buffer.SetGlobalTexture(ShaderIDs._GPURPEmissionMap, data.resources.clusterResources.emissionPool.rt); buffer.SetGlobalTexture(ShaderIDs._GPURPBumpMap, data.resources.clusterResources.normalPool.rt); buffer.SetGlobalTexture(ShaderIDs._GPURPHeightMap, data.resources.clusterResources.heightPool.rt); buffer.DrawProceduralIndirect(Matrix4x4.identity, clusterMat, 0, MeshTopology.Triangles, SceneController.baseBuffer.instanceCountBuffer, 0); #if UNITY_EDITOR } #endif } SceneController.RenderScene(ref data, ref opaqueFilter, ref drawSettings, ref proper.cullResults); if (MTerrain.current) { MTerrain.current.DrawTerrain(buffer, 0, proper.frustumPlanes); } //Draw AlphaTest /* SortingSettings st = drawSettings.sortingSettings; * st.criteria = SortingCriteria.SortingLayer | SortingCriteria.RenderQueue | SortingCriteria.OptimizeStateChanges; * drawSettings.sortingSettings = st;*/ SceneController.RenderScene(ref data, ref alphaTestFilter, ref drawSettings, ref proper.cullResults); //Draw Recheck HIZ Occlusion if (useHiZ && SceneController.gpurpEnabled) { #if UNITY_EDITOR if (Application.isPlaying) #endif SceneController.DrawCluster_RecheckHiz(ref options, ref hizDepth, hizOccData, clusterMat, linearMat, cam); } //Draw Depth data.buffer.Blit(ShaderIDs._DepthBufferTexture, ShaderIDs._CameraDepthTexture); if (needUpdateGeometryBuffer) { needUpdateGeometryBuffer = false; data.ExecuteCommandBuffer(); data.context.ExecuteCommandBuffer(m_afterGeometryBuffer); m_afterGeometryBuffer.Clear(); } }
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; //Color Texture Descriptor RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); colorRTDesc.graphicsFormat = m_ColorFormat; colorRTDesc.depthBufferBits = depthBufferBits; colorRTDesc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); colorRTDesc.msaaSamples = 1; colorRTDesc.enableRandomWrite = false; //Set Temp RT & set render target to the RT CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); DrawingSettings drawSettingsDistortion = new DrawingSettings(m_PassNameDistortion, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); cmd.ClearRenderTarget(true, true, Color.blue); 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); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Blit to color texture CommandBuffer cmdBlitToTex = new CommandBuffer(); cmdBlitToTex.name = "(" + camera.name + ")" + "Blit to Color Texture"; cmdBlitToTex.Blit(BuiltinRenderTextureType.CameraTarget, m_ColorRT); cmdBlitToTex.SetGlobalTexture(m_ColorRTid, m_ColorRT); //cmdBlitToTex.Blit(m_ColorRTid,BuiltinRenderTextureType.CameraTarget); cmdBlitToTex.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); //Blit will change target, so make sure to reset it context.ExecuteCommandBuffer(cmdBlitToTex); cmdBlitToTex.Release(); //Distortion object sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsDistortion, ref filterSettings); //Clean Up CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_ColorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }