调整 OpenGL 大小时变形形状 window

Deforming a shape when resizing an OpenGL window

我使用着色器程序和 VAO 绘制对象
但是当我把window变形的时候,我的身材也变形了。 我的顶点着色器没有做任何事情,片段着色器只设置了橙色。

vertshader.vert

#version 330 core
layout (location = 0) in vec3 aPos;
 
void main()
{
    gl_Position = vec4(aPos, 1.0);
}

gl 初始化函数

float vertexes_normalized[12] =
                 {-0.5, 0.5, 0,
                   0.5, 0.5, 0,
                   0.5, -0.5, 0,
                  -0.5, -0.5, 0};

glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-this->width() / 2, this->width() / 2, -this->height() / 2, this->height() / 2);
glViewport(0, 0, this->width(), this->height());

//Compile shader program
unsigned int shaderProgram = makeShaderProgram(":/glshaders/vertshader.vert", ":/glshaders/fragshader.frag");
if(!shaderProgram) {
    qDebug("[ERROR]initializeGL: makeShaderProgram failed!");
    return;
}
gShaderProgram = shaderProgram;

//Vertex buffer object
unsigned int VBO = 0;
//Allocate 1 buffer
glGenBuffers(1, &VBO);
//Linking a buffer object to an OpenGL buffer
glBindBuffer(GL_ARRAY_BUFFER, VBO);
//Copying vertex data from the array to VBO
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexes_normalized), vertexes_normalized, GL_STATIC_DRAW);
gVBO = VBO;

//Configuring the interpretation of the vertex buffer data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

glUseProgram(shaderProgram);

在绘图函数中,我只是这样做:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glDrawArrays(GL_POLYGON, 0, 4);

我还有一个在 window 调整大小

期间调用的函数
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-newW / 2, newW / 2, -newH / 2, newH / 2);
glViewport(0, 0, newW, newH);

这是我第一次运行程序时得到的

但是如果我调整 window

的大小会发生什么

如果我在没有着色器程序的情况下使用 glBegin(); glVertex(); glEnd(); 进行常规渲染,那么一切正常,并且当 window 更改时形状不会变形。

如何使用 VBO 和 VAO 实现同样的效果?

您将已弃用的 OpenGL 矩阵与“现代”OpenGL 混合使用。 gluOrtho2D 在使用着色器程序时无效。您必须使用矩阵 Uniform 变量。


在着色器程序中添加一个Uniform类型mat4的变量,并将顶点坐标乘以矩阵:

#version 330 core
layout (location = 0) in vec3 aPos;
 
uniform mat4 projection;

void main()
{
    gl_Position = projection * vec4(aPos, 1.0);
}

获取着色器程序与glGetUniformLocation链接后(glLinkProgram之后)的制服位置索引:

GLint projection_loc = glGetUniformLocation(shaderProgram, "projection");

指定并Orthographic projection matrix. A option is to use the OpenGL Mathematics (GLM) library and to set the orthographic projection with glm::ortho:

glm::mat4 projection = glm::ortho(-this->width() / 2, this->width() / 2, -this->height() / 2, this->height() / 2);

安装程序后(glUseProgram之后)使用glUniformMatrix4fv设置统一变量的值:

glUniformMatrix4fv(projection_loc , 1, GL_FALE, glm::value_ptr(projection));