OpenGL 应用程序控制台未关闭

问题描述

我正在使用 Visual Studio 社区,并且正在尝试创建 OpenGL 应用程序。 我正在使用 GLFW 打开这样的窗口:

int main() {
    //Init stuff
    int width = 1920;


    int height = 1080;
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MInor,3);
    glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);
    GLFWwindow* window = glfwCreateWindow(width,height,"LearnopenGL",NULL,NULL);
    if (window == NULL) {
        std::cout << "Failed to create Window du schmok" << std::endl;

        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    if (glewInit() != GLEW_OK) {
        std::cout << "Glew was not initialized du schmok" << std::endl;
    }
    glViewport(0,width,height);

    VertexBuffer vbo(vertices,sizeof(vertices));
    IndexBuffer ibo(indices,6);

    while (!glfwWindowShouldClose(window))
    {
        glClearColor(0.0f,0.3f,1.0f,1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}

我已将索引缓冲区和顶点缓冲区抽象为如下所示的类: 顶点缓冲区:

VertexBuffer::VertexBuffer(float data[],unsigned int size)
{
    GL_CALL(glGenBuffers(1,&m_ID));
    GL_CALL(glBindBuffer(GL_ARRAY_BUFFER,m_ID));
    GL_CALL(glBufferData(GL_ARRAY_BUFFER,size,data,GL_STATIC_DRAW));
}

VertexBuffer::~VertexBuffer()
{
    GL_CALL(glDeleteBuffers(1,&m_ID));
}

void VertexBuffer::Bind()
{
    GL_CALL(glBindBuffer(GL_ARRAY_BUFFER,m_ID));
}

void VertexBuffer::Unbind()
{
    GL_CALL(glBindBuffer(GL_ARRAY_BUFFER,0));
}

和索引缓冲区:

IndexBuffer::IndexBuffer(unsigned int indices[],unsigned int count)
{
    m_Count = count;
    GL_CALL(glGenBuffers(1,&m_ID));
    GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,m_ID));
    GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER,m_Count * sizeof(unsigned int),indices,GL_STATIC_DRAW));
}

IndexBuffer::~IndexBuffer()
{
    GL_CALL(glDeleteBuffers(1,&m_ID));
}

void IndexBuffer::Bind()
{
    GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,m_ID));
}

void IndexBuffer::Unbind()
{
    GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,0));
}

问题是关闭窗口后控制台保持打开状态并闪烁等待。我只能使用 Visual Studio 或手动关闭控制台来终止程序。 我已经尝试过代码,这是因为我为缓冲区创建对象的两行: 没有这两行它就可以工作。有谁知道这是为什么?

解决方法

正如评论中提到的,问题来自缓冲区的破坏:程序试图在 OpenGL 上下文被破坏后调用 glDestroyX(在缓冲区析构函数中),这会引发错误 GL_Call尝试使用 GL 上下文进行处理,因此它本身也会引发错误等等。

要解决这个问题,请在范围内声明并使用缓冲区,并在范围结束后销毁 GL 上下文,以便在销毁 GL 上下文之前 销毁 GL 对象。