Question about Dispatch/Groups/ThreadID in Compute Shader

Hi,

I am newby on ComputeShader, but I thought I d got the global idea about them until I get Dispatch NbGroup/NbThread/ThreadID values not matching what I expected.

So for the investigation I have tried the simplest compute shader I can make:

#pragma kernel CSMain
RWStructuredBuffer<int> result;

[numthreads(8, 8, 8)]
void CSMain(int id : SV_DispatchThreadID )
{
    result[id] = id;
}

called by

public class DispatchShader : MonoBehaviour
{
    public ComputeShader compute;

    // Use this for initialization
    void Start()
    {
        Dispatch();
    }

    void Dispatch()
    {
        ComputeBuffer resultBuffer = new ComputeBuffer(8*8*8, sizeof(int));
      
        var kernel = compute.FindKernel("CSMain");
        compute.SetBuffer(kernel, "result", resultBuffer);
        compute.Dispatch(kernel,1,1,1);

        int[] result = new int[8 * 8 * 8];
        resultBuffer.GetData(result);
    
        resultBuffer.Release();
    }
}

From my understanding:

  • each computing group can be modelized as a “8x8x8 cube” ([numthreads(8, 8, 8)])
  • I am calling it on a single group (compute.Dispatch(kernel,1,1,1):wink:

It look like only the “x” thread values are considered (numthreads:8 * dispatch:x).

This test is quite dummy -I know- but it illustrate quite well the dispatching.
And the results I get are not the one I expected ([numthreads(8, 8, 8)] + compute.Dispatch(kernel,1,1,1) => each value in the array should match each index)

maybe, someone have any idea of what I misunderstand/missing/making wrong? :slight_smile:

Thx :slight_smile:

SV_DispatchThreadID is actually a vector of 3 values. If you create a new compute shader you will see it defined as follows: uint3 id : SV_DispatchThreadID

You truncated it to a single value, just the x component, and hence the observed behavior.

For more information on the various semantics to index threads you can read:

Specifically the semantic you want to get the behaviour you are after is:
SV_GroupIndex

1 Like

Thx a lot!

I naively thought declaring SV_DispatchThreadID as “uint” would alias the vector by a uniqueID==“thread index” but I was wrong: as you said declaring it as int will just consider x.

Hi where can i see the debug window here?