Screen-space Shader Debug

I’m trying to write a fragment shader that works in screen-space, to produce an even gradient across the screen.
I’ve made some progress thanks to this Unity Answer, but for some reason my shader’s gradient doesn’t stretch the whole width of the screen, only some of the middle. Here’s an image of the effect. alt text

Here is the shader. It could be shorter but I’ve tried to keep it verbose for clarity for myself.

Shader "Debug/AllInput" { 
   SubShader { 
      Pass { 
         CGPROGRAM 
 
         #include "UnityCG.cginc"

         #pragma vertex vert  
         #pragma fragment frag 
 
         struct vertexInput {
            float4 vertex : POSITION;
         };
         struct vertexOutput {
            float4 pos : SV_POSITION;
            float4 vertPos : TEXCOORD5; 
         };
 
         vertexOutput vert(vertexInput input) {
            vertexOutput output;

            output.pos = mul(UNITY_MATRIX_MVP, input.vertex);

            // We're now in clipspace, ranging from -1,-1,-1, to 1,1,1
            float4 clipSpace =  mul(UNITY_MATRIX_MVP, input.vertex);

            // Convert from -1~1 to 0~1
            clipSpace.xy = 0.5*(clipSpace.xy+1.0);

            // Convert from 0~1 to 0~1280 (etc.)
            // Skip this, 0~1 more useful for debug rendering
            //clipSpace.xy *= _ScreenParams.xy;

            output.vertPos = clipSpace;
            return output;
         }
 
         float4 frag(vertexOutput input) : COLOR {
            return float4(input.vertPos.x, input.vertPos.x, input.vertPos.x, 1.0); 
         }
 
         ENDCG  
      }
   }
}

Could someone tell me why this is?

I'm guessing the output of the transform isn't what you are expecting. Try just plotting intput.vertPos.x, input.vertPos.x/1000 etc - see what you are actually getting. No pic BTW!

1 Answer

1

I went back to the original post, and I think I fixed it. I was forgetting to divide by the width of the screen, to convert from Clip Space which is square, to the actual perspective.
It’s mentioned as “perspective divide” in the CG article from the previous Answer

So the calculations now look like:

    float4 clipSpace =  mul(UNITY_MATRIX_MVP, input.vertex);
    clipSpace.xy /= clipSpace.w;
    clipSpace.xy = 0.5*(clipSpace.xy+1.0);

Thanks again everyone :slight_smile:

Optimized for mad: clipSpace.xy = clipSpace.xy * 0.5f + 0.5f; (Always multiply then add, in that order)