Hello everyone,
I have been working on a marching cube mesh generation game and would like to change the color of my mesh depending on the height of each vertex inside the mesh.
I could do it directly without compute shader but processing time was too long so I tried to move it to a compute shader.
Unfortunately I’m not so good with shaders so I’m now stuck …
For test pupose, I put all the vertiges of my mesh to blue and try to move it to red, I feel like once this base is done it will just be adding the scale and lerp the gradiant to get the colors I want.
If I run my shader now I get this error on each chunk:
ColorCompute.compute: Kernel at index (0) is invalid
And when clicking on the shader in my project folder I can see
array dimension must be literal scalar expression at kernel CSMain
Here is the script
public class ColorGenerator : MonoBehaviour
{
//reference the marchingCube.compute shader that will be used later
public ComputeShader ColorCompute;
public Mesh ApplyColors(Mesh mesh, float chunkPositionY, Gradient heightGradient)
{
//Create the vertex count and assign the kernel id to an integer
int vertexCount = mesh.vertexCount;
int kernelID = ColorCompute.FindKernel("CSMain");
// Create a compute buffer to hold vertex color data
ComputeBuffer colorBuffer = new ComputeBuffer(vertexCount, sizeof(float) * 4, ComputeBufferType.Default);
colorBuffer.SetData(mesh.colors);
ColorCompute.SetBuffer(kernelID, "ColorBuffer", colorBuffer);
// paramaters to calculate the color to apply
ColorCompute.SetInt("numVertices", vertexCount); // Pass the number of vertices
// Dispatch the compute shader
int threadGroups = Mathf.CeilToInt(vertexCount/ 256.0f);
ColorCompute.SetInt("threadGroups", threadGroups);
// Dispatch the compute shader
ColorCompute.Dispatch(kernelID, threadGroups, 1, 1);
// Get the modified vertex color data back from the compute buffer
Color[] modifiedColors = new Color[vertexCount];
colorBuffer.GetData(modifiedColors);
// Update the mesh with the modified vertex colors
mesh.colors = modifiedColors;
return mesh;
}
}
and the Shader
#pragma kernel CSMain
StructuredBuffer<float4> ColorBuffer;
uint numVertices;
uint threadGroups;
float4 modifiedColor;
[numthreads(threadGroups, 1, 1)]
void CSMain(uint3 id : SV_DispatchThreadID)
{
float4 newColor[numVertices];
// Evaluate the gradient at the computed position
newColor[id.x].x = ColorBuffer[id.x].x + 1;
newColor[id.x].y = ColorBuffer[id.x].y;
newColor[id.x].z = ColorBuffer[id.x].z - 1;
newColor[id.x].r = ColorBuffer[id.x].r;
// Update the RGB channels of the vertex color
ColorBuffer[id.x] = newColor;
}