新版OpenGL学习入门(一)——初始化窗口

主要用来记录一下学习代码,每次新建一个项目还要配置太麻烦啦

配置网址:https://blog.csdn.net/qq_19003345/article/details/76098781 

学习的是可编辑管线,不过顺便也配置了一下旧版本的,这样可以偶尔运行一下别人的代码

题外话:新版OpenGL比较少,一不小心就找到旧的了。而且和旧版相比,新版需要理解的东西太多了

学习网址:https://learnopengl-cn.github.io/01%20Getting%20started/03%20Hello%20Window/

这个代码全部都是原来教程上的,不过加了一点自己的备注

建议跟着教程阅读,直接看代码很累

update:如果只是为了写出东西的话,这一块初始化内容完全可以不要去管它

#include <glad/glad.h>
#include <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: initialize and configure   不需要做任何改动
	glfwInit();                                             //初始化GLFW
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);          //主版本号为3
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);          //次版本号为3
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);   //核心模式

#ifdef __APPLE__
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);    // 对于OS X
#endif


	// glfw 窗口对象   不需要改动
	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);    //告诉glfw窗口大小会根据改变


	// glad: load all OpenGL function pointers  加载系统相关的OpenGL函数指针地址的函数   不需要改动
	if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
	{
		std::cout << "Failed to initialize GLAD" << std::endl;
		return -1;
	}


	// render loop  渲染循环,这样可以保持一直运行
	while (!glfwWindowShouldClose(window))
	{
		// 输入
		processInput(window);

		//渲染指令
		glClearColor(0.8f, 0.3f, 0.3f, 1.0f);    //设置清空屏幕所用的颜色,每次循环重新渲染,因此需要清空,也因此这是屏幕的背景色。RGB色
		glClear(GL_COLOR_BUFFER_BIT);            //清楚颜色缓冲

		// 检查并调用事件、交换缓冲
		glfwSwapBuffers(window);      //交换颜色缓冲
		glfwPollEvents();             //检查事件触发
	}


	// glfw: terminate, clearing all previously allocated GLFW resources.
	glfwTerminate();     //终止glfw
	return 0;
}

// 输入控制
void processInput(GLFWwindow *window)
{
	if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)    //判断是否按下Esc
		glfwSetWindowShouldClose(window, true);               //如果时Esc,那么glfw需要关闭窗口
}


// glfw: whenever the window size changed (by OS or user resize) this callback function executes 根据窗口大小改变显示大小
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
	// 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);    //窗口左下角的坐标x、y
}

猜你喜欢

转载自blog.csdn.net/yueyue200830/article/details/84672369