简体   繁体   中英

Computing texture coordinates in fragment shader (iOS/OpenGL ES 2.0)

I am finding that in my fragment shader, these 2 statements give identical output:

// #1
// pos is set from gl_Position in vertex shader   
highp vec2 texc = ((pos.xy / pos.w) + 1.0) / 2.0; 

// #2 - equivalent?
highp vec2 texc2 = gl_FragCoord.xy/uWinDims.xy;

If this is correct, could you please explain the math? I understand #2, which is what I came up with, but saw #1 in a paper. Is this an NDC (normalized device coordinate) calculation?

The context is that I am using the texture coordinates with an FBO the same size as the viewport. It's all working, but I'd like to understand the math.

Relevant portion of vertex shader:

attribute vec4 position;
uniform mat4 modelViewProjectionMatrix;
varying lowp vec4 vColor;
// transformed position
varying highp vec4 pos;

void main()
{
    gl_Position = modelViewProjectionMatrix * position;

    // for fragment shader
    pos = gl_Position;
    vColor = aColor;
}

Relevant portion of fragment shader:

// transformed position - from vsh
varying highp vec4 pos;
// viewport dimensions
uniform highp vec2 uWinDims;

void main()
{
    highp vec2 texc = ((pos.xy / pos.w) + 1.0) / 2.0; 

    // equivalent?
    highp vec2 texc2 = gl_FragCoord.xy/uWinDims.xy;

...

}

(pos.xy / pos.w) is the coordinate value in normalized device coordinates (NDC). This value ranges from -1 to 1 in each dimension.

(NDC + 1.0)/2.0 changes the range from (-1 to 1) to (0 to 1) (0 on the left of the screen, and 1 on the right, similar for top/bottom).

Alternatively, gl_FragCoord gives the coordinate in pixels, so it ranges from (0 to width) and (0 to height) .

Dividing this value by width and height (uWinDims), gives the position again from 0 on the left side of the screen, to 1 on the right side.

So yes they appear to be equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM