實作用空間中六個正方形做出正立方體
---
程式碼:
#include "GL\glut.h"
#include <windows.h>
#include <iostream>
GLdouble camera_fovy = 20.0f; //視野廣角的角度
//GLdouble camera_aspect = 1; //投影布幕的 width/height比例
GLdouble camera_near = 0.01f; //最近可以看到的距離
GLdouble camera_far = 100.0f; //最遠可以看到的距離
void drawCube() //畫正立方體
{
//開始畫圖
glBegin(GL_QUADS); //畫四邊形
glColor3f(1, 0, 0); glVertex3f(0, 0, 0);
glColor3f(1, 0, 0); glVertex3f(0, 1, 0);
glColor3f(1, 0, 0); glVertex3f(1, 1, 0);
glColor3f(1, 0, 0); glVertex3f(1, 0, 0);
glEnd();
//結束畫圖
//開始畫圖
glBegin(GL_QUADS); //畫四邊形
glColor3f(1, 0, 0); glVertex3f(0, 0, 1);
glColor3f(1, 0, 0); glVertex3f(0, 1, 1);
glColor3f(1, 0, 0); glVertex3f(1, 1, 1);
glColor3f(1, 0, 0); glVertex3f(1, 0, 1);
glEnd();
//結束畫圖
//開始畫圖
glBegin(GL_QUADS); //畫四邊形
glColor3f(0, 1, 0); glVertex3f(0, 0, 0);
glColor3f(0, 1, 0); glVertex3f(0, 0, 1);
glColor3f(0, 1, 0); glVertex3f(1, 0, 1);
glColor3f(0, 1, 0); glVertex3f(1, 0, 0);
glEnd();
//結束畫圖
//開始畫圖
glBegin(GL_QUADS); //畫四邊形
glColor3f(0, 1, 0); glVertex3f(0, 1, 0);
glColor3f(0, 1, 0); glVertex3f(0, 1, 1);
glColor3f(0, 1, 0); glVertex3f(1, 1, 1);
glColor3f(0, 1, 0); glVertex3f(1, 1, 0);
glEnd();
//結束畫圖
//開始畫圖
glBegin(GL_POLYGON); //畫多邊形
glColor3f(0, 0, 1); glVertex3f(0, 0, 0);
glColor3f(0, 0, 1); glVertex3f(0, 0, 1);
glColor3f(0, 0, 1); glVertex3f(0, 1, 1);
glColor3f(0, 0, 1); glVertex3f(0, 1, 0);
glEnd();
//結束畫圖
//開始畫圖
glBegin(GL_POLYGON); //畫四邊形
glColor3f(0, 0, 1); glVertex3f(1, 0, 0);
glColor3f(0, 0, 1); glVertex3f(1, 0, 1);
glColor3f(0, 0, 1); glVertex3f(1, 1, 1);
glColor3f(0, 0, 1); glVertex3f(1, 1, 0);
glEnd();
//結束畫圖
}
void reshape(GLsizei width, GLsizei height) {
if (height == 0) height = 1; // 防止height為0
GLfloat aspect = (GLfloat)width / (GLfloat)height; //確保圖片不會被延展
glViewport(0, 0, width, height); //重繪窗口
glMatrixMode(GL_PROJECTION); // 投影視野
glLoadIdentity(); // 設置乘投影視野
gluPerspective(camera_fovy, aspect, camera_near, camera_far); //乘上投影矩陣
gluLookAt(
5, 10, 10, //攝影機座標
0, 0, 0, //要看的座標
0, 1, 0); //攝影機頭頂的向量
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // 清出BUFFER
glMatrixMode(GL_MODELVIEW); //模型視野
glLoadIdentity(); //設置成模型視野
drawCube(); //畫出正立方體
glutSwapBuffers(); //把畫好的東西刷上去
}
void initGL()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // 清空顏色
glClearDepth(1.0f); // 清空深度
glEnable(GL_DEPTH_TEST); // 打開"根據座標的遠近自動隱藏被遮住的圖形"
glDepthFunc(GL_LEQUAL); // 深度緩衝比較函數設為"輸入的深度值小於或等於參考值"則通過
glShadeModel(GL_SMOOTH); // 設定著色模式為"使用頂點渲染"
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // 指定顏色和紋理的差值質量 -> 最高質量
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);//初始化glut
glutInitDisplayMode(GLUT_DOUBLE); //初始化顯示器
glutInitWindowPosition(100, 100); //初始化視窗左上角的位置
glutInitWindowSize(600, 600); //初始化視窗大小
glutCreateWindow("DING"); //視窗名稱
glutIdleFunc(render); //設置全局的回調函數
glutDisplayFunc(render); //顯示器
glutReshapeFunc(reshape); //呈現
initGL(); //初始畫面
glutMainLoop();
return 0;
}
---
運行結果: