void ExecuteBuffer(ScriptableRenderContext context, Camera camera) { context.ExecuteCommandBuffer(buffer); buffer.Clear(); }
void ExecuteBuffer() { context.ExecuteCommandBuffer(buffer); buffer.Clear(); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(context, cameras); foreach (Camera camera in cameras) { BeginCameraRendering(context, camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects if (m_PipelineAsset.drawOpaqueObjects) //Use the settings on the asset { sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); } //Transparent objects if (m_PipelineAsset.drawTransparentObjects) //Use the settings on the asset { 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); }
protected void RenderCamera(ScriptableRenderContext context, Camera camera) { m_CameraRender.Render(context, camera); return; BeginCameraRendering(context, camera); if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } //setup camera //culling ScriptableCullingParameters cullingParams; camera.TryGetCullingParameters(out cullingParams); //setup shadow cullingParams.shadowDistance = Mathf.Min(m_PipelineConfig.ShadowSetting.maxDistance, camera.farClipPlane); #if UNITY_EDITOR if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullingResults cullResult = context.Cull(ref cullingParams); SetupRenderContext(ref context, ref cullResult, camera); #if UNITY_EDITOR RenderGizmo(context, camera, GizmoSubset.PreImageEffects); #endif RenderShadow(ref m_RenderContext); context.SetupCameraProperties(camera); cmd.Clear(); cmd.ClearRenderTarget(true, true, Color.clear); context.ExecuteCommandBuffer(cmd); context.Submit(); RenderObject(context, camera, ref cullResult); //draw skybox context.DrawSkybox(camera); #if UNITY_EDITOR RenderGizmo(context, camera, GizmoSubset.PostImageEffects); #endif Cleanup(ref m_RenderContext); context.Submit(); EndCameraRendering(context, camera); }
private void RenderCamera(ref ScriptableRenderContext context, Camera camera) { if (m_ShadowMap == null) { m_ShadowMap = new RenderTexture(1024, 1024, 24, RenderTextureFormat.Shadowmap); m_ShadowMap.name = "Shadow Map"; m_ShadowMap.Create(); } if (camera.TryGetCullingParameters(out ScriptableCullingParameters cullingParameters)) { // Start camera render RenderPipeline.BeginCameraRendering(context, camera); cullingParameters.shadowDistance = 30; // Perform culling operations CullingResults cullingResults = context.Cull(ref cullingParameters); // Shadow map rendering Matrix4x4 worldToShadowMatrix = Matrix4x4.identity; bool didRenderShadowMap = RenderShadowMaps(ref context, ref cullingResults, ref worldToShadowMatrix); // Setup camera for rendering context.SetupCameraProperties(camera); // Clear camera CommandBuffer cb_ClearCamera = new CommandBuffer(); cb_ClearCamera.name = "ClearCamera"; cb_ClearCamera.SetRenderTarget(camera.targetTexture); cb_ClearCamera.ClearRenderTarget(true, true, camera.backgroundColor); context.ExecuteCommandBuffer(cb_ClearCamera); // Draw opaque objects SortingSettings sortSettings = new SortingSettings(camera); sortSettings.criteria = SortingCriteria.CommonOpaque; FilteringSettings filterSettings = FilteringSettings.defaultValue; filterSettings.renderQueueRange = RenderQueueRange.opaque; if (didRenderShadowMap) { CommandBuffer cb = new CommandBuffer(); cb.name = "Set up shadow shader properties"; cb.SetGlobalTexture("_ShadowMapTexture", m_ShadowMap); cb.SetGlobalMatrix("_WorldToShadowMatrix", worldToShadowMatrix); cb.SetGlobalVector("_LightDirection", -cullingResults.visibleLights[0].light.transform.forward); // Direction towards the light context.ExecuteCommandBuffer(cb); } DrawingSettings opaqueDrawSettings = new DrawingSettings(s_OpaquePassTag, sortSettings); context.DrawRenderers(cullingResults, ref opaqueDrawSettings, ref filterSettings); // Draw skybox context.DrawSkybox(camera); // Final submission context.Submit(); // End camera render RenderPipeline.EndCameraRendering(context, camera); } }
public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, SRP07CustomParameter SRP07CP) { string tx = ""; foreach (Camera camera in cameras) { ScriptableCullingParameters cullingParams; // Stereo-aware culling parameters are configured to perform a single cull for both eyes if (!CullResults.GetCullingParameters(camera, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); // Setup camera for rendering (sets render target, view/projection matrices and other // per-camera built-in shader variables). context.SetupCameraProperties(camera); // clear depth buffer CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(true, !SRP07CP.DrawSkybox, SRP07CP.ClearColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); if (SRP07CP.DrawSkybox) { // Draw skybox context.DrawSkybox(camera); } // Setup DrawSettings and FilterSettings ShaderPassName passName = new ShaderPassName("BasicPass"); DrawRendererSettings drawSettings = new DrawRendererSettings(camera, passName); FilterRenderersSettings filterSettings = new FilterRenderersSettings(true); // //////////////////////////////////////////////////////////// VisibleLight[] ls = cull.visibleLights.ToArray(); DrawShadowsSettings[] shadowsSettings = new DrawShadowsSettings[ls.Length]; for (int i = 0; i < shadowsSettings.Length; i++) { shadowsSettings[i] = new DrawShadowsSettings(cull, i); } /* * if(camera == Camera.main) //Only generate result from main cam * { * tx += "DrawShadowsSettings" + "\n"+ "\n"; * * for (int i=0; i<ls.Length; i++) * { * tx += "lightIndex = " + shadowsSettings[i].lightIndex + " (" + ls[i].light.name + ") " + "\n"; * tx += "splitData.cullingPlaneCount = " + shadowsSettings[i].splitData.cullingPlaneCount + "\n"; * tx += "splitData.cullingSphere = " + shadowsSettings[i].splitData.cullingSphere + "\n"+ "\n"; * } * * // Output to text * if (textMesh != null) * { * textMesh.text = tx; * Debug.Log("<color=#0F0>TextMesh is updated</color>"); * } * else * { * tx = "<color=#F00>TextMesh is null</color> Please hit play if you hasn't"; * Debug.Log(tx); * } * } */ // //////////////////////////////////////////////////////////// if (SRP07CP.DrawOpaque) { // Draw opaque objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonOpaque; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); for (int i = 0; i < shadowsSettings.Length; i++) { //if(ls[i].light.shadows != LightShadows.None) //context.DrawShadows(ref shadowsSettings[i]); } } if (SRP07CP.DrawTransparent) { // 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(); } }
/// <inheritdoc/> public override void Execute(ScriptableRenderContext context, ref UnityEngine.Rendering.Universal.RenderingData renderingData) { CommandBuffer cmd = CommandBufferPool.Get("Light Shafts"); int divider = 4; if (EnviroSkyMgr.instance.LightShaftsSettings.resolution == EnviroPostProcessing.SunShaftsResolution.Normal) { divider = 2; } else if (EnviroSkyMgr.instance.LightShaftsSettings.resolution == EnviroPostProcessing.SunShaftsResolution.High) { divider = 1; } Vector3 v = Vector3.one * 0.5f; if (lightSource) { v = myCam.WorldToViewportPoint(lightSource.position); } else { v = new Vector3(0.5f, 0.5f, 0.0f); } int rtW = renderingData.cameraData.cameraTargetDescriptor.width / divider; int rtH = renderingData.cameraData.cameraTargetDescriptor.height / divider; RenderTextureDescriptor textureDescriptor = renderingData.cameraData.cameraTargetDescriptor; textureDescriptor.width = rtW; textureDescriptor.height = rtH; textureDescriptor.depthBufferBits = 0; textureDescriptor.colorFormat = RenderTextureFormat.Default; if (lrDepthBuffer == null) { lrDepthBuffer = new RenderTexture(textureDescriptor); } if (lrColorB == null) { lrColorB = new RenderTexture(textureDescriptor); } // lrDepthBuffer = RenderTexture.GetTemporary(textureDescriptor); cmd.SetGlobalVector("_BlurRadius4", new Vector4(1.0f, 1.0f, 0.0f, 0.0f) * EnviroSkyMgr.instance.LightShaftsSettings.blurRadius); cmd.SetGlobalVector("_SunPosition", new Vector4(v.x, v.y, v.z, EnviroSkyMgr.instance.LightShaftsSettings.maxRadius)); cmd.SetGlobalVector("_SunThreshold", treshold); if (blitMaterial == null) { blitMaterial = new Material(Shader.Find("Enviro/Effects/LightShafts")); } blitMaterial.SetVector("_BlurRadius4", new Vector4(1.0f, 1.0f, 0.0f, 0.0f) * EnviroSkyMgr.instance.LightShaftsSettings.blurRadius); blitMaterial.SetVector("_SunPosition", new Vector4(v.x, v.y, v.z, EnviroSkyMgr.instance.LightShaftsSettings.maxRadius)); blitMaterial.SetVector("_SunThreshold", treshold); RenderTextureDescriptor textureDescriptorSource = renderingData.cameraData.cameraTargetDescriptor; textureDescriptorSource.graphicsFormat = Experimental.Rendering.GraphicsFormat.R32G32B32A32_SFloat; textureDescriptorSource.depthBufferBits = 0; RenderTexture sourceRT = RenderTexture.GetTemporary(textureDescriptorSource); Blit(cmd, source, sourceRT); Graphics.Blit(sourceRT, lrDepthBuffer, blitMaterial, 2); //Blit(cmd, source, lrDepthBuffer, blitMaterial, 2); if (clearMaterial == null) { clearMaterial = new Material(Shader.Find("Enviro/Effects/ClearLightShafts")); } // paint a small black small border to get rid of clamping problems if (myCam.stereoActiveEye == Camera.MonoOrStereoscopicEye.Mono) { DrawBorder(lrDepthBuffer, clearMaterial); } // radial blur: radialBlurIterations = Mathf.Clamp(radialBlurIterations, 1, 4); float ofs = EnviroSkyMgr.instance.LightShaftsSettings.blurRadius * (1.0f / 768.0f); cmd.SetGlobalVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); cmd.SetGlobalVector("_SunPosition", new Vector4(v.x, v.y, v.z, EnviroSkyMgr.instance.LightShaftsSettings.maxRadius)); blitMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); blitMaterial.SetVector("_SunPosition", new Vector4(v.x, v.y, v.z, EnviroSkyMgr.instance.LightShaftsSettings.maxRadius)); for (int it2 = 0; it2 < radialBlurIterations; it2++) { Graphics.Blit(lrDepthBuffer, lrColorB, blitMaterial, 1); //Blit(cmd, lrDepthBuffer, lrColorB, blitMaterial, 1); // RenderTexture.ReleaseTemporary(lrDepthBuffer); ofs = EnviroSkyMgr.instance.LightShaftsSettings.blurRadius * (((it2 * 2.0f + 1.0f) * 6.0f)) / 768.0f; cmd.SetGlobalVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); blitMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); //lrDepthBuffer = RenderTexture.GetTemporary(textureDescriptor); Graphics.Blit(lrColorB, lrDepthBuffer, blitMaterial, 1); //Blit(cmd, lrColorB, lrDepthBuffer, blitMaterial, 1); //RenderTexture.ReleaseTemporary(lrColorB); ofs = EnviroSkyMgr.instance.LightShaftsSettings.blurRadius * (((it2 * 2.0f + 2.0f) * 6.0f)) / 768.0f; cmd.SetGlobalVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); blitMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); } // put together: if (v.z >= 0.0f) { cmd.SetGlobalVector("_SunColor", new Vector4(clr.r, clr.g, clr.b, clr.a) * EnviroSkyMgr.instance.LightShaftsSettings.intensity); } else { cmd.SetGlobalVector("_SunColor", Vector4.zero); // no backprojection ! } //FINAL // blitMaterial.SetTexture("_ColorBuffer", lrDepthBuffer); cmd.SetGlobalTexture("_ColorBuffer", lrDepthBuffer); Blit(cmd, sourceRT, source, blitMaterial, (EnviroSkyMgr.instance.LightShaftsSettings.screenBlendMode == EnviroPostProcessing.ShaftsScreenBlendMode.Screen) ? 0 : 4); // RenderTexture.ReleaseTemporary(lrDepthBuffer); RenderTexture.ReleaseTemporary(sourceRT); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
private void SetUpRealtimeLightingVariables(ScriptableRenderContext context, CullingResults cull) { for (var i = 0; i < lightCount; i++) { lightColor[i] = Vector4.zero; lightData[i] = Vector4.zero; lightSpotDir[i] = Vector4.zero; if (i >= cull.visibleLights.Length) { continue; } VisibleLight light = cull.visibleLights[i]; if (light.lightType == LightType.Directional) { lightData[i] = light.localToWorldMatrix.MultiplyVector(Vector3.back); lightColor[i] = light.finalColor; lightColor[i].w = -1; //for identifying it is a directional light in shader } else if (light.lightType == LightType.Point) { lightData[i] = light.localToWorldMatrix.GetColumn(3); lightData[i].w = light.range; lightColor[i] = light.finalColor; lightColor[i].w = -2; //for identifying it is a point light in shader } else if (light.lightType == LightType.Spot) { lightData[i] = light.localToWorldMatrix.GetColumn(3); lightData[i].w = 1f / Mathf.Max(light.range * light.range, 0.00001f); lightSpotDir[i] = light.localToWorldMatrix.GetColumn(2); lightSpotDir[i].x = -lightSpotDir[i].x; lightSpotDir[i].y = -lightSpotDir[i].y; lightSpotDir[i].z = -lightSpotDir[i].z; lightColor[i] = light.finalColor; float outerRad = Mathf.Deg2Rad * 0.5f * light.spotAngle; float outerCos = Mathf.Cos(outerRad); float outerTan = Mathf.Tan(outerRad); float innerCos = Mathf.Cos(Mathf.Atan(((46f / 64f) * outerTan))); float angleRange = Mathf.Max(innerCos - outerCos, 0.001f); //Spotlight attenuation lightSpotDir[i].w = 1f / angleRange; lightColor[i].w = -outerCos * lightSpotDir[i].w; } else { // If it's not a point / directional / spot light, we ignore the light. continue; } } CommandBuffer cmdLight = CommandBufferPool.Get("Set-up Light Buffer"); cmdLight.SetGlobalVectorArray(lightDataID, lightData); cmdLight.SetGlobalVectorArray(lightColorID, lightColor); cmdLight.SetGlobalVectorArray(lightSpotDirID, lightSpotDir); context.ExecuteCommandBuffer(cmdLight); CommandBufferPool.Release(cmdLight); }
private void RenderDepthPeeling(ScriptableRenderContext context, ref MyRenderingData 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 = false, perObjectData = PerObjectData.ReflectionProbes, }; RenderStateBlock stateBlock = new RenderStateBlock(RenderStateMask.Nothing); var cmd = CommandBufferPool.Get(k_profilerTag_depthPeeling); using (new ProfilingScope(cmd, profilingSampler_depthPeeling)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); List <int> colorRTs = new List <int>(asset.depthPeelingPass); List <int> depthRTs = new List <int>(asset.depthPeelingPass); for (var i = 0; i < asset.depthPeelingPass; i++) { colorRTs.Add(Shader.PropertyToID($"_DepthPeelingColor{i}")); depthRTs.Add(Shader.PropertyToID($"_DepthPeelingDepth{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); // cmd.Blit(renderingData.depthTarget, depthRTs[i], copyDepthMat, 0); // cmd.SetRenderTarget(new RenderTargetIdentifier[] {colorRTs[i], depthRTs[i]}, depthRTs[i]); 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(renderingData.colorTarget, renderingData.depthTarget); for (var i = asset.depthPeelingPass - 1; i >= 0; i--) { cmd.SetGlobalTexture("_DepthTex", depthRTs[i]); cmd.Blit(colorRTs[i], renderingData.colorTarget, transparentMat, i == 0 ? 5 : 4); cmd.ReleaseTemporaryRT(colorRTs[i]); cmd.ReleaseTemporaryRT(depthRTs[i]); } cmd.SetRenderTarget(renderingData.colorTarget, renderingData.depthTarget); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
void RenderCascadedShadows(ScriptableRenderContext context) { float tileSize = shadowMapSize / 2; cascadedShadowMap = SetShadowRenderTarget(); shadowBuffer.BeginSample("Render Shadows"); //shadowBuffer.SetGlobalVector( // globalShadowDataId, new Vector4(0f, shadowDistance * shadowDistance) //); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); Light shadowLight = cull.visibleLights[0].light; shadowBuffer.SetGlobalFloat( shadowBiasId, shadowLight.shadowBias ); var shadowSettings = new DrawShadowsSettings(cull, 0); var tileMatrix = Matrix4x4.identity; tileMatrix.m00 = tileMatrix.m11 = 0.5f; for (int i = 0; i < shadowCascades; i++) { Matrix4x4 viewMatrix, projectionMatrix; ShadowSplitData splitData; cull.ComputeDirectionalShadowMatricesAndCullingPrimitives( 0, i, shadowCascades, shadowCascadeSplit, (int)tileSize, shadowLight.shadowNearPlane, out viewMatrix, out projectionMatrix, out splitData ); Vector2 tileOffset = ConfigureShadowTile(i, 2, tileSize); shadowBuffer.SetViewProjectionMatrices(viewMatrix, projectionMatrix); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); cascadeCullingSpheres[i] = shadowSettings.splitData.cullingSphere = splitData.cullingSphere; cascadeCullingSpheres[i].w *= splitData.cullingSphere.w; context.DrawShadows(ref shadowSettings); CalculateWorldToShadowMatrix( ref viewMatrix, ref projectionMatrix, out worldToShadowCascadeMatrices[i] ); tileMatrix.m03 = tileOffset.x * 0.5f; tileMatrix.m13 = tileOffset.y * 0.5f; worldToShadowCascadeMatrices[i] = tileMatrix * worldToShadowCascadeMatrices[i]; } shadowBuffer.DisableScissorRect(); shadowBuffer.SetGlobalTexture(cascadedShadowMapId, cascadedShadowMap); shadowBuffer.SetGlobalVectorArray( cascadeCullingSpheresId, cascadeCullingSpheres ); shadowBuffer.SetGlobalMatrixArray( worldToShadowCascadeMatricesId, worldToShadowCascadeMatrices ); float invShadowMapSize = 1f / shadowMapSize; shadowBuffer.SetGlobalVector( cascadedShadowMapSizeId, new Vector4( invShadowMapSize, invShadowMapSize, shadowMapSize, shadowMapSize ) ); shadowBuffer.SetGlobalFloat( cascadedShadoStrengthId, shadowLight.shadowStrength ); bool hard = shadowLight.shadows == LightShadows.Hard; CoreUtils.SetKeyword(shadowBuffer, cascadedShadowsHardKeyword, hard); CoreUtils.SetKeyword(shadowBuffer, cascadedShadowsSoftKeyword, !hard); //CoreUtils.SetKeyword(shadowBuffer, clippingKeyword, true); shadowBuffer.EndSample("Render Shadows"); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); }
void Render(ScriptableRenderContext context, Camera camera) { ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, out cullingParameters)) { return; } cullingParameters.shadowDistance = Mathf.Min(shadowDistance, camera.farClipPlane); #if UNITY_EDITOR //ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif 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); //cameraBuffer.DisableShaderKeyword(clippingKeyword); } } else { cameraBuffer.SetGlobalVector(lightIndicesOffsetAndCountID, Vector4.zero); cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword); cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword); cameraBuffer.DisableShaderKeyword(shadowsHardKeyword); cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword); //cameraBuffer.DisableShaderKeyword(clippingKeyword); } context.SetupCameraProperties(camera); var myPipelineCamera = camera.GetComponent <MyPipelineCamera>(); MyPostProcessingStack activeStack = myPipelineCamera ? myPipelineCamera.PostProcessingStack : defaultStack; bool scaledRendering = (renderScale <1f || 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; bool needsDirectDepth = needsDepth && renderSamples == 1; bool needsDepthOnlyPass = needsDepth && renderSamples > 1; RenderTextureFormat format = allowHDR && camera.allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; if (renderToTexture) { 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.SetGlobalVectorArray( visibleLightColorsId, visibleLightColors ); cameraBuffer.SetGlobalVectorArray( visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions ); cameraBuffer.SetGlobalVectorArray( visibleLightAttenuationsId, visibleLightAttenuations ); cameraBuffer.SetGlobalVectorArray( visibleLightSpotDirectionsId, visibleLightSpotDirections ); cameraBuffer.SetGlobalVectorArray( visibleLightOcclusionMasksId, visibleLightOcclusionMasks ); globalShadowData.z = 1f - cullingParameters.shadowDistance * globalShadowData.y; cameraBuffer.SetGlobalVector(globalShadowDataId, globalShadowData); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("SRPDefaultUnlit")) { flags = drawFlags //, //rendererConfiguration = RendererConfiguration.PerObjectLightIndices8 }; 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; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers( cull.visibleRenderers, ref drawSettings, filterSettings ); context.DrawSkybox(camera); if (activeStack) { if (needsDepthOnlyPass) { var depthOnlyDrawSettings = new DrawRendererSettings( camera, new ShaderPassName("DepthOnly") ) { flags = drawFlags }; depthOnlyDrawSettings.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(); //cameraBuffer.SetRenderTarget( // cameraColorTextureId, // RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, // cameraDepthTextureId, // RenderBufferLoadAction.Load, RenderBufferStoreAction.Store //); 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 Camera33"); //CoreUtils.SetKeyword(cameraBuffer, clippingKeyword, true); context.ExecuteCommandBuffer(cameraBuffer); cameraBuffer.Clear(); context.Submit(); if (shadowMap) { RenderTexture.ReleaseTemporary(shadowMap); shadowMap = null; } if (cascadedShadowMap) { RenderTexture.ReleaseTemporary(cascadedShadowMap); cascadedShadowMap = null; } }
void RenderShadows(ScriptableRenderContext context) { int split; if (shadowTileCount <= 1) { split = 1; } else if (shadowTileCount <= 4) { split = 2; } else if (shadowTileCount <= 9) { split = 3; } else { split = 4; } float tileSize = shadowMapSize / split; float tileScale = 1f / split; globalShadowData.x = tileScale; //Rect tileViewport = new Rect(0f, 0f, tileSize, tileSize); //shadowMap = RenderTexture.GetTemporary( // shadowMapSize, shadowMapSize, 16, RenderTextureFormat.Shadowmap //); //shadowMap.filterMode = FilterMode.Bilinear; //shadowMap.wrapMode = TextureWrapMode.Clamp; //CoreUtils.SetRenderTarget(shadowBuffer, shadowMap, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, ClearFlag.Depth); shadowMap = SetShadowRenderTarget(); shadowBuffer.BeginSample("Render Shadows"); //shadowBuffer.SetGlobalVector( // globalShadowDataId, new Vector4(tileScale, shadowDistance * shadowDistance) //); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); int tileIndex = 0; bool hardShadows = false; bool softShadows = false; for (int i = mainLightExists ? 1 : 0; i < cull.visibleLights.Count; i++) { if (i == maxVisibleLights) { break; } if (shadowData[i].x <= 0f) { continue; } Matrix4x4 viewMatrix, projectionMatrix; ShadowSplitData splitData; //计算出世界坐标系到视图坐标系转换矩阵和投影矩阵 //if (!cull.ComputeSpotShadowMatricesAndCullingPrimitives( // i, out viewMatrix, out projectionMatrix, out splitData //)) //{ // shadowData[i].x = 0f; // continue; //} bool validShadows; if (shadowData[i].z > 0f) { validShadows = cull.ComputeDirectionalShadowMatricesAndCullingPrimitives( i, 0, 1, Vector3.right, (int)tileSize, cull.visibleLights[i].light.shadowNearPlane, out viewMatrix, out projectionMatrix, out splitData ); } else { validShadows = cull.ComputeSpotShadowMatricesAndCullingPrimitives( i, out viewMatrix, out projectionMatrix, out splitData ); } if (!validShadows) { shadowData[i].x = 0f; continue; } //float tileOffsetX = tileIndex % split; //float tileOffsetY = tileIndex / split; //tileViewport.x = tileOffsetX * tileSize; //tileViewport.y = tileOffsetY * tileSize; Vector2 tileOffset = ConfigureShadowTile(tileIndex, split, tileSize); shadowData[i].z = tileOffset.x * tileScale; shadowData[i].w = tileOffset.y * tileScale; //shadowBuffer.SetViewport(tileViewport); //shadowBuffer.EnableScissorRect(new Rect( // tileViewport.x + 4f, tileViewport.y + 4f, // tileSize - 8f, tileSize - 8f //)); shadowBuffer.SetViewProjectionMatrices(viewMatrix, projectionMatrix); shadowBuffer.SetGlobalFloat( shadowBiasId, cull.visibleLights[0].light.shadowBias ); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); var shadowSettings = new DrawShadowsSettings(cull, 0); shadowSettings.splitData.cullingSphere = splitData.cullingSphere; context.DrawShadows(ref shadowSettings); CalculateWorldToShadowMatrix( ref viewMatrix, ref projectionMatrix, out worldToShadowMatrices[i] ); //if (SystemInfo.usesReversedZBuffer) //{ // projectionMatrix.m20 = -projectionMatrix.m20; // projectionMatrix.m21 = -projectionMatrix.m21; // projectionMatrix.m22 = -projectionMatrix.m22; // projectionMatrix.m23 = -projectionMatrix.m23; //} //var scaleOffset = Matrix4x4.TRS( // Vector3.one * 0.5f, Quaternion.identity, Vector3.one * 0.5f // ); ////Matrix4x4 worldToShadowMatrix = //// scaleOffset * (projectionMatrix * viewMatrix); ////shadowBuffer.SetGlobalMatrix(worldToShadowMatrixId, worldToShadowMatrix); //worldToShadowMatrices[i] = scaleOffset * (projectionMatrix * viewMatrix); //if (split > 1) //{ // var tileMatrix = Matrix4x4.identity; // tileMatrix.m00 = tileMatrix.m11 = tileScale; // tileMatrix.m03 = tileOffsetX * tileScale; // tileMatrix.m13 = tileOffsetY * tileScale; // worldToShadowMatrices[i] = tileMatrix * worldToShadowMatrices[i]; //} tileIndex += 1; if (shadowData[i].y <= 0f) { hardShadows = true; } else { softShadows = true; } } shadowBuffer.DisableScissorRect(); shadowBuffer.SetGlobalTexture(shadowMapId, shadowMap); shadowBuffer.SetGlobalMatrixArray( worldToShadowMatricesId, worldToShadowMatrices ); //shadowBuffer.SetGlobalFloat( // shadowStrengthId, cull.visibleLights[0].light.shadowStrength //); shadowBuffer.SetGlobalVectorArray(shadowDataId, shadowData); float invShadowMapSize = 1f / shadowMapSize; shadowBuffer.SetGlobalVector( shadowMapSizeId, new Vector4( invShadowMapSize, invShadowMapSize, shadowMapSize, shadowMapSize ) ); CoreUtils.SetKeyword(shadowBuffer, shadowsHardKeyword, hardShadows); CoreUtils.SetKeyword(shadowBuffer, shadowsSoftKeyword, softShadows); //CoreUtils.SetKeyword(shadowBuffer, clippingKeyword, true); shadowBuffer.EndSample("Render Shadows"); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); }
private void ExecuteCurrentBuffer() { _context.ExecuteCommandBuffer(_currentBuffer); _currentBuffer.Clear(); }
/// <inheritdoc/> public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { // NOTE: Do NOT mix ProfilingScope with named CommandBuffers i.e. CommandBufferPool.Get("name"). // Currently there's an issue which results in mismatched markers. CommandBuffer cmd = CommandBufferPool.Get(); using (new ProfilingScope(cmd, m_ProfilingSampler)) { // Global render pass data containing various settings. // x,y,z are currently unused // w is used for knowing whether the object is opaque(1) or alpha blended(0) Vector4 drawObjectPassData = new Vector4(0.0f, 0.0f, 0.0f, (m_IsOpaque) ? 1.0f : 0.0f); cmd.SetGlobalVector(s_DrawObjectPassDataPropID, drawObjectPassData); // scaleBias.x = flipSign // scaleBias.y = scale // scaleBias.z = bias // scaleBias.w = unused float flipSign = (renderingData.cameraData.IsCameraProjectionMatrixFlipped()) ? -1.0f : 1.0f; Vector4 scaleBias = (flipSign < 0.0f) ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f) : new Vector4(flipSign, 0.0f, 1.0f, 1.0f); cmd.SetGlobalVector(ShaderPropertyId.scaleBiasRt, scaleBias); context.ExecuteCommandBuffer(cmd); cmd.Clear(); Camera camera = renderingData.cameraData.camera; var sortFlags = (m_IsOpaque) ? renderingData.cameraData.defaultOpaqueSortFlags : SortingCriteria.CommonTransparent; var filterSettings = m_FilteringSettings; #if UNITY_EDITOR // When rendering the preview camera, we want the layer mask to be forced to Everything if (renderingData.cameraData.isPreviewCamera) { filterSettings.layerMask = -1; } #endif DrawingSettings drawSettings = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortFlags); if ((DebugHandler != null) && DebugHandler.IsActiveForCamera(ref renderingData.cameraData)) { foreach (DebugRenderSetup debugRenderSetup in DebugHandler.CreateDebugRenderSetupEnumerable(context, cmd)) { DrawingSettings debugDrawingSettings = debugRenderSetup.CreateDrawingSettings(ref renderingData, drawSettings); if (debugRenderSetup.GetRenderStateBlock(out RenderStateBlock renderStateBlock)) { context.DrawRenderers(renderingData.cullResults, ref debugDrawingSettings, ref filterSettings, ref renderStateBlock); } else { context.DrawRenderers(renderingData.cullResults, ref debugDrawingSettings, ref filterSettings, ref m_RenderStateBlock); } } } else { context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings, ref m_RenderStateBlock); // Render objects that did not match any shader pass with error shader RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None); } } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras) { bool *propertyCheckedFlags = stackalloc bool[resources.allEvents.Length]; UnsafeUtility.MemClear(propertyCheckedFlags, resources.allEvents.Length); GraphicsSettings.useScriptableRenderPipelineBatching = resources.useSRPBatcher; SceneController.SetState(); #if UNITY_EDITOR int tempID = Shader.PropertyToID("_TempRT"); foreach (var pair in bakeList) { PipelineCamera pipelineCam = pair.pipelineCamera; for (int i = 0; i < pair.worldToCamera.Length; ++i) { pipelineCam.cam.worldToCameraMatrix = pair.worldToCamera[i]; pipelineCam.cam.projectionMatrix = pair.projection[i]; pipelineCam.cameraTarget = tempID; data.buffer.GetTemporaryRT(tempID, pair.texArray.width, pair.texArray.height, pair.texArray.depth, FilterMode.Point, pair.texArray.format, RenderTextureReadWrite.Linear); Render(pipelineCam, ref renderContext, pipelineCam.cam, propertyCheckedFlags); data.buffer.CopyTexture(tempID, 0, 0, pair.texArray, i, 0); data.buffer.ReleaseTemporaryRT(tempID); data.ExecuteCommandBuffer(); renderContext.Submit(); } pair.worldToCamera.Dispose(); pair.projection.Dispose(); renderContext.ExecuteCommandBuffer(pair.buffer); pair.buffer.Clear(); renderContext.Submit(); } bakeList.Clear(); #endif if (PipelineCamera.allCamera.isCreated) { foreach (var cam in cameras) { PipelineCamera pipelineCam; UIntPtr pipelineCamPtr; if (!PipelineCamera.allCamera.Get(cam.gameObject.GetInstanceID(), out pipelineCamPtr)) { #if UNITY_EDITOR renderingEditor = true; var pos = cam.transform.eulerAngles; pos.z = 0; cam.transform.eulerAngles = pos; if (!PipelineCamera.allCamera.Get(Camera.main.gameObject.GetInstanceID(), out pipelineCamPtr)) { continue; } #else continue; #endif } else { renderingEditor = false; } pipelineCam = MUnsafeUtility.GetObject <PipelineCamera>(pipelineCamPtr.ToPointer()); Render(pipelineCam, ref renderContext, cam, propertyCheckedFlags); data.ExecuteCommandBuffer(); renderContext.Submit(); } if (bufferAfterFrame.Count > 0) { foreach (var i in bufferAfterFrame) { i(data.buffer); } data.ExecuteCommandBuffer(); bufferAfterFrame.Clear(); renderContext.Submit(); } } else { if (bufferAfterFrame.Count > 0) { foreach (var i in bufferAfterFrame) { i(data.buffer); } Graphics.ExecuteCommandBuffer(data.buffer); bufferAfterFrame.Clear(); } } }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(context, cameras); foreach (Camera camera in cameras) { #if UNITY_EDITOR bool isSceneViewCam = camera.cameraType == CameraType.SceneView; if (isSceneViewCam) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); //This makes the UI Canvas geometry appear on scene view } #endif BeginCameraRendering(context, camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); DrawingSettings drawSettingsDefault = new DrawingSettings(m_PassNameDefault, sortingSettings); //This will let you draw shader passes without the LightMode, //thus it draws the default UGUI materials drawSettingsDefault.SetShaderPassName(1, m_PassNameDefault); 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); //Opaque default context.DrawRenderers(cull, ref drawSettingsDefault, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Transparent default context.DrawRenderers(cull, ref drawSettingsDefault, ref filterSettings); //SceneView fix, so that it draws the gizmos on scene view #if UNITY_EDITOR if (isSceneViewCam) { // context.DrawGizmos(camera, GizmoSubset.PostImageEffects); } #endif context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
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; //Set Depth texture temp RT CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; 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 }; //Clear Depth Texture CommandBuffer cmdDepth = new CommandBuffer(); cmdDepth.name = "(" + camera.name + ")" + "Depth Clear Flag"; cmdDepth.SetRenderTarget(m_DepthRT); //Set CameraTarget to the depth texture cmdDepth.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmdDepth); cmdDepth.Release(); //Draw Depth with Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettingsDepth.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettings); //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(BuiltinRenderTextureType.CameraTarget); //Rember to reset 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); //Clean Up CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_DepthRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); } }
/// <inheritdoc/> public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { if (m_CopyDepthMaterial == null) { Debug.LogErrorFormat("Missing {0}. {1} render pass will not execute. Check for missing reference in the renderer resources.", m_CopyDepthMaterial, GetType().Name); return; } CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag); RenderTargetIdentifier depthSurface = source.Identifier(); RenderTargetIdentifier copyDepthSurface = destination.Identifier(); RenderTextureDescriptor descriptor = renderingData.cameraData.cameraTargetDescriptor; int cameraSamples = descriptor.msaaSamples; CameraData cameraData = renderingData.cameraData; switch (cameraSamples) { case 8: cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4); cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa8); break; case 4: cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2); cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa4); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8); break; case 2: cmd.EnableShaderKeyword(ShaderKeywordStrings.DepthMsaa2); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8); break; // MSAA disabled default: cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa2); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa4); cmd.DisableShaderKeyword(ShaderKeywordStrings.DepthMsaa8); break; } cmd.SetGlobalTexture("_CameraDepthAttachment", source.Identifier()); // Blit has logic to flip projection matrix when rendering to render texture. // Currently the y-flip is handled in CopyDepthPass.hlsl by checking _ProjectionParams.x // If you replace this Blit with a Draw* that sets projection matrix double check // to also update shader. // scaleBias.x = flipSign // scaleBias.y = scale // scaleBias.z = bias // scaleBias.w = unused float flipSign = (cameraData.IsCameraProjectionMatrixFlipped()) ? -1.0f : 1.0f; Vector4 scaleBias = (flipSign < 0.0f) ? new Vector4(flipSign, 1.0f, -1.0f, 1.0f) : new Vector4(flipSign, 0.0f, 1.0f, 1.0f); cmd.SetGlobalVector(m_ScaleBiasId, scaleBias); cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, m_CopyDepthMaterial); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
// Setup lighting variables for shader to use private static void SetupLightShaderVariables(List <VisibleLight> lights, ScriptableRenderContext context) { // We only support up to 8 visible lights here. More complex approaches would // be doing some sort of per-object light setups, but here we go for simplest possible // approach. const int kMaxLights = 8; // Just take first 8 lights. Possible improvements: sort lights by intensity or distance // to the viewer, so that "most important" lights in the scene are picked, and not the 8 // that happened to be first. int lightCount = Mathf.Min(lights.Count, kMaxLights); // Prepare light data Vector4[] lightColors = new Vector4[kMaxLights]; Vector4[] lightPositions = new Vector4[kMaxLights]; Vector4[] lightSpotDirections = new Vector4[kMaxLights]; Vector4[] lightAtten = new Vector4[kMaxLights]; for (var i = 0; i < lightCount; ++i) { VisibleLight light = lights[i]; lightColors[i] = light.finalColor; if (light.lightType == LightType.Directional) { // light position for directional lights is: (-direction, 0) var dir = light.localToWorld.GetColumn(2); lightPositions[i] = new Vector4(-dir.x, -dir.y, -dir.z, 0); } else { // light position for point/spot lights is: (position, 1) var pos = light.localToWorld.GetColumn(3); lightPositions[i] = new Vector4(pos.x, pos.y, pos.z, 1); } // attenuation set in a way where distance attenuation can be computed: // float lengthSq = dot(toLight, toLight); // float atten = 1.0 / (1.0 + lengthSq * LightAtten[i].z); // and spot cone attenuation: // float rho = max (0, dot(normalize(toLight), SpotDirection[i].xyz)); // float spotAtt = (rho - LightAtten[i].x) * LightAtten[i].y; // spotAtt = saturate(spotAtt); // and the above works for all light types, i.e. spot light code works out // to correct math for point & directional lights as well. float rangeSq = light.range * light.range; float quadAtten = (light.lightType == LightType.Directional) ? 0.0f : 25.0f / rangeSq; // spot direction & attenuation if (light.lightType == LightType.Spot) { var dir = light.localToWorld.GetColumn(2); lightSpotDirections[i] = new Vector4(-dir.x, -dir.y, -dir.z, 0); float radAngle = Mathf.Deg2Rad * light.spotAngle; float cosTheta = Mathf.Cos(radAngle * 0.25f); float cosPhi = Mathf.Cos(radAngle * 0.5f); float cosDiff = cosTheta - cosPhi; lightAtten[i] = new Vector4(cosPhi, (cosDiff != 0.0f) ? 1.0f / cosDiff : 1.0f, quadAtten, rangeSq); } else { // non-spot light lightSpotDirections[i] = new Vector4(0, 0, 1, 0); lightAtten[i] = new Vector4(-1, 1, quadAtten, rangeSq); } } // ambient lighting spherical harmonics values const int kSHCoefficients = 7; Vector4[] shConstants = new Vector4[kSHCoefficients]; SphericalHarmonicsL2 ambientSH = RenderSettings.ambientProbe * RenderSettings.ambientIntensity; GetShaderConstantsFromNormalizedSH(ref ambientSH, shConstants); // setup global shader variables to contain all the data computed above CommandBuffer cmd = CommandBufferPool.Get(); cmd.SetGlobalVectorArray("globalLightColor", lightColors); cmd.SetGlobalVectorArray("globalLightPos", lightPositions); cmd.SetGlobalVectorArray("globalLightSpotDir", lightSpotDirections); cmd.SetGlobalVectorArray("globalLightAtten", lightAtten); cmd.SetGlobalVector("globalLightCount", new Vector4(lightCount, 0, 0, 0)); cmd.SetGlobalVectorArray("globalSH", shConstants); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
public static void RenderSingleCamera(LightweightRenderPipeline pipelineInstance, ScriptableRenderContext context, Camera camera, ref CullResults cullResults, IRendererSetup setup = null) { if (pipelineInstance == null) { Debug.LogError("Trying to render a camera with an invalid render pipeline instance."); return; } ScriptableCullingParameters cullingParameters; if (!CullResults.GetCullingParameters(camera, IsStereoEnabled(camera), out cullingParameters)) { return; } CommandBuffer cmd = CommandBufferPool.Get(k_RenderCameraTag); using (new ProfilingSample(cmd, k_RenderCameraTag)) { CameraData cameraData; PipelineSettings settings = pipelineInstance.settings; ScriptableRenderer renderer = pipelineInstance.renderer; InitializeCameraData(settings, camera, out cameraData); SetupPerCameraShaderConstants(cameraData); cullingParameters.shadowDistance = Mathf.Min(cameraData.maxShadowDistance, camera.farClipPlane); context.ExecuteCommandBuffer(cmd); cmd.Clear(); #if UNITY_EDITOR // Emit scene view UI if (cameraData.isSceneViewCamera) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif CullResults.Cull(ref cullingParameters, context, ref cullResults); RenderingData renderingData; InitializeRenderingData(settings, ref cameraData, ref cullResults, renderer.maxVisibleAdditionalLights, renderer.maxPerObjectAdditionalLights, out renderingData); var setupToUse = setup; if (setupToUse == null) { setupToUse = defaultRendererSetup; } renderer.Clear(); setupToUse.Setup(renderer, ref renderingData); renderer.Execute(context, ref renderingData); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); context.Submit(); #if UNITY_EDITOR Handles.DrawGizmos(camera); #endif }
void ExecuteBuffer() { _context.ExecuteCommandBuffer(_buffer); _buffer.Clear(); }
protected virtual void RenderCamera(ScriptableRenderContext context, Camera camera) { var p = Matrix4x4.Perspective(30, 16.0f / 9, .3f, 1000); var v = new Vector4(.5f, .5f, 10, 1); camera.TryGetCullingParameters(out var cullingParameters); var cmd = CommandBufferPool.Get(camera.name); cmd.Clear(); if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } var cullResults = context.Cull(ref cullingParameters); var projectionMat = camera.projectionMatrix; var jitteredProjectionMat = projectionMat; jitteredProjectionMat.m02 += (projectionJitter.Current.x * 2 - 1) / camera.pixelWidth; jitteredProjectionMat.m12 += (projectionJitter.Current.x * 2 - 1) / camera.pixelHeight; var renderingData = new RenderingData() { camera = camera, cullResults = cullResults, ColorTarget = BuiltinRenderTextureType.CameraTarget, DepthTarget = BuiltinRenderTextureType.CameraTarget, ColorBufferFormat = RenderTextureFormat.Default, shadowMapData = new Dictionary <Light, ShadowMapData>(), FrameID = frameID, DiscardFrameBuffer = true, ViewMatrix = camera.worldToCameraMatrix, ProjectionMatrix = projectionMat, JitteredProjectionMatrix = jitteredProjectionMat, ProjectionJitter = new Vector2(.5f, .5f), NextProjectionJitter = new Vector2(.5f, .5f), }; this.Setup(context, ref renderingData); context.SetupCameraProperties(camera, false); InitRenderQueue(camera); SetupLight(ref renderingData); /*RenderTargetBinding binding = new RenderTargetBinding(); * binding.colorRenderTargets = new RenderTargetIdentifier[] { ColorTarget }; * binding.colorLoadActions = new RenderBufferLoadAction[] { RenderBufferLoadAction.Clear }; * binding.depthRenderTarget = DepthTarget; * binding.depthLoadAction = RenderBufferLoadAction.Clear; * binding.colorStoreActions = new RenderBufferStoreAction[] { RenderBufferStoreAction.Store }; * binding.depthStoreAction = RenderBufferStoreAction.Store;*/ cmd.SetRenderTarget(ColorTarget, DepthTarget); cmd.ClearRenderTarget(true, true, Color.black, 1); cmd.SetRenderTarget(DepthTarget, DepthTarget); cmd.ClearRenderTarget(true, true, Color.black, 1); cmd.SetRenderTarget(ColorTarget, DepthTarget); context.ExecuteCommandBuffer(cmd); cmd.Clear(); context.DrawSkybox(camera); foreach (var pass in RenderPassQueue) { pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } // Draw global user passes foreach (var pass in globalUserPasses) { pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } // Draw user passes var userPasses = camera.GetComponents <UserPass>(); foreach (var pass in userPasses) { if (pass.Global) { continue; } pass.Setup(context, ref renderingData); pass.Render(context, ref renderingData); } cmd.Blit(renderingData.ColorTarget, BuiltinRenderTextureType.CameraTarget); //cmd.CopyTexture(renderingData.DepthTarget, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmd); cmd.Clear(); if (camera.cameraType == CameraType.SceneView) { context.DrawGizmos(camera, GizmoSubset.PreImageEffects); context.DrawGizmos(camera, GizmoSubset.PostImageEffects); } foreach (var pass in RenderPassQueue) { pass.Cleanup(context, ref renderingData); } foreach (var pass in globalUserPasses) { pass.Cleanup(context, ref renderingData); } foreach (var pass in userPasses) { pass.Cleanup(context, ref renderingData); } this.Cleanup(context, ref renderingData); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); context.Submit(); projectionJitter.Next = renderingData.NextProjectionJitter; }
override public void Update(FrameId frameId, ScriptableRenderContext renderContext, CullResults cullResults, VisibleLight[] lights) { var profilingSample = new Utilities.ProfilingSample("Shadowmap" + m_TexSlot, renderContext); if (!string.IsNullOrEmpty(m_ShaderKeyword)) { var cb = new CommandBuffer(); cb.name = "Shadowmap.EnableShadowKeyword"; cb.EnableShaderKeyword(m_ShaderKeyword); renderContext.ExecuteCommandBuffer(cb); cb.Dispose(); } // loop for generating each individual shadowmap uint curSlice = uint.MaxValue; Bounds bounds; DrawShadowsSettings dss = new DrawShadowsSettings(cullResults, 0); for (uint i = 0; i < m_ActiveEntriesCount; ++i) { if (!cullResults.GetShadowCasterBounds(m_EntryCache[i].key.visibleIdx, out bounds)) { continue; } var cb = new CommandBuffer(); uint entrySlice = m_EntryCache[i].current.slice; if (entrySlice != curSlice) { Debug.Assert(curSlice == uint.MaxValue || entrySlice >= curSlice, "Entries in the entry cache are not ordered in slice order."); cb.name = "Shadowmap.Update.Slice" + entrySlice; if (curSlice != uint.MaxValue) { PostUpdate(frameId, cb, curSlice); } curSlice = entrySlice; PreUpdate(frameId, cb, curSlice); } cb.name = "Shadowmap.Update - slice: " + curSlice + ", vp.x: " + m_EntryCache[i].current.viewport.x + ", vp.y: " + m_EntryCache[i].current.viewport.y + ", vp.w: " + m_EntryCache[i].current.viewport.width + ", vp.h: " + m_EntryCache[i].current.viewport.height; cb.SetViewport(m_EntryCache[i].current.viewport); cb.SetViewProjectionMatrices(m_EntryCache[i].current.view, m_EntryCache[i].current.proj); cb.SetGlobalVector("g_vLightDirWs", m_EntryCache[i].current.lightDir); renderContext.ExecuteCommandBuffer(cb); cb.Dispose(); dss.lightIndex = m_EntryCache[i].key.visibleIdx; dss.splitData = m_EntryCache[i].current.splitData; renderContext.DrawShadows(ref dss); // <- if this was a call on the commandbuffer we would get away with using just once commandbuffer for the entire shadowmap, instead of one per face } // post update if (!string.IsNullOrEmpty(m_ShaderKeyword)) { var cb = new CommandBuffer(); cb.name = "Shadowmap.DisableShaderKeyword"; cb.DisableShaderKeyword(m_ShaderKeyword); renderContext.ExecuteCommandBuffer(cb); cb.Dispose(); } m_ActiveEntriesCount = 0; profilingSample.Dispose(); }
/// <inheritdoc/> public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { CameraData cameraData = renderingData.cameraData; Camera camera = cameraData.camera; var activeDebugHandler = GetActiveDebugHandler(renderingData); if (activeDebugHandler != null) { // TODO: The skybox needs to work the same as the other shaders, but until it does we'll not render it // when certain debug modes are active (e.g. wireframe/overdraw modes) if (activeDebugHandler.IsScreenClearNeeded) { return; } } #if ENABLE_VR && ENABLE_XR_MODULE // XRTODO: Remove this code once Skybox pass is moved to SRP land. if (cameraData.xr.enabled) { // Setup Legacy XR buffer states if (cameraData.xr.singlePassEnabled) { // Setup legacy skybox stereo buffer camera.SetStereoProjectionMatrix(Camera.StereoscopicEye.Left, cameraData.GetProjectionMatrix(0)); camera.SetStereoViewMatrix(Camera.StereoscopicEye.Left, cameraData.GetViewMatrix(0)); camera.SetStereoProjectionMatrix(Camera.StereoscopicEye.Right, cameraData.GetProjectionMatrix(1)); camera.SetStereoViewMatrix(Camera.StereoscopicEye.Right, cameraData.GetViewMatrix(1)); CommandBuffer cmd = CommandBufferPool.Get(); // Use legacy stereo instancing mode to have legacy XR code path configured cmd.SetSinglePassStereo(SystemInfo.supportsMultiview ? SinglePassStereoMode.Multiview : SinglePassStereoMode.Instancing); context.ExecuteCommandBuffer(cmd); cmd.Clear(); // Calling into built-in skybox pass context.DrawSkybox(camera); // Disable Legacy XR path cmd.SetSinglePassStereo(SinglePassStereoMode.None); context.ExecuteCommandBuffer(cmd); // We do not need to submit here due to special handling of stereo matrices in core. // context.Submit(); CommandBufferPool.Release(cmd); camera.ResetStereoProjectionMatrices(); camera.ResetStereoViewMatrices(); } else { camera.projectionMatrix = cameraData.GetProjectionMatrix(0); camera.worldToCameraMatrix = cameraData.GetViewMatrix(0); context.DrawSkybox(camera); // XRTODO: remove this call because it creates issues with nested profiling scopes // See examples in UniversalRenderPipeline.RenderSingleCamera() and in ScriptableRenderer.Execute() context.Submit(); // Submit and execute the skybox pass before resetting the matrices camera.ResetProjectionMatrix(); camera.ResetWorldToCameraMatrix(); } } else #endif { context.DrawSkybox(camera); } }
void DrawCameraRecursive(ScriptableRenderContext context, Camera camera, Camera portalCamera, int depth) { BeginCameraRendering(context, camera); CullingResults cullingResults = Cull(context, camera); InitializeLightData(ref cullingResults, out LightData lightData); m_lights.Setup(context, ref lightData); bool enableDynamicBatching = false; bool enableInstancing = false; PerObjectData perObjectData = PerObjectData.LightData | PerObjectData.LightIndices; FilteringSettings opaqueFilteringSettings = new FilteringSettings(RenderQueueRange.opaque); FilteringSettings transparentFilteringSettings = new FilteringSettings(RenderQueueRange.transparent); SortingSettings opaqueSortingSettings = new SortingSettings(camera); opaqueSortingSettings.criteria = SortingCriteria.CommonOpaque; SortingSettings transparentSortingSettings = new SortingSettings(camera); transparentSortingSettings.criteria = SortingCriteria.CommonTransparent; // ShaderTagId must match the "LightMode" tag inside the shader pass. // If not "LightMode" tag is found the object won't render. DrawingSettings opaqueDrawingSettings = new DrawingSettings(ShaderPassTag.forwardLit, opaqueSortingSettings); opaqueDrawingSettings.enableDynamicBatching = enableDynamicBatching; opaqueDrawingSettings.enableInstancing = enableInstancing; opaqueDrawingSettings.perObjectData = perObjectData; DrawingSettings transparentDrawingSettings = new DrawingSettings(ShaderPassTag.forwardLit, transparentSortingSettings); transparentDrawingSettings.enableDynamicBatching = enableDynamicBatching; transparentDrawingSettings.enableInstancing = enableInstancing; transparentDrawingSettings.perObjectData = perObjectData; ProfilingSampler cameraSampler = new ProfilingSampler(camera.name); CommandBuffer cameraCmd = CommandBufferPool.Get(cameraSampler.name); using (new ProfilingScope(cameraCmd, cameraSampler)) { context.ExecuteCommandBuffer(cameraCmd); cameraCmd.Clear(); context.SetupCameraProperties(camera); DrawRenderersProfiled(context, cullingResults, "Opaque", ref opaqueDrawingSettings, ref opaqueFilteringSettings); if (portalCamera != null) { // TODO set portal camera position DrawCameraRecursive(context, portalCamera, null, depth + 1); // TODO reset portal camera position (optional) } context.SetupCameraProperties(camera); DrawRenderersProfiled(context, cullingResults, "Transparent", ref transparentDrawingSettings, ref transparentFilteringSettings); } context.ExecuteCommandBuffer(cameraCmd); CommandBufferPool.Release(cameraCmd); EndCameraRendering(context, camera); }
// Here you can implement the rendering logic. // Use <c>ScriptableRenderContext</c> to issue drawing commands or execute command buffers // https://docs.unity3d.com/ScriptReference/Rendering.ScriptableRenderContext.html // You don't have to call ScriptableRenderContext.submit, the render pipeline will call it at specific points in the pipeline. public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag); RenderTextureDescriptor blitTargetDescriptor = renderingData.cameraData.cameraTargetDescriptor; blitTargetDescriptor.depthBufferBits = 0; isSourceAndDestinationSameTarget = settings.sourceType == settings.destinationType && (settings.sourceType == BufferType.CameraColor || settings.sourceTextureId == settings.destinationTextureId); if (settings.sourceType == BufferType.CameraColor) { sourceId = -1; } else { sourceId = Shader.PropertyToID(settings.sourceTextureId); cmd.GetTemporaryRT(sourceId, blitTargetDescriptor, filterMode); source = new RenderTargetIdentifier(sourceId); } //if (isSourceAndDestinationSameTarget) { // destinationId = temporaryRTId; // cmd.GetTemporaryRT(destinationId, blitTargetDescriptor, filterMode); // destination = new RenderTargetIdentifier(destinationId); //} else if (settings.destinationType == BufferType.CameraColor) { destinationId = -1; destination = RenderTargetHandle.CameraTarget.Identifier(); } else { destinationId = Shader.PropertyToID(settings.destinationTextureId); cmd.GetTemporaryRT(destinationId, blitTargetDescriptor, filterMode); destination = new RenderTargetIdentifier(destinationId); } if (!settings.postProcessing) { Blit(cmd, source, destination); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); return; } int width = blitTargetDescriptor.width; int height = blitTargetDescriptor.height; for (int i = 0; i < gOutput.Length; i++) { gOutput[i] = createIfInvalid(gOutput[i], width, height, true, false); } // Set cbuffer values cmd.SetGlobalInt("screenWidth", width); cmd.SetGlobalInt("screenHeight", height); const int DispatchGroupWidth = 64; // pass 0 { cmd.SetComputeTextureParam(settings.postProcessShaderH, watercolorHKernelIndex, noiseTexSlot, noiseTex); cmd.SetComputeTextureParam(settings.postProcessShaderH, watercolorHKernelIndex, mainCameraOutputTexSlot, source); cmd.SetComputeTextureParam(settings.postProcessShaderH, watercolorHKernelIndex, inputTexSlot, depthTex); cmd.SetComputeTextureParam(settings.postProcessShaderH, watercolorHKernelIndex, outputUavSlot, gOutput[0]); cmd.DispatchCompute(settings.postProcessShaderH, watercolorHKernelIndex, MathUtil.DivideByMultiple(width, DispatchGroupWidth), height, 1); } // pass 1 { cmd.SetComputeTextureParam(settings.postProcessShaderV, watercolorVKernelIndex, noiseTexSlot, noiseTex); cmd.SetComputeTextureParam(settings.postProcessShaderV, watercolorVKernelIndex, mainCameraOutputTexSlot, source); cmd.SetComputeTextureParam(settings.postProcessShaderV, watercolorVKernelIndex, inputTexSlot, gOutput[0]); cmd.SetComputeTextureParam(settings.postProcessShaderV, watercolorVKernelIndex, outputUavSlot, gOutput[1]); cmd.DispatchCompute(settings.postProcessShaderV, watercolorVKernelIndex, width, MathUtil.DivideByMultiple(height, DispatchGroupWidth), 1); } cmd.SetGlobalTexture("_SourceTex", gOutput[1]); cmd.SetRenderTarget(source, depthTex); // This does not work! // For some reason the DSV is not bound here //cmd.Blit(gOutput[1], source, settings.maskedCopyMatl); // Instead, we have to do this... // Credits to https://forum.unity.com/threads/841150/ for figuring this out cmd.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity); cmd.DrawMesh(RenderingUtils.fullscreenMesh, Matrix4x4.identity, settings.maskedCopyMatl); Camera camera = renderingData.cameraData.camera; cmd.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); }
void ExecuteBuffer() { ctx.ExecuteCommandBuffer(buffer); buffer.Clear(); }
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { if (m_CameraSettings.camera == null) { // NOTE: This API is being used for simplicity's sake. Please modify this to hook into a static // Camera manager in your project. //GameObject cameraGO = GameObject.FindWithTag(m_CameraSettings.cameraTag); GameObject cameraGO = GameObject.Find(m_CameraSettings.cameraName); if (cameraGO != null) { Camera camera = cameraGO.GetComponent <Camera>(); m_CameraSettings.camera = camera; } } if (m_RenderersToRender.renderersToRender == null) { m_RenderersToRender.renderersToRender = new List <Renderer>(); } m_RenderersToRender.renderersToRender.Clear(); for (int i = 0; i < m_RenderersToRender.rendererNames.Count; i++) { GameObject rendererGO = GameObject.Find(m_RenderersToRender.rendererNames[i]); if (rendererGO != null) { Renderer rendererToAdd = rendererGO.GetComponent <Renderer>(); if (rendererToAdd != null) { m_RenderersToRender.renderersToRender.Add(rendererToAdd); } } } Camera originalCamera = renderingData.cameraData.camera; Camera rtCamera = m_CameraSettings.camera; if (rtCamera != null && rtCamera.targetTexture != null) { float originalCameraAspect = (float)originalCamera.pixelWidth / (float)originalCamera.pixelHeight; float rtCameraAspect = (float)rtCamera.pixelWidth / (float)rtCamera.pixelHeight; CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag); using (new ProfilingSample(cmd, m_ProfilerTag)) { context.ExecuteCommandBuffer(cmd); cmd.Clear(); Matrix4x4 rtProjectionMatrix; if (!rtCamera.orthographic) { rtProjectionMatrix = Matrix4x4.Perspective(rtCamera.fieldOfView, rtCameraAspect, rtCamera.nearClipPlane, rtCamera.farClipPlane); } else { float vertical = rtCamera.orthographicSize; float horizontal = vertical * rtCamera.aspect; float left = horizontal * -1; float right = horizontal; float top = vertical; float bottom = vertical * -1; rtProjectionMatrix = Matrix4x4.Ortho(left, right, bottom, top, rtCamera.nearClipPlane, rtCamera.farClipPlane); } cmd.SetRenderTarget(rtCamera.targetTexture); cmd.SetViewProjectionMatrices(rtCamera.worldToCameraMatrix, rtProjectionMatrix); cmd.ClearRenderTarget(true, true, Color.clear); context.ExecuteCommandBuffer(cmd); cmd.Clear(); for (int i = 0; i < m_RenderersToRender.renderersToRender.Count; i++) { for (int j = 0; j < m_RenderersToRender.renderersToRender[i].sharedMaterials.Count(); j++) { for (int k = 0; k < m_RenderersToRender.passesToRender.Count; k++) { cmd.DrawRenderer(m_RenderersToRender.renderersToRender[i], m_RenderersToRender.renderersToRender[i].sharedMaterials[j], j, m_RenderersToRender.passesToRender[k]); } } } context.ExecuteCommandBuffer(cmd); // restore Matrix4x4 originalProjectionMatrix = Matrix4x4.Perspective(originalCamera.fieldOfView, originalCameraAspect, originalCamera.nearClipPlane, originalCamera.farClipPlane); cmd.Clear(); cmd.SetRenderTarget(m_ColorTextureHandle.Identifier(), m_DepthAttachmentTextureHandle.Identifier()); cmd.SetViewProjectionMatrices(originalCamera.worldToCameraMatrix, originalCamera.projectionMatrix); } context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); } }
// Main entry point for our scriptable render loop public static void Render(ScriptableRenderContext context, IEnumerable <Camera> cameras, bool useIntermediateBlitPath) { bool stereoEnabled = XRSettings.isDeviceActive; foreach (var camera in cameras) { // Culling ScriptableCullingParameters cullingParams; // Stereo-aware culling parameters are configured to perform a single cull for both eyes if (!CullResults.GetCullingParameters(camera, stereoEnabled, out cullingParams)) { continue; } CullResults cull = new CullResults(); CullResults.Cull(ref cullingParams, context, ref cull); // Setup camera for rendering (sets render target, view/projection matrices and other // per-camera built-in shader variables). // If stereo is enabled, we also configure stereo matrices, viewports, and XR device render targets context.SetupCameraProperties(camera, stereoEnabled); // Draws in-between [Start|Stop]MultiEye are stereo-ized by engine if (stereoEnabled) { context.StartMultiEye(camera); } RenderTargetIdentifier intermediateRTID = new RenderTargetIdentifier(BuiltinRenderTextureType.CurrentActive); bool isIntermediateRTTexArray = false; if (useIntermediateBlitPath) { ConfigureAndBindIntermediateRenderTarget(context, camera, stereoEnabled, out intermediateRTID, out isIntermediateRTTexArray); } // clear depth buffer var cmd = CommandBufferPool.Get(); cmd.ClearRenderTarget(true, false, Color.black); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); // Setup global lighting shader variables SetupLightShaderVariables(cull.visibleLights, context); // Draw opaque objects using BasicPass shader pass var drawSettings = new DrawRendererSettings(camera, new ShaderPassName("BasicPass")) { sorting = { flags = SortFlags.CommonOpaque } }; var filterSettings = new FilterRenderersSettings(true) { renderQueueRange = RenderQueueRange.opaque }; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); // Draw skybox context.DrawSkybox(camera); // Draw transparent objects using BasicPass shader pass drawSettings.sorting.flags = SortFlags.CommonTransparent; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull.visibleRenderers, ref drawSettings, filterSettings); if (useIntermediateBlitPath) { BlitFromIntermediateToCameraTarget(context, intermediateRTID, isIntermediateRTTexArray); } if (stereoEnabled) { context.StopMultiEye(camera); // StereoEndRender will reset state on the camera to pre-Stereo settings, // and invoke XR based events/callbacks. context.StereoEndRender(camera); } context.Submit(); } }
void RenderShadows(ScriptableRenderContext context) { int split; if (shadowTileCount <= 1) { split = 1; } else if (shadowTileCount <= 4) { split = 2; } else if (shadowTileCount <= 9) { split = 3; } else { split = 4; } float tileSize = shadowMapSize / split; float tileScale = 1f / split; shadowMap = SetShadowRenderTarget(); shadowBuffer.BeginSample("Render Shadows"); shadowBuffer.SetGlobalVector( globalShadowDataId, new Vector4( tileScale, shadowDistance * shadowDistance ) ); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); int tileIndex = 0; bool hardShadows = false; bool softShadows = false; for (int i = mainLightExists ? 1 : 0; i < cull.visibleLights.Count; i++) { if (i == maxVisibleLights) { break; } if (shadowData[i].x <= 0f) { continue; } Matrix4x4 viewMatrix, projectionMatrix; ShadowSplitData splitData; bool validShadows; if (shadowData[i].z > 0f) { validShadows = cull.ComputeDirectionalShadowMatricesAndCullingPrimitives( i, 0, 1, Vector3.right, (int)tileSize, cull.visibleLights[i].light.shadowNearPlane, out viewMatrix, out projectionMatrix, out splitData ); } else { validShadows = cull.ComputeSpotShadowMatricesAndCullingPrimitives( i, out viewMatrix, out projectionMatrix, out splitData ); } if (!validShadows) { shadowData[i].x = 0f; continue; } Vector2 tileOffset = ConfigureShadowTile(tileIndex, split, tileSize); shadowData[i].z = tileOffset.x * tileScale; shadowData[i].w = tileOffset.y * tileScale; shadowBuffer.SetViewProjectionMatrices(viewMatrix, projectionMatrix); shadowBuffer.SetGlobalFloat( shadowBiasId, cull.visibleLights[i].light.shadowBias ); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); var shadowSettings = new DrawShadowsSettings(cull, i); shadowSettings.splitData.cullingSphere = splitData.cullingSphere; context.DrawShadows(ref shadowSettings); CalculateWorldToShadowMatrix( ref viewMatrix, ref projectionMatrix, out worldToShadowMatrices[i] ); tileIndex += 1; if (shadowData[i].y <= 0f) { hardShadows = true; } else { softShadows = true; } } shadowBuffer.DisableScissorRect(); shadowBuffer.SetGlobalTexture(shadowMapId, shadowMap); shadowBuffer.SetGlobalMatrixArray( worldToShadowMatricesId, worldToShadowMatrices ); shadowBuffer.SetGlobalVectorArray(shadowDataId, shadowData); float invShadowMapSize = 1f / shadowMapSize; shadowBuffer.SetGlobalVector( shadowMapSizeId, new Vector4( invShadowMapSize, invShadowMapSize, shadowMapSize, shadowMapSize ) ); CoreUtils.SetKeyword(shadowBuffer, shadowsHardKeyword, hardShadows); CoreUtils.SetKeyword(shadowBuffer, shadowsSoftKeyword, softShadows); shadowBuffer.EndSample("Render Shadows"); context.ExecuteCommandBuffer(shadowBuffer); shadowBuffer.Clear(); }