UV offset in surface shader.

Hello there,
I am working on a simple surface shader that blurs its texture, mainly as an experiment for uv coordinate offsets.
Here is the code that i am using.

half4 p;
for(i=0;i<3;i++)
   for(j=0;j<3;j++){
     p.rgb+=tex2D (_MainTex, float2(IN.uv_MainTex.x+(i-1),IN.uv_MainTex.y+(j-1)))/9;
   }
 o.Albedo=p.rgb;

Unfortunately, this makes the object’s surface completely black. Removing the +(i-1) and +(j-1) parts makes the shader behave normally again, but obviously without the desired result.

What am i doing wrong?

It’s hard to say why the lookup becomes black without knowing what the texture looks like and whether its wrap mode is set to Repeat or Clamp. But I think part of your problem stems from a slight misunderstanding about UVs: They are not discrete, integer pixel coordinates. You can’t “move to the next pixel” by adding or subtracting 1. Instead, they are normalized ranges across the texture. 0,0 is the lower left corner of the texture and 1,1 is the upper right corner. So when you add whole integers to the UV coordinates before your lookup, you’re causing the UVs to leave the 0-1 range, becoming < 0 and > 1 as the loops iterate.

To grab the next pixel, you have to include a division by the texture’s height and width and then add that to the pixel’s interpolated UV. Try that, and see if it has an effect on the calculated color.

On another note, try to limit divisions or avoiding them entirely in shaders where possible. A division is a lot more computationally expensive than a multiplication. E.g. here, instead of dividing by 9, multiply by 0.111111f. :slight_smile: