Esempio n. 1
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag);

            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);
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();

                Camera camera         = renderingData.cameraData.camera;
                var    sortFlags      = (m_IsOpaque) ? renderingData.cameraData.defaultOpaqueSortFlags : SortingCriteria.CommonTransparent;
                var    drawSettings   = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortFlags);
                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

                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);
        }
Esempio n. 2
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer gbufferCommands = CommandBufferPool.Get();

            using (new ProfilingScope(gbufferCommands, m_ProfilingSampler))
            {
                if (m_DeferredLights.AccurateGbufferNormals)
                {
                    gbufferCommands.EnableShaderKeyword(ShaderKeywordStrings._GBUFFER_NORMALS_OCT);
                }
                else
                {
                    gbufferCommands.DisableShaderKeyword(ShaderKeywordStrings._GBUFFER_NORMALS_OCT);
                }

                context.ExecuteCommandBuffer(gbufferCommands); // send the gbufferCommands to the scriptableRenderContext - this should be done *before* calling scriptableRenderContext.DrawRenderers
                gbufferCommands.Clear();

                DrawingSettings drawingSettings = CreateDrawingSettings(m_ShaderTagId, ref renderingData, renderingData.cameraData.defaultOpaqueSortFlags);

                ref CameraData cameraData = ref renderingData.cameraData;
                Camera         camera     = cameraData.camera;

                context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref m_FilteringSettings /*, ref m_RenderStateBlock*/);

                // Render objects that did not match any shader pass with error shader
                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, m_FilteringSettings, SortingCriteria.None);
            }
        static bool ValidateRendererGraphicsAPIsForLightLayers(UniversalRenderPipelineAsset pipelineAsset, out string unsupportedGraphicsApisMessage)
        {
            unsupportedGraphicsApisMessage = null;

            BuildTarget platform = EditorUserBuildSettings.activeBuildTarget;

            GraphicsDeviceType[] graphicsAPIs = PlayerSettings.GetGraphicsAPIs(platform);

            for (int apiIndex = 0; apiIndex < graphicsAPIs.Length; apiIndex++)
            {
                if (!RenderingUtils.SupportsLightLayers(graphicsAPIs[apiIndex]))
                {
                    if (unsupportedGraphicsApisMessage != null)
                    {
                        unsupportedGraphicsApisMessage += ", ";
                    }
                    unsupportedGraphicsApisMessage += System.String.Format("{0}", graphicsAPIs[apiIndex]);
                }
            }

            if (unsupportedGraphicsApisMessage != null)
            {
                unsupportedGraphicsApisMessage += ".";
            }

            return(unsupportedGraphicsApisMessage == null);
        }
