コード例 #1
0
 private void SetupBuffer()
 {
     if (shapeBuffer == null || !shapeBuffer.IsValid())
     {
         shapeBuffer = new ComputeBuffer(1, ShapeData.GetSize());
         rayMarchingShader.SetBuffer(0, "shapes", shapeBuffer);
         shapeBuffer.Release();
     }
 }
コード例 #2
0
 private static void CreateBuffer(int numPoints)
 {
     if (points == null || !points.IsValid() || points.count != numPoints)
     {
         points = new ComputeBuffer(numPoints, 16);
     }
 }
コード例 #3
0
 public void CheckAndReleaseBuffer()
 {
     if (_colorsComputeBuffer != null && _colorsComputeBuffer.IsValid())
     {
         _colorsComputeBuffer.Release();
     }
 }
コード例 #4
0
        /// <summary>
        /// To be called whenever the settings universal to this group change.
        /// </summary>
        public void OnSettingsChanged()
        {
            m_settingsArray[0] = new Settings()
            {
                //Smoothing = Mathf.Max(MIN_SMOOTHING, m_smoothing),
                NormalSmoothing      = Mathf.Max(MIN_SMOOTHING, m_normalSmoothing),
                ThicknessMaxDistance = m_thicknessMaxDistance,
                ThicknessFalloff     = m_thicknessFalloff,
            };

            if (m_settingsBuffer == null || !m_settingsBuffer.IsValid())
            {
                m_settingsBuffer?.Dispose();
                m_settingsBuffer = new ComputeBuffer(1, Settings.Stride, ComputeBufferType.Structured);
            }

            for (int i = 0; i < m_sdfComponents.Count; i++)
            {
                m_sdfComponents[i].UpdateSettingsBuffer(m_settingsBuffer);
            }

            Mapper.SetSettings(m_settingsArray[0]);

            m_settingsBuffer.SetData(m_settingsArray);
        }
コード例 #5
0
 private void OnDestroy()
 {
     if (sphereBuffer.IsValid())
     {
         sphereBuffer.Dispose();
     }
 }
コード例 #6
0
 public static void SafeCommandBufferReleaseAndDispose(ComputeBuffer computeBuffer)
 {
     if (computeBuffer != null && computeBuffer.IsValid())
     {
         computeBuffer.Release();
         computeBuffer.Dispose();
     }
 }
コード例 #7
0
        private bool BindBufferToTensor(int tensorIndex, ComputeBuffer buffer)
        {
            Debug.Assert(buffer.IsValid());
            Debug.Assert(Delegate != TfLiteDelegate.Zero);
            uint bufferID = (uint)buffer.GetNativeBufferPtr().ToInt32();
            var  status   = TfLiteGpuDelegateBindBufferToTensor(Delegate, bufferID, tensorIndex);

            return(status == Interpreter.Status.Ok);
        }
コード例 #8
0
        private void OnDestroy()
        {
            if (m_initialise)
            {
                m_massBuffer.Release();

                m_springBuffer.Release();

                if (m_sphereColliderBuffer != null)
                {
                    if (m_sphereColliderBuffer.IsValid())
                    {
                        m_sphereColliderBuffer.Release();
                    }
                }

                GeneralForces.s_instance.m_sphereColliderUpdate -= UpdateSphereColliders;
            }
        }
コード例 #9
0
        public static void CreateStructuredBuffer <T>(ref ComputeBuffer buffer, int count)
        {
            int  stride          = System.Runtime.InteropServices.Marshal.SizeOf(typeof(T));
            bool createNewBuffer = buffer == null || !buffer.IsValid() || buffer.count != count || buffer.stride != stride;

            if (createNewBuffer)
            {
                Release(buffer);
                buffer = new ComputeBuffer(count, stride);
            }
        }
コード例 #10
0
    private void OnDestroy()
    {
        if (_depthBuffer != null && _depthBuffer.IsValid())
        {
            _depthBuffer.Release();
        }

        if (_outputRT != null)
        {
            _outputRT.Release();
        }
    }
コード例 #11
0
 public void Dispose()
 {
     if (argsBuffer != null && argsBuffer.IsValid())
     {
         argsBuffer.Dispose();
         argsBuffer = null;
     }
     if (instanceTransformations != null && instanceTransformations.IsValid())
     {
         instanceTransformations.Dispose();
         instanceTransformations = null;
     }
 }
コード例 #12
0
ファイル: Flock.cs プロジェクト: Olof-AV/GPGPU-Boid-Flocking
 //Release anything left at this point
 void OnDestroy()
 {
     if (bufferWithArgs.IsValid())
     {
         bufferWithArgs.Release();
     }
     if (cBufferBoid.IsValid())
     {
         cBufferBoid.Release();
     }
     if (cBufferEnemy.IsValid())
     {
         cBufferEnemy.Release();
     }
 }
