示例#1
0
            public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
            {
                var cmd = CommandBufferPool.Get();

                using ProfilingScope scope = new ProfilingScope(cmd, profilingSampler);
                cmd.DrawMeshInstancedIndirect(m_hizCullSetting.TargetMesh, 0, m_hizCullSetting.TargetMaterial, 0, m_hizCullSetting.Data.BufferWithArags);
                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);
            }
示例#2
0
        private static ProfilingScope Profile(Delegate action)
        {
            var result = new ProfilingScope();

#if false
            result.Action    = action;
            result.Stopwatch = new Stopwatch();
            result.Stopwatch.Start();
#endif
            return(result);
        }
示例#3
0
        private static ProfilingScope GetInitializedScope(string scopeName)
        {
            ProfilingScope scope;

            if (!scopes.TryGetValue(scopeName, out scope))
            {
                scope = new ProfilingScope(scopeName);
                scopes.Add(scopeName, scope);
            }

            return(scope);
        }
示例#4
0
        public void Step()
        {
            if (!IsActive)
            {
                return;
            }

            using (ProfilingScope.Open(ActiveState))
            {
                CurrentState.Run(StateStatus.Execute);

                TryChangingState();
            }
        }
示例#5
0
        public void Step()
        {
            Debug.Assert(startState != null);

            if (activeState == null)
            {
                activeState = startState;
                activeState.StartState();
            }

            using (ProfilingScope.Open(activeState))
            {
                //Find the first triggered transition and consume it
                var transitions = activeState.Transitions;
                foreach (var transition in transitions)
                {
                    if (!transition.IsUsable || !transition.HasTriggered)
                    {
                        continue;
                    }

                    var targetState = transition.TryConsumingTrigger();
                    if (targetState == null)
                    {
                        continue;
                    }

                    //Stop the last state, and start the next one
                    activeState.StopState();
                    activeState = targetState;
                    activeState.StartState();

                    break;
                }

                //Execute the current active state
                activeState.Execute();
            }
        }
示例#6
0
        public bool Setup(ref RenderingData renderingData)
        {
            using var profScope = new ProfilingScope(null, m_ProfilingSetupSampler);

            if (!renderingData.shadowData.supportsMainLightShadows)
            {
                return(false);
            }

            Clear();
            int shadowLightIndex = renderingData.lightData.mainLightIndex;

            if (shadowLightIndex == -1)
            {
                return(false);
            }

            VisibleLight shadowLight = renderingData.lightData.visibleLights[shadowLightIndex];
            Light        light       = shadowLight.light;

            if (light.shadows == LightShadows.None)
            {
                return(false);
            }

            if (shadowLight.lightType != LightType.Directional)
            {
                Debug.LogWarning("Only directional lights are supported as main light.");
            }

            Bounds bounds;

            if (!renderingData.cullResults.GetShadowCasterBounds(shadowLightIndex, out bounds))
            {
                return(false);
            }

            m_ShadowCasterCascadesCount = renderingData.shadowData.mainLightShadowCascadesCount;

            int shadowResolution = ShadowUtils.GetMaxTileResolutionInAtlas(renderingData.shadowData.mainLightShadowmapWidth,
                                                                           renderingData.shadowData.mainLightShadowmapHeight, m_ShadowCasterCascadesCount);

            renderTargetWidth  = renderingData.shadowData.mainLightShadowmapWidth;
            renderTargetHeight = (m_ShadowCasterCascadesCount == 2) ?
                                 renderingData.shadowData.mainLightShadowmapHeight >> 1 :
                                 renderingData.shadowData.mainLightShadowmapHeight;

            for (int cascadeIndex = 0; cascadeIndex < m_ShadowCasterCascadesCount; ++cascadeIndex)
            {
                bool success = ShadowUtils.ExtractDirectionalLightMatrix(ref renderingData.cullResults, ref renderingData.shadowData,
                                                                         shadowLightIndex, cascadeIndex, renderTargetWidth, renderTargetHeight, shadowResolution, light.shadowNearPlane,
                                                                         out m_CascadeSplitDistances[cascadeIndex], out m_CascadeSlices[cascadeIndex]);

                if (!success)
                {
                    return(false);
                }
            }

            m_MainLightShadowmapTexture = ShadowUtils.GetTemporaryShadowTexture(renderTargetWidth, renderTargetHeight, k_ShadowmapBufferBits);
            m_MaxShadowDistanceSq       = renderingData.cameraData.maxShadowDistance * renderingData.cameraData.maxShadowDistance;
            m_CascadeBorder             = renderingData.shadowData.mainLightShadowCascadeBorder;

            return(true);
        }
