compute shader texture sampling issue

Hello everyone! I’m currently in the process of learning how to work with compute shaders and I’ve experienced an issue with texture sampling in compute shader. When I sample a texture, it always gives me same value for whatever position I sample.

Input texture is usually a texture with resolution of 64x64, RGBA32 type, resolution is also 64 and threads is 8 (for testing purpouses).

Simplified compute shader code

Texture2D<float4> _HeightMap;
SamplerState sampler_HeightMap;
RWStructuredBuffer<float3> Vertices;
uniform int Resolution;

// Calculate index in buffer
int GetIndex(uint3 id)
{
	return id.y + Resolution* id.x;
}

[numthreads(8,8,1)]
void CalculateVertices(uint3 id : SV_DispatchThreadID)
{
	// Calculate vertex id in buffer
	int idx = GetIndex(id);
	// Sample heightmap, set height to some value and add vertex to a buffer
	Vertices[idx] = float3(id.x, _HeightMap[id.xy].b, id.y);
}

Simplified c# code

public Mesh GenerateMesh(Texture2D input, int resolution, int threads)
{
    //buffers for vertices and map of vertices to make triangles
    int numIndices = 2*(resolution-1)*(resolution- 1) * 3;
    ComputeBuffer vertexBuffer = new ComputeBuffer(resolution* resolution, sizeof(float) * 3, ComputeBufferType.Default);
    						
    int vertexKernel = _terrainShader.FindKernel("CalculateVertices");
    // Init buffers and other fields
    _terrainShader.SetBuffer(vertexKernel, "Vertices", vertexBuffer);	
    _terrainShader.SetTexture(vertexKernel, "_HeightMap", input);
    _terrainShader.SetInt("Resolution", resolution);
    _terrainShader.Dispatch(vertexKernel, resolution / threads, resolution / threads, 1);
}

What I’ve tried
I’ve tried to sample texture using _HeightMap.SampleLevel(), I’ve also tried using RWTexture

Thank you all for your help.

Alright I think I’ve finally found a solution after a few days of try and error. The source of the error wasn’t sampling in the compute shader as I initially expected. Issue was in the input texture itself. Unity and your hardware has only limited graphics formats and texture formats that can handle ([Unity - Manual: Recommended, default, and supported texture formats, by platform][1]) and because I was downloading that texture on the fly from the web, graphicformat was set to some weird value (outside the GraphicFormat enum range), even thou unity kinda understood its data when I’ve save it.


Fix: It’s a kind of a hack but its OK for my application. Just call Compress() on the texture2D and graphicsFormat and format shoud fix itself. Or you can create a new texture, change formats to something appropriate and copy data using Graphics.Blit().

tl;dr if your sampled texture in compute shader is some grayish color, check your texture2d formats :slight_smile: