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

时间:2018-11-16 23:13:28

标签: c++ opengl glsl fragment-shader orthographic

您好,我有一个opengl程序,可以在正交投影中渲染2D多边形。在执行程序的开头或窗口大小更改时,将调用函数reshape。这是重塑功能的代码:

    /* 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}
}

1 个答案:

答案 0 :(得分:1)

如果要转换gl_FragCoord来规范化设备空间,则建议创建统一的文件,其中包含视口的大小:

if ".htm" in item and "EX" in item.xpath("..//following-sibling::td/text"):
AttributeError: 'lxml.etree._ElementUnicodeResult' object has no attribute 'xpath'

uniform vec2 u_resolution; // with and height of the viewport 包含片段的“窗口”坐标,gl_FragCoord.xy包含深度范围内的深度,如果您未按{{3进行更改,则为[0,1] }}。

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

所以转换是:

gl_FragCoord.z

或者,如果仅要转换vec3 ndc = -1.0 + 2.0 * gl_FragCoord.xyz/vec3(u_resolution.xy, 1.0); x组件,则执行以下操作:

y