コード例 #13
0
    protected void CreateBuffers()
    {
        if (!Application.isPlaying || PointsBuffer == null || !PointsBuffer.IsValid() || NumPoints != PointsBuffer.count)
        {
            if (Application.isPlaying)
            {
                ReleaseBuffers();
            }

            TrianglesBuffer = new ComputeBuffer(MaxTriangleCount, sizeof(float) * 3 * 3, ComputeBufferType.Append);
            PointsBuffer    = new ComputeBuffer(NumPoints, sizeof(float) * 4);
            TriCountBuffer  = new ComputeBuffer(1, sizeof(int), ComputeBufferType.Raw);
            SetComputeBuffers();
        }
    }
コード例 #14
0
        public void UpdateDataBuffer(ComputeBuffer computeBuffer, int count)
        {
            if (m_propertyBlock == null)
            {
                m_propertyBlock = new MaterialPropertyBlock();
            }

            if (computeBuffer != null && computeBuffer.IsValid())
            {
                m_propertyBlock.SetBuffer(MaterialProperties.SDFData_StructuredBuffer, computeBuffer);
            }

            m_propertyBlock.SetInt(MaterialProperties.SDFDataCount_Int, count);

            m_renderer.SetPropertyBlock(m_propertyBlock);
        }
コード例 #15
0
ファイル: HistogramUtility.cs プロジェクト: jjmac/Mixture
        public static void AllocateHistogramData(int histogramBucketCount, HistogramMode mode, out HistogramData data)
        {
            data                 = new HistogramData();
            data.bucketCount     = histogramBucketCount;
            data.mode            = mode;
            data.histogram       = new ComputeBuffer(histogramBucketCount, sizeof(uint) * 4, ComputeBufferType.Structured);
            data.histogramData   = new ComputeBuffer(1, sizeof(uint) * 2, ComputeBufferType.Structured);
            data.previewMaterial = new Material(Shader.Find("Hidden/HistogramPreview"))
            {
                hideFlags = HideFlags.HideAndDontSave
            };

            if (luminanceBuffer == null || !luminanceBuffer.IsValid())
            {
                luminanceBuffer = new ComputeBuffer(1048576, sizeof(float) * 2, ComputeBufferType.Structured);
            }
            _dataCount++;
        }
コード例 #16
0
 public void CheckAndReleaseBuffers()
 {
     if (_additiveCoefficientsBuffer?.IsValid() ?? false)
     {
         _additiveCoefficientsBuffer.Release();
     }
     if (_centersPositionsBuffer?.IsValid() ?? false)
     {
         _centersPositionsBuffer.Release();
     }
     if (_multiplicativeCoefficientsBuffer?.IsValid() ?? false)
     {
         _multiplicativeCoefficientsBuffer.Release();
     }
     if (_stopConditionComputeBuffer?.IsValid() ?? false)
     {
         _stopConditionComputeBuffer?.Release();
     }
 }
コード例 #17
0
 public override void UpdateScene()
 {
     base.UpdateScene();
     if (intersections.Length != 0)
     {
         if (intersectionBuffer == null)
         {
             intersectionBuffer = new ComputeBuffer(intersections.Length, sizeof(IntersectionType));
         }
         else if (!intersectionBuffer.IsValid() || intersections.Length != intersectionBuffer.count)
         {
             intersectionBuffer.Release();
             intersectionBuffer = new ComputeBuffer(intersections.Length, sizeof(IntersectionType));
         }
         intersectionBuffer.SetData(intersections);
     }
     else
     {
         intersectionBuffer.Release();
         intersectionBuffer = new ComputeBuffer(1, sizeof(IntersectionType));
         intersectionBuffer.SetData(new IntersectionType[1]);
     }
     rayMarchingShader.SetBuffer(0, "intersections", intersectionBuffer);
 }
コード例 #18
0
        public void Init()
        {
            if (!blocks.IsCreated)
            {
                // init native containers
                blocks          = new NativeArray <BlockType>(FixedChunkSizeXZ * ChunkSizeY * FixedChunkSizeXZ, Allocator.Persistent);
                lightingData    = new NativeArray <int>(FixedChunkSizeXZ * ChunkSizeY * FixedChunkSizeXZ, Allocator.Persistent);
                biomeTypes      = new NativeArray <BiomeType>(FixedChunkSizeXZ * FixedChunkSizeXZ, Allocator.Persistent);
                blockParameters = new NativeHashMap <BlockParameter, short>(2048, Allocator.Persistent);

                blockVerticles = new NativeList <float3>(16384, Allocator.Persistent);
                blockTriangles = new NativeList <int>(32768, Allocator.Persistent);
                blockUVs       = new NativeList <float2>(16384, Allocator.Persistent);

                liquidVerticles = new NativeList <float3>(8192, Allocator.Persistent);
                liquidTriangles = new NativeList <int>(16384, Allocator.Persistent);
                liquidUVs       = new NativeList <float2>(8192, Allocator.Persistent);

                plantsVerticles = new NativeList <float3>(4096, Allocator.Persistent);
                plantsTriangles = new NativeList <int>(8192, Allocator.Persistent);
                plantsUVs       = new NativeList <float2>(4096, Allocator.Persistent);

                chunkDissapearingAnimation = GetComponent <ChunkDissapearingAnimation>();
                chunkAnimation             = GetComponent <ChunkAnimation>();
            }

            if (lightingBuffer == null || !lightingBuffer.IsValid())
            {
                lightingBuffer = new ComputeBuffer(FixedChunkSizeXZ * ChunkSizeY * FixedChunkSizeXZ, sizeof(int), ComputeBufferType.Default);
                var mr = blockMeshFilter.GetComponent <MeshRenderer>();
                mr.material.SetBuffer("lightData", lightingBuffer);
            }

            World.TimeToBuild += BuildBlocks;
            StartCoroutine(CheckNeighbours());
        }
