0
\$\begingroup\$

I'm having some very strange behavior trying to calculate gradients in a shader. In both snippets, uv is the texture coordinate, duv is a float3 proportional to (1/width,1/height,0), c is tex2D(_SelfTexture2D,uv), and output is a float4 that I return from my fragment shader.

output.r = tex2D(_SelfTexture2D, uv - duv.zy).r +
        tex2D(_SelfTexture2D, uv + duv.zy).r +
        tex2D(_SelfTexture2D, uv - duv.xz).r +
        tex2D(_SelfTexture2D, uv + duv.xz).r - 4 * c.r

produces the expected output- I put in a gaussian, and I get a smooth gradient out.

If I instead write any of

float4 left = tex2D(_SelfTexture2D, uv-duv.xz);
float4 right = tex2D(_SelfTexture2D, uv + duv.xz);
float4 top = tex2D(_SelfTexture2D, uv + duv.zy);
float4 bottom = tex2D(_SelfTexture2D, uv - duv.zy);
output.r = (left + right + bottom + top - 4 * c).r;

or

float4 left = tex2D(_SelfTexture2D, uv-duv.xz);
float4 right = tex2D(_SelfTexture2D, uv + duv.xz);
float4 top = tex2D(_SelfTexture2D, uv + duv.zy);
float4 bottom = tex2D(_SelfTexture2D, uv - duv.zy);
output.r = (left.r + right.r + bottom.r + top.r - 4 * c.r);

or

float4 left = tex2D(_SelfTexture2D, uv-duv.xz).r;
float4 right = tex2D(_SelfTexture2D, uv + duv.xz).r;
float4 top = tex2D(_SelfTexture2D, uv + duv.zy).r;
float4 bottom = tex2D(_SelfTexture2D, uv - duv.zy).r;
output.r = (left + right + bottom + top - 4 * c.r);

I instead get alternating concentric rings of reasonable values and just 0, at a scale roughly proportional to duv- clearly the way in which I access the texture is affecting the results, but I have no idea how or why.

\$\endgroup\$
  • \$\begingroup\$ I don't see any obvious errors in this code, though it's unclear why you're using float4 for left right top and bottom if you only want a single channel from them. Are you certain that this bloc of code is the only part that's changed between your working and non-working examples? \$\endgroup\$ – DMGregory May 20 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.