OpenGL是圖形硬件接口,提供了豐富的函數。在OpenGL中使用幾何圖元(點、直線、多邊形)來構建模型。GLUT是OpenGL實用工具包,本文將在Win8.1環境下,配置GLUT以方便的學習OpenGL。
工具/原料
GLUT
方法/步驟
從網上下載GLUT後,解壓即可。解壓後共得到5個文件。
我這裡用VS版本是2013,安裝在D盤。將解壓後得到的glut.h放入“D:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\GL”。注意:VS2013在include目錄下沒有GL文件夾,自己新建即可。
將解壓後得到的glut.lib 和 glut32.lib放入“D:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\lib”。
到此配置完畢。下面進行測試。打開VS2013,新建一個Win32控制檯應用程序。在設置嚮導中選擇“空項目”,然後向工程添加一個源文件“源.cpp”
在“源.cpp”中輸入:
#include
#include
#include
#define ColoredVertex(c,v)do{glColor3fv(c);glVertex3fv(v);}while(0)
#define WIDTH 400
#define HEIGHT 400
GLfloat angle = 0.0f;
void myDisplay(void)
{
static int list = 0;
if (list == 0)
{
GLfloat
PointA[] = { 0.5f, -sqrt(6.0f) / 12, -sqrt(3.0f) / 6 },
PointB[] = { -0.5f, -sqrt(6.0f) / 12, -sqrt(3.0f) / 6 },
PointC[] = { 0.0f, -sqrt(6.0f) / 12, sqrt(3.0f) / 3 },
PointD[] = { 0.0f, sqrt(6.0f) / 4, 0 };
GLfloat
ColorR[] = { 1, 0, 0 },
ColorG[] = { 0, 1, 0 },
ColorB[] = { 0, 0, 1 },
ColorY[] = { 1, 1, 0 };
list = glGenLists(1);
glNewList(list, GL_COMPILE);
glBegin(GL_TRIANGLES);
ColoredVertex(ColorR, PointA);
ColoredVertex(ColorG, PointB);
ColoredVertex(ColorB, PointC);
ColoredVertex(ColorR, PointA);
ColoredVertex(ColorB, PointC);
ColoredVertex(ColorY, PointD);
ColoredVertex(ColorB, PointC);
ColoredVertex(ColorG, PointB);
ColoredVertex(ColorY, PointD);
// 平面 BAD
ColoredVertex(ColorG, PointB);
ColoredVertex(ColorR, PointA);
ColoredVertex(ColorY, PointD);
glEnd();
glEndList();
glEnable(GL_DEPTH_TEST);
std::cout << list << std::endl;
}
glClear(GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotatef(angle, 1, 0.5, 0);
glCallList(list);
glPopMatrix();
glutSwapBuffers();
}
void myIdle(void)
{
angle+=0.01;
if (angle >= 360.0f)
angle = 0.0f;
myDisplay();
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA GLUT_DOUBLE);
glutInitWindowPosition(200, 200);
glutInitWindowSize(WIDTH, HEIGHT);
glutCreateWindow("OpenGL 窗口");
glutDisplayFunc(&myDisplay);
glutIdleFunc(&myIdle);
glutMainLoop();
return 0;
}
運行結果如圖。
注意事項
對於配置glut.dll、glut32.dll兩個文件。若想直接運行生成的.exe文件,可將其放入到系統的system32文件夾內。