Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate gl_FragCoord in glsl

Ok, in my GLSL fragment shader I want to be able to calculate the distance of the fragment from a particular line in space.

The result of this is that I am first trying to use a varying vec2 set in my vertex shader to mirror what ends up in gl_FragCoord:

varying vec2 fake_frag_coord;
//in vertex shader:
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
fake_frag_coord=(gl_ModelViewProjectionMatrix * gl_Vertex).xy;

Now in the fragment shader I expect:

gl_FragCoord.xy==fake_frag_coord

But it does not. What operation does the pipeline do on gl_Position to turn it into gl_FragCoord that I am neglecting to do on fake_frag_coord?

like image 322
DaedalusFall Avatar asked Aug 17 '09 14:08

DaedalusFall


People also ask

What is gl_FragCoord?

The input variable gl_FragCoord is an input variable that allows us to read screen-space coordinates and get the depth value of the current fragment, but it is a read-only variable. We can't influence the screen-space coordinates of the fragment, but it is possible to set the depth value of the fragment.

What is a varying variable GLSL?

GLSL also allows user defined varying variables. These must be declared in both the vertex and fragment shaders, for instance: varying float intensity; A varying variable must be written on a vertex shader, where we compute the value of the variable for each vertex.

What is a fragment GLSL?

Each fragment represents a sample-sized segment of a rasterized Primitive. The size covered by a fragment is related to the pixel area, but rasterization can produce multiple fragments from the same triangle per-pixel, depending on various multisampling parameters and OpenGL state.

What type of vertex shader variable has the same value for each vertex?

There are three types of variables in shaders: uniforms, attributes, and varyings: Uniforms are variables that have the same value for all vertices - lighting, fog, and shadow maps are examples of data that would be stored in uniforms. Uniforms can be accessed by both the vertex shader and the fragment shader.


1 Answers

gl_FragCoord is screen coordinates, so you'd need to have information about the screen size and such to produce it based on the Position. The fake_frag_coord you've produced will correspond to a point in the screen in normalized device coordinates I think (-1 to 1). So if you were to multiply by half the screen's size in a particular dimension, and then add that size, you'd get actual screen pixels.

like image 171
Jay Kominek Avatar answered Sep 21 '22 05:09

Jay Kominek