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 = 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); //这里不是移除renderTarget而是清空其RT上的颜色 context.ExecuteCommandBuffer(cmdDepth); //DebugRT------------------------------------- DebugRT = RenderTexture.GetTemporary(depthRTDesc); cmdDepth.CopyTexture(m_ColorRT, DebugIdt); //-------------------------------------------- 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(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
// 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) { SortingCriteria sortingCriteria = (_renderQueueType == RenderQueueType.Transparent) ? SortingCriteria.CommonTransparent : renderingData.cameraData.defaultOpaqueSortFlags; DrawingSettings drawingSettings = CreateDrawingSettings(ShaderTagIdList, ref renderingData, sortingCriteria); // 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, _profilingSampler)) { //Clear small RT cmd.ClearRenderTarget(true, true, Color.clear); context.ExecuteCommandBuffer(cmd); cmd.Clear(); //Blit Camera Depth Texture Blit(cmd, _cameraDepthTargetId, _metaballRT, _blitCopyDepthMaterial); context.ExecuteCommandBuffer(cmd); cmd.Clear(); //Draw to RT context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref _filteringSettings, ref _renderStateBlock); context.ExecuteCommandBuffer(cmd); cmd.Clear(); //Blur cmd.SetGlobalTexture("_BlurDepthTex", _metaballDepthRT); cmd.SetGlobalFloat("_BlurDistance", BlurDistance); float offset = 1.5f; cmd.SetGlobalFloat("_Offset", offset); Blit(cmd, _metaballRT, _metaballRT2, _blurMaterial); context.ExecuteCommandBuffer(cmd); cmd.Clear(); var tmpRT = _metaballRT; _metaballRT = _metaballRT2; _metaballRT2 = tmpRT; for (int i = 1; i < BlurPasses; ++i) { offset += 1.0f; cmd.SetGlobalFloat("_Offset", offset); Blit(cmd, _metaballRT, _metaballRT2, _blurMaterial); context.ExecuteCommandBuffer(cmd); cmd.Clear(); tmpRT = _metaballRT; _metaballRT = _metaballRT2; _metaballRT2 = tmpRT; } //Draw to Camera Target Blit(cmd, _metaballRT, _cameraTargetId, BlitMaterial); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
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; //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings SortingSettings sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //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); //Error Opaque //DrawErrorShader(context,sortingSettings,cull,filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Error Opaque+Transparent DrawErrorShader(context, sortingSettings, cull, filterSettings); context.Submit(); } }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(out cullingParameters)) { return; } cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif cullingResults = context.Cull(ref cullingParameters); if (cullingResults.visibleLights.Length > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadow(context); } else { cameraBuffer.DisableShaderKeyword(cascadeShadowHardKeyword); cameraBuffer.DisableShaderKeyword(cascadeShadowSoftKeyword); } if (shadowMapTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowHardKeyWord); cameraBuffer.DisableShaderKeyword(shadowSoftKeyWord); } } else { cameraBuffer.SetGlobalVector( lightIndicesOffsetAndCountID, Vector4.zero ); cameraBuffer.DisableShaderKeyword(shadowHardKeyWord); cameraBuffer.DisableShaderKeyword(shadowSoftKeyWord); cameraBuffer.DisableShaderKeyword(cascadeShadowHardKeyword); cameraBuffer.DisableShaderKeyword(cascadeShadowSoftKeyword); } context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); cameraBuffer.BeginSample("Render Camera"); CamBufferSendInfoToGPU(); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawingSettings( new ShaderTagId("SRPDefaultUnlit"), new SortingSettings(camera) { criteria = SortingCriteria.CommonOpaque } ); drawSettings.enableDynamicBatching = useDynamicBatching; drawSettings.enableInstancing = useGPUInstance; if (cullingResults.visibleLights.Length > 0) { drawSettings.perObjectData = PerObjectData.LightData | PerObjectData.LightIndices; } drawSettings.perObjectData |= PerObjectData.ReflectionProbes; var filterSettings = FilteringSettings.defaultValue; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers( cullingResults, ref drawSettings, ref filterSettings ); context.DrawSkybox(camera); drawSettings.sortingSettings = new SortingSettings(camera) { criteria = SortingCriteria.CommonTransparent }; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cullingResults, ref drawSettings, ref filterSettings ); DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); RelaseRenderTexture(ref shadowMap); RelaseRenderTexture(ref cascadedShadowMap); }
private static void RenderToCubemap(ScriptableRenderContext context, CommandBuffer cmd, HDCamera hd, SensorRenderTarget target, ShaderTagId pass, Color clearColor) { hd.SetupGlobalParams(cmd, 0); context.SetupCameraProperties(hd.camera); var transform = hd.camera.transform; var r = transform.rotation; var originalProj = hd.camera.projectionMatrix; hd.camera.projectionMatrix = CubeProj; var sensor = hd.camera.GetComponent <CameraSensorBase>(); var renderPostprocess = sensor != null && sensor.Postprocessing != null && sensor.Postprocessing.Count > 0; for (var i = 0; i < 6; ++i) { // Custom face order is used for dynamic exposure - this way it will be based on forward cube face var faceIndex = CubemapFaceOrder[i]; if ((target.CubeFaceMask & (1 << faceIndex)) == 0) { continue; } transform.localRotation = Quaternion.LookRotation(CoreUtils.lookAtList[faceIndex], CoreUtils.upVectorList[faceIndex]); var view = hd.camera.worldToCameraMatrix; SetupGlobalParamsForCubemap(cmd, view, target.ColorHandle.rt.width); CoreUtils.SetRenderTarget(cmd, target.ColorHandle, target.DepthHandle, ClearFlag.None, 0, (CubemapFace)faceIndex); cmd.ClearRenderTarget(true, true, clearColor); context.ExecuteCommandBuffer(cmd); cmd.Clear(); if (hd.camera.TryGetCullingParameters(out var culling)) { var cull = context.Cull(ref culling); var sorting = new SortingSettings(hd.camera); var drawing = new DrawingSettings(pass, sorting); var filter = new FilteringSettings(RenderQueueRange.all); // NOTE: This should flip culling, not hard-set it to front. SRP API does not provide this option // currently. Expected issues with front-culled geometry. // TODO: investigate HDAdditionalCameraData.FlipYMode.ForceFlipY, it might be a way to solve this var stateBlock = new RenderStateBlock(RenderStateMask.Raster) { rasterState = new RasterState { cullingMode = CullMode.Front } }; context.DrawRenderers(cull, ref drawing, ref filter, ref stateBlock); if (renderPostprocess) { SimulatorManager.Instance.Sensors.PostProcessSystem.RenderForSensor(cmd, hd, sensor, target.ColorHandle, (CubemapFace)i); } } } if (renderPostprocess) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); } transform.rotation = r; hd.camera.projectionMatrix = originalProj; }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { base.Render(context, cameras); foreach (var camera in cameras) { if (!CullResults.Cull(camera, context, out cullResults)) { continue; } context.SetupCameraProperties(camera); // PropertyToID will return an ID that uniquely identifies the property name. The function we're going // to use later on requires us to use these IDs, so we compute them here. // You could also pre-calculate these, but for simplicity we're keeping them here. // We need a color and a depth render target. var colorRT = Shader.PropertyToID("_ColorRT"); var colorRTID = new RenderTargetIdentifier(colorRT); var depthRT = Shader.PropertyToID("_CameraDepthTexture"); var depthRTID = new RenderTargetIdentifier(depthRT); { var cmd = CommandBufferPool.Get("Set-up Render Targets"); // GetTemporaryRT gets us a temporary render target we can render into. Internally Unity re-uses // these as they get returned to the pool. // Get our color render target. No need for any depth bits as we're getting a separate depth buffer. cmd.GetTemporaryRT(colorRT, camera.pixelWidth, camera.pixelHeight, 0, FilterMode.Point, RenderTextureFormat.ARGB32); // Get our depth render target. cmd.GetTemporaryRT(depthRT, camera.pixelWidth, camera.pixelHeight, 24, FilterMode.Point, RenderTextureFormat.Depth); // We can now set the active render target to our newly acquired render targets. // Important: Do _not_ use the implicit conversion from `int` to `RenderTargetIdentifier`. This will // sometimes silently select the wrong overload of `SetRenderTarget` for you, leading to pain and // suffering. cmd.SetRenderTarget(colorRTID, depthRTID); // Clear like before, but now with our new render targets. cmd.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } { var cmd = CommandBufferPool.Get("Set-up Light Buffer"); var lightCount = cullResults.visibleLights.Count; var lightArray = new NativeArray <Vector4>(lightCount * 2, Allocator.Temp); for (var i = 0; i < lightCount; i++) { var light = cullResults.visibleLights[i]; Vector4 lightData; if (light.lightType == LightType.Directional) { lightData = light.localToWorld.MultiplyVector(Vector3.back); lightData.w = -1; } else if (light.lightType == LightType.Point) { lightData = light.localToWorld.GetColumn(3); lightData.w = light.range; } else { continue; } lightArray[i * 2] = lightData; lightArray[i * 2 + 1] = light.finalColor; } lightBuffer.SetData(lightArray); lightArray.Dispose(); cmd.SetGlobalBuffer("_LightBuffer", lightBuffer); cmd.SetGlobalInt("_LightCount", lightCount); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("Forward")); var filterSettings = new FilterRenderersSettings(true); drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, filterSettings); // Draw the skybox. Note that you could also do your completely own thing here, and not use the built-in // skybox. It's important that this happens after opaque rendering, but before transparent. The // built-in skybox uses the depth buffer to only draw where no other objects draw. context.DrawSkybox(camera); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cullResults.visibleRenderers, ref drawSettings, filterSettings); // Copy the depth from our own depth render target into the camera target. { var cmd = CommandBufferPool.Get("Copy Depth"); // Blit does a fullscreen pass. We're using the same input as output, because we're binding the // input ourselves, but Unity doesn't like a null value here. We use the copy depth material we set // in the asset. cmd.Blit(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CameraTarget, copyDepthMaterial); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } { var cmd = CommandBufferPool.Get("Final Blit"); cmd.Blit(colorRT, BuiltinRenderTextureType.CameraTarget); cmd.ReleaseTemporaryRT(colorRT); cmd.ReleaseTemporaryRT(depthRT); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } context.Submit(); } }
public bool RenderCharacterShadowmap(ScriptableRenderContext context, CommandBuffer cmd, ref RenderingData renderingData) { Camera camera = renderingData.cameraData.camera; int shadowLightIndex = renderingData.lightData.mainLightIndex; if (shadowLightIndex == -1) { return(false); } VisibleLight shadowLight = renderingData.lightData.visibleLights[shadowLightIndex]; Light light = shadowLight.light; if (light == null || characterShadow == null) { return(false); } Debug.Assert(light.type == LightType.Directional); if (light.shadows == LightShadows.None) { return(false); } bool renderShadow = characterShadow.UpdateFocus(light, camera); if (!renderShadow) { return(false); } //using (new ProfilingSample(cmd, m_ProfilerTag)) { //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { return(false); } cullingParams.isOrthographic = true; cullingParams.cullingMatrix = characterShadow.ProjMatrix * characterShadow.ViewMatrix; cullingParams.origin = characterShadow.CameraCenter; cullingParams.cullingOptions = CullingOptions.ShadowCasters; //cullingParams.SetLayerCullingDistance Plane[] planes = GeometryUtility.CalculateFrustumPlanes(cullingParams.cullingMatrix); cullingParams.cullingPlaneCount = 6; for (int i = 0; i < planes.Length; ++i) { cullingParams.SetCullingPlane(i, planes[i]); } m_CharacterShadowCullResult = context.Cull(ref cullingParams); float frusumSize = 2.0f / characterShadow.ProjMatrix.m00; const float kernelRadius = 2.5f; float m_texelSize = frusumSize / Mathf.Min(m_ShadowmapWidth, m_ShadowmapHeight); float m_depthBias = -characterShadow.Bias * m_texelSize; float m_normalBias = -characterShadow.NormalBias * m_texelSize; if (light.shadows == LightShadows.Soft) { m_depthBias *= kernelRadius; m_normalBias *= kernelRadius; } //CoreUtils.SetKeyword(cmd, GRenderKeywords.AdditionalShadowStr, false); Vector3 lightDirection = -light.transform.forward; cmd.SetGlobalVector("_ShadowBias", new Vector4(m_depthBias, m_normalBias, m_texelSize * 1.4142135623730950488016887242097f, 0.0f)); cmd.SetGlobalVector("_LightDirection", new Vector4(lightDirection.x, lightDirection.y, lightDirection.z, 0.0f)); //CoreUtils.SetRenderTarget(cmd, m_CharacterShadowmapTexture, ClearFlag.Depth); Utilities.SetViewProjectionMatrices(cmd, characterShadow.ViewMatrix, characterShadow.ProjMatrix); context.ExecuteCommandBuffer(cmd); cmd.Clear(); var sortFlags = renderingData.cameraData.defaultOpaqueSortFlags; var drawSettings = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortFlags); FilteringSettings filterSettings = m_FilteringSettings; context.DrawRenderers(m_CharacterShadowCullResult, ref drawSettings, ref filterSettings); context.ExecuteCommandBuffer(cmd); //set shader params float width = m_ShadowmapWidth; float height = m_ShadowmapHeight; cmd.SetGlobalTexture(m_CharacterShadowmap.id, m_CharacterShadowmapTexture); cmd.SetGlobalMatrix(CharacterShadowConstantBuffer._CharacterShadowMatrix, characterShadow.ShadowMatrix); cmd.SetGlobalVector(CharacterShadowConstantBuffer._CharacterShadowmapSize, new Vector4(1 / width, 1 / height, width, height)); cmd.SetGlobalVector(CharacterShadowConstantBuffer._CharacterShadowFilterWidth, characterShadow.GetFilterWidth(width, height)); } return(true); }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { var prevPipe = Shader.globalRenderPipeline; Shader.globalRenderPipeline = "LowEndMobilePipeline"; base.Render(context, cameras); foreach (Camera camera in cameras) { CullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { continue; } cullingParameters.shadowDistance = m_ShadowSettings.maxShadowDistance; CullResults cull = CullResults.Cull(ref cullingParameters, context); VisibleLight[] visibleLights = cull.visibleLights; int pixelLightsCount, vertexLightsCount; GetMaxSupportedLights(visibleLights.Length, out pixelLightsCount, out vertexLightsCount); // TODO: handle shader keywords when no lights are present SortLights(ref visibleLights, pixelLightsCount); // TODO: Add remaining lights to SH // Render Shadow Map bool shadowsRendered = false; if (m_ShadowLightIndex > -1) { shadowsRendered = RenderShadows(cull, visibleLights[m_ShadowLightIndex], context); } // Setup camera matrices and RT context.SetupCameraProperties(camera); // Clear RenderTarget to avoid tile initialization on mobile GPUs // https://community.arm.com/graphics/b/blog/posts/mali-performance-2-how-to-correctly-handle-framebuffers var cmd = new CommandBuffer() { name = "Clear" }; cmd.ClearRenderTarget(true, true, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Dispose(); // Setup light and shadow shader constants SetupLightShaderVariables(visibleLights, pixelLightsCount, vertexLightsCount, context); if (shadowsRendered) { SetupShadowShaderVariables(context, m_ShadowCasterCascadesCount); } // Render Opaques var settings = new DrawRendererSettings(cull, camera, m_ForwardBasePassName); settings.sorting.flags = SortFlags.CommonOpaque; settings.inputFilter.SetQueuesOpaque(); if (m_Asset.EnableLightmap) { settings.rendererConfiguration |= RendererConfiguration.PerObjectLightmaps; } if (m_Asset.EnableAmbientProbe) { settings.rendererConfiguration |= RendererConfiguration.PerObjectLightProbe; } context.DrawRenderers(ref settings); // Release temporary RT var discardRT = new CommandBuffer(); discardRT.ReleaseTemporaryRT(m_ShadowMapProperty); context.ExecuteCommandBuffer(discardRT); discardRT.Dispose(); // TODO: Check skybox shader context.DrawSkybox(camera); // Render Alpha blended settings.sorting.flags = SortFlags.CommonTransparent; settings.inputFilter.SetQueuesTransparent(); context.DrawRenderers(ref settings); } context.Submit(); Shader.globalRenderPipeline = prevPipe; }
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { #if UNITY_EDITOR || DEBUG if (renderingData.cameraData.isSceneViewCamera || !Application.isPlaying) { return; } if (renderingData.cameraData.camera.cameraType == CameraType.Preview) { return; } if (this.blitMaterial == null) { return; } #endif var volumeComponent = VolumeManager.instance.stack.GetComponent <fMotionBlur>(); if (!volumeComponent.IsActive()) { return; } CommandBuffer cmd = CommandBufferPool.Get(PASS_NAME); using (new ProfilingScope(cmd, profilingSampler)) { #if UNITY_EDITOR || DEBUG // for FrameDebugger context.ExecuteCommandBuffer(cmd); #endif cmd.Clear(); var camera = renderingData.cameraData.camera; // NOTE: UnityEngine require this flags to update unity_PreviousM. camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth; #if UNITY_EDITOR || DEBUG // for FrameDebugger CommandBuffer preCmd = CommandBufferPool.Get(PRE_PASS_NAME); preCmd.Clear(); #else var preCmd = cmd; #endif var descriptor = renderingData.cameraData.cameraTargetDescriptor; // Create MotionVectorTexture // NOTE : Depth Buffer is faster 32bit(24bit) than 16bit. https://gpuopen.com/dcc-overview/ preCmd.GetTemporaryRT(MOTION_TEXTURE, descriptor.width, descriptor.height, 32, FilterMode.Point, RenderTextureFormat.RGHalf); this.Blit(preCmd, BuiltinRenderTextureType.None, MOTION_TEXTURE, this.blitMaterial, 1); context.ExecuteCommandBuffer(preCmd); #if UNITY_EDITOR || DEBUG // for FrameDebugger CommandBufferPool.Release(preCmd); #endif // Camara Motion //var proj = GL.GetGPUProjectionMatrix(camera.nonJitteredProjectionMatrix, true); // if you want to use previousViewProjectionMatrix var proj = camera.nonJitteredProjectionMatrix; var view = camera.worldToCameraMatrix; var viewProj = proj * view; this.blitMaterial.SetMatrix(PROP_VPMATRIX, viewProj); // NOTE: camera.previousViewProjectionMatrix doesn't be updated when camera don't move. this.blitMaterial.SetMatrix(PROP_PREV_VPMATRIX, this.previousVP); this.previousVP = viewProj; var drawingSettings = this.CreateDrawingSettings(SHADER_TAG_FORWARD, ref renderingData, SortingCriteria.CommonOpaque); drawingSettings.overrideMaterial = this.blitMaterial; drawingSettings.overrideMaterialPassIndex = 0; drawingSettings.perObjectData |= PerObjectData.MotionVectors; // MotionVector—LŒø‰» var filteringSettings = new FilteringSettings(RenderQueueRange.opaque, this.settings.LayerMask); var renderStateBlock = new RenderStateBlock(RenderStateMask.Nothing); context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings, ref renderStateBlock); } #if UNITY_EDITOR || DEBUG // for FrameDebugger context.ExecuteCommandBuffer(cmd); #endif CommandBufferPool.Release(cmd); }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); //cameraBuffer.ClearRenderTarget(true, false, Color.clear); cameraBuffer.BeginSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit") ); drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); context.DrawSkybox(camera); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); }
private static readonly ShaderPassName m_UnlitPassName = new ShaderPassName("SRPDefaultUnlit"); //For default shaders public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras) { foreach (Camera camera in cameras) { // Culling ScriptableCullingParameters cullingParams; if (!CullResults.GetCullingParameters(camera, out cullingParams)) { continue; } CullResults cull = new CullResults(); // Record time for performance (before) if (camera == Camera.main) { t = Time.realtimeSinceStartup; } //Do Culling CullResults.Cull(ref cullingParams, context, ref cull); // Record time for performance (after) if (camera == Camera.main) { t = Time.realtimeSinceStartup - t; if (text == null) { text = Camera.main.GetComponent <UpdateText>(); } if (count > skipcount) { //After Cull t *= 1000.000000000000f; //Average alltime += t; if (count == 2000) { avgt = alltime / ((count - skipcount) * 1.000000000f); //Show cull time string content = "Delta Time = " + t + "ms \n Average = " + avgt + "ms \n count = " + count; Debug.Log(content); if (text != null) { text.UpdateTextContent(content); } } else if (count < 2000) { Debug.Log("now sampling 1000 frames..."); if (text != null) { text.UpdateTextContent("now sampling 1000 frames..." + count); } } } else { Debug.Log("skipping first 1000 frames..."); if (text != null) { text.UpdateTextContent("skipping first 1000 frames..." + count); } } count++; } //Start rendering part context.SetupCameraProperties(camera); // clear depth buffer CommandBuffer cmd = new CommandBuffer();; cmd.ClearRenderTarget(true, false, Color.black); context.ExecuteCommandBuffer(cmd); cmd.Release(); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); // Draw skybox context.DrawSkybox(camera); // Setup DrawSettings and FilterSettings ShaderPassName passName = new ShaderPassName("BasicPass"); DrawRendererSettings drawSettings = new DrawRendererSettings(camera, passName); drawSettings.SetShaderPassName(1, m_UnlitPassName); //For drawing default shaders FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); // Draw opaque objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // Draw transparent objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); context.Submit(); } }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { base.Render(context, cameras); foreach (var camera in cameras) { ScriptableCullingParameters cullingParams; if (!CullResults.GetCullingParameters(camera, out cullingParams)) { continue; } CullResults cull = CullResults.Cull(ref cullingParams, context); context.SetupCameraProperties(camera); var cmd = new CommandBuffer(); int width, height; if (camera.targetTexture) { width = camera.targetTexture.width; height = camera.targetTexture.height; } else { width = Screen.width; height = Screen.height; } cmd.GetTemporaryRT(gBuffer0, width, height, 24, FilterMode.Trilinear, RenderTextureFormat.ARGBFloat); cmd.GetTemporaryRT(gBuffer1, width, height, 0, FilterMode.Trilinear, RenderTextureFormat.ARGBFloat); cmd.GetTemporaryRT(gBuffer2, width, height, 0, FilterMode.Trilinear, RenderTextureFormat.ARGBFloat); cmd.GetTemporaryRT(gBuffer3, width, height, 0, FilterMode.Trilinear, RenderTextureFormat.ARGBFloat); cmd.SetRenderTarget(gBuffers, gBuffer0); cmd.ClearRenderTarget(true, true, Color.black); var visibleLights = cull.visibleLights; var mainLightIndex = GetMainLight(visibleLights); if (mainLightIndex < 0) { cmd.SetGlobalVector("_DirectionalLightDir", new Vector3(0, 1, 0)); cmd.SetGlobalColor("_DirectionalLightColor", Color.black); } else { var mainLight = visibleLights[mainLightIndex]; cmd.SetGlobalVector("_DirectionalLightDir", -mainLight.light.transform.forward); cmd.SetGlobalColor("_DirectionalLightColor", mainLight.finalColor); RemoveFromList(visibleLights, mainLightIndex); } var lightCount = Mathf.Min(256, visibleLights.Count); for (int i = 0; i < lightCount; ++i) { var light = visibleLights[i]; var pos = light.light.transform.position; _LightWorldPosArray[i] = new Vector4(pos.x, pos.y, pos.z, light.range); _LightWorldColorArray[i] = light.finalColor; } cmd.SetGlobalVectorArray("_LightWorldPos", _LightWorldPosArray); cmd.SetGlobalFloat("_LightCount", lightCount); cmd.SetGlobalVectorArray("_LightFinalColor", _LightWorldColorArray); frustumCorner[0] = camera.ViewportToWorldPoint(new Vector3(0, 0, camera.farClipPlane)); frustumCorner[1] = camera.ViewportToWorldPoint(new Vector3(1, 0, camera.farClipPlane)); frustumCorner[2] = camera.ViewportToWorldPoint(new Vector3(0, 1, camera.farClipPlane)); frustumCorner[3] = camera.ViewportToWorldPoint(new Vector3(1, 1, camera.farClipPlane)); cmd.SetGlobalVectorArray("_FrustumCorner", frustumCorner); context.ExecuteCommandBuffer(cmd); var settings = new DrawRendererSettings(camera, new ShaderPassName("Deferred")); settings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers(cull.visibleRenderers, ref settings, filterSettings); cmd.Clear(); cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmd); cmd.Clear(); context.DrawSkybox(camera); cmd.Blit(null, BuiltinRenderTextureType.CameraTarget, deferredmat); context.ExecuteCommandBuffer(cmd); cmd.Release(); context.Submit(); } }
/// <inheritdoc/> public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData) { if (renderer == null) { throw new ArgumentNullException("renderer"); } CommandBuffer cmd = CommandBufferPool.Get(k_DepthNormalsTag); using (new ProfilingSample(cmd, k_DepthNormalsTag)) { cmd.GetTemporaryRT(depthNormalsHandle.id, descriptor, FilterMode.Bilinear); if (isDepthPrepassEnabled) { SetRenderTarget( cmd, depthNormalsHandle.Identifier(), RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, depthAttachmentHandle.Identifier(), RenderBufferLoadAction.Load, RenderBufferStoreAction.DontCare, ClearFlag.Color, Color.black, TextureDimension.Tex2D); cmd.DisableShaderKeyword("_ALPHATEST_ON"); } else { SetRenderTarget( cmd, depthNormalsHandle.Identifier(), RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.Color | ClearFlag.Depth, Color.black, TextureDimension.Tex2D); cmd.EnableShaderKeyword("_ALPHATEST_ON"); } context.ExecuteCommandBuffer(cmd); cmd.Clear(); cmd.SetGlobalInt("_DepthNormalsZWrite", isDepthPrepassEnabled ? 0 : 1); cmd.SetGlobalInt("_DepthNormalsZTest", (int)(isDepthPrepassEnabled ? ZTest.Equal : ZTest.LEqual)); var sortFlags = renderingData.cameraData.defaultOpaqueSortFlags; var drawSettings = CreateDrawRendererSettings(renderingData.cameraData.camera, sortFlags, RendererConfiguration.None, renderingData.supportsDynamicBatching); if (renderingData.cameraData.isStereoEnabled) { Camera camera = renderingData.cameraData.camera; context.StartMultiEye(camera); context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, opaqueFilterSettings); context.StopMultiEye(camera); } else { context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, opaqueFilterSettings); } } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
// Temporarily only support one camera, will render the same thing for the others. // TODO: Add support for multi-camera setups protected void Render(ScriptableRenderContext context, Camera camera) { // Culling ScriptableCullingParameters cullingParams; // TryGetCullingParameters return false if it failed to create valid params if (!camera.TryGetCullingParameters(out cullingParams)) { return; } // Inject world space UI into scene view #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif // Sends culling instructions to context cullingResults = context.Cull(ref cullingParams); // Sets up camera specific global shader params context.SetupCameraProperties(camera); // Explicitly clear the render target with command buffers CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); ConfigureLights(); cameraBuffer.BeginSample("Render Camera"); // Setup light buffers cameraBuffer.SetGlobalVectorArray(visibleLightColorsId, visibleLightColors); cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions); cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationId, visibleLightAttenuations); cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionId, visibleLightSpotDirections); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // Setup default shaders for drawing DrawingSettings drawingSettings = new DrawingSettings(); drawingSettings.SetShaderPassName(0, new ShaderTagId(MYST_SHADERID_DEFAULT_UNLIT)); drawingSettings.enableDynamicBatching = (currentPipelineFlags & PipelineFlags.DynamicBatching) != 0; drawingSettings.enableInstancing = (currentPipelineFlags & PipelineFlags.Instancing) != 0; // Setup default sort mode SortingSettings sortingSettings = new SortingSettings(camera); drawingSettings.sortingSettings = sortingSettings; // Filters objects to draw different stuff in each pass FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); // Setup sort mode for opaque (front to back) sortingSettings.criteria = SortingCriteria.CommonOpaque; drawingSettings.sortingSettings = sortingSettings; // Render opaque pass filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cullingResults, ref drawingSettings, ref filterSettings); // Sends instructions to draw skybox // context.DrawSkybox(camera); // Setup sort mode for transparent (back to front) sortingSettings.criteria = SortingCriteria.CommonTransparent; drawingSettings.sortingSettings = sortingSettings; // Render transparent pass filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cullingResults, ref drawingSettings, ref filterSettings); // Fallback for everything else DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); // Submit render loop for execution context.Submit(); }
/// <inheritdoc/> public override void Execute(ScriptableRenderer renderer, ScriptableRenderContext context, ref RenderingData renderingData) { if (renderer == null) { throw new ArgumentNullException("renderer"); } CommandBuffer cmd = CommandBufferPool.Get(k_OITDepthPrepassTag); using (new ProfilingSample(cmd, k_OITDepthPrepassTag)) { //cmd.GetTemporaryRT(depthAttachmentHandle.id, descriptor, FilterMode.Point); SetRenderTarget( cmd, depthAttachmentHandle.Identifier(), RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, ClearFlag.None, Color.black, descriptor.dimension); if (descriptor.msaaSamples > 1) { cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthNoMsaa); if (descriptor.msaaSamples == 4) { cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2); cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa4); } else { cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa2); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4); } } else { cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthNoMsaa); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4); } CoreUtils.SetKeyword(cmd, "_ALPHATEST_ON", true); context.ExecuteCommandBuffer(cmd); cmd.Clear(); var drawSettings = CreateDrawRendererSettings(renderingData.cameraData.camera, SortFlags.None, RendererConfiguration.None, renderingData.supportsDynamicBatching); if (renderingData.cameraData.isStereoEnabled) { Camera camera = renderingData.cameraData.camera; context.StartMultiEye(camera); context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, oitFilterSettings); context.StopMultiEye(camera); } else { context.DrawRenderers(renderingData.cullResults.visibleRenderers, ref drawSettings, oitFilterSettings); } CoreUtils.SetKeyword(cmd, "_ALPHATEST_ON", false); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
//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(); } }
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); context.ExecuteCommandBuffer(cmdDepth); 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); 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); cmd.Release(); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //************************** Rendering 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 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); 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); }
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); //SetUp Lighting variables SetUpRealtimeLightingVariables(context, cull); //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 var cmd = CommandBufferPool.Get("Clear"); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings) { perObjectData = PerObjectData.LightIndices | PerObjectData.LightData }; FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); if (!GraphicsSettings.useScriptableRenderPipelineBatching) { Debug.Log("SRP Batcher is turned off so enabling it for this RenderPipeline now."); GraphicsSettings.useScriptableRenderPipelineBatching = true; } //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); }
void RenderDepthPeeling(ScriptableRenderContext context, ref RenderingData renderingData) { var camera = renderingData.camera; FilteringSettings filteringSettings = new FilteringSettings(RenderQueueRange.transparent); SortingSettings sortingSettings = new SortingSettings(camera); sortingSettings.criteria = SortingCriteria.CommonTransparent; DrawingSettings drawingSettings = new DrawingSettings(new ShaderTagId("DepthPeelingFirstPass"), sortingSettings) { enableDynamicBatching = true, perObjectData = PerObjectData.ReflectionProbes, }; RenderStateBlock stateBlock = new RenderStateBlock(RenderStateMask.Nothing); var cmd = CommandBufferPool.Get("Depth Peeling"); using (new ProfilingSample(cmd, "Depth Peeling")) { // Start profilling context.ExecuteCommandBuffer(cmd); cmd.Clear(); List <int> colorRTs = new List <int>(asset.DepthPeelingPass); List <int> depthRTs = new List <int>(asset.DepthPeelingPass); // Perform depth peeling for (var i = 0; i < asset.DepthPeelingPass; i++) { depthRTs.Add(Shader.PropertyToID($"_DepthPeelingDepth{i}")); colorRTs.Add(Shader.PropertyToID($"_DepthPeelingColor{i}")); cmd.GetTemporaryRT(colorRTs[i], camera.pixelWidth, camera.pixelHeight, 0); cmd.GetTemporaryRT(depthRTs[i], camera.pixelWidth, camera.pixelHeight, 32, FilterMode.Point, RenderTextureFormat.RFloat); if (i == 0) { drawingSettings.SetShaderPassName(0, new ShaderTagId("DepthPeelingFirstPass")); cmd.SetRenderTarget(new RenderTargetIdentifier[] { colorRTs[i], depthRTs[i] }, depthRTs[i]); cmd.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmd); cmd.Clear(); context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings, ref stateBlock); } else { cmd.SetGlobalTexture("_MaxDepthTex", depthRTs[i - 1]); drawingSettings.SetShaderPassName(0, new ShaderTagId("DepthPeelingPass")); cmd.SetRenderTarget(new RenderTargetIdentifier[] { colorRTs[i], depthRTs[i] }, depthRTs[i]); cmd.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmd); cmd.Clear(); context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref filteringSettings, ref stateBlock); } } cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CameraTarget); var mat = new Material(Shader.Find("SarRP/Transparent")); for (var i = asset.DepthPeelingPass - 1; i >= 0; i--) { cmd.SetGlobalTexture("_DepthTex", depthRTs[i]); cmd.Blit(colorRTs[i], BuiltinRenderTextureType.CameraTarget, mat, 4); cmd.ReleaseTemporaryRT(depthRTs[i]); cmd.ReleaseTemporaryRT(colorRTs[i]); } cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmd); cmd.Clear(); } context.ExecuteCommandBuffer(cmd); cmd.Clear(); }
private void Render(ScriptableRenderContext context, Camera camera) { if (!CullResults.GetCullingParameters(camera, out var cullingParameters)) { return; } #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref _cullResults); if (_cullResults.visibleLights.Count > 0) { ConfigureLights(); } else { _cameraBuffer.SetGlobalVector(LightIndicesOffsetAndCountId, Vector4.zero); } context.SetupCameraProperties(camera); var clearFlags = camera.clearFlags; _cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); _cameraBuffer.SetGlobalVectorArray(LightColorsId, _lightColors); _cameraBuffer.SetGlobalVectorArray(LightDirectionsOrPositionsId, _lightDirectionsOrPositions); _cameraBuffer.SetGlobalVectorArray(LightAttenuationsId, _lightAttenuations); _cameraBuffer.SetGlobalVectorArray(LightSpotDirectionsId, _lightSpotDirections); _cameraBuffer.SetGlobalVector(WorldSpaceCameraPosId, camera.transform.position); context.ExecuteCommandBuffer(_cameraBuffer); _cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("Super")) { flags = _drawFlags }; if (_cullResults.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } var filterSettings = new FilterRenderersSettings(true); if (_pipelineAsset.DrawOpaque) { drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(_cullResults.visibleRenderers, ref drawSettings, filterSettings); } if (_pipelineAsset.DrawSkybox) { context.DrawSkybox(camera); } if (_pipelineAsset.DrawTransparent) { drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(_cullResults.visibleRenderers, ref drawSettings, filterSettings); } DrawDefaultPipeline(context, camera); context.ExecuteCommandBuffer(_cameraBuffer); _cameraBuffer.Clear(); context.Submit(); }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else { cameraBuffer.SetGlobalVector( lightIndicesOffsetAndCountID, Vector4.zero ); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } context.SetupCameraProperties(camera); CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget( (clearFlags & CameraClearFlags.Depth) != 0, (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor ); cameraBuffer.BeginSample("Render Camera"); cameraBuffer.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings( camera, new ShaderPassName("SRPDefaultUnlit") ) { flags = drawFlags }; if (cull.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.sorting.flags = SortFlags.CommonOpaque; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); context.DrawSkybox(camera); drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); DrawDefaultPipeline(context, camera); cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } }
public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras) { //************************** SetRenderingFeatures **************************************** #if UNITY_EDITOR SupportedRenderingFeatures.active = new SupportedRenderingFeatures() { reflectionProbeSupportFlags = SupportedRenderingFeatures.ReflectionProbeSupportFlags.None, defaultMixedLightingMode = SupportedRenderingFeatures.LightmapMixedBakeMode.Subtractive, supportedMixedLightingModes = SupportedRenderingFeatures.LightmapMixedBakeMode.Subtractive, supportedLightmapBakeTypes = LightmapBakeType.Baked | LightmapBakeType.Mixed, supportedLightmapsModes = LightmapsMode.CombinedDirectional | LightmapsMode.NonDirectional, rendererSupportsLightProbeProxyVolumes = false, rendererSupportsMotionVectors = false, rendererSupportsReceiveShadows = true, rendererSupportsReflectionProbes = true }; SceneViewDrawMode.SetupDrawMode(); #endif // ////////////////////////////////////////////////////////////////////////////////// foreach (Camera camera in cameras) { //************************** Culling **************************************** ScriptableCullingParameters cullingParams; if (!CullResults.GetCullingParameters(camera, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); //************************** Cam Properties ********************************** context.SetupCameraProperties(camera); //************************** Clear Flags ************************************ CommandBuffer cmd = new CommandBuffer(); cmd.name = "Clear Flag"; ClearFlag(cmd, camera); context.ExecuteCommandBuffer(cmd); cmd.Release(); //************************** Lighting Variables ***************************** CommandBuffer cmdLighting = new CommandBuffer(); cmdLighting.name = "Lighting variable"; int additionalLightSet = 0; int mainLightIndex = -1; for (int i = 0; i < cull.visibleLights.Count; i++) { VisibleLight light = cull.visibleLights[i]; if (mainLightIndex == -1) //Directional light { if (light.lightType == LightType.Directional) { cmdLighting.SetGlobalVector("_LightColor0", light.light.color); Vector4 dir = light.localToWorld.GetColumn(2); cmdLighting.SetGlobalVector("_WorldSpaceLightPos0", new Vector4(-dir.x, -dir.y, -dir.z, 0)); mainLightIndex = i; } } else { additionalLightSet++; continue;//so far just do only 1 directional light } } context.ExecuteCommandBuffer(cmdLighting); cmdLighting.Release(); //************************** Draw Settings ************************************ FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); DrawRendererSettings drawSettingsDefault = new DrawRendererSettings(camera, passNameDefault); drawSettingsDefault.rendererConfiguration = renderConfig; drawSettingsDefault.SetShaderPassName(5, m_UnlitPassName); DrawRendererSettings drawSettingsBase = new DrawRendererSettings(camera, passNameBase); drawSettingsBase.rendererConfiguration = renderConfig; DrawRendererSettings drawSettingsAdd = new DrawRendererSettings(camera, passNameAdd); drawSettingsAdd.rendererConfiguration = renderConfig; DrawRendererSettings drawSettingsShadow = new DrawRendererSettings(camera, passNameShadow); //DrawRendererSettings drawSettingsMeta = new DrawRendererSettings(camera, passNameMeta); //************************** Skybox ************************************ if (camera.clearFlags == CameraClearFlags.Skybox) { context.DrawSkybox(camera); } //************************** Opaque ************************************ // Opaque filterSettings.renderQueueRange = RenderQueueRange.opaque; // Draw OPAQUE objects using DEFAULT pass drawSettingsDefault.sorting.flags = SortFlags.CommonOpaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDefault, filterSettings); // Draw OPAQUE objects using BASE pass drawSettingsBase.sorting.flags = SortFlags.CommonOpaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettingsBase, filterSettings); // Draw OPAQUE objects using ADD pass drawSettingsAdd.sorting.flags = SortFlags.CommonOpaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettingsAdd, filterSettings); //************************** Transparent ************************************ filterSettings.renderQueueRange = RenderQueueRange.transparent; // Draw TRANSPARENT objects using DEFAULT pass drawSettingsDefault.sorting.flags = SortFlags.CommonTransparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettingsDefault, filterSettings); // Draw TRANSPARENT objects using BASE pass drawSettingsBase.sorting.flags = SortFlags.CommonTransparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettingsBase, filterSettings); // Draw TRANSPARENT objects using ADD pass drawSettingsAdd.sorting.flags = SortFlags.CommonTransparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettingsAdd, filterSettings); context.Submit(); } }
public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, SimpleRenderPipeline.Mode mode) { foreach (var camera in cameras) { // Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); context.SetupCameraProperties(camera); AttachmentDescriptor color = new AttachmentDescriptor(RenderTextureFormat.ARGB32); AttachmentDescriptor depth = new AttachmentDescriptor(RenderTextureFormat.Depth); bool needsFinalBlit = camera.cameraType == CameraType.SceneView; RenderTargetIdentifier tmpBuf = new RenderTargetIdentifier("TempSurface"); if (needsFinalBlit) { using (var cmd = new CommandBuffer()) { cmd.GetTemporaryRT(Shader.PropertyToID("TempSurface"), camera.pixelWidth, camera.pixelHeight, 24, FilterMode.Bilinear, RenderTextureFormat.ARGB32); context.ExecuteCommandBuffer(cmd); } color.ConfigureTarget(tmpBuf, false, true); } else { color.ConfigureTarget(BuiltinRenderTextureType.CameraTarget, false, true); } // No configure target for depth means depth will be memoryless color.ConfigureClear(Color.blue / 3 + Color.red / 2); depth.ConfigureClear(Color.black, 1.0f, 0); using (var attachmentsDisposable = new NativeArray <AttachmentDescriptor>(2, Allocator.Temp)) { var attachments = attachmentsDisposable; const int depthIndex = 0, colorIndex = 1; attachments[depthIndex] = depth; attachments[colorIndex] = color; using (context.BeginScopedRenderPass(camera.pixelWidth, camera.pixelHeight, 1, attachments, depthIndex)) { var fs = new FilteringSettings(RenderQueueRange.opaque); if (mode == SimpleRenderPipeline.Mode.DepthPrepass) { var depthPrePasssettings = new DrawingSettings(new ShaderTagId("DepthPrepass"), new SortingSettings(camera)); using (var depthOnlyDisposable = new NativeArray <int>(0, Allocator.Temp)) { var depthArray = depthOnlyDisposable; using (context.BeginScopedSubPass(depthArray)) { context.DrawRenderers(cull, ref depthPrePasssettings, ref fs); } } var mainPasssettings = new DrawingSettings(new ShaderTagId("AfterZPrepass"), new SortingSettings(camera)); using (var colorsDisposable = new NativeArray <int>(1, Allocator.Temp)) { var colors = colorsDisposable; colors[0] = colorIndex; using (context.BeginScopedSubPass(colors)) { context.DrawRenderers(cull, ref mainPasssettings, ref fs); } } } else if (mode == SimpleRenderPipeline.Mode.OnePassAlphaTest) { var mainPasssettings = new DrawingSettings(new ShaderTagId("OnePassAlphaClip"), new SortingSettings(camera)); using (var colorsDisposable = new NativeArray <int>(1, Allocator.Temp)) { var colors = colorsDisposable; colors[0] = colorIndex; using (context.BeginScopedSubPass(colors)) { context.DrawRenderers(cull, ref mainPasssettings, ref fs); } } } else if (mode == SimpleRenderPipeline.Mode.OnePassAlphaBlend) { var sortingSettings = new SortingSettings(camera); sortingSettings.criteria = SortingCriteria.BackToFront; var mainPasssettings = new DrawingSettings(new ShaderTagId("OnePassAlphaBlend"), sortingSettings); using (var colorsDisposable = new NativeArray <int>(1, Allocator.Temp)) { var colors = colorsDisposable; colors[0] = colorIndex; using (context.BeginScopedSubPass(colors)) { context.DrawRenderers(cull, ref mainPasssettings, ref fs); } } } } } if (needsFinalBlit) { using (var cmd = new CommandBuffer()) { cmd.Blit(tmpBuf, new RenderTargetIdentifier(BuiltinRenderTextureType.CameraTarget)); context.ExecuteCommandBuffer(cmd); } } context.Submit(); } }
public override void Render(ScriptableRenderContext context, Camera[] cameras) { base.Render(context, cameras); bool stereoEnabled = XRSettings.isDeviceActive; foreach (Camera camera in cameras) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, stereoEnabled, out cullingParameters)) { continue; } cullingParameters.shadowDistance = Mathf.Min(m_ShadowSettings.maxShadowDistance, camera.farClipPlane); CullResults.Cull(ref cullingParameters, context, ref m_CullResults); VisibleLight[] visibleLights = m_CullResults.visibleLights.ToArray(); LightData lightData; InitializeLightData(visibleLights, out lightData); // Render Shadow Map if (lightData.shadowLightIndex > -1) { lightData.shadowsRendered = RenderShadows(ref m_CullResults, ref visibleLights[lightData.shadowLightIndex], lightData.shadowLightIndex, ref context); } // Setup camera matrices and RT context.SetupCameraProperties(camera, stereoEnabled); // Setup light and shadow shader constants SetupShaderLightConstants(visibleLights, ref lightData, ref m_CullResults, ref context); if (lightData.shadowsRendered) { SetupShadowShaderConstants(ref context, ref visibleLights[lightData.shadowLightIndex], lightData.shadowLightIndex, m_ShadowCasterCascadesCount); } SetShaderKeywords(ref lightData, ref context); RendererConfiguration configuration = RendererConfiguration.PerObjectReflectionProbes; if (m_Asset.EnableLightmap) { configuration |= RendererConfiguration.PerObjectLightmaps; } if (m_Asset.EnableAmbientProbe) { configuration |= RendererConfiguration.PerObjectLightProbe; } if (!lightData.isSingleDirectionalLight) { configuration |= RendererConfiguration.PerObjectLightIndices8; } BeginForwardRendering(camera, ref context, stereoEnabled); // Render Opaques var litSettings = new DrawRendererSettings(m_CullResults, camera, m_LitPassName); litSettings.sorting.flags = SortFlags.CommonOpaque; litSettings.inputFilter.SetQueuesOpaque(); litSettings.rendererConfiguration = configuration; var unlitSettings = new DrawRendererSettings(m_CullResults, camera, m_UnlitPassName); unlitSettings.sorting.flags = SortFlags.CommonTransparent; unlitSettings.inputFilter.SetQueuesTransparent(); context.DrawRenderers(ref litSettings); // TODO: Check skybox shader context.DrawSkybox(camera); // Render Alpha blended litSettings.sorting.flags = SortFlags.CommonTransparent; litSettings.inputFilter.SetQueuesTransparent(); context.DrawRenderers(ref litSettings); context.DrawRenderers(ref unlitSettings); EndForwardRendering(camera, ref context, stereoEnabled); // Release temporary RT var discardRT = CommandBufferPool.Get(); discardRT.ReleaseTemporaryRT(m_ShadowMapProperty); discardRT.ReleaseTemporaryRT(m_CameraRTProperty); context.ExecuteCommandBuffer(discardRT); CommandBufferPool.Release(discardRT); } context.Submit(); }
private void RenderList(ScriptableRenderContext context, ref RenderingData renderingData, SortingCriteria sortFlags) { var drawSettings = CreateDrawingSettings(passList, ref renderingData, sortFlags); context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filteringSettings); }
public override void Render(ScriptableRenderContext renderContext, Camera[] cameras) { //example base.Render(renderContext, cameras); //core 核心 1设置渲染操作,2执行渲染操作,3上传渲染操作 //var cmd = new CommandBuffer(); //culling ScriptableCullingParameters cullingParams; Debug.Log(cameras[0].name); if (!CullResults.GetCullingParameters(Camera.main, stereoEnable, out cullingParams)) { return; } cullingParams.isOrthographic = true; CullResults cullResults = new CullResults(); CullResults.Cull(ref cullingParams, renderContext, ref cullResults); List <VisibleLight> lights = cullResults.visibleLights; foreach (var item in lights) { if (item.lightType == LightType.Directional)//设置直射光 { Vector4 dir = -item.localToWorld.GetColumn(2); Shader.SetGlobalVector("LightColor0", item.finalColor); Shader.SetGlobalVector("WorldSpaceLightPos0", item.finalColor); break; } } //end culling //filter var opaqueRange = new FilterRenderersSettings(); opaqueRange.renderQueueRange = new RenderQueueRange() { min = 0, max = (int)UnityEngine.Rendering.RenderQueue.GeometryLast, }; opaqueRange.layerMask = ~0; //end filter //draw var drs = new DrawRendererSettings(Camera.main, new ShaderPassName("Opaque")); drs.flags = DrawRendererFlags.EnableInstancing; drs.rendererConfiguration = RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightmaps; drs.sorting.flags = SortFlags.CommonOpaque; //draw!!! renderContext.DrawRenderers(cullResults.visibleRenderers, ref drs, opaqueRange); //end draw //cmd.DrawRenderer(renderContext, new Material()); //cmd.ClearRenderTarget(true, true, screenColor);//1 //renderContext.ExecuteCommandBuffer(cmd);//2 //cmd.Release(); renderContext.Submit();//3 }
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"); cmd.Clear(); Profiler.BeginSample("RenderSpritesWithLighting - Create Render Textures"); RendererLighting.CreateRenderTextures(cmd, camera); Profiler.EndSample(); cmd.SetGlobalFloat("_HDREmulationScale", m_RendererData.hdrEmulationScale); cmd.SetGlobalFloat("_InverseHDREmulationScale", 1.0f / m_RendererData.hdrEmulationScale); RendererLighting.SetShapeLightShaderGlobals(cmd); context.ExecuteCommandBuffer(cmd); Profiler.BeginSample("RenderSpritesWithLighting - Prepare"); DrawingSettings combinedDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent); DrawingSettings normalsDrawSettings = CreateDrawingSettings(k_NormalsRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent); FilteringSettings filterSettings = new FilteringSettings(); filterSettings.renderQueueRange = RenderQueueRange.all; filterSettings.layerMask = -1; filterSettings.renderingLayerMask = 0xFFFFFFFF; filterSettings.sortingLayerRange = SortingLayerRange.all; Profiler.EndSample(); for (int i = 0; i < s_SortingLayers.Length; 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. short layerValue = (short)s_SortingLayers[i].value; var lowerBound = (i == 0) ? short.MinValue : layerValue; var upperBound = (i == s_SortingLayers.Length - 1) ? short.MaxValue : layerValue; filterSettings.sortingLayerRange = new SortingLayerRange(lowerBound, upperBound); int layerToRender = s_SortingLayers[i].id; Light2D.LightStats lightStats; lightStats = Light2D.GetLightStatsByLayer(layerToRender); if (lightStats.totalNormalMapUsage > 0) { RendererLighting.RenderNormals(context, renderingData.cullResults, normalsDrawSettings, filterSettings); } cmd.Clear(); if (lightStats.totalLights > 0) { #if UNITY_EDITOR cmd.name = "Render Lights - " + SortingLayer.IDToName(layerToRender); #endif RendererLighting.RenderLights(camera, cmd, layerToRender); } else { RendererLighting.ClearDirtyLighting(cmd); } CoreUtils.SetRenderTarget(cmd, colorAttachment, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, 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(); #if UNITY_EDITOR cmd.name = "Render Light Volumes" + SortingLayer.IDToName(layerToRender); #endif RendererLighting.RenderLightVolumes(camera, cmd, layerToRender); context.ExecuteCommandBuffer(cmd); cmd.Clear(); } } 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 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; //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //cmd.BeginSample("xxx"); //cmd.EndSample("xxx"); //UnityEngine.Profiling.Profiler.BeginSample("xxx"); //UnityEngine.Profiling.Profiler.EndSample(); //Camera clear flag { debugTag = "Debug - ClearRenderTarget"; CommandBuffer cmd = CommandBufferPool.Get(debugTag); using (new ProfilingSample(cmd, debugTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // cmd.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); cmd.SetRenderTarget(m_ColorRT); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } // Skybox { debugTag = "Debug - DrawSkyBox"; CommandBuffer cmd = CommandBufferPool.Get(debugTag); using (new ProfilingSample(cmd, debugTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // if (drawSkyBox) { context.DrawSkybox(camera); } // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } //Opaque objects { debugTag = "Debug - DrawOpaqueObjects"; CommandBuffer cmd = CommandBufferPool.Get(debugTag); using (new ProfilingSample(cmd, debugTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } //Transparent objects { debugTag = "Debug - DrawTransparentObjects"; CommandBuffer cmd = CommandBufferPool.Get(debugTag); using (new ProfilingSample(cmd, debugTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } //Blit to screen { debugTag = "Debug - BlitToScreen"; CommandBuffer cmd = CommandBufferPool.Get(debugTag); using (new ProfilingSample(cmd, debugTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // cmd.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } //Clean Up { debugTag = "Debug - CleanUp"; CommandBuffer cmd = CommandBufferPool.Get(debugTag); using (new ProfilingSample(cmd, debugTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); // cmd.ReleaseTemporaryRT(m_ColorRTid); // } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
public void Render(ScriptableRenderContext context, Camera camera) { if (!CullResults.GetCullingParameters(camera, out var cullingParameters)) { return; } cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { //将UI几何体发射到“场景”视图中以进行渲染。 ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } else if (mainCamera == null && camera.cameraType == CameraType.Game && camera == Camera.main) { mainCamera = camera; } #endif //CullResults cull = CullResults.Cull(ref cullingParameters, context); CullResults.Cull(ref cullingParameters, context, ref cull); if (cull.visibleLights.Count > 0) { ConfigureLights(); if (mainLightExists) { RenderCascadedShadows(context); } else { cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); } if (shadowTileCount > 0) { RenderShadows(context); } else { cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } } else { cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); } context.SetupCameraProperties(camera); var myPipelineCamera = camera.GetComponent <MyPipelineCamera>(); MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack; bool scaledRendering = renderScale != 1f && camera.cameraType == CameraType.Game; int renderWidth = camera.pixelWidth; int renderHeight = camera.pixelHeight; if (scaledRendering) { renderWidth = (int)(renderWidth * renderScale); renderHeight = (int)(renderHeight * renderScale); } int renderSamples = camera.allowMSAA ? msaaSamples : 1; bool renderToTexture = scaledRendering || renderSamples > 1 || activeStack; bool needsDepth = activeStack && activeStack.NeedsDepth; //如果MSAA != 1 , 则 主贴图需要 24位深度 用来ZTestWrite画 bool needsDirectDepth = needsDepth && renderSamples == 1; //专门用DepthOnly 来画深度图 bool needsDepthOnlyPass = needsDepth && renderSamples > 1; RenderTextureFormat format = allowHDR && camera.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; if (renderToTexture) { //需要深度进行处理的的时候 要单独的深度图 不让它进行MSAA //否则可以跟随主颜色进行MSAA cameraBuffer.GetTemporaryRT(cameraColorTextureID, renderWidth, renderHeight, needsDirectDepth ? 0 : 24 , FilterMode.Bilinear, format, RenderTextureReadWrite.Default, renderSamples); if (needsDepth) { cameraBuffer.GetTemporaryRT(cameraDepthTextureID, renderWidth, renderHeight, 24 , FilterMode.Point, RenderTextureFormat.Depth, RenderTextureReadWrite.Linear, 1); } if (needsDirectDepth) { cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, cameraDepthTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); } else { cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); } } CameraClearFlags clearFlags = camera.clearFlags; cameraBuffer.ClearRenderTarget((clearFlags & CameraClearFlags.Depth) != 0 , (clearFlags & CameraClearFlags.Color) != 0, camera.backgroundColor); cameraBuffer.BeginSample("Render Camera"); cameraBuffer.SetGlobalVectorArray(visibleLightColorsID, visibleLightColors); cameraBuffer.SetGlobalVectorArray(visibleLightDirectionsOrPositionsID, visibleLightDirectionsOrPositions); cameraBuffer.SetGlobalVectorArray(visibleLightAttenuationsID, visibleLightAttenuations); cameraBuffer.SetGlobalVectorArray(visibleLightSpotDirectionsID, visibleLightSpotDirections); cameraBuffer.SetGlobalVectorArray(visibleLightOcclusionMaskID, visibleLightOcclusionMasks); globalShadowData.z = 1f - cullingParameters.shadowDistance * globalShadowData.y; cameraBuffer.SetGlobalVector(globalShadowDataID, globalShadowData); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); //这样就可以走SRP的SubShader 如果没有则都走 //Shader SubShader Tags{"RenderPipeline"="MySRPPipeline"} //Shader.globalRenderPipeline = "MySRPPipeline"; //我们必须通过提供相机和一个shader pass 作为draw setting的构造函数的参数。 //这个相机用来设置排序和裁剪层级(culling layers), //而shader pass 控制使用那个shader pass进行渲染。 //如果Pass未指定LightMode,Unity会自动将其设置为SRPDefaultUnlit var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit")) { flags = drawFlags, rendererConfiguration = RendererConfiguration.None }; if (cull.visibleLights.Count > 0) { drawSettings.rendererConfiguration = RendererConfiguration.PerObjectLightIndices8; } drawSettings.rendererConfiguration |= RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe | RendererConfiguration.PerObjectLightProbeProxyVolume | RendererConfiguration.PerObjectShadowMask | RendererConfiguration.PerObjectOcclusionProbe | RendererConfiguration.PerObjectOcclusionProbeProxyVolume; drawSettings.sorting.flags = SortFlags.CommonOpaque; //因为 Unity 更喜欢将对象空间化地分组以减少overdraw var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings); context.DrawSkybox(camera); if (activeStack) { if (needsDepth) { if (needsDepthOnlyPass) { var depthOnlyDrawSettings = new DrawRendererSettings( camera, new ShaderPassName("DepthOnly")) { flags = drawFlags, sorting = { flags = SortFlags.CommonOpaque } }; cameraBuffer.SetRenderTarget(cameraDepthTextureID, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store); cameraBuffer.ClearRenderTarget(true, false, Color.clear); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.DrawRenderers(cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings); } } activeStack.RenderAfterOpaque( postProcessingBuffer, cameraColorTextureID, cameraDepthTextureID , renderWidth, renderHeight, renderSamples, format); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); if (needsDirectDepth) { cameraBuffer.SetRenderTarget( cameraColorTextureID, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store , cameraDepthTextureID, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); } else { cameraBuffer.SetRenderTarget(cameraColorTextureID, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); } context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); } drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings); DrawDefaultPipeline(context, camera); if (renderToTexture) { if (activeStack) { activeStack.RenderAfterTransparent(postProcessingBuffer, cameraColorTextureID, cameraDepthTextureID , renderWidth, renderHeight, renderSamples, format); context.ExecuteCommandBuffer(postProcessingBuffer); postProcessingBuffer.Clear(); } else { cameraBuffer.Blit(cameraColorTextureID, BuiltinRenderTextureType.CameraTarget); } cameraBuffer.ReleaseTemporaryRT(cameraColorTextureID); if (needsDepth) { cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureID); } } cameraBuffer.EndSample("Render Camera"); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
/// <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_rpp.bDynamicBatching; //是否开启GPU Instancing drawingSettings.enableInstancing = m_rpp.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); } } }