In OpenGL ES 2.0, How to read neighboring texels from a Sampler

glslopengl-esopengl-es-2.0

I am passing a texture with NxM size as a sampler in the GLSL fragment shader (OpenGL ES 2.0). What is the right way to read the texel data from the neighboring texel ? I do not have a "varying" texture coordinate in the fragment shader. I can only use fragment coordinate to read the texture information.

following is my shader, I am not sure if its actually reading the data:

precision mediump float;

uniform sampler2D Sampler;

#define OFFSET 1.0

void main()
{

    vec2 T = gl_FragCoord.xy;

    //Find neighboring velocities:
    vec2 N = texture2D(Sampler,vec2(T.x,T.y+OFFSET)).xy;
    vec2 S = texture2D(Sampler,vec2(T.x,T.y-OFFSET)).xy;
    vec2 E = texture2D(Sampler,vec2(T.x+OFFSET,T.y)).xy; 
    vec2 W = texture2D(Sampler,vec2(T.x-OFFSET,T.y)).xy; 
}

Is the OFFSET value should be 1.0 OR something else for NxM size texture ?

Best Answer

Nem is right in his answer that the texture coordinate should be in [0,1]. But keep in mind, that the values of gl_FragCoord are in [0,N]x[0,M] (assuming your viewport is NxM, too). So you are correct in adding an offset of 1 to the fragment coordinate, but this sum has then to be divided by the screen size (which is probably the same as the texture size):

precision mediump float;

uniform sampler2D Sampler;
uniform vec2 invScreenSize;

void main()
{

    vec2 T = gl_FragCoord.xy;

    //Find neighboring velocities:
    vec2 N = texture2D(Sampler,vec2(T.x,T.y+1.0)*invScreenSize).xy;
    vec2 S = texture2D(Sampler,vec2(T.x,T.y-1.0)*invScreenSize).xy;
    vec2 E = texture2D(Sampler,vec2(T.x+1.0,T.y)*invScreenSize).xy; 
    vec2 W = texture2D(Sampler,vec2(T.x-1.0,T.y)*invScreenSize).xy; 
}

where invScreenSize is the reciprocal screen size (1/N, 1/M), to prevent division in the shader.

Related Topic