为什么OpenGL深度缓冲区不起作用?

时间:2020-07-22 14:30:05

标签: c++ opengl depth-buffer color-depth

Hello Stackoverflow社区,

我是OpenGL的新手,我只是尝试制作第一个立方体。但是,即使我启用了GL_DEPTH_TEST并使用GL_DEPTH_BUFFER_BIT清除了,应该位于背面且不可见的多维数据集片段也会闪过。

int main() {
sf::Window window(sf::VideoMode(S_WIDTH, S_HEIGHT), "OpenGL");
window.setFramerateLimit(60);
glewExperimental = GL_TRUE;
window.setActive(true);
glewInit();
glEnable(GL_DEPTH_TEST);

GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

float vertices[] = {
    0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
    0.0f, 0.0f, 0.5f, 0.0f, 1.0f, 0.0f,
    0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 1.0f,
    0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
    0.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
    0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f,
    0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 1.0f
};

GLuint elements[] = {
    0, 1, 2, 2, 0, 3,
    1, 0, 5, 1, 4, 5,
    1, 2, 5, 2, 7, 5,
    2, 3, 6, 2, 7, 6,
    5, 4, 6, 7, 6, 5,
    0, 3, 6, 0, 6, 4
};

GLuint ebo;
glGenBuffers(1, &ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(elements), elements, GL_STATIC_DRAW);

GLuint vbo;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

GLuint shaderProgram = CreateShaderProgram();

GLint posAttrib = glGetAttribLocation(shaderProgram, "position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), 0);

GLint colAttrib = glGetAttribLocation(shaderProgram, "color");
glEnableVertexAttribArray(colAttrib);
glVertexAttribPointer(colAttrib, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));

float rad = 0;

glm::mat4 mvp;
glm::mat4 model = glm::mat4(1.0f);
model = glm::rotate(model, glm::radians(rad), glm::vec3(0.0f, 0.0f, 1.0f));
glm::mat4 view = glm::lookAt(
    glm::vec3(2.0f, 2.0f, 2.0f),
    glm::vec3(0.0f, 0.0f, 0.0f),
    glm::vec3(0.0f, 0.0f, 1.0f)
);
glm::mat4 proj = glm::perspective(glm::radians(60.0f), (float)S_WIDTH / (float)S_HEIGHT, 0.5f, 10.0f);
mvp = proj * view * model;
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "mvp"), 1, GL_FALSE, glm::value_ptr(mvp));

while (1) {
    sf::Event e;
    while (window.pollEvent(e)) {
        switch (e.type) {
        case sf::Event::Closed:
            return 0;
            break;
        }
        
    }
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glDrawElements(GL_TRIANGLES, sizeof(elements), GL_UNSIGNED_INT, 0);
    window.display();
}

return 0; 
}

此外,这是我的顶点着色器的代码:

#version 150 core

in vec3 position;
in vec3 color;

out vec3 Color;

uniform mat4 mvp;

void main()
{
    Color = color;
    gl_Position = mvp * vec4(position, 1.0);
}

添加glDepthFunc(GL_LESS)也不起作用。 我已经阅读了一些关于stackoverflow的解决方案,但是没有一个对我有用。

0 个答案:

没有答案