I’m voxelizing a scene on the GPU similarly to nvidia’s article and writing it to an RWStructuredBuffer. It was working all fine and dandy when I first implemented it, but for some reason it started giving me a very strange bug where whenever I read from the red channel (using buffer[index].rgba, buffer[index].r, etc) in an image effect, the rest of the color channels (gba) are seemingly overridden by the red value. Reading from any or all of the gba channels works fine, but as soon as I touch the red channel, it seems to override the others. The fact that all of the data is correctly readable separately leads me to believe it’s specifically an error in reading, not writing, the data, but I have no idea why this would be happening.
What it’s supposed to look like (works fine when stepping through in the editor):
What it actually looks like (note that this is red channel of the above image):
Both of the above images are sampled using buffer[index].rgba. The following image is from half4(0, buffer[index].gba) (sorry for the different angle):
The gba image never goes grayscale, and sampling with half4(buffer[index].g, buffer[index].gba) works, too. The strangest part is it only happens on MOST frames. Some frames render fine, as in the first image. Specifically, when I step through in the editor, most frames render correctly, though some don’t.
The code for setting up the compute buffer:
voxelBuffer = new ComputeBuffer(TextureSize * TextureSize * TextureSize, sizeof(float) * 4, ComputeBufferType.Default);
...
Graphics.ClearRandomWriteTargets();
Graphics.SetRandomWriteTarget(1, voxelBuffer);
m_VoxelCamera.RenderWithShader(Voxelize, null);
Graphics.ClearRandomWriteTargets();
Then in the shader, it’s stored like this:
uniform RWStructuredBuffer<float4> _voxelTexture : register(u1);
I know this is a very specific issue and without more of the code it’s not particularly likely that anyone will have a solution, but is there anything I might be messing up which could be inciting this behavior? It’s driving me a little crazy. I’m not sure if sampling the buffer from another shader would cause similar issues, I’m going to test that later today.
EDIT: Apparently it’s an issue when R and G are both read, as determined by the following code:
half4 ret = _voxelTexture[voxelCoords.x * _VoxelTextureSize * _VoxelTextureSize + voxelCoords.y * _VoxelTextureSize + voxelCoords.z];
half r = ret.r;
half g = ret.g;
half b = ret.b;
half a = ret.a;
return half4(r,0,b,a);//ret.b;
}
When sampling with half4(r,g,0,0), the result is the same as the earlier image. When using the above code, it looks like this:
Returning r, g, b, or a yields the correct value.