圖形學opengl實驗二-桌子的矩陣變換
阿新 • • 發佈:2019-01-06
在OpenGL程式設計基礎上,通過實現實驗內容,掌握OpenGL的矩陣使用,並驗證課程中矩陣變換的內容:
#include <GL/glut.h> float size = 0.25; //縮放 float fTranslate; float fRotate; float fScale = 1.0f; // set inital scale value to 1.0f void Draw_Leg() // This function draws one of the table leg { //繪製一個桌子腿 glPushMatrix(); glScalef(1.0f, 1.0f, 3.0f); glutWireCube(1.0*size); glPopMatrix(); } void Draw_Table() // This function draws a Table { glPushMatrix(); //將當前矩陣儲存入堆疊頂(儲存當前矩陣)。 glScalef(5.0f, 4.0f, 1.0f); //縮放函式 glutWireCube(1 * size); //繪製線立方體 glPopMatrix(); //pop出來 glPushMatrix(); //左下角的柱子 glTranslatef(-1.5*size, -1 * size, -1.5*size); //尺寸是相對於中心的座標原點,按照實驗指導上的大小進行的 Draw_Leg(); glPopMatrix(); glPushMatrix(); //右下角的柱子 glTranslatef(1.5*size, -1 * size, -1.5*size); Draw_Leg(); glPopMatrix(); glPushMatrix(); //右上角的柱子 glTranslatef(1.5*size, 1 * size, -1.5*size); Draw_Leg(); glPopMatrix(); glPushMatrix(); //左上角的柱子 glTranslatef(-1.5*size, 1 * size, -1.5*size); Draw_Leg(); glPopMatrix(); } void reshape(int width, int height) { if (height == 0) // Prevent A Divide By Zero By { height = 1; // Making Height Equal One } glViewport(0, 0, width, height); // Reset The Current Viewport glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix // Calculate The Aspect Ratio Of The Window gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f); glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix } void idle() { glutPostRedisplay(); } void redraw() { // If want display in wireframe mode //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glClear(GL_COLOR_BUFFER_BIT); //當前緩衝區清除值,這裡是清除顏色緩衝 glLoadIdentity(); // Reset The Current Modelview Matrix glPushMatrix(); glTranslatef(-2.0f, 0.0f, -6.0f); // Place the triangle Left glTranslatef(0.0f, fTranslate, 0.0f); // Translate in Y direction Draw_Table(); // Draw triangle glPopMatrix(); glPushMatrix(); glTranslatef(0.0f, 0.0f, -6.0f); // Place the triangle at Center glRotatef(fRotate, 0, 1.0f, 0); // Rotate around Y axis Draw_Table(); // Draw triangle glPopMatrix(); glPushMatrix(); glTranslatef(2.0f, 0.0f, -6.0f); // Place the triangle Right glScalef(fScale, fScale, fScale); // Scale with the same value in x,y,z direction Draw_Table(); // Draw triangle glPopMatrix(); fTranslate += 0.005f; fRotate += 0.5f; fScale -= 0.005f; if (fTranslate > 0.5f) fTranslate = 0.0f; if (fScale < 0.5f) fScale = 1.0f; glutSwapBuffers(); } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowSize(640, 480); /////////////////////////////////////// int windowHandle = glutCreateWindow("Simple GLUT App"); glutDisplayFunc(redraw); glutReshapeFunc(reshape); /////////////////////////////////////// glutIdleFunc(idle); /////////////////////////////////////// glutMainLoop(); return 0; }