コード例 #19
0
ファイル: CyberSet.cs プロジェクト: zhu1987/Unity-MPipeline
 public bool Check()
 {
     return(constantBuffer != null && constantBuffer.IsValid());
 }
コード例 #20
0
 private bool BindBufferToTensor(int tensorIndex, ComputeBuffer buffer)
 {
     Debug.Assert(buffer.IsValid());
     Debug.Assert(Delegate != TfLiteDelegate.Zero);
     return(TFLGpuDelegateBindMetalBufferToTensor(Delegate, tensorIndex, buffer.GetNativeBufferPtr()));
 }
コード例 #21
0
        /// <summary>
        /// Repopulate the data relating to SDF primitives (spheres, toruses, cuboids etc) and SDF meshes (which point to where in the list of sample and uv data they begin, and how large they are)
        /// </summary>
        /// <param name="onlySendBufferOnChange">Whether to invoke the components and inform them the buffer has changed. This is only really necessary when the size changes.</param>
        private void RebuildData(bool onlySendBufferOnChange = true)
        {
            m_isLocalDataDirty = false;

            // should we rebuild the buffers which contain mesh sample + uv data?
            bool globalBuffersChanged = false;

            if (m_meshSamplesBuffer == null || !m_meshSamplesBuffer.IsValid() || m_meshPackedUVsBuffer == null || !m_meshPackedUVsBuffer.IsValid() || m_isGlobalMeshDataDirty)
            {
                globalBuffersChanged = RebuildGlobalMeshData(m_sdfObjects, onlySendBufferOnChange);
            }

            // memorize the size of the array before clearing it, for later comparison
            int previousCount = m_data.Count;

            m_data.Clear();

            // add all the sdf objects
            for (int i = 0; i < m_sdfObjects.Count; i++)
            {
                SDFObject sdfObject = m_sdfObjects[i];

                if (!sdfObject)
                {
                    continue;
                }

                sdfObject.SetClean();

                int meshStartIndex = -1;
                int uvStartIndex   = -1;

                if (sdfObject is SDFMesh mesh)
                {
                    // get the index in the global samples buffer where this particular mesh's samples begin
                    if (!m_meshSdfSampleStartIndices.TryGetValue(mesh.ID, out meshStartIndex))
                    {
                        globalBuffersChanged = RebuildGlobalMeshData(m_sdfObjects, onlySendBufferOnChange); // we don't recognize this mesh so we may need to rebuild the entire global list of mesh samples and UVs
                    }
                    // likewise, if this mesh has UVs, get the index where they begin too
                    if (mesh.Asset.HasUVs)
                    {
                        m_meshSdfUVStartIndices.TryGetValue(mesh.ID, out uvStartIndex);
                    }
                }

                m_data.Add(sdfObject.GetSDFGPUData(meshStartIndex, uvStartIndex));
            }

            bool sendBuffer = !onlySendBufferOnChange;

            // check whether we need to create a new buffer. buffers are fixed sizes so the most common occasion for this is simply a change of size
            if (m_dataBuffer == null || !m_dataBuffer.IsValid() || previousCount != m_data.Count)
            {
                sendBuffer = true;

                m_dataBuffer?.Dispose();
                m_dataBuffer = new ComputeBuffer(Mathf.Max(1, m_data.Count), SDFGPUData.Stride, ComputeBufferType.Structured);
            }

            // if the buffer is new, the size has changed, or if it's forced, we resend the buffer to the sdf group component classes
            if (sendBuffer)
            {
                for (int i = 0; i < m_sdfComponents.Count; i++)
                {
                    m_sdfComponents[i].UpdateDataBuffer(m_dataBuffer, m_data.Count);
                }
            }

            if (m_data.Count > 0)
            {
                m_dataBuffer.SetData(m_data);
            }

            // if we also changed the global mesh data buffer in this method, we need to send that as well
            if (!onlySendBufferOnChange || globalBuffersChanged)
            {
                Shader.SetGlobalBuffer(GlobalProperties.MeshSamples_StructuredBuffer, m_meshSamplesBuffer);
                Shader.SetGlobalBuffer(GlobalProperties.MeshPackedUVs_StructuredBuffer, m_meshPackedUVsBuffer);
            }
        }