Esempio n. 4
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            var             cameraData                 = renderingData.cameraData;
            var             cameraPosition             = cameraData.camera.transform.position;
            DrawingSettings transparentDrawingSettings = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, SortingCriteria.CommonTransparent);

            CommandBuffer cmd = CommandBufferPool.Get(ProfilerTag);

            // setup skybox cam
            {
                var viewMatrix        = cameraData.GetViewMatrix();
                var camPosition       = viewMatrix.GetColumn(3);
                var camScale          = camPosition * Scale;
                var cameraTranslation = new Vector4(camScale.x, camScale.y, camScale.z, camPosition.w);
                viewMatrix.SetColumn(3, cameraTranslation);

                RenderingUtils.SetViewAndProjectionMatrices(cmd, viewMatrix, cameraData.GetGPUProjectionMatrix(), true);
                cmd.SetGlobalVector("_WorldSpaceCameraPos", cameraPosition * Scale);
            }

            context.ExecuteCommandBuffer(cmd);
            cmd.Clear();

            //draw transparent skybox
            context.DrawRenderers(renderingData.cullResults, ref transparentDrawingSettings, ref m_TransparentFilteringSettings,
                                  ref m_RenderStateBlock);

            //return normal cam
            {
                RenderingUtils.SetViewAndProjectionMatrices(cmd, cameraData.GetViewMatrix(), cameraData.GetGPUProjectionMatrix(), true);
                cmd.SetGlobalVector("_WorldSpaceCameraPos", cameraPosition);
            }
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
Esempio n. 5
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer gbufferCommands = CommandBufferPool.Get();

            using (new ProfilingScope(gbufferCommands, m_ProfilingSampler))
            {
                // User can stack several scriptable renderers during rendering but deferred renderer should only lit pixels added by this gbuffer pass.
                // If we detect we are in such case (camera isin  overlay mode), we clear the highest bits of stencil we have control of and use them to
                // mark what pixel to shade during deferred pass. Gbuffer will always mark pixels using their material types.
                if (m_DeferredLights.IsOverlay)
                {
                    m_DeferredLights.ClearStencilPartial(gbufferCommands);
                }

                context.ExecuteCommandBuffer(gbufferCommands);
                gbufferCommands.Clear();

                ref CameraData  cameraData               = ref renderingData.cameraData;
                Camera          camera                   = cameraData.camera;
                ShaderTagId     lightModeTag             = s_ShaderTagUniversalGBuffer;
                DrawingSettings drawingSettings          = CreateDrawingSettings(lightModeTag, ref renderingData, renderingData.cameraData.defaultOpaqueSortFlags);
                ShaderTagId     universalMaterialTypeTag = s_ShaderTagUniversalMaterialType;

                NativeArray <ShaderTagId>      tagValues   = new NativeArray <ShaderTagId>(m_ShaderTagValues, Allocator.Temp);
                NativeArray <RenderStateBlock> stateBlocks = new NativeArray <RenderStateBlock>(m_RenderStateBlocks, Allocator.Temp);
                context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref m_FilteringSettings, universalMaterialTypeTag, false, tagValues, stateBlocks);
                tagValues.Dispose();
                stateBlocks.Dispose();

                // Render objects that did not match any shader pass with error shader
                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, m_FilteringSettings, SortingCriteria.None);
            }
        private void brushPatternParamsChanged()
        {
            if (_originalBrushPattern == null)
            {
                _brushPattern = null;
                return;
            }

            if (_brushPattern != null)
            {
                _brushPattern.Dispose();
            }

            _brushPattern = new Bitmap(_originalBrushPattern.Width, _originalBrushPattern.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            for (int i = 0; i < _brushPattern.Width; i++)
            {
                for (int j = 0; j < _brushPattern.Height; j++)
                {
                    Color c = _originalBrushPattern.GetPixel(i, j);

                    Color blendedColor =
                        Color.FromArgb(
                            RenderingUtils.BlendPixels(_fillBackColor.ToArgb(), Color.FromArgb(255 - c.R, _fillForeColor).ToArgb()));

                    _brushPattern.SetPixel(i, j, blendedColor);
                }
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Configure the pass
        /// </summary>
        public void Setup(RenderTextureDescriptor baseDescriptor, RenderTargetHandle depthHandle, RenderTargetHandle normalHandle)
        {
            // Find compatible render-target format for storing normals.
            // Shader code outputs normals in signed format to be compatible with deferred gbuffer layout.
            // Deferred gbuffer format is signed so that normals can be blended for terrain geometry.
            GraphicsFormat normalsFormat;

            if (RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R8G8B8A8_SNorm, FormatUsage.Render))
            {
                normalsFormat = GraphicsFormat.R8G8B8A8_SNorm; // Preferred format
            }
            else if (RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R16G16B16A16_SFloat, FormatUsage.Render))
            {
                normalsFormat = GraphicsFormat.R16G16B16A16_SFloat; // fallback
            }
            else
            {
                normalsFormat = GraphicsFormat.R32G32B32A32_SFloat; // fallback
            }
            this.depthHandle               = depthHandle;
            baseDescriptor.colorFormat     = RenderTextureFormat.Depth;
            baseDescriptor.depthBufferBits = k_DepthBufferBits;
            baseDescriptor.msaaSamples     = 1;// Depth-Only pass don't use MSAA
            depthDescriptor = baseDescriptor;

            this.normalHandle              = normalHandle;
            baseDescriptor.graphicsFormat  = normalsFormat;
            baseDescriptor.depthBufferBits = 0;
            baseDescriptor.msaaSamples     = 1;
            normalDescriptor = baseDescriptor;

            this.allocateDepth  = true;
            this.allocateNormal = true;
            this.shaderTagId    = k_ShaderTagId;
        }
Esempio n. 8
0
        public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
        {
            RTHandle[] gbufferAttachments = m_DeferredLights.GbufferAttachments;

            if (cmd != null)
            {
                var allocateGbufferDepth = true;
                if (m_DeferredLights.UseRenderPass && (m_DeferredLights.DepthCopyTexture != null && m_DeferredLights.DepthCopyTexture.rt != null))
                {
                    m_DeferredLights.GbufferAttachments[m_DeferredLights.GbufferDepthIndex] = m_DeferredLights.DepthCopyTexture;
                    allocateGbufferDepth = false;
                }
                // Create and declare the render targets used in the pass
                for (int i = 0; i < gbufferAttachments.Length; ++i)
                {
                    // Lighting buffer has already been declared with line ConfigureCameraTarget(m_ActiveCameraColorAttachment.Identifier(), ...) in DeferredRenderer.Setup
                    if (i == m_DeferredLights.GBufferLightingIndex)
                    {
                        continue;
                    }

                    // Normal buffer may have already been created if there was a depthNormal prepass before.
                    // DepthNormal prepass is needed for forward-only materials when SSAO is generated between gbuffer and deferred lighting pass.
                    if (i == m_DeferredLights.GBufferNormalSmoothnessIndex && m_DeferredLights.HasNormalPrepass)
                    {
                        continue;
                    }

                    if (i == m_DeferredLights.GbufferDepthIndex && !allocateGbufferDepth)
                    {
                        continue;
                    }

                    // No need to setup temporaryRTs if we are using input attachments as they will be Memoryless
                    if (m_DeferredLights.UseRenderPass && i != m_DeferredLights.GBufferShadowMask && i != m_DeferredLights.GBufferRenderingLayers && (i != m_DeferredLights.GbufferDepthIndex && !m_DeferredLights.HasDepthPrepass))
                    {
                        continue;
                    }

                    RenderTextureDescriptor gbufferSlice = cameraTextureDescriptor;
                    gbufferSlice.depthBufferBits = 0; // make sure no depth surface is actually created
                    gbufferSlice.stencilFormat   = GraphicsFormat.None;
                    gbufferSlice.graphicsFormat  = m_DeferredLights.GetGBufferFormat(i);
                    RenderingUtils.ReAllocateIfNeeded(ref m_DeferredLights.GbufferAttachments[i], gbufferSlice, FilterMode.Point, TextureWrapMode.Clamp, name: DeferredLights.k_GBufferNames[i]);
                    cmd.SetGlobalTexture(m_DeferredLights.GbufferAttachments[i].name, m_DeferredLights.GbufferAttachments[i].nameID);
                }
            }

            if (m_DeferredLights.UseRenderPass)
            {
                m_DeferredLights.UpdateDeferredInputAttachments();
            }

            ConfigureTarget(m_DeferredLights.GbufferAttachments, m_DeferredLights.DepthAttachment, m_DeferredLights.GbufferFormats);

            // We must explicitly specify we don't want any clear to avoid unwanted side-effects.
            // ScriptableRenderer will implicitly force a clear the first time the camera color/depth targets are bound.
            ConfigureClear(ClearFlag.None, Color.black);
        }
 public void Setup(RenderTextureDescriptor baseDescriptor)
 {
     m_RenderTextureDescriptor = baseDescriptor;
     m_RenderTextureDescriptor.depthBufferBits = 0;
     m_RenderTextureDescriptor.msaaSamples     = 1;
     m_RenderTextureDescriptor.colorFormat     = RenderingUtils.SupportsRenderTextureFormat(RenderTextureFormat.R8)
         ? RenderTextureFormat.R8
         : RenderTextureFormat.ARGB32;
 }
Esempio n. 10
0
 public void Setup(RenderTextureDescriptor baseDescriptor)
 {
     m_RenderTextureDescriptor = baseDescriptor;
     m_RenderTextureDescriptor.depthBufferBits = 0;
     m_RenderTextureDescriptor.msaaSamples     = 1;
     m_RenderTextureDescriptor.graphicsFormat  = RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R8_UNorm, FormatUsage.Linear | FormatUsage.Render)
         ? GraphicsFormat.R8_UNorm
         : GraphicsFormat.B8G8R8A8_UNorm;
 }
