glslprocessing

How do you draw a sampler2D?


I am new to GLSL and have absolutely no idea what I am doing. I have been looking for resources to learn however, most of them are either incredibly general like the book of shaders or really overwhelming like this reference.

Anyways, I am looking for what exactly a "fragment" is. I think it is just referring to pixels that need to be rendered. If this is the case what does gl_FragCoord return? I've messed around with it and I don't think it returns the x,y of the current fragment but the book of shaders says

"vec4 gl_FragCoord, which holds the screen coordinates of the pixel or screen fragment that the active thread is working on."

I have also seen that it returns values from 0 to 1, initially (0.5,0.5). I have no idea what (0.5,0.5) is referring to though. Is it percentage of the screen? Like on a 800px by 800px screen will 0.5,0.5 correspond to 400,400? If so than why doesn't this sort of thing work:

void main() {
  vec4 screencol = texture2D(displayimg, gl_FragCoord.xy*vec2(width,height));
  gl_FragColor = screencol;
}

Where width and height store the screen dimensions and displaying is a sampler2D.

I am just trying to render a sampler2D and I must be missing something because this seems like something that should be very standard and achievable. With the above code I get an error:

OpenGL error 1282 at top endDraw(): invalid operation

Solution

  • gl_FragCoord.xy contains the window relative coordinates. The bottom left fragment has the coordinate (0.5, 0.5). The top right fragment has the coordinate (width-0.5, height-0.5). See gl_FragCoord.
    However the texture coordinates have to be specified in range [0.0, 1.0]. The bottom left coordinate is (0.0, 0.0). The top right coordinate is (1.0, 1.0). The argument of texture2D needs to be the texture coordinate:

    vec4 screencol = texture2D(displayimg, gl_FragCoord.xy*vec2(width,height));

    vec4 screencol = texture2D(displayimg, gl_FragCoord.xy / vec2(width, height));