示例#7
0
            public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
            {
                var cmd = CommandBufferPool.Get();

                using var scope = new ProfilingScope(cmd, profilingSampler);
                ref var rd = ref renderingData;
示例#8
0
            // Here you can implement the rendering logic.
            // Use <c>ScriptableRenderContext</c> to issue drawing commands or execute command buffers
            // https://docs.unity3d.com/ScriptReference/Rendering.ScriptableRenderContext.html
            // You don't have to call ScriptableRenderContext.submit, the render pipeline will call it at specific points in the pipeline.
            public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
            {
                if (m_hizCullSetting.Density <= 0)
                {
                    return;
                }

                var cmd = CommandBufferPool.Get();

                using var profScope = new ProfilingScope(cmd, ProfilingSampler);
                var cs   = m_hizCullSetting.CullShader;
                var data = m_hizCullSetting.Data;
                var vp   = GL.GetGPUProjectionMatrix(Camera.main.projectionMatrix, false) * Camera.main.worldToCameraMatrix;

                data.Args[1] = 0;
                var md = m_hizCullSetting.GameDepthTempRT;

                if (m_hizCullSetting.Toggle && data.CameraType == CameraType.Game)
                {
                    //m_hizCullSetting.Toggle = false;
                    var mipmap = m_hizCullSetting.GenerateMipmap;


                    //Graphics.Blit(depthTargetIdentifier, md);
                    //m_hizCullSetting.DepthTextureNormalize.SetTexture("_MainTex", d);

                    cmd.Blit(m_hizCullSetting.Data.DepthTargetIdentifier, md);//,m_hizCullSetting.DepthTextureNormalize,0);

                    var size = 512;
                    if (size % 2 == 0 && size > 8)
                    {
                        int maxlevel = Mathf.RoundToInt(Mathf.Log(512, 2));
                        int level    = 0;
                        //Debug.Log(maxlevel);

                        //goto lerrr;
                        while (level < maxlevel - 3)
                        {
                            var current = level;
                            var next    = ++level;
                            cmd.SetComputeTextureParam(mipmap, data.GenerateMiamapKernelID, data.SoureceTexID, md, current);
                            cmd.SetComputeTextureParam(mipmap, data.GenerateMiamapKernelID, data.ResultID, md, next);
                            //level++;
                            var dis = (1 << (maxlevel - level)) / 8;
                            //Debug.Log(dis);
                            cmd.DispatchCompute(mipmap, data.GenerateMiamapKernelID, dis, dis, 1);
                            cmd.SetRenderTarget(md);
                        }
                    }
                }

                //m_bufferWithArags.SetData(args);
                //m_hizCullSetting.CullShader.SetMatrix(vpID, vp);
                //m_hizCullSetting.CullShader.SetBuffer(kernelID, bufferArgsID, m_bufferWithArags);
                //m_hizCullSetting.CullShader.Dispatch(kernelID, (width_x) / 25, (width_z) / 25, m_hizCullSetting.Density);
                //m_hizCullSetting.TargetMaterial.SetBuffer(visPositionBufferID, m_visPosBuffer);


                //commondbuffer 执行方式
                cmd.SetBufferData(data.BufferWithArags, data.Args);
                cmd.SetComputeMatrixParam(cs, data.VPID, vp);
                cmd.SetComputeBufferParam(cs, data.KernelID, data.BufferArgsID, data.BufferWithArags);
                cmd.SetComputeBufferParam(cs, data.KernelID, data.PositionBufferID, data.PosAllBuffer);
                if (md != null)
                {
                    cmd.SetComputeTextureParam(cs, data.KernelID, "_HizDepthMipmap", md);
                }
                cmd.DispatchCompute(cs, data.KernelID, (data.Width_x) / 25, (data.Width_z) / 25, m_hizCullSetting.Density);

                m_hizCullSetting.TargetMaterial.SetBuffer(data.VisPositionBufferID, data.VisPosBuffer);
                m_hizCullSetting.TargetMaterial.EnableKeyword("INSTANCING_ON");
                context.ExecuteCommandBuffer(cmd);
                CommandBufferPool.Release(cmd);
            }
示例#9
0
        public override void Route(string targetHost, int targetPort, bool?proxyDns = null)
        {
            using (var prof = new ProfilingScope("Socks5 Route"))
            {
                if (targetHost is null)
                {
                    throw new ArgumentNullException(nameof(targetHost));
                }

                var stream = Stream;

                var buf = new byte[1024];
                var b   = 0;

                // send authentication header
                buf[b++] = 0x05;                 // Socks ver = 5
                buf[b++] = 0x01;                 // count of auth methods supported
                buf[b++] = 0x00;                 // #1 - no auth (0x00)
                stream.Write(buf, 0, b);
                stream.Flush();
                var count = stream.Read(buf, 0, 2);                 // auth response
                if (count != 2)
                {
                    throw new Exception("Server must respond with 2 bytes (response 1)");
                }
                if (buf[0] != 0x05)
                {
                    throw new Exception("Server do not support v5 (response 1)");
                }
                if (buf[1] != 0x00)
                {
                    throw new Exception("Server requires authentication");
                }

                // here authentication handshake can be added, but I don't see any reason to add clear text passwords

                // send the actual request
                b        = 0;
                buf[b++] = 0x05;                 // ver = 5
                buf[b++] = 0x01;                 // command = stream
                buf[b++] = 0x00;                 // reserved

                var targetIsIp = IPAddress.TryParse(targetHost, out var ip);
                if (!targetIsIp)                 // if targetHost is IP - just use IP, otherwise:
                {
                    var dns  = Dns.GetHostAddresses(targetHost);
                    var ipv4 = dns.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);
                    var ipv6 = dns.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetworkV6);

                    ip = ipv4 ?? ipv6;                     // have to take ipv4 first because ipv6 is not working most of the times and HappyEyeballs is not possible via socks chain due to single connection. Browser will do HappyEyeballs
                }

                if (!targetIsIp && proxyDns != false || proxyDns == true)           // forward the targetHost name
                {
                    buf[b++] = 0x03;                                                // adress type = domain name
                    buf[b++] = checked ((byte)targetHost.Length);                   // len
                    Utils.Ascii.GetBytes(targetHost, 0, targetHost.Length, buf, b); // target host
                    b += targetHost.Length;
                }
                else if (ip != null && ip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    buf[b++] = 0x04;                     // adress type = IPv6
                    ip.GetAddressBytes().CopyTo(buf, b);
                    b += 16;
                }
                else if (ip != null && ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    buf[b++] = 0x01;                     // adress type = IPv4
                    // ip.GetAddressBytes().CopyTo(buf, b);
                    // b += 4;
                    var a = ip.Address;
                    buf[b++] = (byte)(a >> 0);
                    buf[b++] = (byte)(a >> 8);
                    buf[b++] = (byte)(a >> 16);
                    buf[b++] = (byte)(a >> 24);
                }
                else
                {
                    throw new Exception("Host is not resolved: " + targetHost);
                }
                buf[b++] = (byte)(targetPort >> 8);
                buf[b++] = (byte)(targetPort);
                stream.Write(buf, 0, b);
                stream.Flush();

                // response
                var c = stream.Read(buf, 0, 4);
                if (c < 4)
                {
                    throw new Exception("Server did not sent full response (response 2)");
                }
                if (buf[0] != 0x05)
                {
                    throw new Exception("Server does not support v5 (response 2)");
                }
                if (buf[1] != 0x00)
                {
                    var msg = $"Server response: {buf[1]:X}: {GetResponseErrorMessage(buf[1])}";
                    Trace.WriteLine(TraceCategory.NetworkingData, msg);
                    throw new Exception(msg);
                }
                // ignore reserved buf[2] byte
                // read only required number of bytes depending on address type
                switch (buf[3])
                {
                case 1:
                    // IPv4
                    c += stream.Read(buf, c, 4);
                    break;

                case 3:
                    // Name
                    c += stream.Read(buf, c, 1);
                    c += stream.Read(buf, c, buf[c - 1]);                             // 256 max... no reason to protect from owerflow
                    break;

                case 4:
                    // IPv6
                    c += stream.Read(buf, c, 16);
                    break;

                default:
                    throw new Exception("Response address type not supported!");
                }
                b += stream.Read(buf, b, 2);                 // port
                // we don't need those values because it is stream, not bind
            }
        }
        public bool Setup(ref RenderingData renderingData)
        {
            using var profScope = new ProfilingScope(null, m_ProfilingSetupSampler);

            Clear();

            m_ShadowmapWidth  = renderingData.shadowData.additionalLightsShadowmapWidth;
            m_ShadowmapHeight = renderingData.shadowData.additionalLightsShadowmapHeight;

            var visibleLights         = renderingData.lightData.visibleLights;
            int additionalLightsCount = renderingData.lightData.additionalLightsCount;

            if (m_AdditionalLightSlices == null || m_AdditionalLightSlices.Length < additionalLightsCount)
            {
                m_AdditionalLightSlices = new ShadowSliceData[additionalLightsCount];
            }

            if (m_AdditionalLightsShadowData == null || m_AdditionalLightsShadowData.Length < additionalLightsCount)
            {
                m_AdditionalLightsShadowData = new ShaderInput.ShadowData[additionalLightsCount];
            }

            // By default visible lights do not have shadow light indices.
            for (int i = 0; i < visibleLights.Length; ++i)
            {
                m_ShadowCastingLightIndicesMap.Add(-1);
            }

            int  validShadowCastingLights = 0;
            bool supportsSoftShadows      = renderingData.shadowData.supportsSoftShadows;

            for (int i = 0; i < visibleLights.Length && m_AdditionalShadowCastingLightIndices.Count < additionalLightsCount; ++i)
            {
                VisibleLight shadowLight = visibleLights[i];

                // Skip main directional light as it is not packed into the shadow atlas
                if (i == renderingData.lightData.mainLightIndex)
                {
                    continue;
                }

                int  shadowCastingLightIndex = m_AdditionalShadowCastingLightIndices.Count;
                bool isValidShadowSlice      = false;
                if (renderingData.cullResults.GetShadowCasterBounds(i, out var bounds))
                {
                    // We need to iterate the lights even though additional lights are disabled because
                    // cullResults.GetShadowCasterBounds() does the fence sync for the shadow culling jobs.
                    if (!renderingData.shadowData.supportsAdditionalLightShadows)
                    {
                        continue;
                    }

                    if (IsValidShadowCastingLight(ref renderingData.lightData, i))
                    {
                        bool success = ShadowUtils.ExtractSpotLightMatrix(ref renderingData.cullResults,
                                                                          ref renderingData.shadowData,
                                                                          i,
                                                                          out var shadowTransform,
                                                                          out m_AdditionalLightSlices[shadowCastingLightIndex].viewMatrix,
                                                                          out m_AdditionalLightSlices[shadowCastingLightIndex].projectionMatrix);

                        if (success)
                        {
                            m_AdditionalShadowCastingLightIndices.Add(i);
                            var     light          = shadowLight.light;
                            float   shadowStrength = light.shadowStrength;
                            float   softShadows    = (supportsSoftShadows && light.shadows == LightShadows.Soft) ? 1.0f : 0.0f;
                            Vector4 shadowParams   = new Vector4(shadowStrength, softShadows, 0.0f, 0.0f);
                            if (m_UseStructuredBuffer)
                            {
                                m_AdditionalLightsShadowData[shadowCastingLightIndex].worldToShadowMatrix = shadowTransform;
                                m_AdditionalLightsShadowData[shadowCastingLightIndex].shadowParams        = shadowParams;
                            }
                            else
                            {
                                m_AdditionalLightsWorldToShadow[shadowCastingLightIndex] = shadowTransform;
                                m_AdditionalLightsShadowParams[shadowCastingLightIndex]  = shadowParams;
                            }
                            isValidShadowSlice = true;
                            validShadowCastingLights++;
                        }
                    }
                }

                if (m_UseStructuredBuffer)
                {
                    // When using StructuredBuffers all the valid shadow casting slices data
                    // are stored in a the ShadowData buffer and then we setup a index map to
                    // map from light indices to shadow buffer index. A index map of -1 means
                    // the light is not a valid shadow casting light and there's no data for it
                    // in the shadow buffer.
                    int indexMap = (isValidShadowSlice) ? shadowCastingLightIndex : -1;
                    m_AdditionalShadowCastingLightIndicesMap.Add(indexMap);
                }
                else if (!isValidShadowSlice)
                {
                    // When NOT using structured buffers we have no performant way to sample the
                    // index map as int[]. Unity shader compiler converts int[] to float4[] to force memory alignment.
                    // This makes indexing int[] arrays very slow. So, in order to avoid indexing shadow lights we
                    // setup slice data and reserve shadow map space even for invalid shadow slices.
                    // The data is setup with zero shadow strength. This has the same visual effect of no shadow
                    // attenuation contribution from this light.
                    // This makes sampling shadow faster but introduces waste in shadow map atlas.
                    // The waste increases with the amount of additional lights to shade.
                    // Therefore Universal RP try to keep the limit at sane levels when using uniform buffers.
                    Matrix4x4 identity = Matrix4x4.identity;
                    m_AdditionalShadowCastingLightIndices.Add(i);
                    m_AdditionalLightsWorldToShadow[shadowCastingLightIndex]          = identity;
                    m_AdditionalLightsShadowParams[shadowCastingLightIndex]           = Vector4.zero;
                    m_AdditionalLightSlices[shadowCastingLightIndex].viewMatrix       = identity;
                    m_AdditionalLightSlices[shadowCastingLightIndex].projectionMatrix = identity;
                }

                m_ShadowCastingLightIndicesMap[i] = isValidShadowSlice ? shadowCastingLightIndex : -1;
            }

            // Lights that need to be rendered in the shadow map atlas
            if (validShadowCastingLights == 0)
            {
                return(false);
            }

            int atlasWidth      = renderingData.shadowData.additionalLightsShadowmapWidth;
            int atlasHeight     = renderingData.shadowData.additionalLightsShadowmapHeight;
            int sliceResolution = ShadowUtils.GetMaxTileResolutionInAtlas(atlasWidth, atlasHeight, validShadowCastingLights);

            // In the UI we only allow for square shadow map atlas. Here we check if we can fit
            // all shadow slices into half resolution of the atlas and adjust height to have tighter packing.
            int maximumSlices = (m_ShadowmapWidth / sliceResolution) * (m_ShadowmapHeight / sliceResolution);

            if (validShadowCastingLights <= (maximumSlices / 2))
            {
                m_ShadowmapHeight /= 2;
            }

            int   shadowSlicesPerRow = (atlasWidth / sliceResolution);
            float oneOverAtlasWidth  = 1.0f / m_ShadowmapWidth;
            float oneOverAtlasHeight = 1.0f / m_ShadowmapHeight;

            int       sliceIndex = 0;
            int       shadowCastingLightsBufferCount = m_AdditionalShadowCastingLightIndices.Count;
            Matrix4x4 sliceTransform = Matrix4x4.identity;

            sliceTransform.m00 = sliceResolution * oneOverAtlasWidth;
            sliceTransform.m11 = sliceResolution * oneOverAtlasHeight;

            for (int i = 0; i < shadowCastingLightsBufferCount; ++i)
            {
                // we can skip the slice if strength is zero. Some slices with zero
                // strength exists when using uniform array path.
                if (!m_UseStructuredBuffer && Mathf.Approximately(m_AdditionalLightsShadowParams[i].x, 0.0f))
                {
                    continue;
                }

                m_AdditionalLightSlices[i].offsetX    = (sliceIndex % shadowSlicesPerRow) * sliceResolution;
                m_AdditionalLightSlices[i].offsetY    = (sliceIndex / shadowSlicesPerRow) * sliceResolution;
                m_AdditionalLightSlices[i].resolution = sliceResolution;

                sliceTransform.m03 = m_AdditionalLightSlices[i].offsetX * oneOverAtlasWidth;
                sliceTransform.m13 = m_AdditionalLightSlices[i].offsetY * oneOverAtlasHeight;

                // We bake scale and bias to each shadow map in the atlas in the matrix.
                // saves some instructions in shader.
                if (m_UseStructuredBuffer)
                {
                    m_AdditionalLightsShadowData[i].worldToShadowMatrix = sliceTransform * m_AdditionalLightsShadowData[i].worldToShadowMatrix;
                }
                else
                {
                    m_AdditionalLightsWorldToShadow[i] = sliceTransform * m_AdditionalLightsWorldToShadow[i];
                }
                sliceIndex++;
            }

            return(true);
        }