OpenGL学习(2)

创建一个窗口

由上一篇我们已经创建出一个窗口了,那么其程序是如何的呢?这是我们要讨论的下一个问题。

利用GLFW库创建一个窗口的具体步骤如下:

1.利用glfwInit() 函数初始化GLFE,并判断是否初始化成功;


	if (!glfwInit())
	{
		fprintf(stderr,"Failed to the initialized GLFW.\n");
		return;
	}

2.利用函数glfwCreateWindow() 创建窗口,并判断是否创建成功;


	m_Window=glfwCreateWindow(m_Width,m_Height,m_Title,NULL,NULL);

	if (m_Width==NULL)
	{
		fprintf(stderr,"Failed to the create window.\n");
		glfwTerminate();
		return ;
	}


3.利用glfwMakeContextCurrent() 函数,创建窗口背景;


	glfwMakeContextCurrent(m_Window);

4.利用glewInit() 函数初始化GLEW,并判断是否初始化成功;


	glewExperimental=GL_TRUE;

	if (glewInit()!=GLEW_OK)
	{
		fprintf(stderr,"Failed to the initialized the GLEW.\n");
		glfwTerminate();
		return ;
	}

5.进行主循环渲染操作,包括使用glClearColor() 函数设置窗口背景、glClear() 函数清除帧缓冲区、自定义函数画图、glfwSwapBuffers() 函数交换缓冲区和glfwPollEvents() 函数设定事件轮询方式;


	do 
	{
		glClearColor(1.0f,1.0f,0.0f,0.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		DrawSomething();

		glfwSwapBuffers(m_Window);
		glfwPollEvents();

	} while (glfwWindowShouldClose(m_Window)==0);

P.S:上述5个步骤的操作是必须的,且顺序不可改变。为使按下Esc键可以实现程序的退出,可以使用glfwSetInputMode() 函数来设置为按键输入模式,使用glfwGetKey() 函数来判断是否Esc键已按下。(完整程序如下)

	if (!glfwInit())
	{
		fprintf(stderr,"Failed to the initialized GLFW.\n");
		return;
	}

	m_Window=glfwCreateWindow(m_Width,m_Height,m_Title,NULL,NULL);

	if (m_Width==NULL)
	{
		fprintf(stderr,"Failed to the create window.\n");
		glfwTerminate();
		return ;
	}

	glfwMakeContextCurrent(m_Window);

	glewExperimental=GL_TRUE;

	if (glewInit()!=GLEW_OK)
	{
		fprintf(stderr,"Failed to the initialized the GLEW.\n");
		glfwTerminate();
		return ;
	}

	glfwSetInputMode(m_Window,GLFW_STICKY_KEYS,GL_TRUE);

	do 
	{
		glClearColor(1.0f,1.0f,0.0f,0.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		DrawSomething();

		glfwSwapBuffers(m_Window);
		glfwPollEvents();

	} while (glfwGetKey(m_Window,GLFW_KEY_ESCAPE)!=GLFW_PRESS
		&& glfwWindowShouldClose(m_Window)==0);

	glfwTerminate();

	return ;






你可能感兴趣的:(OpenGL)