How to prevent out of range buffer in compute shader?

I write in a shader:
uint index = gl_GlobalInvocationID.x;
But since the number of elements in the buffer is not a multiple of local_size_x gl_GlobalInvocationID.x can go out of buffer range, how to prevent this from happening?

Is there something wrong with the obvious solution of “put more space in the buffer”? If you want to index into a buffer, you need to make sure the buffer has sufficient storage so that it can read/write whatever data it’s trying to access.

1 Like

If you use an unbound array such as a shader storage buffer, you can always just use the length function of said buffer and do an early return:

if (index > particleIn.length() - 1) { 
	return;
}
1 Like

Thanks for the reply! If I use local_size_x not equal to degree 2(16, 32, 64, 128, etc.) will there be performance degradation? Or local_size_x = 64 and local_size_x = 63 or 65 will work with the same performance?

Performance for different work group and dispatch sizes is heavily implementation dependent. There is no general answer other than “you need to profile”.

1 Like