コード例 #22
0
        /// <summary>
        /// Some mesh data is shared across all instances, such as the sample and UV information as well as the start indices in those static buffers
        /// for all meshes. Returns true if the static buffers have been changed and need to be resent to the groups.
        /// </summary>
        /// <param name="locals">List of SDFMesh objects to ensure are in the global list.</param>
        /// <param name="onlySendBufferOnChange">Whether to invoke the components and inform them the buffer has changed. This is only really necessary when the size changes.</param>
        private static bool RebuildGlobalMeshData(IList <SDFObject> locals, bool onlySendBufferOnChange = true)
        {
            int previousMeshSamplesCount = m_meshSamples.Count;
            int previousMeshUVsCount     = m_meshPackedUVs.Count;

            m_meshSamples.Clear();
            m_meshPackedUVs.Clear();

            m_meshSdfSampleStartIndices.Clear();
            m_meshSdfUVStartIndices.Clear();

            // remove null refs
            for (int i = m_globalSDFMeshes.Count - 1; i >= 0; --i)
            {
                if (m_globalSDFMeshes[i] == null || m_globalSDFMeshes[i].Asset == null)
                {
                    m_globalSDFMeshes.RemoveAt(i);
                }
            }

            for (int i = 0; i < locals.Count; i++)
            {
                if (locals[i] is SDFMesh mesh && !m_globalSDFMeshes.Contains(mesh))
                {
                    m_globalSDFMeshes.Add(mesh);
                }
            }

            // loop over each mesh, adding its samples/uvs to the sample buffer
            // and taking note of where each meshes samples start in the buffer.
            // check for repeats so we don't add the same mesh to the samples buffer twice
            for (int i = 0; i < m_globalSDFMeshes.Count; i++)
            {
                SDFMesh mesh = m_globalSDFMeshes[i];

                // ignore meshes which are in the list but not present in any group
                if (m_meshCounts.TryGetValue(mesh.ID, out int count) && count <= 0)
                {
                    continue;
                }

                mesh.Asset.GetDataArrays(out float[] samples, out float[] packedUVs);

                if (!m_meshSdfSampleStartIndices.ContainsKey(mesh.ID))
                {
                    int startIndex = m_meshSamples.Count;
                    m_meshSamples.AddRange(samples);
                    m_meshSdfSampleStartIndices.Add(mesh.ID, startIndex);
                }

                if (mesh.Asset.HasUVs && !m_meshSdfUVStartIndices.ContainsKey(mesh.ID))
                {
                    int startIndex = m_meshPackedUVs.Count;
                    m_meshPackedUVs.AddRange(packedUVs);
                    m_meshSdfUVStartIndices.Add(mesh.ID, startIndex);
                }
            }

            bool newBuffers = false;

            if (m_meshSamplesBuffer == null || !m_meshSamplesBuffer.IsValid() || previousMeshSamplesCount != m_meshSamples.Count)
            {
                m_meshSamplesBuffer?.Dispose();
                m_meshSamplesBuffer = new ComputeBuffer(Mathf.Max(1, m_meshSamples.Count), sizeof(float), ComputeBufferType.Structured);
                newBuffers          = true;
            }

            if (m_meshSamples.Count > 0)
            {
                m_meshSamplesBuffer.SetData(m_meshSamples);
            }

            if (m_meshPackedUVsBuffer == null || !m_meshPackedUVsBuffer.IsValid() || previousMeshUVsCount != m_meshPackedUVs.Count)
            {
                m_meshPackedUVsBuffer?.Dispose();
                m_meshPackedUVsBuffer = new ComputeBuffer(Mathf.Max(1, m_meshPackedUVs.Count), sizeof(float), ComputeBufferType.Structured);
                newBuffers            = true;
            }

            if (m_meshPackedUVs.Count > 0)
            {
                m_meshPackedUVsBuffer.SetData(m_meshPackedUVs);
            }

            m_isGlobalMeshDataDirty = false;

            return(newBuffers);
        }
コード例 #23
0
 public override bool CheckProperty()
 {
     return(randomBuffer.IsValid());
 }
