学习opengl计划
学习教的是glut和glew,所以我准备同时跟着learnopengl学glfw和glad。
建立步骤
- glfw初始化
- 创建窗口
- glad初始化
- 渲染循环(输入控制也放入这个循环中)
- 建立一个函数,随着窗口大小改变视口也跟着改变
- 销毁窗口
代码
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main()
{
// glfw初始化
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //控制版本号为3.3
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//创建窗口
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad初始化,因为glad控制opengl指针。所以在调用opengl函数前先初始化glad
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
//渲染循环
while (!glfwWindowShouldClose(window)) //glfwWindowShouldClose函数在我们每次循环的开始前检查一次GLFW是否被要求退出,如果是的话该函数返回true然后渲染循环便结束了
{
//控制输入函数
processInput(window);
glClearColor(0, 0.3f, 0, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glfwSwapBuffers(window); //函数会交换颜色缓冲,把后缓冲内容交换到前缓冲上
glfwPollEvents(); //glfwPollEvents函数检查有没有触发什么事件(比如键盘输入、鼠标移动等)、更新窗口状态
}
//销毁窗口
glfwTerminate();
return 0;
}
//输入控制
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true); //按下esc窗口退出
}
//随着窗口改变视图也会跟着改变
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height); //前两个参数窗口左下角坐标,后两个坐标窗口像素
}