Esempio n. 11
0
        bool CanCopyDepth(ref CameraData cameraData)
        {
            bool msaaEnabledForCamera = cameraData.cameraTargetDescriptor.msaaSamples > 1;
            bool supportsTextureCopy  = SystemInfo.copyTextureSupport != CopyTextureSupport.None;
            bool supportsDepthTarget  = RenderingUtils.SupportsRenderTextureFormat(RenderTextureFormat.Depth);
            bool supportsDepthCopy    = !msaaEnabledForCamera && (supportsDepthTarget || supportsTextureCopy);

            // TODO:  We don't have support to highp Texture2DMS currently and this breaks depth precision.
            // currently disabling it until shader changes kick in.
            //bool msaaDepthResolve = msaaEnabledForCamera && SystemInfo.supportsMultisampledTextures != 0;
            bool msaaDepthResolve = false;

            return(supportsDepthCopy || msaaDepthResolve);
        }
Esempio n. 12
0
        private void CopyCameraSortingLayerRenderTexture(ScriptableRenderContext context, RenderingData renderingData)
        {
            var cmd = CommandBufferPool.Get();

            cmd.Clear();
            this.CreateCameraSortingLayerRenderTexture(renderingData, cmd, m_Renderer2DData.cameraSortingLayerDownsamplingMethod);

            Material copyMaterial = m_Renderer2DData.cameraSortingLayerDownsamplingMethod == Downsampling._4xBox ? m_SamplingMaterial : m_BlitMaterial;

            RenderingUtils.Blit(cmd, colorAttachment, m_Renderer2DData.cameraSortingLayerRenderTarget.id, copyMaterial, 0, false, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.DontCare);
            cmd.SetRenderTarget(colorAttachment);
            cmd.SetGlobalTexture(k_CameraSortingLayerTextureID, m_Renderer2DData.cameraSortingLayerRenderTarget.id);
            context.ExecuteCommandBuffer(cmd);
        }
Esempio n. 13
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            bool isLitView = true;

#if UNITY_EDITOR
            if (renderingData.cameraData.isSceneViewCamera)
            {
                isLitView = UnityEditor.SceneView.currentDrawingSceneView.sceneLighting;
            }

            if (renderingData.cameraData.camera.cameraType == CameraType.Preview)
            {
                isLitView = false;
            }

            if (!Application.isPlaying)
            {
                s_SortingLayers = SortingLayer.layers;
            }
#endif
            Camera camera = renderingData.cameraData.camera;

            FilteringSettings filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;


            CommandBuffer   cmd = CommandBufferPool.Get("RenderFeature Unlit");
            DrawingSettings unlitDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);

            CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
            cmd.SetGlobalTexture("_ShapeLightTexture0", Texture2D.blackTexture);
            cmd.SetGlobalTexture("_ShapeLightTexture1", Texture2D.blackTexture);
            cmd.SetGlobalTexture("_ShapeLightTexture2", Texture2D.blackTexture);
            cmd.SetGlobalTexture("_ShapeLightTexture3", Texture2D.blackTexture);
            cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f);
            cmd.SetGlobalColor("_RendererColor", Color.white);
            cmd.EnableShaderKeyword("USE_SHAPE_LIGHT_TYPE_0");
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);

            Profiler.BeginSample("RenderFeature Unlit");
            context.DrawRenderers(renderingData.cullResults, ref unlitDrawSettings, ref filterSettings);
            Profiler.EndSample();

            RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
        }
Esempio n. 14
0
 internal static GraphicsFormat GetGraphicsFormat()
 {
     if (RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R8G8B8A8_SNorm, FormatUsage.Render))
     {
         return(GraphicsFormat.R8G8B8A8_SNorm); // Preferred format
     }
     else if (RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R16G16B16A16_SFloat, FormatUsage.Render))
     {
         return(GraphicsFormat.R16G16B16A16_SFloat); // fallback
     }
     else
     {
         return(GraphicsFormat.R32G32B32A32_SFloat); // fallback
     }
 }
Esempio n. 15
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            if (m_SamplingMaterial == null)
            {
                Debug.LogErrorFormat("Missing {0}. {1} render pass will not execute. Check for missing reference in the renderer resources.", m_SamplingMaterial, GetType().Name);
                return;
            }

            CommandBuffer cmd = CommandBufferPool.Get();

            //It is possible that the given color target is now the frontbuffer
            if (source == renderingData.cameraData.renderer.GetCameraColorFrontBuffer(cmd))
            {
                source = renderingData.cameraData.renderer.cameraColorTarget;
            }

            using (new ProfilingScope(cmd, ProfilingSampler.Get(URPProfileId.CopyColor)))
            {
                RenderTargetIdentifier opaqueColorRT = destination.Identifier();

                ScriptableRenderer.SetRenderTarget(cmd, opaqueColorRT, BuiltinRenderTextureType.CameraTarget, clearFlag,
                                                   clearColor);

                bool useDrawProceduleBlit = renderingData.cameraData.xr.enabled;
                switch (m_DownsamplingMethod)
                {
                case Downsampling.None:
                    RenderingUtils.Blit(cmd, source, opaqueColorRT, m_CopyColorMaterial, 0, useDrawProceduleBlit);
                    break;

                case Downsampling._2xBilinear:
                    RenderingUtils.Blit(cmd, source, opaqueColorRT, m_CopyColorMaterial, 0, useDrawProceduleBlit);
                    break;

                case Downsampling._4xBox:
                    m_SamplingMaterial.SetFloat(m_SampleOffsetShaderHandle, 2);
                    RenderingUtils.Blit(cmd, source, opaqueColorRT, m_SamplingMaterial, 0, useDrawProceduleBlit);
                    break;

                case Downsampling._4xBilinear:
                    RenderingUtils.Blit(cmd, source, opaqueColorRT, m_CopyColorMaterial, 0, useDrawProceduleBlit);
                    break;
                }
            }

            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
