How to correctly sample a shadow map from a render texture?

I’m trying to implement a custom shader to determine shadows on a terrain based on the sun position.

I have the pov of the sun light rendering depth to a render texture, and this, along with the matrix is an input to my custom terrain shader.

Here’s a screenshot showing the render texture and the depth of the pixels in view from the light:

alt text

So it looks like so far, so good. The part I am struggling with is projecting my rendertexture (which is a shadow depth map) onto the terrain surface from the camera pov.

It seems no matter what I try, the depth values for the projection always come out as 0 (i.e. they look fully black when I visualise them on the surface).

I am currently trying:
Code:

 float4 shadow_depth4 = tex2Dproj(_RenderPaintTexture, i.sh);
 float shadow_depth = DecodeFloatRG(shadow_depth4.zw);

Where i.sh is output from the vertex shader as:

Code:

o.sh = mul(_Object2World, v.vertex);
o.sh = mul(_ShadowDepthMatrix, o.sh);

…but that doesn’t appear to work. If I output shadow_depth from the frag shader, I get this:

alt text

Obviously any shadow depth test is going to return all pixels as in shadow using this.

Any ideas where I am going wrong? Thanks in advance.

Ok, I figured it out, so might as well answer my own Q…

//Get the distance to the camera from the depth buffer for this point.
//To do this, we sample the shadow map from our calculated texel position.
//This gives us the depth from the light to the closest lit pixel in view (from the light pov).
float4 shadow_depth4 = tex2Dproj(_RenderPaintTexture, i.sh.xyw);
float shadow_depth = DecodeFloatRG(shadow_depth4.zw);
			
//calculate the depth of the visible pixel from the light position
float view_depth = (i.sh.z / i.sh.w) * 0.99;
			
half4 shadow_col;
if(shadow_depth < view_depth) {
    //Pixel is in shadow
shadow_col = half4(0.0,0.0,1.0,1.0);
} else {
    //Pixel is in sun
    shadow_col = half4(1.0,0.5,0.0,1.0);
}