gpt4 book ai didi

c++ - OpenGL glClearColor 总是黑屏

转载 作者:搜寻专家 更新时间:2023-10-31 00:29:32 24 4
gpt4 key购买 nike

我正在尝试在 C++ 中运行我的第一个 opengl 程序,它会在 Mac OS X 上的终端打开一个窗口、设置背景颜色并给出标题。

代码可以正常编译和链接。当我运行该程序时,窗口和标题可以正常打开,但背景颜色始终为黑色。

据我了解,函数 glClearColor 设置背景色。但是,无论我向函数传递什么参数,窗口的背景颜色始终是黑色。

如果有人能向我解释我所犯的错误,我将不胜感激。谢谢,下面是代码:

#include <iostream>

#define GLEW_STATIC
#include <GL/glew.h>

#include <GLFW/glfw3.h>

const GLint WIDTH = 800, HEIGHT = 600;

int main()
{
glfwInit();

glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Learn OpenGL", nullptr, nullptr);

int screenWidth, screenHeight;
glfwGetFramebufferSize(window, &screenWidth, &screenHeight);

if(nullptr == window)
{
std::cout << "Failed to create GLFW window" << '\n';
glfwTerminate();

return -1;
}

glewExperimental = GL_TRUE;
GLenum err=glewInit();

if(err != glewInit())
{
std::cout << "Failed to initialize GLEW" << '\n';

return -1;
}

glViewport(0, 0, screenWidth, screenHeight);

while(!glfwWindowShouldClose(window))
{
glfwPollEvents();

glClearColor(0.2f, 0.2f, 0.9f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT);

glfwSwapBuffers(window);
}

glfwTerminate();

return 0;
}

最佳答案

glClearColor,与所有 OpenGL 函数一样,在当前 OpenGL 上下文中工作。

您没有将窗口的上下文设置为调用线程的当前上下文,因此您对 glClearColor 的调用在这里不执行任何操作。添加:

glfwMakeContextCurrent(window);

在你的循环之前。

来自 glfwMakeContextCurrent文档:

This function makes the OpenGL or OpenGL ES context of the specified window current on the calling thread. A context can only be made current on a single thread at a time and each thread can have only a single current context at a time.

关于c++ - OpenGL glClearColor 总是黑屏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40716375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com