コード例 #24
0
    void CreateMesh()
    {
        if (vertexGPUBuffer != null && vertexGPUBuffer.IsValid())
        {
            vertexGPUBuffer.Dispose();
            vertexGPUBuffer = null;
        }

        var verticesOnEdge = chunkConfig.numberOfVerticesOnEdge;

        {
            int aIndex = 0;
            int bIndex = verticesOnEdge - 1;
            int cIndex = verticesOnEdge * verticesOnEdge - 1;
            int dIndex = cIndex - (verticesOnEdge - 1);
            rangePosToCalculateScreenSizeOn_localToPlanet.a = vertexCPUBuffer[aIndex].position;
            rangePosToCalculateScreenSizeOn_localToPlanet.b = vertexCPUBuffer[bIndex].position;
            rangePosToCalculateScreenSizeOn_localToPlanet.c = vertexCPUBuffer[cIndex].position;
            rangePosToCalculateScreenSizeOn_localToPlanet.d = vertexCPUBuffer[dIndex].position;

            if (!GenerateUsingPlanetGlobalPos)
            {
                rangePosToCalculateScreenSizeOn_localToPlanet.a += offsetFromPlanetCenter;
                rangePosToCalculateScreenSizeOn_localToPlanet.b += offsetFromPlanetCenter;
                rangePosToCalculateScreenSizeOn_localToPlanet.c += offsetFromPlanetCenter;
                rangePosToCalculateScreenSizeOn_localToPlanet.d += offsetFromPlanetCenter;
            }
        }

        if (generatingData.mesh)
        {
            Mesh.Destroy(generatingData.mesh);
        }
        // TODO: optimize: fill mesh vertices on GPU instead of CPU, remember we still need vertices on CPU for mesh collider
        generatingData.mesh      = new Mesh();
        generatingData.mesh.name = this.ToString();
        generatingData.mesh.SetVertexBufferParams(
            vertexCPUBuffer.Length,
            new[]
        {
            new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3),
            new VertexAttributeDescriptor(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3),
            new VertexAttributeDescriptor(VertexAttribute.Tangent, VertexAttributeFormat.Float32, 3),
        }
            );
        generatingData.mesh.SetVertexBufferData(vertexCPUBuffer, 0, 0, vertexCPUBuffer.Length);
        generatingData.mesh.triangles = planet.GetChunkMeshTriangles();
        generatingData.mesh.uv        = planet.GetChunkMeshUVs();
        generatingData.mesh.RecalculateBounds();

        if (true || !chunkConfig.generateChunkNormapMap)
        {
            //generatedData.mesh.RecalculateNormals();
            //generatedData.mesh.RecalculateTangents();

            //generatingData.mesh.normals = RecalculateNormals(ref vertexCPUBuffer, planet.GetChunkMeshTriangles(), planet.GetChunkMeshUVs(), planet.GetChunkMeshIndiciesEdge());
            //generatingData.mesh.tangents = RecalculateTangents(ref vertexCPUBuffer, planet.GetChunkMeshTriangles(), planet.GetChunkMeshUVs(), planet.GetChunkMeshIndiciesEdge());
        }
        else
        {
            generatingData.mesh.normals  = new Vector3[] { };
            generatingData.mesh.tangents = new Vector4[] { };
        }
    }
コード例 #25
0
        protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
        {
            bool *propertyCheckedFlags = stackalloc bool[resources.allEvents.Length];
            bool  needSubmit           = false;

            CustomDrawRequest.Initialize();
            UnsafeUtility.MemClear(propertyCheckedFlags, resources.allEvents.Length);
            GraphicsSettings.useScriptableRenderPipelineBatching = resources.useSRPBatcher;
            SceneController.SetState();
            data.context   = renderContext;
            data.resources = resources;
            if (motionVectorMatricesBuffer == null || !motionVectorMatricesBuffer.IsValid())
            {
                motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4));
            }
            else if (motionVectorMatricesBuffer.count < MotionVectorDrawer.Capacity)
            {
                motionVectorMatricesBuffer.Dispose();
                motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4));
            }
            MotionVectorDrawer.ExecuteBeforeFrame(motionVectorMatricesBuffer);
            data.buffer.SetGlobalBuffer(ShaderIDs._LastFrameModel, motionVectorMatricesBuffer);

#if UNITY_EDITOR
            int tempID = Shader.PropertyToID("_TempRT");

            foreach (var pair in bakeList)
            {
                PipelineCamera pipelineCam = pair.pipelineCamera;
                for (int i = 0; i < pair.worldToCamera.Length; ++i)
                {
                    pipelineCam.cam.worldToCameraMatrix = pair.worldToCamera[i];
                    pipelineCam.cam.projectionMatrix    = pair.projection[i];
                    pipelineCam.cameraTarget            = tempID;
                    data.buffer.GetTemporaryRT(tempID, pair.texArray.width, pair.texArray.height, pair.texArray.depth, FilterMode.Point, pair.texArray.format, RenderTextureReadWrite.Linear);
                    Render(pipelineCam, ref renderContext, pipelineCam.cam, propertyCheckedFlags);
                    data.buffer.CopyTexture(tempID, 0, 0, pair.texArray, i, 0);
                    data.buffer.ReleaseTemporaryRT(tempID);
                    data.ExecuteCommandBuffer();
                    renderContext.Submit();
                    needSubmit = false;
                }
                pair.worldToCamera.Dispose();
                pair.projection.Dispose();
                renderContext.ExecuteCommandBuffer(pair.buffer);
                pair.buffer.Clear();
                renderContext.Submit();
                needSubmit = false;
            }
            bakeList.Clear();