Esempio n. 16
0
        /// <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    drawSettings   = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortFlags);
                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

                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);
        }
Esempio n. 17
0
        public void Setup(RenderTextureDescriptor baseDescriptor)
        {
            m_RenderTextureDescriptor = baseDescriptor;
            m_RenderTextureDescriptor.depthBufferBits = 0;
            m_RenderTextureDescriptor.msaaSamples     = 1;

            // PWRD* majiao, 使用RG16格式,g通道存储 Distance Shadowmaskģ 模式时Shadowmask的范围 //
            //m_RenderTextureDescriptor.colorFormat = RenderingUtils.SupportsRenderTextureFormat(RenderTextureFormat.R8)
            //? RenderTextureFormat.R8
            //: RenderTextureFormat.ARGB32;

            m_RenderTextureDescriptor.colorFormat = RenderingUtils.SupportsRenderTextureFormat(RenderTextureFormat.RG16)
                ? RenderTextureFormat.RG16
                : RenderTextureFormat.ARGB32;
            // PWRD* majiao //
        }
Esempio n. 18
0
        /// <inheritdoc/>
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer cmd = CommandBufferPool.Get(m_ProfilerTag);

            using (new ProfilingScope(cmd, m_ProfilingSampler))
            {
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();

                Camera camera       = renderingData.cameraData.camera;
                var    sortFlags    = (m_IsOpaque) ? renderingData.cameraData.defaultOpaqueSortFlags : SortingCriteria.CommonTransparent;
                var    drawSettings = CreateDrawingSettings(m_ShaderTagIdList, ref renderingData, sortFlags);
                context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref m_FilteringSettings, ref m_RenderStateBlock);

                // Render objects that did not match any shader pass with error shader
                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, m_FilteringSettings, SortingCriteria.None);
            }
            context.ExecuteCommandBuffer(cmd);
            CommandBufferPool.Release(cmd);
        }
Esempio n. 19
0
        public static RenderTextureDescriptor CreateRenderTextureDescriptor(Camera camera, float renderScale,
                                                                            bool isStereoEnabled, bool isHdrEnabled, int msaaSamples, bool needsAlpha)
        {
            RenderTextureDescriptor desc;
            RenderTextureFormat     renderTextureFormatDefault = RenderTextureFormat.Default;

            if (isStereoEnabled)
            {
                desc = XRGraphics.eyeTextureDesc;
                renderTextureFormatDefault = desc.colorFormat;
            }
            else
            {
                desc        = new RenderTextureDescriptor(camera.pixelWidth, camera.pixelHeight);
                desc.width  = (int)((float)desc.width * renderScale);
                desc.height = (int)((float)desc.height * renderScale);
            }

            bool use32BitHDR = !needsAlpha && RenderingUtils.SupportsRenderTextureFormat(RenderTextureFormat.RGB111110Float);
            RenderTextureFormat hdrFormat = (use32BitHDR) ? RenderTextureFormat.RGB111110Float : RenderTextureFormat.DefaultHDR;

            if (camera.targetTexture != null)
            {
                desc.colorFormat     = camera.targetTexture.descriptor.colorFormat;
                desc.depthBufferBits = camera.targetTexture.descriptor.depthBufferBits;
                desc.msaaSamples     = camera.targetTexture.descriptor.msaaSamples;
                desc.sRGB            = camera.targetTexture.descriptor.sRGB;
            }
            else
            {
                desc.colorFormat     = isHdrEnabled ? hdrFormat : renderTextureFormatDefault;
                desc.depthBufferBits = 32;
                desc.msaaSamples     = msaaSamples;
                desc.sRGB            = (QualitySettings.activeColorSpace == ColorSpace.Linear);
            }

            desc.enableRandomWrite = false;
            desc.bindMS            = false;
            desc.useDynamicScale   = camera.allowDynamicResolution;
            return(desc);
        }
Esempio n. 20
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            CommandBuffer gbufferCommands = CommandBufferPool.Get();

            using (new ProfilingScope(gbufferCommands, m_ProfilingSampler))
            {
                context.ExecuteCommandBuffer(gbufferCommands);
                gbufferCommands.Clear();

                if (m_DeferredLights.AccurateGbufferNormals)
                {
                    gbufferCommands.EnableShaderKeyword(ShaderKeywordStrings._GBUFFER_NORMALS_OCT);
                }
                else
                {
                    gbufferCommands.DisableShaderKeyword(ShaderKeywordStrings._GBUFFER_NORMALS_OCT);
                }

                context.ExecuteCommandBuffer(gbufferCommands); // send the gbufferCommands to the scriptableRenderContext - this should be done *before* calling scriptableRenderContext.DrawRenderers
                gbufferCommands.Clear();

                ref CameraData  cameraData               = ref renderingData.cameraData;
                Camera          camera                   = cameraData.camera;
                ShaderTagId     lightModeTag             = s_ShaderTagUniversalGBuffer;
                DrawingSettings drawingSettings          = CreateDrawingSettings(lightModeTag, ref renderingData, renderingData.cameraData.defaultOpaqueSortFlags);
                ShaderTagId     universalMaterialTypeTag = s_ShaderTagUniversalMaterialType;

                NativeArray <ShaderTagId>      tagValues   = new NativeArray <ShaderTagId>(m_ShaderTagValues, Allocator.Temp);
                NativeArray <RenderStateBlock> stateBlocks = new NativeArray <RenderStateBlock>(m_RenderStateBlocks, Allocator.Temp);
                context.DrawRenderers(renderingData.cullResults, ref drawingSettings, ref m_FilteringSettings, universalMaterialTypeTag, false, tagValues, stateBlocks);
                tagValues.Dispose();
                stateBlocks.Dispose();

                // Render objects that did not match any shader pass with error shader
                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, m_FilteringSettings, SortingCriteria.None);
            }
