C++ GLSL将gl_FragCoord.xy映射到正交投影中的坐标

C++ GLSL将gl_FragCoord.xy映射到正交投影中的坐标,c++,opengl,glsl,fragment-shader,orthographic,C++,Opengl,Glsl,Fragment Shader,Orthographic,您好,我有一个opengl程序,可以在正交投影中渲染二维多边形。在porgram开始时,或者当窗口大小改变时,调用函数reformate。以下是重塑功能的代码: /* Call back when the windows is re-sized */ void reshape(GLsizei width, GLsizei height) { // Compute aspect ratio of the new window if (height == 0) hei

您好,我有一个opengl程序,可以在正交投影中渲染二维多边形。在porgram开始时,或者当窗口大小改变时,调用函数reformate。以下是重塑功能的代码:

    /* Call back when the windows is re-sized */
    void reshape(GLsizei width, GLsizei height) {
    // Compute aspect ratio of the new window
    if (height == 0) height = 1;                
    // To prevent divide by 0
    GLfloat aspect = (GLfloat)width / 
    (GLfloat)height;

    // Set the viewport to cover the new window
    glViewport(0, 0, width, height);

    // Set the aspect ratio of the clipping area to match the viewport
    glMatrixMode(GL_PROJECTION);  // To operate on the Projection matrix
    glLoadIdentity();             // Reset the projection matrix
    if (width >= height) {
    clipAreaXLeft = -1.0 * aspect;
    clipAreaXRight = 1.0 * aspect;
    clipAreaYBottom = -1.0;
    clipAreaYTop = 1.0;
    }
    else {
    clipAreaXLeft = -1.0;
    clipAreaXRight = 1.0;
    clipAreaYBottom = -1.0 / aspect;
    clipAreaYTop = 1.0 / aspect;
    }
    clipAreaXLeft *= 600;
    clipAreaYBottom *= 600;
    clipAreaXRight *= 600;
    clipAreaYTop *= 600;

   gluOrtho2D(clipAreaXLeft, clipAreaXRight, 
clipAreaYBottom, clipAreaYTop);
    glScissor(0, 0, width, height);
    glEnable(GL_SCISSOR_TEST);

    }
以下是GLSL片段着色器的一些代码:

#version 420 core
out vec4 color
void main(){
vec2 orthoXY =... need help here, should 
convert window-space to ortho-space, 
maybe use projection matrix from fixed 
pipeline?
color=vec4{1,1,1,1}
}
如果要变换以规范化设备空间,则我建议创建统一,其中包含视口的大小:

uniform vec2 u_resolution; // with and height of the viewport
gl_FragCoord.xy
包含碎片的“窗口”坐标,
gl_FragCoord.z
包含深度范围内的深度,即[0,1],如果您没有更改它

标准化设备空间是一个立方体,具有左、下、前坐标(-1,-1,-1)和右、上、后坐标(1,1,1):

因此,转变是:

vec3 ndc = -1.0 + 2.0 * gl_FragCoord.xyz/vec3(u_resolution.xy, 1.0);
或者,如果只想变换
x
y
组件,请执行以下操作:

vec2 ndc_xy = -1.0 + 2.0 * gl_FragCoord.xy/u_resolution.xy;

和往常一样-在顶点着色器中创建投影矩阵并变换顶点位置。