glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); \\主版本号
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); \\次版本号
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); \\核心渲染模式
// glfwCreateWindow函数需要窗口的宽和高作为它的前两个参数。第三个参数表示这个窗口的名称,后两个参数可以暂时忽略
GLFWwindow* window = glfwCreateWindow(800, 600, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// glViewport函数前两个参数控制窗口左下角的位置。第三个和第四个参数控制渲染窗口的宽度和高度(像素)。
glViewport(0, 0, 800, 600);
glfwTerminate();
return 0;
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
// 在main注册回调函数,使得每次调整窗口大小都调用这个函数
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
while(!glfwWindowShouldClose(window))
{
glfwSwapBuffers(window);
glfwPollEvents() // 函数检查有没有触发什么事件(比如键盘输入、鼠标移动等)、更新窗口状态,并调用对应的回调函数;
}
void processInput(GLFWwindow *window)
{
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
因此,得到最终的渲染循环为:
// 渲染循环
while(!glfwWindowShouldClose(window))
{
// 输入
processInput(window);
// 渲染指令, 我们自定义了一个有颜色屏幕
glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // RGBAlpha(透明度)
glClear(GL_COLOR_BUFFER_BIT); //清空上一次渲染颜色缓冲,并使得整个颜色缓冲都会被填充为glClearColor里所设置的颜色
// 检查并调用事件,交换缓冲
glfwPollEvents();
glfwSwapBuffers(window);
}
完成代码链接
https://github.com/purse1996/OpenGLExamples/blob/master/ConsoleApplication2/ConsoleApplication2/1.cpp