Esempio n. 21
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            bool isLitView = true;

#if UNITY_EDITOR
            if (renderingData.cameraData.isSceneViewCamera)
            {
                isLitView = UnityEditor.SceneView.currentDrawingSceneView.sceneLighting;
            }

            if (renderingData.cameraData.camera.cameraType == CameraType.Preview)
            {
                isLitView = false;
            }

            if (!Application.isPlaying)
            {
                s_SortingLayers = SortingLayer.layers;
            }
#endif
            Camera camera = renderingData.cameraData.camera;

            FilteringSettings filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;


            bool isSceneLit = Light2D.IsSceneLit(camera);
            if (isSceneLit)
            {
                RendererLighting.Setup(renderingData, m_Renderer2DData);

                CommandBuffer cmd = CommandBufferPool.Get();
                cmd.Clear();

                using (new ProfilingScope(cmd, m_ProfilingSampler))
                {
                    RendererLighting.CreateNormalMapRenderTexture(cmd);

                    cmd.SetGlobalFloat("_HDREmulationScale", m_Renderer2DData.hdrEmulationScale);
                    cmd.SetGlobalFloat("_InverseHDREmulationScale", 1.0f / m_Renderer2DData.hdrEmulationScale);
                    cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f);
                    cmd.SetGlobalColor("_RendererColor", Color.white);
                    RendererLighting.SetShapeLightShaderGlobals(cmd);

                    context.ExecuteCommandBuffer(cmd);

                    DrawingSettings combinedDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);
                    DrawingSettings normalsDrawSettings  = CreateDrawingSettings(k_NormalsRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent);

                    SortingSettings sortSettings = combinedDrawSettings.sortingSettings;
                    GetTransparencySortingMode(camera, ref sortSettings);
                    combinedDrawSettings.sortingSettings = sortSettings;
                    normalsDrawSettings.sortingSettings  = sortSettings;

                    for (int i = 0; i < m_BlendStyleInitialized.Length; ++i)
                    {
                        m_BlendStyleInitialized[i] = false;
                    }

                    for (int i = 0; i < s_SortingLayers.Length; i++)
                    {
                        // Some renderers override their sorting layer value with short.MinValue or short.MaxValue.
                        // When drawing the first sorting layer, we should include the range from short.MinValue to layerValue.
                        // Similarly, when drawing the last sorting layer, include the range from layerValue to short.MaxValue.
                        short layerValue = (short)s_SortingLayers[i].value;
                        var   lowerBound = (i == 0) ? short.MinValue : layerValue;
                        var   upperBound = (i == s_SortingLayers.Length - 1) ? short.MaxValue : layerValue;
                        filterSettings.sortingLayerRange = new SortingLayerRange(lowerBound, upperBound);

                        int layerToRender = s_SortingLayers[i].id;

                        Light2D.LightStats lightStats;
                        lightStats = Light2D.GetLightStatsByLayer(layerToRender, camera);

                        cmd.Clear();
                        for (int blendStyleIndex = 0; blendStyleIndex < k_BlendStylesCount; blendStyleIndex++)
                        {
                            uint blendStyleMask = (uint)(1 << blendStyleIndex);
                            bool blendStyleUsed = (lightStats.blendStylesUsed & blendStyleMask) > 0;

                            if (blendStyleUsed && !m_BlendStyleInitialized[blendStyleIndex])
                            {
                                RendererLighting.CreateBlendStyleRenderTexture(cmd, blendStyleIndex);
                                m_BlendStyleInitialized[blendStyleIndex] = true;
                            }

                            RendererLighting.EnableBlendStyle(cmd, blendStyleIndex, blendStyleUsed);
                        }

                        context.ExecuteCommandBuffer(cmd);

                        // Start Rendering
                        if (lightStats.totalNormalMapUsage > 0)
                        {
                            RendererLighting.RenderNormals(context, renderingData.cullResults, normalsDrawSettings,
                                                           filterSettings, depthAttachment);
                        }

                        cmd.Clear();
                        if (lightStats.totalLights > 0)
                        {
                            RendererLighting.RenderLights(camera, cmd, layerToRender, lightStats.blendStylesUsed);
                        }
                        else
                        {
                            RendererLighting.ClearDirtyLighting(cmd, lightStats.blendStylesUsed);
                        }

                        CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
                        context.ExecuteCommandBuffer(cmd);

                        Profiler.BeginSample("RenderSpritesWithLighting - Draw Transparent Renderers");
                        context.DrawRenderers(renderingData.cullResults, ref combinedDrawSettings, ref filterSettings);
                        Profiler.EndSample();

                        if (lightStats.totalVolumetricUsage > 0)
                        {
                            cmd.Clear();
                            RendererLighting.RenderLightVolumes(camera, cmd, layerToRender, colorAttachment,
                                                                depthAttachment, lightStats.blendStylesUsed);
                            context.ExecuteCommandBuffer(cmd);
                            cmd.Clear();
                        }
                    }

                    cmd.Clear();
                    Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures");
                    RendererLighting.ReleaseRenderTextures(cmd);
                    Profiler.EndSample();
                }

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

                filterSettings.sortingLayerRange = SortingLayerRange.all;
                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
            }
            else
            {
                DrawingSettings unlitDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData,
                                                                          SortingCriteria.CommonTransparent);

                CommandBuffer cmd = CommandBufferPool.Get();
                using (new ProfilingScope(cmd, m_ProfilingSamplerUnlit))
                {
                    CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
                    cmd.SetGlobalTexture("_ShapeLightTexture0", Texture2D.blackTexture);
                    cmd.SetGlobalTexture("_ShapeLightTexture1", Texture2D.blackTexture);
                    cmd.SetGlobalTexture("_ShapeLightTexture2", Texture2D.blackTexture);
                    cmd.SetGlobalTexture("_ShapeLightTexture3", Texture2D.blackTexture);
                    cmd.SetGlobalFloat("_UseSceneLighting", isLitView ? 1.0f : 0.0f);
                    cmd.SetGlobalColor("_RendererColor", Color.white);
                    cmd.EnableShaderKeyword("USE_SHAPE_LIGHT_TYPE_0");
                }

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

                Profiler.BeginSample("Render Sprites Unlit");
                context.DrawRenderers(renderingData.cullResults, ref unlitDrawSettings, ref filterSettings);
                Profiler.EndSample();

                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
            }
        }
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                s_SortingLayers = SortingLayer.layers;
            }
