前面讲过了glfw封装了这一基础过程,因此本节只是API的基础使用方法,不做深入了解
1.窗体创建
GLFWwindow* Util::InitWindow()
{
//初始化glfw,GLFW是一个专门针对OpenGL的C语言库,
//它提供了一些渲染物体所需的最低限度的接口。它允许用户创建OpenGL上下文,定义窗口参数以及处理用户输入
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR,3); //OpenGL主版本号
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3); //OpenGL副版本号
glfwWindowHint(GLFW_OPENGL_CORE_PROFILE,GLFW_OPENGL_CORE_PROFILE); //渲染模式:核心模式(可编程渲染管线)和立即渲染模式(固定管线)
//创建窗体
GLFWwindow* window = glfwCreateWindow(800,600,"learnOpenGL",NULL,NULL);
if(window == NULL)
{
std::cout<<"failed to create GLFW window"<<std::endl;
glfwTerminate();
return NULL;
}
glfwMakeContextCurrent(window); //激活窗体
//初始化GLAD,GLAD用于帮助完成获取opengl函数地址
if(!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout<<"Failed to initialize GLAD"<<std::endl;
return NULL;
}
//注册窗体大小调整回调函数
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
return window;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
2.渲染循环
GLFWwindow* window = Util::InitWindow();
while(!glfwWindowShouldClose(window))
{
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
在while中我们就可以编译使用我们的OpenGL程序了