#endif
            foreach (var cam in preFrameRenderCamera)
            {
                Render(cam, ref renderContext, cam.cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
                renderContext.Submit();
                needSubmit = false;
            }
            preFrameRenderCamera.Clear();

            if (CustomDrawRequest.allEvents.Count > 0 || JobProcessEvent.allEvents.Count > 0)
            {
                foreach (var i in CustomDrawRequest.allEvents)
                {
                    i.PrepareJob(resources);
                }
                foreach (var i in JobProcessEvent.allEvents)
                {
                    i.PrepareJob();
                }
                JobHandle.ScheduleBatchedJobs();
                foreach (var i in CustomDrawRequest.allEvents)
                {
                    i.FinishJob();
                }
            }
            if (useBeforeFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_beforeFrameBuffer);
                m_beforeFrameBuffer.Clear();
                needSubmit           = true;
                useBeforeFrameBuffer = false;
            }
            foreach (var cam in cameras)
            {
                PipelineCamera pipelineCam = cam.GetComponent <PipelineCamera>();
                if (!pipelineCam)
                {
#if UNITY_EDITOR
                    if (cam.cameraType == CameraType.SceneView)
                    {
                        renderingEditor = true;
                        var pos = cam.transform.eulerAngles;
                        pos.z = 0;
                        cam.transform.eulerAngles = pos;
                        if (!Camera.main || !(pipelineCam = Camera.main.GetComponent <PipelineCamera>()))
                        {
                            continue;
                        }
                    }
                    else if (cam.cameraType == CameraType.Game)
                    {
                        renderingEditor = false;
                        pipelineCam     = cam.gameObject.AddComponent <PipelineCamera>();
                    }
                    else
                    {
                        continue;
                    }
#else
                    renderingEditor = false;
                    pipelineCam     = cam.gameObject.AddComponent <PipelineCamera>();
#endif
                }
                else
                {
                    renderingEditor = false;
                }
                Render(pipelineCam, ref renderContext, cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
#if UNITY_EDITOR
                if (renderingEditor)
                {
                    renderContext.DrawGizmos(cam, GizmoSubset.PostImageEffects);
                }
#endif
                renderContext.Submit();
                needSubmit = false;
            }

            if (useAfterFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_afterFrameBuffer);
                m_afterFrameBuffer.Clear();
                needSubmit          = true;
                useAfterFrameBuffer = false;
            }
            if (needSubmit)
            {
                renderContext.Submit();
            }
            MotionVectorDrawer.ExecuteAfterFrame();
            foreach (var i in JobProcessEvent.allEvents)
            {
                i.FinishJob();
            }
        }
コード例 #26
0
        /// <param name="erosionBrushRadius"></param>
        /// <param name="mapSize">Square map size</param>
        /// <param name="heightmap"></param>
        /// <param name="numErosionIterations"></param>
        public void Erode(RenderTexture heightmap, int erosionBrushRadius, int numErosionIterations)
        {
            var mapSize = heightmap.width;// * heightmap.height;

            var erodeKernel  = erosion.FindKernel("CSMain");
            var packKernel   = erosion.FindKernel("CSPackHeight");
            var unpackKernel = erosion.FindKernel("CSUnPackHeight");

            // Create brush
            if (brushIndexOffsets == null)
            {
                brushIndexOffsets = new List <int>();
            }
            else
            {
                brushIndexOffsets.Clear();
            }

            if (brushWeights == null)
            {
                brushWeights = new List <float>();
            }
            brushWeights.Clear();

            float weightSum = 0;

            for (var brushY = -erosionBrushRadius; brushY <= erosionBrushRadius; brushY++)
            {
                for (var brushX = -erosionBrushRadius; brushX <= erosionBrushRadius; brushX++)
                {
                    float sqrDst = brushX * brushX + brushY * brushY;
                    if (sqrDst < erosionBrushRadius * erosionBrushRadius)
                    {
                        brushIndexOffsets.Add(brushY * mapSize + brushX);
                        var brushWeight = 1 - Mathf.Sqrt(sqrDst) / erosionBrushRadius;
                        weightSum += brushWeight;
                        brushWeights.Add(brushWeight);
                    }
                }
            }

            for (var i = 0; i < brushWeights.Count; i++)
            {
                brushWeights[i] /= weightSum;
            }

            // Send brush data to compute shader
            if (brushIndexBuffer == null || !brushIndexBuffer.IsValid() || brushIndexBuffer.count != brushIndexOffsets.Count)
            {
                if (brushIndexBuffer != null && brushIndexBuffer.IsValid())
                {
                    brushIndexBuffer.Release();
                }
                brushIndexBuffer = new ComputeBuffer(brushIndexOffsets.Count, sizeof(int));
            }
            brushIndexBuffer.SetData(brushIndexOffsets);
            erosion.SetBuffer(0, "brushIndices", brushIndexBuffer);

            if (brushWeightBuffer == null || !brushWeightBuffer.IsValid() || brushWeightBuffer.count != brushWeights.Count)
            {
                if (brushWeightBuffer != null && brushWeightBuffer.IsValid())
                {
                    brushWeightBuffer.Release();
                }
                brushWeightBuffer = new ComputeBuffer(brushWeights.Count, sizeof(int));
            }
            brushWeightBuffer.SetData(brushWeights);
            erosion.SetBuffer(0, "brushWeights", brushWeightBuffer);

            // Generate random indices for droplet placement
            var randomIndices = new int[numErosionIterations];

            for (var i = 0; i < numErosionIterations; i++)
            {
                var randomX = Random.Range(erosionBrushRadius, mapSize + erosionBrushRadius);
                var randomY = Random.Range(erosionBrushRadius, mapSize + erosionBrushRadius);
                randomIndices[i] = randomY * mapSize + randomX;
            }

            // Send random indices to compute shader
            if (randomIndexBuffer == null || !randomIndexBuffer.IsValid() || randomIndexBuffer.count != randomIndices.Length)
            {
                if (randomIndexBuffer != null && randomIndexBuffer.IsValid())
                {
                    randomIndexBuffer.Release();
                }
                randomIndexBuffer = new ComputeBuffer(randomIndices.Length, sizeof(int));
            }
            randomIndexBuffer.SetData(randomIndices);
            erosion.SetBuffer(erodeKernel, "randomIndices", randomIndexBuffer);

            // Heightmap buffer
            var heightBufferSize = heightmap.width * heightmap.height;

            if (heightBuffer == null || !heightBuffer.IsValid() || heightBuffer.count != heightBufferSize)
            {
                if (heightBuffer != null && heightBuffer.IsValid())
                {
                    heightBuffer.Release();
                }
                heightBuffer = new ComputeBuffer(heightBufferSize, sizeof(float));
            }

            erosion.SetBuffer(erodeKernel, "map", heightBuffer);

            // Settings
            erosion.SetInt("borderSize", erosionBrushRadius);
            erosion.SetInt("mapSize", mapSize);
            erosion.SetInt("brushLength", brushIndexOffsets.Count);
            erosion.SetInt("maxLifetime", maxLifetime);
            erosion.SetFloat("inertia", inertia);
            erosion.SetFloat("sedimentCapacityFactor", sedimentCapacityFactor);
            erosion.SetFloat("minSedimentCapacity", minSedimentCapacity);
            erosion.SetFloat("depositSpeed", depositSpeed);
            erosion.SetFloat("erodeSpeed", erodeSpeed);
            erosion.SetFloat("evaporateSpeed", evaporateSpeed);
            erosion.SetFloat("gravity", gravity);
            erosion.SetFloat("startSpeed", startSpeed);
            erosion.SetFloat("startWater", startWater);

            erosion.SetBuffer(packKernel, "map", heightBuffer);
            erosion.SetTexture(packKernel, "heightTexture", heightmap);
            erosion.SetBuffer(unpackKernel, "map", heightBuffer);
            erosion.SetTexture(unpackKernel, "heightTexture", heightmap);

            var threadsPackingX = Mathf.CeilToInt(heightmap.width / 32f);
            var threadsPackingY = Mathf.CeilToInt(heightmap.height / 32f);

            erosion.Dispatch(packKernel, threadsPackingX, threadsPackingY, 1);
            var erodeThreads = Mathf.CeilToInt(numErosionIterations / 1024f);

            erosion.Dispatch(erodeKernel, erodeThreads, 1, 1);
            erosion.Dispatch(unpackKernel, threadsPackingX, threadsPackingY, 1);
        }
