ComputeShader中Counter类型的使用

接上一篇:https://www.cnblogs.com/hont/p/10122129.html

 

除了Append类型对应的Consume/AppendStructuredBuffer还有一个Counter类型可以进行计数操作。

 

那么测试一下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ComputeShaderTest : MonoBehaviour
{
    public ComputeShader computeShader;


    void Awake()
    {
        var kernelID = computeShader.FindKernel("CSMain");
        var counterBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.Counter);
        counterBuffer.SetCounterValue(5);

        computeShader.SetBuffer(kernelID, "counter", counterBuffer);
        computeShader.Dispatch(kernelID, 1, 1, 1);

        var argBuffer = new ComputeBuffer(1, sizeof(int), ComputeBufferType.IndirectArguments);
        ComputeBuffer.CopyCount(counterBuffer, argBuffer, 0);
        //通过这个方法拿到第一个数据。

        int[] counter = new int[1] { 0 };
        argBuffer.GetData(counter);

        int count = counter[0];

        Debug.Log("count: " + count);

        argBuffer.Release();
        counterBuffer.Dispose();
    }
}

 

computer shader:

#pragma kernel CSMain

RWStructuredBuffer<int> counter;

[numthreads(8, 1, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
    if (id.x == 1 || id.x == 2 || id.x == 3)
    {
        //counter.IncrementCounter();
        counter.DecrementCounter();
    }
}

 

测试的是DecrementCounter最终打印2。

 

 

另外需要注意,如果在同一个csmain里同时进行加减操作则会报错:

RWStructuredBuffers may increment or decrement their counters, but not both. at kernel CSMain

 

posted @ 2018-12-16 11:00  HONT  阅读(1878)  评论(0编辑  收藏  举报