#endif
            Camera camera = renderingData.cameraData.camera;
            RendererLighting.Setup(m_RendererData);

            CommandBuffer cmd = CommandBufferPool.Get("Render 2D Lighting");

            Profiler.BeginSample("RenderSpritesWithLighting - Create Render Textures");
            RendererLighting.CreateRenderTextures(cmd, camera);
            Profiler.EndSample();

            cmd.SetGlobalFloat("_LightIntensityScale", m_RendererData.lightIntensityScale);
            cmd.SetGlobalFloat("_InverseLightIntensityScale", 1.0f / m_RendererData.lightIntensityScale);
            RendererLighting.SetShapeLightShaderGlobals(cmd);

            context.ExecuteCommandBuffer(cmd);

            Profiler.BeginSample("RenderSpritesWithLighting - Prepare");
            DrawingSettings drawSettings = CreateDrawingSettings(k_CombinedRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent);

            FilteringSettings filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;
            Profiler.EndSample();

            bool cleared = false;
            for (int i = 0; i < s_SortingLayers.Length; i++)
            {
                short layerValue = (short)s_SortingLayers[i].value;
                filterSettings.sortingLayerRange = new SortingLayerRange(layerValue, layerValue);

                RendererLighting.RenderNormals(context, renderingData.cullResults, drawSettings, filterSettings);

                cmd.Clear();
                int layerToRender = s_SortingLayers[i].id;
                RendererLighting.RenderLights(camera, cmd, layerToRender);

                // This should have an optimization where I can determine if this needs to be called.
                // And the clear is only needed if no previous pass has cleared the camera RT yet.
                var clearFlag  = cleared ? ClearFlag.None : ClearFlag.All;
                var clearColor = renderingData.cameraData.camera.backgroundColor;
                cleared = true;
                SetRenderTarget(cmd, BuiltinRenderTextureType.CameraTarget, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, clearFlag, clearColor, TextureDimension.Tex2D);

                context.ExecuteCommandBuffer(cmd);

                Profiler.BeginSample("RenderSpritesWithLighting - Draw Renderers");
                context.DrawRenderers(renderingData.cullResults, ref drawSettings, ref filterSettings);
                Profiler.EndSample();

                cmd.Clear();
                RendererLighting.RenderLightVolumes(camera, cmd, layerToRender);
                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();
            }

            Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures");
            RendererLighting.ReleaseRenderTextures(cmd);
            Profiler.EndSample();

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

            filterSettings.sortingLayerRange = SortingLayerRange.all;
            RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
        }
Esempio n. 23
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                s_SortingLayers = SortingLayer.layers;
            }
#endif
            Camera camera = renderingData.cameraData.camera;
            RendererLighting.Setup(m_RendererData);

            CommandBuffer cmd = CommandBufferPool.Get("Render 2D Lighting");
            cmd.Clear();

            Profiler.BeginSample("RenderSpritesWithLighting - Create Render Textures");
            RendererLighting.CreateRenderTextures(cmd, camera);
            Profiler.EndSample();

            cmd.SetGlobalFloat("_HDREmulationScale", m_RendererData.hdrEmulationScale);
            cmd.SetGlobalFloat("_InverseHDREmulationScale", 1.0f / m_RendererData.hdrEmulationScale);
            RendererLighting.SetShapeLightShaderGlobals(cmd);

            context.ExecuteCommandBuffer(cmd);

            Profiler.BeginSample("RenderSpritesWithLighting - Prepare");
            DrawingSettings combinedDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);
            DrawingSettings normalsDrawSettings  = CreateDrawingSettings(k_NormalsRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent);

            FilteringSettings filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;
            Profiler.EndSample();

            for (int i = 0; i < s_SortingLayers.Length; i++)
            {
                // The canvas renderer overrides its sorting layer value with short.MaxValue in the editor.
                // When drawing the last sorting layer, include the range from layerValue to short.MaxValue
                // so that UI can be rendered in the scene view.
                short layerValue = (short)s_SortingLayers[i].value;
                var   upperBound = (i == s_SortingLayers.Length - 1) ? short.MaxValue : layerValue;
                filterSettings.sortingLayerRange = new SortingLayerRange(layerValue, upperBound);

                int layerToRender = s_SortingLayers[i].id;

                Light2D.LightStats lightStats;
                lightStats = Light2D.GetLightStatsByLayer(layerToRender);

                if (lightStats.totalNormalMapUsage > 0)
                {
                    RendererLighting.RenderNormals(context, renderingData.cullResults, normalsDrawSettings, filterSettings);
                }

                cmd.Clear();
                if (lightStats.totalLights > 0)
                {
#if UNITY_EDITOR
                    cmd.name = "Render Lights - " + SortingLayer.IDToName(layerToRender);
#endif
                    RendererLighting.RenderLights(camera, cmd, layerToRender);
                }
                else
                {
                    RendererLighting.ClearDirtyLighting(cmd);
                }

                CoreUtils.SetRenderTarget(cmd, colorAttachment, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, ClearFlag.None, Color.white);
                context.ExecuteCommandBuffer(cmd);

                Profiler.BeginSample("RenderSpritesWithLighting - Draw Transparent Renderers");
                context.DrawRenderers(renderingData.cullResults, ref combinedDrawSettings, ref filterSettings);
                Profiler.EndSample();

                if (lightStats.totalVolumetricUsage > 0)
                {
                    cmd.Clear();
#if UNITY_EDITOR
                    cmd.name = "Render Light Volumes" + SortingLayer.IDToName(layerToRender);
#endif
                    RendererLighting.RenderLightVolumes(camera, cmd, layerToRender);
                    context.ExecuteCommandBuffer(cmd);
                    cmd.Clear();
                }
            }

            cmd.Clear();
            Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures");
            RendererLighting.ReleaseRenderTextures(cmd);
            Profiler.EndSample();

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

            filterSettings.sortingLayerRange = SortingLayerRange.all;
            RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
        }
