Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Compute Buffer, layout in memory

Discussion in 'Shaders' started by Tom_Olsen, Oct 12, 2021.

  1. Tom_Olsen

    Tom_Olsen

    Joined:
    Oct 11, 2020
    Posts:
    10
    Hello community,

    I have GPU programming experience (HIP and Cuda), but am new to compute shaders in unity.
    The following datastructure on my CPU will create an array of structs. This data structure is mostly good for CPU cash efficiency when all values in the struct are needed simulatiously.

    Code (CSharp):
    1. public struct DataStruct
    2. {
    3.     public int state;
    4.     public float intensity;
    5.     public float rho;
    6.     public Vector2 u;
    7. }
    8.  
    9. DataStruct data = new DataStruct[1024]
    However on my GPU i would prefer a struct of arrays (warning, c++ styled pseudo code),

    Code (CSharp):
    1. template<int N>
    2. struct DataStruct
    3. {
    4.     int* state = new int[N];
    5.     float* intensity = new float[N];
    6.     float* rho = new float[N];
    7.     Vector2* u = new Vector2[N];
    8. }
    9.  
    10. DataStruct data[1024];
    How does unity actually interpret my DataStruct in the compute shader? Will it just copy my CPU DataStruct and thus create an array of structs. Or does it convert it to a struct of arrays for coalescent data access?

    If it remains an array of struct, what is the best way to create a struct of arrays? As far as i can tell you can't create structs with arrays in them with dynamic length in c#. The only solution I came up with would be to create one compute buffer for each array.

    @forum: Why isn't there a 'compute shader' or 'compute buffer' tag?
     
  2. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
    That's not possible. A SOA contains pointers (references in C#), which are not blittable data. To reproduce the SOA pattern, you need a separate compute buffer for each array.