GLSL: gl_FragCoord issues

2019-03-19 07:41发布

问题:

I am experimenting with GLSL for OpenGL ES 2.0. I have a quad and a texture I am rendering. I can successfully do it this way:

//VERTEX SHADER
attribute highp vec4 vertex;
attribute mediump vec2 coord0;

uniform mediump mat4 worldViewProjection;

varying mediump vec2 tc0;

void main()
{
    // Transforming The Vertex
    gl_Position = worldViewProjection * vertex;

    // Passing The Texture Coordinate Of Texture Unit 0 To The Fragment Shader
    tc0 = vec2(coord0);
}

//FRAGMENT SHADER
varying mediump vec2 tc0;

uniform sampler2D my_color_texture;

void main()
{
    gl_FragColor = texture2D(my_color_texture, tc0);
}

So far so good. However, I'd like to do some pixel-based filtering, e.g. Median. So, I'd like to work in pixel coordinates rather than in normalized (tc0) and then convert the result back to normalized coords. Therefore, I'd like to use gl_FragCoord instead of a uv attribute (tc0). But I don't know how to go back to normalized coords because I don't know the range of gl_FragCoords. Any idea how I could get it? I have got that far, using a fixed value for 'normalization', though it's not working perfectly as it is causing stretching and tiling (but at least is showing something):

//FRAGMENT SHADER
varying mediump vec2 tc0;

uniform sampler2D my_color_texture;

void main()
{
    gl_FragColor = texture2D(my_color_texture, vec2(gl_FragCoord) / vec2(256, 256));
}

So, the simple question is, what should I use in the place of vec2(256, 256) so that I could get the same result as if I were using the uv coords.

Thanks!

回答1:

gl_FragCoord is in screen coordinates, so to get normalized coords you need to divide by the viewport width and height. You can use a uniform variable to pass that information to the shader, since there is no built in variable for it.



回答2:

You can also sample the texture by un-normalized coordinates if:

  • sampling by texture() from GL_TEXTURE_RECTANGLE
  • sampling by texelFetch() from a regular texture or texture buffer