コード例 #27
0
 public override bool CheckProperty()
 {
     return(reflectionIndices.IsValid() && ssrEvents.MaterialEnabled());
 }
コード例 #28
0
 public override bool CheckProperty()
 {
     return(reflectionIndices.IsValid());
 }
コード例 #29
0
 public void PushDataToGlobal()
 {
     Debug.Assert(m_Buffer.count > 0);
     Debug.Assert(m_Buffer.IsValid());
     Shader.SetGlobalBuffer(m_PropertyID, m_Buffer);
 }
コード例 #30
0
        protected override void Render(ScriptableRenderContext renderContext, Camera[] cameras)
        {
            currentFrameCamera.Clear();
            PipelineCamera.InitializeDict();
            foreach (var cam in cameras)
            {
                CameraSetting csg;
                ulong         pipelineCamPtr;
                if (!PipelineCamera.CameraSearchDict.Get(cam.gameObject.GetInstanceID(), out pipelineCamPtr))
                {
                    if (!cam.TryGetComponent(out csg.pipeCam))
                    {
#if UNITY_EDITOR
                        if (cam.cameraType == CameraType.SceneView)
                        {
                            csg.isRenderingEditor = true;
                            var pos = cam.transform.eulerAngles;
                            pos.z = 0;
                            cam.transform.eulerAngles = pos;
                            if (!Camera.main || !(csg.pipeCam = Camera.main.GetComponent <PipelineCamera>()))
                            {
                                continue;
                            }
                        }
                        else if (cam.cameraType == CameraType.Game)
                        {
                            csg.isRenderingEditor = false;
                            csg.pipeCam           = cam.gameObject.AddComponent <PipelineCamera>();
                        }
                        else
                        {
                            continue;
                        }
#else
                        csg.isRenderingEditor = false;
                        csg.pipeCam           = cam.gameObject.AddComponent <PipelineCamera>();
#endif
                    }
                    else
                    {
                        csg.isRenderingEditor = false;
                        csg.pipeCam.AddToDict();
                    }
                }
                else
                {
                    csg.isRenderingEditor = false;
                    csg.pipeCam           = MUnsafeUtility.GetObject <PipelineCamera>((void *)pipelineCamPtr);
                }
                csg.cam         = cam;
                csg.pipeCam.cam = cam;
                csg.pipeCam.BeforeFrameRendering();
                currentFrameCamera.Add(csg);
            }
            bool *propertyCheckedFlags = stackalloc bool[resources.allEvents.Length];
            bool  needSubmit           = false;
            CustomDrawRequest.Initialize();
            UnsafeUtility.MemClear(propertyCheckedFlags, resources.allEvents.Length);
            SceneController.SetState();
            data.context   = renderContext;
            data.resources = resources;
            if (motionVectorMatricesBuffer == null || !motionVectorMatricesBuffer.IsValid())
            {
                motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4));
            }
            else if (motionVectorMatricesBuffer.count < MotionVectorDrawer.Capacity)
            {
                motionVectorMatricesBuffer.Dispose();
                motionVectorMatricesBuffer = new ComputeBuffer(MotionVectorDrawer.Capacity, sizeof(float3x4));
            }
            MotionVectorDrawer.ExecuteBeforeFrame(motionVectorMatricesBuffer);
            data.buffer.SetGlobalBuffer(ShaderIDs._LastFrameModel, motionVectorMatricesBuffer);

