OpenGL: 一个简单的例子

使用GLUT工具包,显示列表绘制一个三角形,根据OpenGL版本判定使用基本的glBegin,glEnd方法,还是glVertexPointer,glDrawArrays方法。

#include 
#include 
#include 
#include 
#include 
#pragma comment(lib, "OpenGL32.lib")
#pragma comment(lib, "GLAux.lib")
#pragma comment(lib, "GLU32.lib")
#pragma comment(lib, "GLut32.lib")

#include 
#include 
#include 

static const int QUIT_VALUE(99);

GLuint listID;

static void display()
{
	glClear(GL_COLOR_BUFFER_BIT);

	glLoadIdentity();
	glTranslatef(0.0f, 0.0f, -4.0f);

	glCallList(listID);

	glutSwapBuffers();

	assert(glGetError() == GL_NO_ERROR);
}

static void reshape(int w, int h)
{
	glViewport(0, 0, w, h);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(50, (double)w / (double)h, 1.0, 10.0);

	glMatrixMode(GL_MODELVIEW);

	assert(glGetError() == GL_NO_ERROR);
}
static void mainMenuCB(int value)
{
	if (value == QUIT_VALUE)
	{
		exit(0);
	}
}
static void init()
{
	glDisable(GL_DITHER);

	std::string ver((const char*)glGetString(GL_VERSION));
	assert(!ver.empty());
	std::istringstream verStream(ver);

	int major, minor;
	char dummySep;
	verStream >> major >> dummySep >> minor;
	const bool useVertexArrays = ((major >= 1) && (minor >= 1));
	const GLfloat data[] = 
	{
		-1.0f, -1.0f, 0.0f,
		1.0f, -1.0f, 0.0f,
		0.0f, 1.0f, 0.0f
	};
	if (useVertexArrays)
	{
		glEnable(GL_VERTEX_ARRAY);
		glVertexPointer(3, GL_FLOAT, 0, data);
	}

	listID = glGenLists(1);
	glNewList(listID, GL_COMPILE);

	if (useVertexArrays)
	{
		glDrawArrays(GL_TRIANGLES, 0, 3);
	}
	else
	{
		glBegin(GL_TRIANGLES);
		glVertex3fv(&data[0]);
		glVertex3fv(&data[3]);
		glVertex3fv(&data[6]);
		glEnd();
	}

	glEndList();

	assert(glGetError() == GL_NO_ERROR);

	glutDisplayFunc(display);
	glutReshapeFunc(reshape);

	int mainMenu = glutCreateMenu(mainMenuCB);
	glutAddMenuEntry("Quit", QUIT_VALUE);
	glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int main(int argc, char **argv)
{
	glutInit(&argc, argv);

	glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(300, 300);
	glutCreateWindow("Simple Example");

	init();

	glutMainLoop();
	glDeleteLists(listID, 1);

	return 0;
}
运行效果如下:
OpenGL: 一个简单的例子_第1张图片


你可能感兴趣的:(OpenGL)