OpenGL 01:创建新窗口

OpenGL 01:创建窗口

main.cpp

// glad会重复定义OpenGL头文件,需要被include在最前面
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>

void framebuffer_size_callback(GLFWwindow* window, int width, int height); 

int main()
{
    // 1. 在使用GLFW*函数前,初始化 GLFW 库
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // GLFW版本号 3.3.x
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 不兼容以前版本
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif

    // 2. 创建并使用一个GLFW window对象
    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);
	// 这个callback函数使窗口可以相应调整大小
	glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);

	// 3. 在使用gl*函数前,用glad加载OpenGL函数
	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
	{
    	std::cout << "Failed to initialize GLAD" << std::endl;
    	return -1;
	}
	
	// 4. 用while loop检测是否需要关闭window
	while(!glfwWindowShouldClose(window))
	{
    	glfwSwapBuffers(window); // [1]
    	glfwPollEvents(); // [2]
	}
	
	// 5. 程序结束
	glfwTerminate();
    return 0;
}

void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
    glViewport(0, 0, width, height);
}

[1]: 双缓冲机制:由于计算机渲染图像需要时间,如果直接在屏幕缓冲区上渲染由于不同位置渲染完成时间不一致会导致屏幕闪烁。因此,OpenGL引入另一片缓冲区,渲染完成后再它与屏幕缓冲区交换,这样就可以解决屏幕闪烁问题。SwapBuffers就是在渲染完成后交换缓冲区。

[2]: PollEvents检查外部输入是否改变了window的状态。如果有改变,那么调用之前注册过的回调函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值