Search code examples
opengl-esglsltexturesopengl-es-2.0fragment-shader

How to replace vacant pixels of texture2D after offsetting from original vec4?


Basically I'm offsetting a texture2D from its original inputImageTexture with this code

highp vec2 toprightcoord = textureCoordinate + 0.25;
highp vec4 tr = texture2D(inputImageTexture, toprightcoord);

It's does what it supposed to do, however it leaves a stretched pixel color from the edge of the offsetted texture (like a cheese from pulled pizza slice). How to replace it to any color or transparent?


Solution

  • I assume that you have set the texture wrap parameters to GL_CLAMP_TO_EDGE. See glTexParameter. This causes the stretched pixels when access the texture with the texture lookup function texture2D, out of the range [0.0, 1.0].

    You can create a "tiled" texture with the wrap parameter GL_REPEAT.

    But if you want

    "How to replace it to any color or transparent?"

    , then you have to do a range check.

    The following code sets the alpha channel to 0.0, if the limit of 1.0 is exceeded at either the x or y coordinate. Where the variable inBounds is set to 1.0 if the texture coordinate is in bounds and else it is set to 0.0:

    vec2 toprightcoord = textureCoordinate + 0.25;
    vec4 tr = texture2D(inputImageTexture, toprightcoord);
    
    vec2  boundsTest = step(toprightcoord, vec2(1.0));
    flaot inBounds   = boundsTest.x * boundsTest.y;
    tr.a *= inBounds;
    

    You can extend this, to a range test in [0.0, 1.0]:

    vec2 boundsTest = step(vec2(0.0), toprightcoord) * step(toprightcoord, vec2(1.0)); 
    

    Note, the glsl function step

    genType step( genType edge, genType x);
    

    returnes 0.0, if x[i] < edge[i], and 1.0 is returned otherwise.

    With the glsl function mix, the color can be replaced by a different one:

    vec4 red = vec4(1.0, 0.0, 0.0, 1.0); 
    tr = mix(red, tr, inBounds);