简体   繁体   English

透视投影在OpenGL中不起作用

[英]Perspective projection not working in OpenGL

I'was displaying a cube in opengl. 我在opengl中显示一个多维数据集。 Here is my file for vertex shader 这是我的顶点着色器文件

#version 330

layout(location = 0) in vec4 position;
layout(location = 1) in vec4 color;

smooth out vec4 theColor;

uniform vec3 offset;
uniform mat4 perspectiveMatrix;

void main()
{
    vec4 cameraPos = position + vec4(offset.x, offset.y, offset.z, 0.0);

    //gl_Position = perspectiveMatrix * cameraPos;
    gl_Position.xy = cameraPos.xy;
    gl_Position.z = cameraPos.z*2.0f + 3.0f;
    gl_Position.w = -cameraPos.z;

    float tmp = gl_Position.z / gl_Position.w;
    theColor = color;

}

RET

The result is weird.It seems that the five faces other than the front face are showed, which should all be disappeared.The back face is now in front of the front face.Here is the two triangles for the front face: 结果很奇怪,似乎显示了除正面以外的五个面,这些面都应该消失了,背面现在在正面的前面,这是正面的两个三角形:

0.25f,  0.25f, -1.0f, 1.0f,
0.25f, -0.25f, -1.0f, 1.0f,
-0.25f,  0.25f, -1.0f, 1.0f,

 0.25f, -0.25f, -1.0f, 1.0f,
-0.25f, -0.25f, -1.0f, 1.0f,
-0.25f,  0.25f, -1.0f, 1.0f,

the data for the back face: 背面的数据:

0.25f,  0.25f, -3.0f, 1.0f,
-0.25f,  0.25f, -3.0f, 1.0f,
0.25f, -0.25f, -3.0f, 1.0f,

0.25f, -0.25f, -3.0f, 1.0f,
-0.25f,  0.25f, -3.0f, 1.0f,
-0.25f, -0.25f, -3.0f, 1.0f,

I choose -1.0f and 3.0f for the near and far plane respectively,so (n + f) / (f - n) = 2.0f and (2 * n * f) / (f - n) = 3.0f.Why the result is such weird? 我分别为近平面和远平面选择-1.0f和3.0f,所以(n + f)/(f-n)= 2.0f和(2 * n * f)/(f-n)= 3.0f。结果是如此怪异?

After some test,I get the correct image. 经过一番测试,我得到了正确的图像。

RET

I know what did I do wrong now. 我知道我现在做错了什么。

First, the window I created didn't have a depth buffer and I did't enable the depth test.As the data of the five faces other than the front face was loaded after the front face, they were all be drawn. 首先,我创建的窗口没有深度缓冲区,并且没有启用深度测试,因为在正面之后加载了除正面以外的五个面的数据,因此全部被绘制。

Second, (n + f) / (f - n) and (2 * n * f) / (f - n) should change to (n + f) / (f - n) and (2 * n * f) / (f - n) . 其次,(n + f)/(f-n)和(2 * n * f)/(f-n)应更改为(n + f)/(f-n)和(2 * n * f)/ (f-n)。

Why the negations? OpenGL wants to present to the programmer a  
right-handed coordinate system before projection and left-handed 
coordinate system after projection.

That's the information I found.The larger z values will finally become smaller z value in the window space, which is exactly the depth value. 这就是我发现的信息。较大的z值最终将在窗口空间中变为较小的z值,这恰好是深度值。 And as the default value for glDepthFunc is GL_LESS, the front face will show before the other faces. 并且由于glDepthFunc的默认值为GL_LESS,因此正面将显示在其他面之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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