Hi,
I have been working with compute shaders for some months on Mac and Unity 2020.
I’m testing the following very simple compute shader on Unity 2021.3.4f1:
#pragma kernel PerlinHeightMapCompute
float4 perlinHeightMapOffset;
uint mapLength;
RWStructuredBuffer<float> heightMap;
[numthreads(32,32,1)]
void PerlinHeightMapCompute (uint3 id : SV_DispatchThreadID)
{
if(id.x < mapLength && id.y < mapLength)
{
heightMap[id.y * mapLength + id.x] = 1;
}
}
I set the values for the compute shader with this c· code:
shader.SetInt("mapLength", heightMapSettings.mapSize);
shader.SetBuffer(kernelHandle, "heightMap", heightMapBuffer);
shader.SetBuffer(kernelHandle, "CurveKeyframes", keysArrayBuffer);
shader.SetInt("CubicHermiteSplineFramesCount", keysArrayBuffer.count);
shader.DispatchIndirect(kernelHandle, computeArgsBuffer);
AsyncGPUReadback.Request(heightMapBuffer, HeightMapBufferCallback);
And receive the heightMapBuffer with:
heightMapBuffer = new ComputeBuffer(settings.m_heightMapSettings.mapSize * settings.m_heightMapSettings.mapSize, sizeof(float));
void HeightMapBufferCallback(AsyncGPUReadbackRequest readbackRequest)
{
if (!readbackRequest.hasError)
{
if (readbackRequest.done)
{
Log();
gpuDataCount++;
DataReady();
}
}
}
The Log function just logs some data that is consistent except for the values of heightMapBuffer which all are zero:
heightMapSettings.mapSize = 64
computeArgsBuffer = [2,2,1]
This is consistent because of [numthreads(32,32,1)] in the compute shader (2 * 34 = 64)
readbackRequest.width = 16384
Which is the size that I set for heightMapBuffer:
heightMapBuffer = new ComputeBuffer(settings.m_heightMapSettings.mapSize * settings.m_heightMapSettings.mapSize, sizeof(float));
Indeed I have use nearly the same code in other projects.
Any idea why the AsyncGPUReadbackRequest is retrieving me:
[0,0,0,0,0, …0] (like not prossesed or retrieved too early) instead of [1,1,1,1,…1]
Edit:
It’s definitely the AsyncGPUReadbackRequest, because when I replace:
shader.DispatchIndirect(kernelHandle, computeArgsBuffer);
AsyncGPUReadback.Request(heightMapBuffer, HeightMapBufferCallback);
by
shader.Dispatch(kernelHandle, 2, 3, 1);
Log();
I get the values [1,1,1,1,…1] for heightMapBuffer.
The Log function is:
float[] heightMap = new float[settings.m_heightMapSettings.mapSize * settings.m_heightMapSettings.mapSize];
heightMapBuffer.GetData(heightMap);
Debug.Log(string.Join(",", heightMap));
Thanks.