OpenGL学习(1)——创建窗口
前言在我们画出出色的效果之前首先要做的就是创建一个OpenGL上下文(Context)和一个用于显示的窗口。然而这些操作在每个系统上都是不一样的OpenGL有意将这些操作抽象(Abstract)出去。这意味着我们不得不自己处理创建窗口定义OpenGL上下文以及处理用户输入。幸运的是有一些库已经提供了我们所需的功能其中一部分是特别针对OpenGL的。这些库节省了我们书写操作系统相关代码的时间提供给我们一个窗口和一个OpenGL上下文用来渲染。最流行的几个库有GLUTSDLSFML和GLFW。在教程里我们将使用GLFW。你可以随意选用其他类似的库大多数库的配置方法和GLFW差不多。GLFWGLFW是一个专门针对OpenGL的C语言库它提供了一些渲染物体所需的最低限度的接口。它允许用户创建OpenGL上下文、定义窗口参数以及处理用户输入对我们来说这就够了。本节和下一节的目标是把GLFW环境配好能且能够跑起来并保证它正确创建了OpenGL上下文并显示出一个简单的窗口来让我们随意使用。这篇教程会一步步教你如何获取、编译、链接GLFW库。我们使用的是Microsoft Visual Studio 2019 IDE操作过程在更新的Visual Studio都是相同的。如果你用的不是Visual Studio或者用的是它的旧版本请不要担心大多数IDE上的操作都是类似的。#includeglad/glad.h#includeGLFW/glfw3.h#includeiostreamvoidframebuffer_size_callback(GLFWwindow*window,intwidth,intheight);voidprocessInput(GLFWwindow*window);// settingsconstunsignedintSCR_WIDTH800;constunsignedintSCR_HEIGHT600;intmain(){// glfw: initialize and configure// ------------------------------glfwInit();glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3);glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);glfwWindowHint(GLFW_OPENGL_PROFILE,GLFW_OPENGL_CORE_PROFILE);#ifdef__APPLE__glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE);#endif// glfw window creation// --------------------GLFWwindow*windowglfwCreateWindow(SCR_WIDTH,SCR_HEIGHT,LearnOpenGL,NULL,NULL);if(windowNULL){std::coutFailed to create GLFW windowstd::endl;glfwTerminate();return-1;}glfwMakeContextCurrent(window);glfwSetFramebufferSizeCallback(window,framebuffer_size_callback);// glad: load all OpenGL function pointers// ---------------------------------------if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)){std::coutFailed to initialize GLADstd::endl;return-1;}// render loop// -----------while(!glfwWindowShouldClose(window)){// input// -----processInput(window);// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)// -------------------------------------------------------------------------------glfwSwapBuffers(window);glfwPollEvents();}// glfw: terminate, clearing all previously allocated GLFW resources.// ------------------------------------------------------------------glfwTerminate();return0;}// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly// ---------------------------------------------------------------------------------------------------------voidprocessInput(GLFWwindow*window){if(glfwGetKey(window,GLFW_KEY_ESCAPE)GLFW_PRESS)glfwSetWindowShouldClose(window,true);}// glfw: whenever the window size changed (by OS or user resize) this callback function executes// ---------------------------------------------------------------------------------------------voidframebuffer_size_callback(GLFWwindow*window,intwidth,intheight){// make sure the viewport matches the new window dimensions; note that width and// height will be significantly larger than specified on retina displays.glViewport(0,0,width,height);}运行结果参考https://learnopengl-cn.github.io/01%20Getting%20started/02%20Creating%20a%20window/