Search code examples
glslglsles

Trying to get data from neighbour fragments with texelFetch in GLSL


My ultimate goal is to create an outline around a texture. To do that I've got to get data from the neighbor fragments and I'm trying this out by using texelFetch. In my try to use texelFetch I'm just trying to get the color data from the fragment to the right of every fragment and then turning the fragment's color white if the fragment to the right is not transparent. But this doesn't work, here's my code in the fragment shader to test texelFetch:

varying vec4 v_color;
varying vec2 v_texCoord0;

uniform vec3 dif_color;

uniform sampler2D u_sampler2D;

vec4 color_right;
vec4 color_left;
vec4 color_bottom;
vec4 color_top;

void main(){
    color_right = texelFetch(u_sampler2D, ivec2(v_texCoord0.x + 1, v_texCoord0.y), 0).rgba;

    if(color_right.a != 0){
    color.rgba = (1,1,1,1);
    }
    else{
    color.rgba = (0,0,0,0);
    }

    gl_FragColor = color;
}

Does anyone have an idea of what I could have done wrong?

Thank you very much for checking my question.


Solution

  • There are 2 ways to get the neighbor fragment in a texture. Either you use texelFetch, as you decided, or you use texture:

    If you use texelFetch the address of a texel is the index of the texels row and column. I assume that v_texCoord0 is the texture coordinates in the range (0.0, 1.0) and not the index of the texel. You have to multiply the texture coordinates with the size of the texture to get the index. The size of a texture can be get by textureSize:

    ivec2 texSize  = textureSize(u_sampler2D, 0);
    iVec2 texIndex = ivec2(v_texCoord0.xy * vec2(texSize.xy)); 
    color_right    = texelFetch(u_sampler2D, texIndex + ivec2(1, 0), 0).rgba;
    

    The other possibility is to use texture and to calculate the offset between 2 texels:

    ivec2 texSize  = textureSize(u_sampler2D, 0);
    vec2 texOffset = 1.0 / vec2(texSize.xy);
    color_right    = texture(u_sampler2D, v_texCoord0 + texOffset * vec2(1.0, 0.0)).rgba;