#if UNITY_EDITOR
            int tempID = Shader.PropertyToID("_TempRT");

            foreach (var pair in bakeList)
            {
                PipelineCamera pipelineCam = pair.pipelineCamera;
                for (int i = 0; i < pair.worldToCamera.Length; ++i)
                {
                    pipelineCam.cam.worldToCameraMatrix = pair.worldToCamera[i];
                    pipelineCam.cam.projectionMatrix    = pair.projection[i];
                    pipelineCam.cameraTarget            = tempID;
                    data.buffer.GetTemporaryRT(tempID, pair.texArray.width, pair.texArray.height, pair.texArray.depth, FilterMode.Point, pair.texArray.format, RenderTextureReadWrite.Linear);
                    Render(pipelineCam, ref renderContext, pipelineCam.cam, propertyCheckedFlags);
                    data.buffer.CopyTexture(tempID, 0, 0, pair.texArray, i, 0);
                    data.buffer.ReleaseTemporaryRT(tempID);
                    data.ExecuteCommandBuffer();
                    renderContext.Submit();
                    needSubmit = false;
                }
                pair.worldToCamera.Dispose();
                pair.projection.Dispose();
                renderContext.ExecuteCommandBuffer(pair.buffer);
                pair.buffer.Clear();
                renderContext.Submit();
                needSubmit = false;
            }
            bakeList.Clear();
#endif
            foreach (var cam in preFrameRenderCamera)
            {
                Render(cam, ref renderContext, cam.cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
                renderContext.Submit();
                needSubmit = false;
            }
            preFrameRenderCamera.Clear();
            if (CustomDrawRequest.allEvents.Count > 0 || JobProcessEvent.allEvents.Count > 0)
            {
                foreach (var i in CustomDrawRequest.allEvents)
                {
                    i.PrepareJob(resources);
                }
                foreach (var i in JobProcessEvent.allEvents)
                {
                    i.PrepareJob();
                }
                JobHandle.ScheduleBatchedJobs();
                foreach (var i in CustomDrawRequest.allEvents)
                {
                    i.FinishJob();
                }
                foreach (var i in JobProcessEvent.allEvents)
                {
                    i.FinishJob();
                }
            }
            if (Application.isPlaying && resources.clusterResources)
            {
                resources.clusterResources.UpdateData(data.buffer, resources);
            }
            resources.loadingThread.Update();
            if (useBeforeFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_beforeFrameBuffer);
                m_beforeFrameBuffer.Clear();
                needSubmit           = true;
                useBeforeFrameBuffer = false;
            }
            if (iRunnableObjects.isCreated)
            {
                foreach (var i in iRunnableObjects)
                {
                    IPipelineRunnable func = MUnsafeUtility.GetObject <IPipelineRunnable>((void *)i.value);
                    func.PipelineUpdate(ref data);
                }
            }
            if (cameras.Length > 0)
            {
                data.buffer.SetGlobalVector(ShaderIDs._SceneOffset, new float4(sceneOffset, 1));
            }
            foreach (var cam in currentFrameCamera)
            {
                renderingEditor = cam.isRenderingEditor;

                Render(cam.pipeCam, ref renderContext, cam.cam, propertyCheckedFlags);
                data.ExecuteCommandBuffer();
#if UNITY_EDITOR
                if (renderingEditor)
                {
                    renderContext.DrawGizmos(cam.cam, GizmoSubset.PostImageEffects);
                    ScriptableRenderContext.EmitWorldGeometryForSceneView(cam.cam);
                }
#endif
                renderContext.Submit();
                needSubmit = false;
            }

            if (useAfterFrameBuffer)
            {
                renderContext.ExecuteCommandBuffer(m_afterFrameBuffer);
                m_afterFrameBuffer.Clear();
                needSubmit          = true;
                useAfterFrameBuffer = false;
            }
            if (needSubmit)
            {
                renderContext.Submit();
            }
            MotionVectorDrawer.ExecuteAfterFrame();
            sceneOffset = 0;
            foreach (var cam in currentFrameCamera)
            {
                cam.pipeCam.cam = cam.cam;
                cam.pipeCam.AfterFrameRendering();
            }
        }