Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Unity Compute Shader Indexing Unequal Buffers

Discussion in 'Scripting' started by Shiikarii, May 6, 2018.

  1. Shiikarii

    Shiikarii

    Joined:
    Feb 6, 2014
    Posts:
    89
    As the title already implies, I'm trying to index buffers which do not have the same size.

    Imagine the following example:
    Code (CSharp):
    1. InputBuffer = new ComputeBuffer((int)(size * size), sizeof(float));
    2. OutputBuffer = new ComputeBuffer((int)(size * size * 28), sizeof(int));
    To index both, I thought I could just do:
    Code (CSharp):
    1. StructuredBuffer<float> input;
    2. RWStructuredBuffer<int> output;
    3.  
    4. [numthreads( 16, 16, 1)]
    5. void marching_squares (uint3 idx : SV_DispatchThreadID)
    6. {
    7.     uint iI = idx.x + idx.y * (size);
    8.     uint iO = idx.x + idx.y * (size * 28);
    9.  
    10.     float v = input[iI];
    11.  
    12.     output[iO] = v;
    13.     output[iO + 1] = 42;
    14.     output[iO + 2] = 43;
    15.     output[iO + 3] = 44;
    16. }
    For some reason I'm getting the following debug logs with this print function:
    Code (CSharp):
    1. for (uint i = 0; i < OutputBuffer.Length; i += 28)
    2.             Debug.Log(string.Format("Idx={0}\tCse={1}\tOut1={2}\tOut2={3}\tOut3={4}",
    3.             i, Buffer[i], Buffer[i + 1], Buffer[i + 2], Buffer[i + 3]));
    4.  
    5. Idx=0   Cse=0   Out1=42 Out2=43 Out3=44
    6. Idx=28  Cse=44  Out1=44 Out2=44 Out3=44
    7. Idx=56  Cse=44  Out1=44 Out2=44 Out3=44
    8. Idx=84  Cse=44  Out1=44 Out2=44 Out3=44
    9. Idx=112 Cse=44  Out1=44 Out2=43 Out3=44
    It works only for the first 28 values. Why?
     
  2. voxelholic

    voxelholic

    Joined:
    Feb 2, 2016
    Posts:
    6
    Did you ever figure this out? I'm trying to do something very similar.
     
  3. sstrong

    sstrong

    Joined:
    Oct 16, 2013
    Posts:
    2,192
    If it is a 2D flattened array, you'd need something like this:

    Code (CSharp):
    1. iI = (id.y * size) + id.x;
    where size is the width or resolution of your original 2D array