/// <summary> /// Execute the DrawRenderers with parameters setup from the editor /// </summary> /// <param name="renderContext"></param> /// <param name="cmd"></param> /// <param name="camera"></param> /// <param name="cullingResult"></param> protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult) { ShaderTagId[] shaderPasses = new ShaderTagId[hdrpShaderTags.Count + ((overrideMaterial != null) ? 1 : 0)]; System.Array.Copy(hdrpShaderTags.ToArray(), shaderPasses, hdrpShaderTags.Count); if (overrideMaterial != null) { shaderPasses[hdrpShaderTags.Count] = new ShaderTagId(overrideMaterial.GetPassName(overrideMaterialPassIndex)); overrideMaterial.SetFloat(fadeValueId, fadeValue); } if (shaderPasses.Length == 0) { Debug.LogWarning("Attempt to call DrawRenderers with an empty shader passes. Skipping the call to avoid errors"); return; } var result = new RendererListDesc(shaderPasses, cullingResult, hdCamera.camera) { rendererConfiguration = PerObjectData.None, renderQueueRange = GetRenderQueueRange(renderQueueType), sortingCriteria = sortingCriteria, excludeObjectMotionVectors = false, overrideMaterial = (overrideMaterial != null) ? overrideMaterial : defaultOverrideMaterial, overrideMaterialPassIndex = (overrideMaterial != null) ? overrideMaterialPassIndex : 0, layerMask = layerMask, }; HDUtils.DrawRendererList(renderContext, cmd, RendererList.Create(result)); }
unsafe public void PrepareGPUShadowDatas(CullingResults cullResults, HDCamera camera) { if (m_MaxShadowRequests == 0) { return; } int shadowIndex = 0; m_ShadowDatas.Clear(); // Create all HDShadowDatas and update them with shadow request datas for (int i = 0; i < m_ShadowRequestCount; i++) { Debug.Assert(m_ShadowRequests[i] != null); HDShadowAtlas atlas = m_Atlas; if (m_ShadowRequests[i].isInCachedAtlas) { atlas = cachedShadowManager.punctualShadowAtlas; } if (m_ShadowRequests[i].shadowMapType == ShadowMapType.CascadedDirectional) { atlas = m_CascadeAtlas; } else if (m_ShadowRequests[i].shadowMapType == ShadowMapType.AreaLightAtlas) { atlas = m_AreaLightShadowAtlas; if (m_ShadowRequests[i].isInCachedAtlas) { atlas = cachedShadowManager.areaShadowAtlas; } } HDShadowData shadowData; if (m_ShadowRequests[i].shouldUseCachedShadowData) { shadowData = m_ShadowRequests[i].cachedShadowData; } else { shadowData = CreateShadowData(m_ShadowRequests[i], atlas); m_ShadowRequests[i].cachedShadowData = shadowData; } m_ShadowDatas.Add(shadowData); m_ShadowRequests[i].shadowIndex = shadowIndex++; } int first = k_DirectionalShadowCascadeCount, second = k_DirectionalShadowCascadeCount; fixed(float *sphereBuffer = m_DirectionalShadowData.sphereCascades) { Vector4 *sphere = (Vector4 *)sphereBuffer; for (int i = 0; i < k_DirectionalShadowCascadeCount; i++) { first = (first == k_DirectionalShadowCascadeCount && sphere[i].w > 0.0f) ? i : first; second = ((second == k_DirectionalShadowCascadeCount || second == first) && sphere[i].w > 0.0f) ? i : second; } } // Update directional datas: if (second != k_DirectionalShadowCascadeCount) { m_DirectionalShadowData.cascadeDirection = (GetCascadeSphereAtIndex(second) - GetCascadeSphereAtIndex(first)).normalized; } else { m_DirectionalShadowData.cascadeDirection = Vector4.zero; } m_DirectionalShadowData.cascadeDirection.w = camera.volumeStack.GetComponent <HDShadowSettings>().cascadeShadowSplitCount.value; if (m_ShadowRequestCount > 0) { // Upload the shadow buffers to GPU m_ShadowDataBuffer.SetData(m_ShadowDatas); m_CachedDirectionalShadowData[0] = m_DirectionalShadowData; m_DirectionalShadowDataBuffer.SetData(m_CachedDirectionalShadowData); } }
public LightingParams(CullingResults cullingResults, ShadowSettings shadowSettings) { this.cullingResults = cullingResults; this.shadowSettings = shadowSettings; }
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; //Texture Descriptor - Color RenderTextureDescriptor rtDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); rtDesc.graphicsFormat = m_ColorFormat; rtDesc.depthBufferBits = 0; rtDesc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); rtDesc.msaaSamples = 1; rtDesc.enableRandomWrite = false; //Texture Descriptor - Depth RenderTextureDescriptor rtDescDepth = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); rtDescDepth.colorFormat = RenderTextureFormat.Depth; rtDescDepth.depthBufferBits = 24; rtDescDepth.msaaSamples = 1; rtDescDepth.enableRandomWrite = false; //Get Temp Texture for Color Texture CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; cmdTempId.GetTemporaryRT(m_AlbedoRTid, rtDesc, FilterMode.Point); cmdTempId.GetTemporaryRT(m_EmissionRTid, rtDesc, FilterMode.Point); cmdTempId.GetTemporaryRT(m_DepthRTid, rtDescDepth, FilterMode.Point); 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); //Pass 1========================================================= //SetUp Multi-RenderTargets For the 1st pass & clear CommandBuffer cmdPass1 = new CommandBuffer(); mRTIDs[0] = m_AlbedoRTid; mRTIDs[1] = m_EmissionRTid; cmdPass1.SetRenderTarget(mRTIDs, m_DepthRT); cmdPass1.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmdPass1); cmdPass1.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); //Final blit==================================================== //Blit to CameraTarget, to combine the previous 2 texture results with a blit material CommandBuffer cmd = new CommandBuffer(); cmd.name = "Cam:" + camera.name + " BlitToCamera"; cmd.Blit(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CameraTarget, copyColorMaterial); context.ExecuteCommandBuffer(cmd); cmd.Release(); //CleanUp Texture CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_AlbedoRTid); cmdclean.ReleaseTemporaryRT(m_EmissionRTid); cmdclean.ReleaseTemporaryRT(m_DepthRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
/// <summary> /// Execute the pass with the fullscreen setup /// </summary> /// <param name="cmd"></param> protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult) { if (fullscreenPassMaterial != null) { if (fetchColorBuffer) { ResolveMSAAColorBuffer(cmd, hdCamera); // reset the render target to the UI SetRenderTargetAuto(cmd); } fullscreenPassMaterial.SetFloat(fadeValueId, fadeValue); CoreUtils.DrawFullScreen(cmd, fullscreenPassMaterial, shaderPassId: materialPassIndex); } }
void RaytracingRecursiveRender(HDCamera hdCamera, CommandBuffer cmd, ScriptableRenderContext renderContext, CullingResults cull) { if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.RayTracing)) { return; } RecursiveRendering recursiveSettings = hdCamera.volumeStack.GetComponent <RecursiveRendering>(); if (!recursiveSettings.enable.value) { return; } // Recursive rendering works as follow: // - Shader have a _RayTracing property // When this property is setup to true, a RayTracingPrepass pass on the material is enabled (otherwise it is disabled) // - Before prepass we render all object with a RayTracingPrepass pass enabled into the depth buffer for performance saving. // Note that we will exclude from the rendering of DepthPrepass, GBuffer and Forward pass the raytraced objects but not from // motion vector pass, so we can still benefit from motion vector. This is handled in VertMesh.hlsl (see below). // However currently when rendering motion vector this will tag the stencil for deferred lighting, and thus could produce overshading. // - After Transparent Depth pass we render all object with a RayTracingPrepass pass enabled into output a mask buffer (need to depth test but not to write depth) // Note: we render two times: one to save performance and the other to write the mask, otherwise if we write the mask in the first pass it // will not take into account the objects which could render on top of the raytracing one (If we want to do that we need to perform the pass after that // the depth buffer is ready, which is after the Gbuffer pass, so we can't save performance). // - During RaytracingRecursiveRender we perform a RayTracingRendering.raytrace call on all pixel tag in the mask // It is require to exclude mesh from regular pass to save performance (for opaque) and get correct result (for transparent) // For this we cull the mesh by setuping their position to NaN if _RayTracing is true and _EnableRecursiveRayTracing true. // We use this method to avoid to have to deal with RenderQueue and it allow to dynamically disabled Recursive rendering // and fallback to classic rasterize transparent this way. The code for the culling is in VertMesh() // If raytracing is disable _EnableRecursiveRayTracing is set to false and no culling happen. // Objects are still render in shadow and motion vector pass to keep their properties. // We render Recursive render object before transparent, so transparent object can be overlayed on top // like lens flare on top of headlight. We write the depth, so it correctly z-test object behind as recursive rendering // re-render everything (Mean we should also support fog and sky into it). using (new ProfilingScope(cmd, ProfilingSampler.Get(HDProfileId.RayTracingRecursiveRendering))) { RayTracingShader forwardShader = m_Asset.renderPipelineRayTracingResources.forwardRaytracing; LightCluster lightClusterSettings = hdCamera.volumeStack.GetComponent <LightCluster>(); RayTracingSettings rtSettings = hdCamera.volumeStack.GetComponent <RayTracingSettings>(); // Grab the acceleration structure and the list of HD lights for the target camera RayTracingAccelerationStructure accelerationStructure = RequestAccelerationStructure(); HDRaytracingLightCluster lightCluster = RequestLightCluster(); // Define the shader pass to use for the reflection pass cmd.SetRayTracingShaderPass(forwardShader, "ForwardDXR"); // Set the acceleration structure for the pass cmd.SetRayTracingAccelerationStructure(forwardShader, HDShaderIDs._RaytracingAccelerationStructureName, accelerationStructure); // Inject the ray-tracing sampling data cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._OwenScrambledTexture, m_Asset.renderPipelineResources.textures.owenScrambledRGBATex); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._ScramblingTexture, m_Asset.renderPipelineResources.textures.scramblingTex); // Update Global Constant Buffer. m_ShaderVariablesRayTracingCB._RaytracingRayMaxLength = recursiveSettings.rayLength.value; m_ShaderVariablesRayTracingCB._RaytracingMaxRecursion = recursiveSettings.maxDepth.value; ConstantBuffer.PushGlobal(cmd, m_ShaderVariablesRayTracingCB, HDShaderIDs._ShaderVariablesRaytracing); // Fecth the temporary buffers we shall be using RTHandle flagBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.R0); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._RaytracingFlagMask, flagBuffer); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer()); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._CameraColorTextureRW, m_CameraColorBuffer); // Set ray count texture RayCountManager rayCountManager = GetRayCountManager(); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._RayCountTexture, rayCountManager.GetRayCountTexture()); // LightLoop data lightCluster.BindLightClusterData(cmd); // Note: Just in case, we rebind the directional light data (in case they were not) cmd.SetGlobalBuffer(HDShaderIDs._DirectionalLightDatas, m_LightLoopLightData.directionalLightData); // Set the data for the ray miss cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._SkyTexture, m_SkyManager.GetSkyReflection(hdCamera)); // If this is the right debug mode and we have at least one light, write the first shadow to the de-noised texture RTHandle debugBuffer = GetRayTracingBuffer(InternalRayTracingBuffers.RGBA0); cmd.SetRayTracingTextureParam(forwardShader, HDShaderIDs._RaytracingPrimaryDebug, debugBuffer); // Run the computation cmd.DispatchRays(forwardShader, m_RayGenShaderName, (uint)hdCamera.actualWidth, (uint)hdCamera.actualHeight, (uint)hdCamera.viewCount); HDRenderPipeline hdrp = (RenderPipelineManager.currentPipeline as HDRenderPipeline); hdrp.PushFullScreenDebugTexture(hdCamera, cmd, debugBuffer, FullScreenDebugMode.RecursiveRayTracing); } }
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); DrawingSettings mDW = new DrawingSettings(m_LegacyShaderPassNames[0], sortingSettings); for (int i = 1; i < m_LegacyShaderPassNames.Count; i++) { mDW.SetShaderPassName(i, m_LegacyShaderPassNames[i]); } //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; mDW.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref mDW, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; mDW.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref mDW, ref filterSettings); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
public void SetUp(ref ScriptableRenderContext srContext, ref CullingResults cullResults, ref ShadowSetting shadowSetting) { _dirLightCount = _spotLightCount = _pointLightCount = 0; _shadowMgr.SetUp(ref srContext, ref cullResults, ref shadowSetting); _srContext = srContext; int visibleIndex = 0; foreach(var visibleLight in cullResults.visibleLights) { switch(visibleLight.lightType) { case LightType.Directional: { if (_dirLightCount < MAX_NUM_DIRECTIONAL_LIGHT && visibleLight.light.intensity > 0) { _dirLightColors[_dirLightCount] = visibleLight.finalColor.linear; _dirLightDirections[_dirLightCount] = -visibleLight.light.transform.forward; _dirLightShadowData[_dirLightCount] = _shadowMgr.GetDirectionalShadowData(visibleIndex); _dirLightCount++; } break; } case LightType.Point: { if (_pointLightCount < MAX_NUM_POINT_LIGHT && visibleLight.light.intensity > 0) { _pointLightColors[_pointLightCount] = visibleLight.finalColor.linear; _pointLightPositions[_pointLightCount] = visibleLight.light.transform.position; _pointLightPositions[_pointLightCount].w = visibleLight.light.range; _pointLightShadowData[_pointLightCount] = _shadowMgr.GetPointShadowData(visibleIndex); _pointLightCount++; } break; } case LightType.Spot: { if (_spotLightCount < MAX_NUM_SPOT_LIGHT && visibleLight.light.intensity > 0) { _spotLightColors[_spotLightCount] = visibleLight.finalColor.linear; _spotLightPositions[_spotLightCount] = visibleLight.light.transform.position; _spotLightPositions[_spotLightCount].w = visibleLight.light.range; _spotLightDirections[_spotLightCount] = -visibleLight.light.transform.forward; _spotLightAngles[_spotLightCount].x = Mathf.Deg2Rad * visibleLight.light.innerSpotAngle; _spotLightAngles[_spotLightCount].y = Mathf.Deg2Rad * visibleLight.spotAngle; _spotLightShadowData[_spotLightCount] = _shadowMgr.GetSpotLightShadowData(visibleIndex); _spotLightCount++; } break; } } visibleIndex++; } _shadowMgr.Render(); // generate shadow map _cmdBuffer.BeginSample(CmdBufferName); ExecuteCmdBuffer(); _cmdBuffer.SetGlobalInt(DirLightCountId, _dirLightCount); if (_dirLightCount > 0) { _cmdBuffer.SetGlobalVectorArray(DirLightColorsId, _dirLightColors); _cmdBuffer.SetGlobalVectorArray(DirLightDirectionsId, _dirLightDirections); _cmdBuffer.SetGlobalVectorArray(DirLightShadowDataId, _dirLightShadowData); } _cmdBuffer.SetGlobalInt(SpotLightCountId, _spotLightCount); if (_spotLightCount > 0) { _cmdBuffer.SetGlobalVectorArray(SpotLightColorsId, _spotLightColors); _cmdBuffer.SetGlobalVectorArray(SpotLightPositionsId, _spotLightPositions); _cmdBuffer.SetGlobalVectorArray(SpotLightDirectionsId, _spotLightDirections); _cmdBuffer.SetGlobalVectorArray(SpotLightAnglesId, _spotLightAngles); _cmdBuffer.SetGlobalVectorArray(SpotLightShadowDataId, _spotLightShadowData); } _cmdBuffer.SetGlobalInt(PointLightCountId, _pointLightCount); if (_pointLightCount > 0) { _cmdBuffer.SetGlobalVectorArray(PointLightColorsId, _pointLightColors); _cmdBuffer.SetGlobalVectorArray(PointLightPositionsId, _pointLightPositions); _cmdBuffer.SetGlobalVectorArray(PointLightShadowDataId, _pointLightShadowData); } _cmdBuffer.EndSample(CmdBufferName); ExecuteCmdBuffer(); }
void RenderObjects(ScriptableRenderContext renderContext, CommandBuffer cmd, Material overrideMaterial, int passIndex, CompareFunction depthCompare, CullingResults cullingResult, HDCamera hdCamera, StencilState?overrideStencil = null) { // Render the objects in the layer blur mask into a mask buffer with their materials so we keep the alpha-clip and transparency if there is any. var result = new UnityEngine.Rendering.RendererUtils.RendererListDesc(shaderTags, cullingResult, hdCamera.camera) { rendererConfiguration = PerObjectData.None, renderQueueRange = RenderQueueRange.all, sortingCriteria = SortingCriteria.BackToFront, excludeObjectMotionVectors = false, overrideMaterial = overrideMaterial, overrideMaterialPassIndex = passIndex, layerMask = seeThroughLayer, stateBlock = new RenderStateBlock(RenderStateMask.Depth) { depthState = new DepthState(true, depthCompare) }, }; if (overrideStencil != null) { var block = result.stateBlock.Value; block.mask |= RenderStateMask.Stencil; block.stencilState = overrideStencil.Value; result.stateBlock = block; } CoreUtils.DrawRendererList(renderContext, cmd, renderContext.CreateRendererList(result)); }
public static void ExtractDirectionalLightData(VisibleLight visibleLight, Vector2 viewportSize, uint cascadeIndex, int cascadeCount, float[] cascadeRatios, float nearPlaneOffset, CullingResults cullResults, int lightIndex, out Matrix4x4 view, out Matrix4x4 invViewProjection, out Matrix4x4 projection, out Matrix4x4 deviceProjection, out ShadowSplitData splitData) { Vector4 lightDir; Debug.Assert((uint)viewportSize.x == (uint)viewportSize.y, "Currently the cascaded shadow mapping code requires square cascades."); splitData = new ShadowSplitData(); splitData.cullingSphere.Set(0.0f, 0.0f, 0.0f, float.NegativeInfinity); splitData.cullingPlaneCount = 0; // get lightDir lightDir = visibleLight.light.transform.forward; // TODO: At some point this logic should be moved to C#, then the parameters cullResults and lightIndex can be removed as well // For directional lights shadow data is extracted from the cullResults, so that needs to be somehow provided here. // Check ScriptableShadowsUtility.cpp ComputeDirectionalShadowMatricesAndCullingPrimitives(...) for details. Vector3 ratios = new Vector3(); for (int i = 0, cnt = cascadeRatios.Length < 3 ? cascadeRatios.Length : 3; i < cnt; i++) { ratios[i] = cascadeRatios[i]; } cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(lightIndex, (int)cascadeIndex, cascadeCount, ratios, (int)viewportSize.x, nearPlaneOffset, out view, out projection, out splitData); // and the compound (deviceProjection will potentially inverse-Z) deviceProjection = GL.GetGPUProjectionMatrix(projection, false); projection = GL.GetGPUProjectionMatrix(projection, true); InvertOrthographic(ref deviceProjection, ref view, out invViewProjection); }
public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer cmd, CullingResults cullResults) { // Avoid to do any commands if there is no shadow to draw if (m_ShadowRequestCount == 0) { return; } // TODO remove DrawShadowSettings, lightIndex and splitData when scriptable culling is available ShadowDrawingSettings dss = new ShadowDrawingSettings(cullResults, 0); // Clear atlas render targets and draw shadows m_Atlas.RenderShadows(renderContext, cmd, dss); m_CascadeAtlas.RenderShadows(renderContext, cmd, dss); }
internal bool Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult, SharedRTManager rtManager, CustomPass.RenderTargets targets) { bool executed = false; // We never execute volume if the layer is not within the culling layers of the camera if ((hdCamera.volumeLayerMask & (1 << gameObject.layer)) == 0) { return(false); } Shader.SetGlobalFloat(HDShaderIDs._CustomPassInjectionPoint, (float)injectionPoint); foreach (var pass in customPasses) { if (pass != null && pass.enabled) { using (new ProfilingSample(cmd, pass.name)) { pass.ExecuteInternal(renderContext, cmd, hdCamera, cullingResult, rtManager, targets, this); executed = true; } } } return(executed); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { m_asset.memoryConsumption = 0f; instance = this; display = displayList.Count > 0 && displayList[0].running ? displayList[0] : null; bool xrEnabled = XRSettings.isDeviceActive; // Sort cameras array by camera depth Array.Sort(cameras, m_CameraComparer); // SetupShaderGlobals // ===================================================================================================== LogTrace("SetupShaderGlobals..."); { CommandBuffer cmd5 = CommandBufferPool.Get("SetupShaderGlobals"); cmd5.SetGlobalFloat("g_AtlasResolutionScale", m_asset.atlasResolutionScale / m_asset.visibilityPassDownscale); float lerpFactor = Mathf.Clamp01((float)timeSinceLastRender / (1f / m_asset.atlasRefreshFps)); //TODO: clamp should't been neccesary cmd5.SetGlobalFloat("g_atlasMorph", lerpFactor); cmd5.SetGlobalTexture("g_Dither", m_asset.dither[0]); if (m_asset.TexelSpaceBackfaceCulling) { cmd5.EnableShaderKeyword("TRIANGLE_CULLING"); } else { cmd5.DisableShaderKeyword("TRIANGLE_CULLING"); } context.ExecuteCommandBuffer(cmd5); CommandBufferPool.Release(cmd5); } bool shouldUpdateAtlas = timeSinceLastRender > 1f / m_asset.atlasRefreshFps; foreach (Camera camera in cameras) { //XR SCREEN_X = camera.pixelWidth; SCREEN_Y = camera.pixelHeight; SortingSettings cameraSortSettings = new SortingSettings(camera); ScriptableCullingParameters cullingParameters; if (!camera.TryGetCullingParameters(xrEnabled, out cullingParameters)) { continue; } m_CullResults = context.Cull(ref cullingParameters); context.SetupCameraProperties(camera, xrEnabled); #region XRtest { var cmd = CommandBufferPool.Get("Test"); if (display != null) //Vr is enabled { #region setup stero rendering // XRTODO: Handle stereo mode selection in URP pipeline asset UI display.textureLayout = XRDisplaySubsystem.TextureLayout.Texture2DArray; display.zNear = camera.nearClipPlane; display.zFar = camera.farClipPlane; display.sRGB = QualitySettings.activeColorSpace == ColorSpace.Linear; display.GetRenderPass(0, out XRDisplaySubsystem.XRRenderPass xrRenderPass); cmd.SetRenderTarget(xrRenderPass.renderTarget); xrRenderPass.GetRenderParameter(camera, 0, out var renderParameter0); xrRenderPass.GetRenderParameter(camera, 1, out var renderParameter1); #endregion #region enable stero rendering //enable single pass (see XRPass.cs:344) if (SystemInfo.supportsMultiview) { cmd.EnableShaderKeyword("STEREO_MULTIVIEW_ON"); cmd.SetGlobalVectorArray("unity_StereoEyeIndices", stereoEyeIndices); } else { cmd.EnableShaderKeyword("STEREO_INSTANCING_ON"); const int viewCount = 2; cmd.SetInstanceMultiplier((uint)viewCount); } cmd.EnableShaderKeyword(ShaderKeywordStrings.UseDrawProcedural); #endregion } else { cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); } cmd.ClearRenderTarget(true, true, Color.green); context.ExecuteCommandBuffer(cmd); //RenderOpaque(context, m_VistaPass, cameraSortSettings); context.DrawSkybox(camera); #region Disable stero rendering if (SystemInfo.supportsMultiview) { cmd.DisableShaderKeyword("STEREO_MULTIVIEW_ON"); } else { cmd.DisableShaderKeyword("STEREO_INSTANCING_ON"); cmd.SetInstanceMultiplier(1); } cmd.DisableShaderKeyword(ShaderKeywordStrings.UseDrawProcedural); #endregion } #endregion int targetAtlasSize = m_asset.maximalAtlasSizePixel; if (g_VistaAtlas_A == null || g_VistaAtlas_A.width != targetAtlasSize) { CommandBuffer cmd5 = CommandBufferPool.Get("(Re)initialize Atlas"); if (g_VistaAtlas_A != null) { g_VistaAtlas_A.Release(); g_VistaAtlas_B.Release(); } g_VistaAtlas_A = new RenderTexture( targetAtlasSize, targetAtlasSize, 0, RenderTextureFormat.ARGB2101010, RenderTextureReadWrite.sRGB); g_VistaAtlas_A.Create(); g_VistaAtlas_B = new RenderTexture(g_VistaAtlas_A); g_VistaAtlas_B.Create(); cmd5.SetRenderTarget(g_VistaAtlas_A); cmd5.ClearRenderTarget(true, true, Color.black); cmd5.SetRenderTarget(g_VistaAtlas_B); cmd5.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmd5); CommandBufferPool.Release(cmd5); } // TODO: reuse uv output to skip rendering objects a third time in VistaPass CommandBuffer createCameraRT = CommandBufferPool.Get("Create Camera RT"); createCameraRT.GetTemporaryRT( g_CameraTarget, SCREEN_X, SCREEN_Y, 24, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB, Mathf.NextPowerOfTwo(m_asset.MSSALevel)); createCameraRT.SetRenderTarget(g_CameraTarget); createCameraRT.ClearRenderTarget(true, true, Color.clear); context.ExecuteCommandBuffer(createCameraRT); if (shouldUpdateAtlas) { //Debug.Log(DateTime.Now.ToString("hh.mm.ss.ffffff") + "render" + timeSinceLastRender.ToString()); target_atlasA = !target_atlasA; // ===================================================================================================== // CopyDataToPreFrameBuffer // ===================================================================================================== // LogVerbose("CopyDataToPreFrameBuffer..."); CommandBuffer cmd = CommandBufferPool.Get("CopyDataToPreFrameBuffer"); cmd.SetComputeBufferParam(m_ResolveCS, m_cs_CopyDataToPreFrameBuffer, "g_ObjectToAtlasProperties", g_ObjectToAtlasProperties); cmd.SetComputeBufferParam(m_ResolveCS, m_cs_CopyDataToPreFrameBuffer, "g_prev_ObjectToAtlasProperties", g_prev_ObjectToAtlasProperties); uint threadsX, threadsY, threadsZ; m_ResolveCS.GetKernelThreadGroupSizes(m_cs_CopyDataToPreFrameBuffer, out threadsX, out threadsY, out threadsZ); cmd.DispatchCompute(m_ResolveCS, m_cs_CopyDataToPreFrameBuffer, Mathf.CeilToInt(MAXIMAL_OBJECTS_PER_VIEW / (float)64.0), 1, 1); cmd.SetComputeBufferParam(m_ResolveCS, m_cs_InitalizePrimitiveVisiblity, g_PrimitiveVisibilityID, g_PrimitiveVisibility); cmd.DispatchCompute(m_ResolveCS, m_cs_InitalizePrimitiveVisiblity, Mathf.CeilToInt(g_PrimitiveVisibility.count / (float)threadsX), 1, 1); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); // ===================================================================================================== // SetupRenderBuffers // ===================================================================================================== LogTrace("SetupRenderBuffers..."); CommandBuffer cmd1 = CommandBufferPool.Get("SetupBuffers"); int screenX = camera.pixelWidth; int screenY = camera.pixelHeight; g_visibilityBuffer_dimension = new Vector2Int( Mathf.CeilToInt(screenX / m_asset.visibilityPassDownscale), Mathf.CeilToInt(screenY / m_asset.visibilityPassDownscale)); cmd1.GetTemporaryRT(g_VisibilityBufferID, g_visibilityBuffer_dimension.x, g_visibilityBuffer_dimension.y, 32, FilterMode.Point, RenderTextureFormat.RInt, RenderTextureReadWrite.Linear, 1); cmd1.SetRenderTarget(g_visibilityBuffer_RT); cmd1.ClearRenderTarget(true, true, Color.clear); cmd1.SetRenderTarget(target_atlasA ? g_VistaAtlas_A : g_VistaAtlas_B); if (m_asset.clearAtlasOnRefresh) { cmd1.ClearRenderTarget(true, true, Color.clear); } cmd1.SetGlobalTexture("g_VistaAtlas", target_atlasA ? g_VistaAtlas_A : g_VistaAtlas_B); cmd1.SetGlobalTexture("g_prev_VistaAtlas", target_atlasA ? g_VistaAtlas_B : g_VistaAtlas_A); cmd1.SetGlobalFloat("g_AtlasSizeExponent", m_asset.maximalAtlasSizeExponent); context.ExecuteCommandBuffer(cmd1); CommandBufferPool.Release(cmd1); // ===================================================================================================== // Visiblity Pass // Figure out what objects (and triangles) are visible and needed to be rendered. // ===================================================================================================== // renders the current view as: objectID, primitveID and mipmap level g_Object_MipmapLevelA.SetCounterValue(0); CommandBuffer cmd2 = CommandBufferPool.Get("RenderTexelCoverage"); cmd2.SetRenderTarget(g_VisibilityBufferID); //cmd.SetGlobalBuffer("g_ObjectToAtlasPropertiesRW", g_ObjectToAtlasProperties); //cmd.SetRandomWriteTarget(1, g_ObjectToAtlasProperties); //g_vertexIDVisiblity_B.SetData(g_vertexIDVisiblity_B_init); context.ExecuteCommandBuffer(cmd2); cameraSortSettings.criteria = SortingCriteria.OptimizeStateChanges; context.StartMultiEye(camera); RenderOpaque(context, m_VisibilityPass, cameraSortSettings); context.StopMultiEye(camera); cmd2.Clear(); cmd2.ClearRandomWriteTargets(); // VISIBLITY DISSOLVE PASS // maps the previous rendered data into usable buffers cmd2.SetComputeTextureParam(m_ResolveCS, m_cs_ExtractVisibility, g_VisibilityBufferID, g_visibilityBuffer_RT); cmd2.SetComputeBufferParam(m_ResolveCS, m_cs_ExtractVisibility, g_PrimitiveVisibilityID, g_PrimitiveVisibility); cmd2.SetComputeBufferParam(m_ResolveCS, m_cs_ExtractVisibility, "g_ObjectToAtlasProperties", g_ObjectToAtlasProperties); cmd2.SetComputeBufferParam(m_ResolveCS, m_cs_ExtractVisibility, "g_ObjectMipMap_append", g_Object_MipmapLevelA); cmd2.DispatchCompute(m_ResolveCS, m_cs_ExtractVisibility, SCREEN_X / COMPUTE_COVERAGE_TILE_SIZE, SCREEN_Y / COMPUTE_COVERAGE_TILE_SIZE, 1); cmd2.CopyCounterValue(g_Object_MipmapLevelA, g_ObjectMipMapCounterValue, 0); cmd2.SetComputeBufferParam(m_ResolveCS, m_cs_MipMapFinalize, "g_ObjectMipMap_consume", g_Object_MipmapLevelA); cmd2.SetComputeBufferParam(m_ResolveCS, m_cs_MipMapFinalize, "g_ObjectToAtlasProperties", g_ObjectToAtlasProperties); cmd2.SetComputeBufferParam(m_ResolveCS, m_cs_MipMapFinalize, "g_ObjectMipMapCounterValue", g_ObjectMipMapCounterValue); cmd2.DispatchCompute(m_ResolveCS, m_cs_MipMapFinalize, 1, 1, 1); context.ExecuteCommandBuffer(cmd2); cmd2.Clear(); // optional debug pass switch (m_asset.debugPass) { case TexelSpaceDebugMode.VisibilityPassObjectID: case TexelSpaceDebugMode.VisibilityPassPrimitivID: case TexelSpaceDebugMode.VisibilityPassMipMapPerObject: case TexelSpaceDebugMode.VisibilityPassMipMapPerPixel: int debugView = Shader.PropertyToID("g_DebugTexture"); cmd2.GetTemporaryRT(debugView, SCREEN_X, SCREEN_Y, 16, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear, 1, true); cmd2.SetComputeTextureParam(m_ResolveCS, m_cs_DebugVisibilityBuffer, g_VisibilityBufferID, g_visibilityBuffer_RT); cmd2.SetComputeTextureParam(m_ResolveCS, m_cs_DebugVisibilityBuffer, "g_DebugTexture", debugView); cmd2.SetComputeBufferParam(m_ResolveCS, m_cs_DebugVisibilityBuffer, "g_ObjectToAtlasPropertiesR", g_ObjectToAtlasProperties); cmd2.SetComputeIntParam(m_ResolveCS, "g_DebugPassID", (int)m_asset.debugPass); cmd2.DispatchCompute( m_ResolveCS, m_cs_DebugVisibilityBuffer, SCREEN_X / 8, SCREEN_Y / 8, 1); cmd2.Blit(debugView, g_CameraTarget); cmd2.ReleaseTemporaryRT(debugView); context.ExecuteCommandBuffer(cmd2); cmd2.Clear(); break; } CommandBufferPool.Release(cmd2); // ===================================================================================================== // PackAtlas // ===================================================================================================== LogTrace("PackAtlas..."); CommandBuffer cmd3 = CommandBufferPool.Get("PackAtlas"); atlasAxisSize = m_asset.maximalAtlasSizePixel; for (int i = 0; i < visibleObjects.Count; i++) { visibleObjects[i].SetAtlasProperties(i + 1, 1); //objectID 0 is reserved for "undefined" } cmd3.SetComputeIntParam(m_ResolveCS, "g_totalObjectsInView", visibleObjects.Count + 1); cmd3.SetComputeIntParam(m_ResolveCS, "g_atlasAxisSize", atlasAxisSize); cmd3.SetComputeBufferParam(m_ResolveCS, m_cs_AtlasPacking, "g_ObjectToAtlasProperties", g_ObjectToAtlasProperties); cmd3.DispatchCompute(m_ResolveCS, m_cs_AtlasPacking, 1, 1, 1); visibleObjects.Clear(); context.ExecuteCommandBuffer(cmd3); CommandBufferPool.Release(cmd3); // ===================================================================================================== // RenderTexelShading // ===================================================================================================== CommandBuffer cmd4 = CommandBufferPool.Get("RenderTexelShading"); LogTrace("setup light array..."); NativeArray <VisibleLight> visibleLights = m_CullResults.visibleLights; g_LightsOriginRange.Clear(); g_LightColorAngle.Clear(); for (int i1 = 0; i1 < MAX_LIGHTS; i1++) { if (i1 >= visibleLights.Length) { // fill up buffer with zero lights g_LightsOriginRange.Add(Vector4.zero); g_LightColorAngle.Add(Vector4.zero); continue; } VisibleLight light = visibleLights[i1]; // if it's a directional light, just treat it as a point light and place it very far away Vector4 lightOriginRange = light.lightType == LightType.Directional ? -light.light.transform.forward * 99999f : light.light.transform.position; lightOriginRange.w = light.lightType == LightType.Directional ? 99999999f : light.range; g_LightsOriginRange.Add(lightOriginRange); Vector4 lightColorAngle; lightColorAngle = light.light.color * light.light.intensity; lightColorAngle.w = light.lightType == LightType.Directional ? Mathf.Cos(light.spotAngle) : 1f; g_LightColorAngle.Add(lightColorAngle); } cmd4.SetGlobalVectorArray("g_LightsOriginRange", g_LightsOriginRange); cmd4.SetGlobalVectorArray("g_LightColorAngle", g_LightColorAngle); cmd4.SetGlobalInt("g_LightsCount", Mathf.Min(MAX_LIGHTS, visibleLights.Length)); cmd4.SetRenderTarget(target_atlasA ? g_VistaAtlas_A : g_VistaAtlas_B); context.ExecuteCommandBuffer(cmd4); RenderOpaque(context, m_TexelSpacePass, cameraSortSettings); cmd4.Clear(); if (m_asset.debugPass == TexelSpaceDebugMode.TexelShadingPass) { cmd4.Blit(g_VistaAtlas_A, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmd4); } CommandBufferPool.Release(cmd4); LogTrace("ReleaseBuffers..."); CommandBuffer cmd6 = CommandBufferPool.Get("ReleaseBuffers"); cmd6.ReleaseTemporaryRT(g_PrimitiveVisibilityID); context.ExecuteCommandBuffer(cmd6); CommandBufferPool.Release(cmd6); #if UNITY_EDITOR // Emit scene view UI if (camera.cameraType == CameraType.SceneView) { ScriptableRenderContext.EmitWorldGeometryForSceneView(camera); } #endif } visibleObjects.Clear(); // ===================================================================================================== // Render Vista + Finalize // ===================================================================================================== CommandBuffer cmdVista = CommandBufferPool.Get("Render Vista"); cmdVista.SetRenderTarget(g_CameraTarget); context.ExecuteCommandBuffer(cmdVista); cmdVista.Clear(); context.StartMultiEye(camera); switch (m_asset.debugPass) { case TexelSpaceDebugMode.None: cameraSortSettings.criteria = SortingCriteria.OptimizeStateChanges; RenderOpaque(context, m_VistaPass, cameraSortSettings); // render vista context.DrawSkybox(camera); break; case TexelSpaceDebugMode.VisibilityPassObjectID: case TexelSpaceDebugMode.VisibilityPassPrimitivID: case TexelSpaceDebugMode.VisibilityPassMipMapPerObject: case TexelSpaceDebugMode.VisibilityPassMipMapPerPixel: break; case TexelSpaceDebugMode.TexelShadingPass: cmdVista.Blit(g_VistaAtlas_A, g_CameraTarget); context.ExecuteCommandBuffer(cmdVista); cmdVista.Clear(); break; default: throw new ArgumentOutOfRangeException(); } context.StopMultiEye(camera); cmdVista.Blit(g_CameraTarget, BuiltinRenderTextureType.CameraTarget); cmdVista.ReleaseTemporaryRT(g_CameraTarget); context.ExecuteCommandBuffer(cmdVista); CommandBufferPool.Release(cmdVista); } if (shouldUpdateAtlas) { timeSinceLastRender = 0f; } timeSinceLastRender += Time.deltaTime; context.Submit(); if (g_VistaAtlas_A) { m_asset.memoryConsumption += g_VistaAtlas_A.width * g_VistaAtlas_A.height * (g_VistaAtlas_A.format == RenderTextureFormat.DefaultHDR ? 8 : 4) * 2; } m_asset.memoryConsumption /= 1024 * 1024; }
internal ShadowResult RenderShadows(RenderGraph renderGraph, HDCamera hdCamera, CullingResults cullResults) { var result = m_ShadowManager.RenderShadows(m_RenderGraph, m_ShaderVariablesGlobalCB, hdCamera, cullResults); // Need to restore global camera parameters. PushGlobalCameraParams(renderGraph, hdCamera); return(result); }
internal ShadowResult RenderShadows(RenderGraph renderGraph, HDCamera hdCamera, CullingResults cullResults) { var result = m_ShadowManager.RenderShadows(m_RenderGraph, hdCamera, cullResults); // TODO: Remove this once shadows don't pollute global parameters anymore. PushGlobalCameraParams(renderGraph, hdCamera); return(result); }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(context, cameras); foreach (Camera camera in cameras) { BeginCameraRendering(context, camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //************************** Set TempRT ************************************ CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; //Color m_ColorFormatActive = camera.allowHDR ? m_ColorFormatHDR : m_ColorFormat; RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); colorRTDesc.graphicsFormat = m_ColorFormatActive; colorRTDesc.depthBufferBits = depthBufferBits; //colorRTDesc.sRGB = ; colorRTDesc.msaaSamples = camera.allowMSAA ? QualitySettings.antiAliasing : 1; colorRTDesc.enableRandomWrite = false; cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); //Depth RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); depthRTDesc.colorFormat = RenderTextureFormat.Depth; depthRTDesc.depthBufferBits = depthBufferBits; cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear); //MotionVector RenderTextureDescriptor motionvectorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); motionvectorRTDesc.graphicsFormat = UnityEngine.Experimental.Rendering.GraphicsFormat.R16G16_SFloat; motionvectorRTDesc.depthBufferBits = depthBufferBits; //colorRTDesc.sRGB = ; motionvectorRTDesc.msaaSamples = 1; motionvectorRTDesc.enableRandomWrite = false; cmdTempId.GetTemporaryRT(m_MotionVectorRTid, motionvectorRTDesc, FilterMode.Bilinear); context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //************************** Setup DrawSettings and FilterSettings ************************************ camera.depthTextureMode |= DepthTextureMode.MotionVectors | DepthTextureMode.Depth; var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); DrawingSettings drawSettingsMotionVector = new DrawingSettings(m_PassName, sortingSettings) { perObjectData = PerObjectData.MotionVectors, overrideMaterial = motionVectorMaterial, overrideMaterialPassIndex = 0 }; FilteringSettings filterSettingsMotionVector = new FilteringSettings(RenderQueueRange.all) { excludeMotionVectorObjects = false }; DrawingSettings drawSettingsDepth = new DrawingSettings(m_PassName, sortingSettings) { //perObjectData = PerObjectData.None, overrideMaterial = depthOnlyMaterial, overrideMaterialPassIndex = 0, }; FilteringSettings filterSettingsDepth = new FilteringSettings(RenderQueueRange.all); //************************** Rendering depth ************************************ //Set RenderTarget & Camera clear flag CommandBuffer cmdDepth = new CommandBuffer(); cmdDepth.name = "(" + camera.name + ")" + "Depth Clear Flag"; cmdDepth.SetRenderTarget(m_DepthRT); //Set CameraTarget to the depth texture cmdDepth.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmdDepth); cmdDepth.Release(); //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettingsDepth.sortingSettings = sortingSettings; filterSettingsDepth.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsDepth, ref filterSettingsDepth); //To let shader has _CameraDepthTexture CommandBuffer cmdDepthTexture = new CommandBuffer(); cmdDepthTexture.name = "(" + camera.name + ")" + "Depth Texture"; cmdDepthTexture.SetGlobalTexture(m_DepthRTid, m_DepthRT); context.ExecuteCommandBuffer(cmdDepthTexture); cmdDepthTexture.Release(); //************************** Rendering motion vectors ************************************ //Camera clear flag CommandBuffer cmdMotionvector = new CommandBuffer(); cmdMotionvector.SetRenderTarget(m_MotionVectorRT); //Set CameraTarget to the motion vector texture cmdMotionvector.ClearRenderTarget(true, true, Color.black); context.ExecuteCommandBuffer(cmdMotionvector); cmdMotionvector.Release(); //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettingsMotionVector.sortingSettings = sortingSettings; filterSettingsMotionVector.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettingsMotionVector, ref filterSettingsMotionVector); //Camera motion vector CommandBuffer cmdCameraMotionVector = new CommandBuffer(); cmdCameraMotionVector.name = "(" + camera.name + ")" + "Camera MotionVector"; _NonJitteredVP = camera.nonJitteredProjectionMatrix * camera.worldToCameraMatrix; cmdCameraMotionVector.SetGlobalMatrix("_CamPrevViewProjMatrix", _PreviousVP); cmdCameraMotionVector.SetGlobalMatrix("_CamNonJitteredViewProjMatrix", _NonJitteredVP); cmdCameraMotionVector.SetViewProjectionMatrices(Matrix4x4.identity, Matrix4x4.identity); cmdCameraMotionVector.DrawMesh(fullscreenMesh, Matrix4x4.identity, motionVectorMaterial, 0, 1, null); // draw full screen quad to make Camera motion cmdCameraMotionVector.SetViewProjectionMatrices(camera.worldToCameraMatrix, camera.projectionMatrix); context.ExecuteCommandBuffer(cmdCameraMotionVector); cmdCameraMotionVector.Release(); //To let shader has MotionVectorTexture CommandBuffer cmdMotionVectorTexture = new CommandBuffer(); cmdMotionVectorTexture.name = "(" + camera.name + ")" + "MotionVector Texture"; cmdMotionVectorTexture.SetGlobalTexture(m_MotionVectorRTid, m_MotionVectorRT); context.ExecuteCommandBuffer(cmdMotionVectorTexture); cmdMotionVectorTexture.Release(); //************************** Rendering color ************************************ //Camera clear flag CommandBuffer cmd = new CommandBuffer(); cmd.SetRenderTarget(m_ColorRT); //Set CameraTarget to the color texture cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); cmd.Release(); //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //************************** SetUp Post-processing ************************************ PostProcessLayer m_CameraPostProcessLayer = camera.GetComponent <PostProcessLayer>(); bool hasPostProcessing = m_CameraPostProcessLayer != null; bool usePostProcessing = false; //bool hasOpaqueOnlyEffects = false; PostProcessRenderContext m_PostProcessRenderContext = null; if (hasPostProcessing) { m_PostProcessRenderContext = new PostProcessRenderContext(); usePostProcessing = m_CameraPostProcessLayer.enabled; //hasOpaqueOnlyEffects = m_CameraPostProcessLayer.HasOpaqueOnlyEffects(m_PostProcessRenderContext); } //************************** Opaque Post-processing ************************************ //Ambient Occlusion, Screen-spaced reflection are generally not supported for SRP //So this part is only for custom opaque post-processing // if(usePostProcessing) // { // CommandBuffer cmdpp = new CommandBuffer(); // cmdpp.name = "("+camera.name+")"+ "Post-processing Opaque"; // m_PostProcessRenderContext.Reset(); // m_PostProcessRenderContext.camera = camera; // m_PostProcessRenderContext.source = m_ColorRT; // m_PostProcessRenderContext.sourceFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetRenderTextureFormat(m_ColorFormatActive); // m_PostProcessRenderContext.destination = m_ColorRT; // m_PostProcessRenderContext.command = cmdpp; // m_PostProcessRenderContext.flip = camera.targetTexture == null; // m_CameraPostProcessLayer.RenderOpaqueOnly(m_PostProcessRenderContext); // context.ExecuteCommandBuffer(cmdpp); // cmdpp.Release(); // } //************************** Rendering Transparent Objects ************************************ sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //************************** Transparent Post-processing ************************************ //Bloom, Vignette, Grain, ColorGrading, LensDistortion, Chromatic Aberration, Auto Exposure, Motion Blur if (usePostProcessing) { CommandBuffer cmdpp = new CommandBuffer(); cmdpp.name = "(" + camera.name + ")" + "Post-processing Transparent"; m_PostProcessRenderContext.Reset(); m_PostProcessRenderContext.camera = camera; m_PostProcessRenderContext.source = m_ColorRT; m_PostProcessRenderContext.sourceFormat = UnityEngine.Experimental.Rendering.GraphicsFormatUtility.GetRenderTextureFormat(m_ColorFormatActive); m_PostProcessRenderContext.destination = BuiltinRenderTextureType.CameraTarget; m_PostProcessRenderContext.command = cmdpp; m_PostProcessRenderContext.flip = camera.targetTexture == null; m_CameraPostProcessLayer.Render(m_PostProcessRenderContext); context.ExecuteCommandBuffer(cmdpp); cmdpp.Release(); } else { //Make sure screen has the thing when Postprocessing is off CommandBuffer cmdBlitToCam = new CommandBuffer(); cmdBlitToCam.name = "(" + camera.name + ")" + "Blit back to Camera"; cmdBlitToCam.Blit(m_ColorRTid, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmdBlitToCam); cmdBlitToCam.Release(); } //************************** Debug ************************************ if (_motionVectorDebug) { CommandBuffer cmdDebug = new CommandBuffer(); cmdDebug.Blit(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CameraTarget, motionVectorDebugMaterial); context.ExecuteCommandBuffer(cmdDebug); cmdDebug.Release(); } //************************** Clean Up ************************************ CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_ColorRTid); cmdclean.ReleaseTemporaryRT(m_DepthRTid); cmdclean.ReleaseTemporaryRT(m_MotionVectorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); //For camera motion vector _PreviousVP = _NonJitteredVP; EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
TextureHandle RenderPostProcess(RenderGraph renderGraph, PrepassOutput prepassOutput, TextureHandle inputColor, TextureHandle backBuffer, CullingResults cullResults, HDCamera hdCamera) { PostProcessParameters parameters = PreparePostProcess(cullResults, hdCamera); TextureHandle afterPostProcessBuffer = renderGraph.defaultResources.blackTextureXR; TextureHandle dest = HDUtils.PostProcessIsFinalPass(parameters.hdCamera) ? backBuffer : renderGraph.CreateTexture( new TextureDesc(Vector2.one, false, true) { colorFormat = GetColorBufferFormat(), name = "Intermediate Postprocess buffer" }); if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.AfterPostprocess)) { // We render AfterPostProcess objects first into a separate buffer that will be composited in the final post process pass using (var builder = renderGraph.AddRenderPass <AfterPostProcessPassData>("After Post-Process", out var passData, ProfilingSampler.Get(HDProfileId.AfterPostProcessing))) { passData.parameters = parameters; passData.afterPostProcessBuffer = builder.UseColorBuffer(renderGraph.CreateTexture( new TextureDesc(Vector2.one, true, true) { colorFormat = GraphicsFormat.R8G8B8A8_SRGB, clearBuffer = true, clearColor = Color.black, name = "OffScreen AfterPostProcess" }), 0); if (passData.parameters.useDepthBuffer) { passData.depthStencilBuffer = builder.UseDepthBuffer(prepassOutput.resolvedDepthBuffer, DepthAccess.ReadWrite); } passData.opaqueAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.opaqueAfterPPDesc)); passData.transparentAfterPostprocessRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparentAfterPPDesc)); builder.SetRenderFunc( (AfterPostProcessPassData data, RenderGraphContext ctx) => { RenderAfterPostProcess(data.parameters, data.opaqueAfterPostprocessRL, data.transparentAfterPostprocessRL, ctx.renderContext, ctx.cmd); }); afterPostProcessBuffer = passData.afterPostProcessBuffer; } } var motionVectors = hdCamera.frameSettings.IsEnabled(FrameSettingsField.MotionVectors) ? prepassOutput.resolvedMotionVectorsBuffer : renderGraph.defaultResources.blackTextureXR; m_PostProcessSystem.Render( renderGraph, parameters.hdCamera, parameters.blueNoise, inputColor, afterPostProcessBuffer, prepassOutput.resolvedDepthBuffer, prepassOutput.depthPyramidTexture, prepassOutput.resolvedNormalBuffer, motionVectors, dest, parameters.flipYInPostProcess ); return(dest); }
private void SetUpRealtimeShadowVariables(Camera cam, ScriptableRenderContext context, CullingResults cull, Light light, int lightIndex) { Bounds bounds; bool doShadow = light.shadows != LightShadows.None && cull.GetShadowCasterBounds(lightIndex, out bounds); //************************** Shadow Mapping ************************************ if (doShadow) { ShadowDrawingSettings shadowSettings = new ShadowDrawingSettings(cull, lightIndex); //For shadowmapping, the matrices from the light's point of view Matrix4x4 view = Matrix4x4.identity; Matrix4x4 proj = Matrix4x4.identity; ShadowSplitData splitData; bool successShadowMap = false; if (light.type == LightType.Directional) { successShadowMap = cull.ComputeDirectionalShadowMatricesAndCullingPrimitives ( lightIndex, 0, 1, new Vector3(1, 0, 0), m_ShadowRes, light.shadowNearPlane, out view, out proj, out splitData ); shadowSettings.splitData = splitData; } else { return; } if (successShadowMap) { CommandBuffer cmdShadow = new CommandBuffer(); cmdShadow.name = "Shadow Mapping: light" + lightIndex; 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); //Set shadowmap texture cmdShadow.DisableScissorRect(); cmdShadow.SetViewProjectionMatrices(cam.worldToCameraMatrix, cam.projectionMatrix); cmdShadow.SetGlobalTexture(m_ShadowMapLightid, m_ShadowMapLight); context.ExecuteCommandBuffer(cmdShadow); cmdShadow.Clear(); cmdShadow.Release(); //Screen Space Shadow ================================================= CommandBuffer cmdShadow2 = new CommandBuffer(); cmdShadow2.name = "Screen Space Shadow: light" + lightIndex; //Bias float sign = (SystemInfo.usesReversedZBuffer) ? 1.0f : -1.0f; float bias = light.shadowBias * proj.m22 * sign; cmdShadow2.SetGlobalFloat("_ShadowBias", bias); //Shadow Transform 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", light.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(); } } }
internal void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult, CustomPass.RenderTargets targets) { Shader.SetGlobalFloat(HDShaderIDs._CustomPassInjectionPoint, (float)injectionPoint); foreach (var pass in customPasses) { if (pass != null && pass.enabled) { using (new ProfilingSample(cmd, pass.name)) pass.ExecuteInternal(renderContext, cmd, hdCamera, cullingResult, targets); } } }
private void SetUpRealtimeLightingVariables(Camera cam, 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 SetUpRealtimeShadowVariables(cam, context, cull, light.light, i); //setup shadow } 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); }
void RenderAdditionalShadowmapAtlas(ref ScriptableRenderContext context, ref CullingResults cullResults, ref LightData lightData, ref ShadowData shadowData) { NativeArray <VisibleLight> visibleLights = lightData.visibleLights; bool additionalLightHasSoftShadows = false; CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag); using (new ProfilingScope(cmd, m_ProfilingSampler)) { bool anyShadowSliceRenderer = false; int shadowSlicesCount = m_AdditionalShadowCastingLightIndices.Count; for (int i = 0; i < shadowSlicesCount; ++i) { // we do the shadow strength check here again here because when using // the uniform array path we might have zero strength shadow lights. // In that case we need the shadow data buffer but we can skip // rendering them to shadowmap. if (!m_UseStructuredBuffer && Mathf.Approximately(m_AdditionalLightsShadowParams[i].x, 0.0f)) { continue; } // Index of the VisibleLight int shadowLightIndex = m_AdditionalShadowCastingLightIndices[i]; VisibleLight shadowLight = visibleLights[shadowLightIndex]; ShadowSliceData shadowSliceData = m_AdditionalLightSlices[i]; var settings = new ShadowDrawingSettings(cullResults, shadowLightIndex); Vector4 shadowBias = ShadowUtils.GetShadowBias(ref shadowLight, shadowLightIndex, ref shadowData, shadowSliceData.projectionMatrix, shadowSliceData.resolution); ShadowUtils.SetupShadowCasterConstantBuffer(cmd, ref shadowLight, shadowBias); ShadowUtils.RenderShadowSlice(cmd, ref context, ref shadowSliceData, ref settings); additionalLightHasSoftShadows |= shadowLight.light.shadows == LightShadows.Soft; anyShadowSliceRenderer = true; } // We share soft shadow settings for main light and additional lights to save keywords. // So we check here if pipeline supports soft shadows and either main light or any additional light has soft shadows // to enable the keyword. // TODO: In PC and Consoles we can upload shadow data per light and branch on shader. That will be more likely way faster. bool mainLightHasSoftShadows = shadowData.supportsMainLightShadows && lightData.mainLightIndex != -1 && visibleLights[lightData.mainLightIndex].light.shadows == LightShadows.Soft; bool softShadows = shadowData.supportsSoftShadows && (mainLightHasSoftShadows || additionalLightHasSoftShadows); CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.AdditionalLightShadows, anyShadowSliceRenderer); CoreUtils.SetKeyword(cmd, ShaderKeywordStrings.SoftShadows, softShadows); if (anyShadowSliceRenderer) { SetupAdditionalLightsShadowReceiverConstants(cmd, ref shadowData, softShadows); } } 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; } cullingParams.shadowDistance = Mathf.Min(m_shadowDistance, camera.farClipPlane); // shadow distance CullingResults cull = context.Cull(ref cullingParams); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings = new DrawingSettings(m_PassName, sortingSettings) { perObjectData = PerObjectData.LightIndices | PerObjectData.LightData }; DrawingSettings drawSettingsDepth = new DrawingSettings(m_passNameShadow, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Set temp RT CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; //Depth RenderTextureDescriptor depthRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); depthRTDesc.colorFormat = RenderTextureFormat.Depth; depthRTDesc.depthBufferBits = depthBufferBits; cmdTempId.GetTemporaryRT(m_DepthRTid, depthRTDesc, FilterMode.Bilinear); //Shadow RenderTextureDescriptor shadowRTDesc = new RenderTextureDescriptor(m_ShadowRes, m_ShadowRes); shadowRTDesc.colorFormat = RenderTextureFormat.Shadowmap; shadowRTDesc.depthBufferBits = depthBufferBits; //have depth because it is also a depth texture cmdTempId.GetTemporaryRT(m_ShadowMapLightid, shadowRTDesc, FilterMode.Bilinear); //depth per light //ScreenSpaceShadowMap RenderTextureDescriptor shadowMapRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); shadowMapRTDesc.colorFormat = RenderTextureFormat.Default; shadowMapRTDesc.depthBufferBits = 0; cmdTempId.GetTemporaryRT(m_ShadowMapid, shadowMapRTDesc, FilterMode.Bilinear); //screen space shadow context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Clear ScreenSpaceShadowMap Texture CommandBuffer cmdSSSMclear = new CommandBuffer(); cmdSSSMclear.name = "(" + camera.name + ")" + "Clear ScreenSpaceShadowMap"; cmdSSSMclear.SetRenderTarget(m_ShadowMap); //Set CameraTarget to the depth texture cmdSSSMclear.ClearRenderTarget(false, true, Color.white); context.ExecuteCommandBuffer(cmdSSSMclear); cmdSSSMclear.Release(); //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(); //SetUp Lighting & shadow variables SetUpRealtimeLightingVariables(camera, context, cull); //Debug ********************************************** // CommandBuffer cmdDebug = new CommandBuffer(); // cmdDebug.name = "Debug"; // cmdDebug.Blit( m_ShadowMap, BuiltinRenderTextureType.CameraTarget ); // context.ExecuteCommandBuffer(cmdDebug); // cmdDebug.Release(); // Color Rendering============================================================================ //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.SetRenderTarget(BuiltinRenderTextureType.CameraTarget); cmd.ClearRenderTarget(clearDepth, clearColor, camera.backgroundColor); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); //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); cmdclean.ReleaseTemporaryRT(m_ShadowMapLightid); cmdclean.ReleaseTemporaryRT(m_ShadowMapid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); context.Submit(); } }
public void RenderShadows(ScriptableRenderContext renderContext, CommandBuffer cmd, CullingResults cullResults, HDCamera hdCamera) { // Avoid to do any commands if there is no shadow to draw if (m_ShadowRequestCount == 0) { return; } // TODO remove DrawShadowSettings, lightIndex and splitData when scriptable culling is available ShadowDrawingSettings dss = new ShadowDrawingSettings(cullResults, 0); dss.useRenderingLayerMaskTest = hdCamera.frameSettings.IsEnabled(FrameSettingsField.LightLayers); // Clear atlas render targets and draw shadows using (new ProfilingSample(cmd, "Punctual Lights Shadows rendering", CustomSamplerId.RenderShadows.GetSampler())) { m_Atlas.RenderShadows(renderContext, cmd, dss); } using (new ProfilingSample(cmd, "Directional Light Shadows rendering", CustomSamplerId.RenderShadows.GetSampler())) { m_CascadeAtlas.RenderShadows(renderContext, cmd, dss); } using (new ProfilingSample(cmd, "Area Light Shadows rendering", CustomSamplerId.RenderShadows.GetSampler())) { m_AreaLightShadowAtlas.RenderShadows(renderContext, cmd, dss); if (m_AreaLightShadowAtlas.HasBlurredEVSM()) { m_AreaLightShadowAtlas.AreaShadowBlurMoments(cmd, hdCamera); } } // If the shadow algorithm is the improved moment shadow if (GetDirectionalShadowAlgorithm() == DirectionalShadowAlgorithm.IMS) { m_CascadeAtlas.ComputeMomentShadows(cmd, hdCamera); } }
protected abstract void ExecutePass( ScriptableRenderContext renderContext, CommandBuffer cmd, Camera camera, CullingResults cullingResult);
protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult) { if (blurMaterial == null) { Debug.LogError("Failed to load Liquid Pass Shaders"); return; } var result = new RendererListDesc(shaderTags, cullingResult, hdCamera.camera) { rendererConfiguration = PerObjectData.None, renderQueueRange = RenderQueueRange.all, sortingCriteria = SortingCriteria.BackToFront, excludeObjectMotionVectors = false, layerMask = layerMask.value, }; // Render objects into the custom buffer: HDUtils.DrawRendererList(renderContext, cmd, RendererList.Create(result)); // Blur the custom buffer: BlurCustomBuffer(cmd, hdCamera); // Composite the result into the camera color buffer SetCameraRenderTarget(cmd); int pass = transparentFullscreenShader.FindPass("Forward"); if (pass == -1) { pass = transparentFullscreenShader.FindPass("ForwardOnly"); } CoreUtils.DrawFullScreen(cmd, blurMaterial, pass); }
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData) { if (m_rendered) { // in case of multipass VR, render pass will be called twice even if renderPassEvent == RenderPassEvent.BeforeRendering... return; } CommandBuffer cmd = CommandBufferPool.Get(); cmd.SetViewProjectionMatrices(m_renderer.projectorCamera.worldToCameraMatrix, m_renderer.projectorCamera.projectionMatrix); context.ExecuteCommandBuffer(cmd); CommandBufferPool.Release(cmd); DrawSceneObject drawScene = m_renderer.drawSceneObject; if (drawScene != null) { ScriptableCullingParameters cullingParameters = new ScriptableCullingParameters(); if (m_renderer.projectorCamera.TryGetCullingParameters(false, out cullingParameters)) { cullingParameters.cullingMask = (uint)drawScene.cullingMask.value; CullingResults cullingResults = context.Cull(ref cullingParameters); if (m_overrideOpaqueMaterial == null) { m_overrideOpaqueMaterial = new Material(drawScene.replacementShader); } else if (m_overrideOpaqueMaterial.shader != drawScene.replacementShader) { m_overrideOpaqueMaterial.shader = drawScene.replacementShader; } if (m_overrideAlphaCutoffMaterial == null) { m_overrideAlphaCutoffMaterial = new Material(drawScene.replacementShader); m_overrideAlphaCutoffMaterial.EnableKeyword("_ALPHATEST_ON"); m_overrideAlphaCutoffMaterial.SetFloat("_DstBlend", 10.0f); // OneMinusSrcAlpha } else if (m_overrideAlphaCutoffMaterial.shader != drawScene.replacementShader) { m_overrideAlphaCutoffMaterial.shader = drawScene.replacementShader; } if (m_overrideTransparentMaterial == null) { m_overrideTransparentMaterial = new Material(drawScene.replacementShader); m_overrideTransparentMaterial.EnableKeyword("_ALPHATEST_ON"); m_overrideTransparentMaterial.EnableKeyword("_ALPHABLEND_ON"); m_overrideTransparentMaterial.SetFloat("_SrcBlend", 5.0f); // SrcAlpha m_overrideTransparentMaterial.SetFloat("_DstBlend", 10.0f); // OneMinusSrcAlpha } else if (m_overrideTransparentMaterial.shader != drawScene.replacementShader) { m_overrideTransparentMaterial.shader = drawScene.replacementShader; } DrawingSettings drawingSettings = new DrawingSettings(drawScene.shaderTagIds[0], new SortingSettings(m_renderer.projectorCamera)); for (int i = 1; i < drawScene.shaderTagIds.Length; ++i) { drawingSettings.SetShaderPassName(i, drawScene.shaderTagIds[i]); } // draw opaque objects drawingSettings.overrideMaterial = m_overrideOpaqueMaterial; drawingSettings.overrideMaterialPassIndex = 0; drawingSettings.enableDynamicBatching = renderingData.supportsDynamicBatching; drawingSettings.enableInstancing = true; drawingSettings.perObjectData = PerObjectData.None; FilteringSettings opaqueFilteringSettings = new FilteringSettings(new RenderQueueRange(RenderQueueRange.opaque.lowerBound, 2400), drawScene.cullingMask); context.DrawRenderers(cullingResults, ref drawingSettings, ref opaqueFilteringSettings); // draw alpha-cutoff objects drawingSettings.overrideMaterial = m_overrideAlphaCutoffMaterial; FilteringSettings alphacutoutFilteringSettings = new FilteringSettings(new RenderQueueRange(2400, RenderQueueRange.opaque.upperBound), drawScene.cullingMask); context.DrawRenderers(cullingResults, ref drawingSettings, ref alphacutoutFilteringSettings); // draw transparent objects drawingSettings.overrideMaterial = m_overrideTransparentMaterial; FilteringSettings transparentFilteringSettings = new FilteringSettings(new RenderQueueRange(RenderQueueRange.transparent.lowerBound, RenderQueueRange.transparent.upperBound), drawScene.cullingMask); context.DrawRenderers(cullingResults, ref drawingSettings, ref transparentFilteringSettings); } } DrawTargetObject drawTarget = m_renderer.drawTargetObject; if (drawTarget != null) { context.ExecuteCommandBuffer(drawTarget.commandBuffer); } m_renderer.ExecutePostRenderProcess(context); m_rendered = true; }
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); } //SceneViewDrawMode #if UNITY_EDITOR bool isSceneViewCam = camera.cameraType == CameraType.SceneView; if (isSceneViewCam) { Material debugMaterial = CustomDrawModeAssetObject.GetDrawModeMaterial(); if (debugMaterial != null) { sortingSettings.criteria = SortingCriteria.None; filterSettings.renderQueueRange = RenderQueueRange.all; DrawingSettings debugSettings = new DrawingSettings(new ShaderTagId("debugMaterial"), sortingSettings) { perObjectData = PerObjectData.None, overrideMaterial = debugMaterial, overrideMaterialPassIndex = 0 }; debugSettings.SetShaderPassName(1, m_PassName); context.DrawRenderers(cull, ref debugSettings, ref filterSettings); context.Submit(); continue; } } #endif //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings, ref filterSettings); context.Submit(); EndCameraRendering(context, camera); } EndFrameRendering(context, cameras); }
public RenderLightVolumesParameters PrepareLightVolumeParameters(HDCamera hdCamera, LightingDebugSettings lightDebugSettings, CullingResults cullResults) { var parameters = new RenderLightVolumesParameters(); parameters.hdCamera = hdCamera; parameters.cullResults = cullResults; parameters.debugLightVolumeMaterial = m_DebugLightVolumeMaterial; parameters.debugLightVolumeCS = m_DebugLightVolumeCompute; parameters.debugLightVolumeKernel = lightDebugSettings.lightVolumeDebugByCategory == LightVolumeDebug.ColorAndEdge ? m_DebugLightVolumeColorsKernel : m_DebugLightVolumeGradientKernel; parameters.maxDebugLightCount = (int)lightDebugSettings.maxDebugLightCount; parameters.colorGradientTexture = m_ColorGradientTexture; return(parameters); }
void RenderTransparencyOverdraw(RenderGraph renderGraph, TextureHandle depthBuffer, CullingResults cull, HDCamera hdCamera) { if (m_CurrentDebugDisplaySettings.IsDebugDisplayEnabled() && m_CurrentDebugDisplaySettings.data.fullScreenDebugMode == FullScreenDebugMode.TransparencyOverdraw) { TextureHandle transparencyOverdrawOutput = TextureHandle.nullHandle; using (var builder = renderGraph.AddRenderPass <TransparencyOverdrawPassData>("Transparency Overdraw", out var passData)) { passData.parameters = PrepareTransparencyOverdrawParameters(hdCamera, cull); passData.output = builder.WriteTexture(renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true) { colorFormat = GetColorBufferFormat() })); passData.depthBuffer = builder.ReadTexture(depthBuffer); passData.transparencyRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparencyRL)); passData.transparencyAfterPostRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparencyAfterPostRL)); passData.transparencyLowResRL = builder.UseRendererList(renderGraph.CreateRendererList(passData.parameters.transparencyLowResRL)); builder.SetRenderFunc( (TransparencyOverdrawPassData data, RenderGraphContext ctx) => { RenderTransparencyOverdraw(data.parameters, data.output, data.depthBuffer, data.transparencyRL, data.transparencyAfterPostRL, data.transparencyLowResRL, ctx.renderContext, ctx.cmd); }); transparencyOverdrawOutput = passData.output; } PushFullScreenDebugTexture(renderGraph, transparencyOverdrawOutput, FullScreenDebugMode.TransparencyOverdraw); } }
protected override void Render(ScriptableRenderContext context, Camera[] cameras) { BeginFrameRendering(cameras); foreach (Camera camera in cameras) { BeginCameraRendering(camera); //Culling ScriptableCullingParameters cullingParams; if (!camera.TryGetCullingParameters(out cullingParams)) { continue; } CullingResults cull = context.Cull(ref cullingParams); //Camera setup some builtin variables e.g. camera projection matrices etc context.SetupCameraProperties(camera); //Get the setting from camera component bool drawSkyBox = camera.clearFlags == CameraClearFlags.Skybox? true : false; bool clearDepth = camera.clearFlags == CameraClearFlags.Nothing? false : true; bool clearColor = camera.clearFlags == CameraClearFlags.Color? true : false; //Color Texture Descriptor RenderTextureDescriptor colorRTDesc = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight); colorRTDesc.colorFormat = m_ColorFormat; colorRTDesc.depthBufferBits = depthBufferBits; colorRTDesc.sRGB = (QualitySettings.activeColorSpace == ColorSpace.Linear); colorRTDesc.msaaSamples = 1; colorRTDesc.enableRandomWrite = false; //Get Temp Texture for Color Texture CommandBuffer cmdTempId = new CommandBuffer(); cmdTempId.name = "(" + camera.name + ")" + "Setup TempRT"; cmdTempId.GetTemporaryRT(m_ColorRTid, colorRTDesc, FilterMode.Bilinear); cmdTempId.SetRenderTarget(m_ColorRT); //so that result won't flip context.ExecuteCommandBuffer(cmdTempId); cmdTempId.Release(); //Setup DrawSettings and FilterSettings var sortingSettings = new SortingSettings(camera); DrawingSettings drawSettings1 = new DrawingSettings(m_PassName1, sortingSettings); DrawingSettings drawSettings2 = new DrawingSettings(m_PassName2, sortingSettings); FilteringSettings filterSettings = new FilteringSettings(RenderQueueRange.all); //Native Arrays for Attachaments NativeArray <AttachmentDescriptor> renderPassAttachments = new NativeArray <AttachmentDescriptor>(4, Allocator.Temp); renderPassAttachments[0] = m_Albedo; renderPassAttachments[1] = m_Emission; renderPassAttachments[2] = m_Output; renderPassAttachments[3] = m_Depth; NativeArray <int> renderPassColorAttachments = new NativeArray <int>(2, Allocator.Temp); renderPassColorAttachments[0] = 0; renderPassColorAttachments[1] = 1; NativeArray <int> renderPassOutputAttachments = new NativeArray <int>(1, Allocator.Temp); renderPassOutputAttachments[0] = 2; //Clear Attachements m_Output.ConfigureTarget(m_ColorRT, false, true); m_Output.ConfigureClear(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1, 0); m_Albedo.ConfigureClear(camera.backgroundColor, 1, 0); m_Emission.ConfigureClear(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1, 0); m_Depth.ConfigureClear(new Color(), 1, 0); //More clean to use ScopedRenderPass instead of BeginRenderPass+EndRenderPass using (context.BeginScopedRenderPass(camera.pixelWidth, camera.pixelHeight, 1, renderPassAttachments, 3)) { //Output to Albedo & Emission using (context.BeginScopedSubPass(renderPassColorAttachments, false)) { //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings1.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings1, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings1.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings1, ref filterSettings); } //Read from Albedo & Emission, then output to Output using (context.BeginScopedSubPass(renderPassOutputAttachments, renderPassColorAttachments)) { //Skybox if (drawSkyBox) { context.DrawSkybox(camera); } //Opaque objects sortingSettings.criteria = SortingCriteria.CommonOpaque; drawSettings2.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.opaque; context.DrawRenderers(cull, ref drawSettings2, ref filterSettings); //Transparent objects sortingSettings.criteria = SortingCriteria.CommonTransparent; drawSettings2.sortingSettings = sortingSettings; filterSettings.renderQueueRange = RenderQueueRange.transparent; context.DrawRenderers(cull, ref drawSettings2, ref filterSettings); } } //Blit To Camera so that the CameraTarget has content and make sceneview works CommandBuffer cmd = new CommandBuffer(); cmd.name = "Cam:" + camera.name + " BlitToCamera"; cmd.Blit(m_ColorRT, BuiltinRenderTextureType.CameraTarget); context.ExecuteCommandBuffer(cmd); cmd.Release(); //CleanUp Texture CommandBuffer cmdclean = new CommandBuffer(); cmdclean.name = "(" + camera.name + ")" + "Clean Up"; cmdclean.ReleaseTemporaryRT(m_ColorRTid); context.ExecuteCommandBuffer(cmdclean); cmdclean.Release(); //Submit the CommandBuffers context.Submit(); //CleanUp NativeArrays renderPassAttachments.Dispose(); renderPassColorAttachments.Dispose(); renderPassOutputAttachments.Dispose(); } }