Sunday, June 26, 2022
HomeGame Developmentunity - Ship an array of struct to compute shader

unity – Ship an array of struct to compute shader


I’m utilizing Unity to ship two varieties of information to the Compute Shader:

A struct:

struct Flock
{
    public Vector3 place;   
    public Vector3 velocity;   
}

And an Array of the above struct.

C# Code:

Flock[] ComputeFlock()
{
    Flock[] output = new Flock[Amount];

    int kernel = FlockComputeShader.FindKernel("MoveFlock");

    // Flock struct
    int dimension = sizeof(float) * 3 + sizeof(float) * 3;
    ComputeBuffer buffer = new ComputeBuffer(_flockAI.Size, dimension);
    buffer.SetData(_flockAI);

    FlockComputeShader.SetBuffer(kernel, "dataBuffer", buffer);

    // Flock array
    ComputeBuffer neighboursBuffer = new ComputeBuffer(_flockAI.Size, dimension * _flockAI.Size);
    neighboursBuffer.SetData(_flockAI);
    FlockComputeShader.SetBuffer(kernel, "neighbours", neighboursBuffer);

    FlockComputeShader.Dispatch(kernel, _flockAI.Size / 16, 1, 1);
    buffer.GetData(output);
    buffer.Dispose();

    return output;
}
                 

Compute Shader:

#pragma kernel MoveFlock

struct FlockVec3Float
{
    float3 place;
    float3 velocity;
};

RWStructuredBuffer<FlockVec3Float> dataBuffer;

StructuredBuffer<FlockVec3Float> neighbours[1024];

[numthreads(16,1,1)]
void MoveFlock(uint3 id : SV_DispatchThreadID)
{
    for (uint i = 0; i < 1024; i++) {
        dataBuffer[id.x].place.xyz = dataBuffer[id.x].place.xyz + neighbours[i].place.xyz;
    }
}

I’m attempting to carried out a type of boids algorithm within the compute shader. The struct is the boid and the array of structs is to establish positions of it is neighbours. What I am unable to determine is how I can ship the complete array of struct to the shader and have it iterate over it.

I can ship the struct and have the shader learn and write to it with none points. Can somebody level out what I is likely to be doing incorrect? I’m questioning whether it is one thing to do with the stride within the buffer. Thanks!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments