I'm using a compute shader in unity to generate density values for the marching cube algorithm and for some it skips the calculation for every 17th value in the buffer and leaves it as 0.
The code to set up the compute buffer is:
public ComputeBuffer Generate(float radius,int width,float resolution,float[] planetCentre,float[] pos)
{
int threadGroups = (int)Mathf.Ceil(((width) + 1) / 8);
densityDebug = new float[((width) + 1) * ((width) + 1) * ((width) + 1)];
ComputeBuffer densityBuffer = new ComputeBuffer(((width) + 1) * ((width) + 1) * ((width) + 1), sizeof(float));
int kernelHandle = shader.FindKernel("CSMain");
shader.SetBuffer(kernelHandle, "densityBuffer", densityBuffer);
shader.SetFloat("resolution", resolution);
shader.SetInt("densityWidth", (width) + 1);
shader.SetFloat("radius", radius);
shader.SetFloats("planetCentre", planetCentre);
shader.SetFloats("pos", pos);
shader.Dispatch(kernelHandle, threadGroups, threadGroups, threadGroups);
densityBuffer.GetData(densityDebug);
return densityBuffer;
}
and the shader code is:
RWStructuredBuffer<float> densityBuffer;
int densityWidth;
float radius;
float3 planetCentre;
float3 pos;
float resolution;
int flattenedIndex(int x, int y, int z)
{
return (x * (densityWidth) * (densityWidth)) + (y * (densityWidth)) + z;
}
[numthreads(8,8,8)]
void CSMain (int3 id : SV_DispatchThreadID)
{
if (id.x >= densityWidth || id.y >= densityWidth || id.z >= densityWidth)
{
return;
}
float dSphere = pow(pos.x + (id.x * resolution) - planetCentre.x, 2) + pow(pos.y + (id.y * resolution) - planetCentre.y, 2) + pow(pos.z + (id.z * resolution) - planetCentre.z, 2) - pow(radius, 2);
densityBuffer[flattenedIndex(id.x, id.y, id.z)] = dSphere;
}
It happens no matter the values but for instance, the width is normally set to 16. Therefore, 3 thread groups are used. I am quite new to compute shaders so it could be something very simple.