Esempio n. 24
0
        private static Texture2D CreatePointLightLookupTexture()
        {
            const int WIDTH  = 256;
            const int HEIGHT = 256;

            var textureFormat = GraphicsFormat.R8G8B8A8_UNorm;

            if (RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R16G16B16A16_SFloat, FormatUsage.SetPixels))
            {
                textureFormat = GraphicsFormat.R16G16B16A16_SFloat;
            }
            else if (RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R32G32B32A32_SFloat, FormatUsage.SetPixels))
            {
                textureFormat = GraphicsFormat.R32G32B32A32_SFloat;
            }

            var texture = new Texture2D(WIDTH, HEIGHT, textureFormat, TextureCreationFlags.None);

            texture.filterMode = FilterMode.Bilinear;
            texture.wrapMode   = TextureWrapMode.Clamp;
            var center = new Vector2(WIDTH / 2.0f, HEIGHT / 2.0f);

            for (var y = 0; y < HEIGHT; y++)
            {
                for (var x = 0; x < WIDTH; x++)
                {
                    var pos       = new Vector2(x, y);
                    var distance  = Vector2.Distance(pos, center);
                    var relPos    = pos - center;
                    var direction = center - pos;
                    direction.Normalize();

                    // red   = 1-0 distance
                    // green  = 1-0 angle
                    // blue = direction.x
                    // alpha = direction.y

                    float red;
                    if (x == WIDTH - 1 || y == HEIGHT - 1)
                    {
                        red = 0;
                    }
                    else
                    {
                        red = Mathf.Clamp(1 - (2.0f * distance / WIDTH), 0.0f, 1.0f);
                    }

                    var cosAngle = Vector2.Dot(Vector2.down, relPos.normalized);
                    var angle    = Mathf.Acos(cosAngle) / Mathf.PI; // 0-1

                    var green = Mathf.Clamp(1 - angle, 0.0f, 1.0f);
                    var blue  = direction.x;
                    var alpha = direction.y;

                    var color = new Color(red, green, blue, alpha);

                    texture.SetPixel(x, y, color);
                }
            }
            texture.Apply();
            return(texture);
        }
Esempio n. 25
0
        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            var isLitView = true;

#if UNITY_EDITOR
            if (renderingData.cameraData.isSceneViewCamera)
            {
                isLitView = UnityEditor.SceneView.currentDrawingSceneView.sceneLighting;
            }

            if (renderingData.cameraData.camera.cameraType == CameraType.Preview)
            {
                isLitView = false;
            }
