Search Unity

Compute buffer and structured buffer

Discussion in 'Shaders' started by TheCelt, Jul 22, 2020.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    742
  2. sstrong

    sstrong

    Joined:
    Oct 16, 2013
    Posts:
    2,252
    I'd suggest StructuredBuffer<type> for items you only want to read in the Compute Shader or RWStructuredBuffer<type> for things you want to update in the shader and then potentially read back onto the CPU with bufName.GetData(1DArray).
     
  3. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    742
    Why is there no mention of StructuredBuffer type on microsoft's website ? Only Buffer<T>?
     
  4. sstrong

    sstrong

    Joined:
    Oct 16, 2013
    Posts:
    2,252
    I think StructuredBuffer is Unity's implementation - BTW have been using them for a few years without problems.
     
  5. aleksandrk

    aleksandrk

    Unity Technologies

    Joined:
    Jul 3, 2017
    Posts:
    3,023
  6. Michal_

    Michal_

    Joined:
    Jan 14, 2015
    Posts:
    365
    Buffer<T> can only use scalar, vector or matrix types as elements and max size of one element is 128 bits.

    Code (CSharp):
    1. Buffer<float> _FloatBuffer;
    2. Buffer<float4> _VectorBuffer;
    3. Buffer<float2x2> _Matrix2x2Buffer;
    4. // this won't compile because float4x4 is larger than 128bits
    5. Buffer<float4x4> _Matrix4x4Bufer;
    6.  
    StructuredBuffer<T> can use structure as an element.

    Code (CSharp):
    1. struct MyStruct
    2. {
    3.     float4 color;
    4.     float3 normal;
    5.     bool flag;
    6. }
    7.  
    8. StructuredBuffer<MyStruct> MyStructBuffer;
    9.  
    10. ...
    11. float4 color = MyStructBuffer[4].color;
    12. ...
    So basically, use Buffer for scalars and vectors and StructuredBuffer for everything else.
     
    henners999 likes this.
  7. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    742
    Ah thank you - this is what i was trying to understand. So if i am using the default shader types - i can just use Buffer instead of StructuredBuffer.
     
  8. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    742
  9. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
    It doesn't mention them because not every platform supports them, for some reason. I had to replace some Buffer<> with StructuredBuffer<> to get the shaders to compile in such cases.