#endif
            var cachedSortingLayers = Light2DManager.GetCachedSortingLayer();
            var camera = renderingData.cameraData.camera;

            var filterSettings = new FilteringSettings();
            filterSettings.renderQueueRange   = RenderQueueRange.all;
            filterSettings.layerMask          = -1;
            filterSettings.renderingLayerMask = 0xFFFFFFFF;
            filterSettings.sortingLayerRange  = SortingLayerRange.all;

            var isSceneLit = m_Renderer2DData.lightCullResult.IsSceneLit();
            if (isSceneLit)
            {
                var cmd = CommandBufferPool.Get();
                cmd.Clear();

                using (new ProfilingScope(cmd, m_ProfilingSampler))
                {
                    this.CreateNormalMapRenderTexture(renderingData, cmd);

                    cmd.SetGlobalFloat(k_HDREmulationScaleID, m_Renderer2DData.hdrEmulationScale);
                    cmd.SetGlobalFloat(k_InverseHDREmulationScaleID, 1.0f / m_Renderer2DData.hdrEmulationScale);
                    cmd.SetGlobalFloat(k_UseSceneLightingID, isLitView ? 1.0f : 0.0f);
                    cmd.SetGlobalColor(k_RendererColorID, Color.white);
                    this.SetShapeLightShaderGlobals(cmd);

                    context.ExecuteCommandBuffer(cmd);

                    var combinedDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);
                    var normalsDrawSettings  = CreateDrawingSettings(k_NormalsRenderingPassName, ref renderingData, SortingCriteria.CommonTransparent);

                    var sortSettings = combinedDrawSettings.sortingSettings;
                    GetTransparencySortingMode(camera, ref sortSettings);
                    combinedDrawSettings.sortingSettings = sortSettings;
                    normalsDrawSettings.sortingSettings  = sortSettings;

                    var blendStylesCount = m_Renderer2DData.lightBlendStyles.Length;
                    for (var i = 0; i < cachedSortingLayers.Length;)
                    {
                        var layerToRender = cachedSortingLayers[i].id;
                        var lightStats    = m_Renderer2DData.lightCullResult.GetLightStatsByLayer(layerToRender);

                        cmd.Clear();
                        for (var blendStyleIndex = 0; blendStyleIndex < blendStylesCount; blendStyleIndex++)
                        {
                            var blendStyleMask = (uint)(1 << blendStyleIndex);
                            var blendStyleUsed = (lightStats.blendStylesUsed & blendStyleMask) > 0;

                            if (blendStyleUsed && !m_Renderer2DData.lightBlendStyles[blendStyleIndex].hasRenderTarget)
                            {
                                this.CreateBlendStyleRenderTexture(renderingData, cmd, blendStyleIndex);
                            }

                            RendererLighting.EnableBlendStyle(cmd, blendStyleIndex, blendStyleUsed);
                        }

                        context.ExecuteCommandBuffer(cmd);

                        // find the highest layer that share the same set of lights as this layer
                        var upperLayerInBatch = FindUpperBoundInBatch(i, cachedSortingLayers);
                        // Some renderers override their sorting layer value with short.MinValue or short.MaxValue.
                        // When drawing the first sorting layer, we should include the range from short.MinValue to layerValue.
                        // Similarly, when drawing the last sorting layer, include the range from layerValue to short.MaxValue.
                        var startLayerValue = (short)cachedSortingLayers[i].value;
                        var lowerBound      = (i == 0) ? short.MinValue : startLayerValue;
                        var endLayerValue   = (short)cachedSortingLayers[upperLayerInBatch].value;
                        var upperBound      = (upperLayerInBatch == cachedSortingLayers.Length - 1) ? short.MaxValue : endLayerValue;
                        // renderer within this range share the same set of lights so they should be rendered together
                        filterSettings.sortingLayerRange = new SortingLayerRange(lowerBound, upperBound);

                        // Start Rendering
                        if (lightStats.totalNormalMapUsage > 0)
                        {
                            this.RenderNormals(context, renderingData.cullResults, normalsDrawSettings, filterSettings, depthAttachment);
                        }

                        cmd.Clear();
                        if (lightStats.totalLights > 0)
                        {
                            this.RenderLights(renderingData, cmd, layerToRender, lightStats.blendStylesUsed);
                        }
                        else
                        {
                            this.ClearDirtyLighting(cmd, lightStats.blendStylesUsed);
                        }

                        CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
                        context.ExecuteCommandBuffer(cmd);

                        Profiler.BeginSample("RenderSpritesWithLighting - Draw Transparent Renderers");
                        context.DrawRenderers(renderingData.cullResults, ref combinedDrawSettings, ref filterSettings);
                        Profiler.EndSample();

                        if (lightStats.totalVolumetricUsage > 0)
                        {
                            cmd.Clear();
                            this.RenderLightVolumes(renderingData, cmd, layerToRender, colorAttachment, depthAttachment, lightStats.blendStylesUsed);
                            context.ExecuteCommandBuffer(cmd);
                            cmd.Clear();
                        }

                        // move on to the next one
                        i = upperLayerInBatch + 1;
                    }

                    cmd.Clear();
                    Profiler.BeginSample("RenderSpritesWithLighting - Release RenderTextures");
                    this.ReleaseRenderTextures(cmd);
                    Profiler.EndSample();
                }

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

                filterSettings.sortingLayerRange = SortingLayerRange.all;
                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
            }
            else
            {
                var unlitDrawSettings = CreateDrawingSettings(k_ShaderTags, ref renderingData, SortingCriteria.CommonTransparent);

                var cmd = CommandBufferPool.Get();
                using (new ProfilingScope(cmd, m_ProfilingSamplerUnlit))
                {
                    CoreUtils.SetRenderTarget(cmd, colorAttachment, depthAttachment, ClearFlag.None, Color.white);
                    cmd.SetGlobalTexture(k_ShapeLightTexture0ID, Texture2D.blackTexture);
                    cmd.SetGlobalTexture(k_ShapeLightTexture1ID, Texture2D.blackTexture);
                    cmd.SetGlobalTexture(k_ShapeLightTexture2ID, Texture2D.blackTexture);
                    cmd.SetGlobalTexture(k_ShapeLightTexture3ID, Texture2D.blackTexture);
                    cmd.SetGlobalFloat(k_UseSceneLightingID, isLitView ? 1.0f : 0.0f);
                    cmd.SetGlobalColor(k_RendererColorID, Color.white);
                    cmd.EnableShaderKeyword("USE_SHAPE_LIGHT_TYPE_0");
                }

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

                Profiler.BeginSample("Render Sprites Unlit");
                context.DrawRenderers(renderingData.cullResults, ref unlitDrawSettings, ref filterSettings);
                Profiler.EndSample();

                RenderingUtils.RenderObjectsWithError(context, ref renderingData.cullResults, camera, filterSettings, SortingCriteria.None);
            }
        }
Esempio n. 26
0
        static public Texture2D CreatePointLightLookupTexture()
        {
            const float    WIDTH         = 256;
            const float    HEIGHT        = 256;
            GraphicsFormat textureFormat = GraphicsFormat.R8G8B8A8_UNorm;

            if (RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R16G16B16A16_SFloat, FormatUsage.SetPixels))
            {
                textureFormat = GraphicsFormat.R16G16B16A16_SFloat;
            }
            else if (RenderingUtils.SupportsGraphicsFormat(GraphicsFormat.R32G32B32A32_SFloat, FormatUsage.SetPixels))
            {
                textureFormat = GraphicsFormat.R32G32B32A32_SFloat;
            }

            s_PointLightLookupTexture            = new Texture2D((int)WIDTH, (int)HEIGHT, textureFormat, TextureCreationFlags.None);
            s_PointLightLookupTexture.filterMode = FilterMode.Bilinear;
            s_PointLightLookupTexture.wrapMode   = TextureWrapMode.Clamp;
            if (s_PointLightLookupTexture != null)
            {
                Vector2 center = new Vector2(WIDTH / 2, HEIGHT / 2);

                for (int y = 0; y < HEIGHT; y++)
                {
                    for (int x = 0; x < WIDTH; x++)
                    {
                        Vector2 pos       = new Vector2(x, y);
                        float   distance  = Vector2.Distance(pos, center);
                        Vector2 relPos    = pos - center;
                        Vector2 direction = center - pos;
                        direction.Normalize();

                        // red   = 1-0 distance
                        // green  = 1-0 angle
                        // blue = direction.x
                        // alpha = direction.y

                        float red;
                        if (x == WIDTH - 1 || y == HEIGHT - 1)
                        {
                            red = 0;
                        }
                        else
                        {
                            red = Mathf.Clamp(1 - (2.0f * distance / WIDTH), 0.0f, 1.0f);
                        }

                        float cosAngle = Vector2.Dot(Vector2.down, relPos.normalized);
                        float angle    = Mathf.Acos(cosAngle) / Mathf.PI; // 0-1

                        float green = Mathf.Clamp(1 - angle, 0.0f, 1.0f);
                        float blue  = direction.x;
                        float alpha = direction.y;

                        Color color = new Color(red, green, blue, alpha);


                        s_PointLightLookupTexture.SetPixel(x, y, color);
                    }
                }
            }
            s_PointLightLookupTexture.Apply();

            return(s_PointLightLookupTexture);
        }