OpenGL之路(七)为立方体加入丰富色彩
在立方体的六个面贴上不同的颜色,假设想达到混合颜色的效果,能够參照立方体的前面代码在每一行前都加上颜色
代码例如以下
#include <gl/glut.h> #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glut32.lib") #pragma comment(lib, "glu32.lib") #pragma comment(lib, "glut.lib") void Box(float x, float y, float z) //长方体 { glPushMatrix(); glScalef(x, y, z); glBegin(GL_QUADS); glColor3f(1, 0, 0); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);// 前 glColor3f(0, 1, 0); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 1.0f); glColor3f(0, 0, 1); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f); glColor3f(0, 1, 1); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glColor3f(1, 0, 0); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);// 后 glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, -1.0f, -1.0f); glColor3f(0, 1, 0); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);// 上 glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, -1.0f); glColor3f(0, 0, 1); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);// 下 glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, -1.0f, -1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glColor3f(1, 1, 0); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, -1.0f, -1.0f);// 左 glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0f, -1.0f, 1.0f); glColor3f(0, 1, 1); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);// 右 glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f); glEnd(); glPopMatrix(); } void renderScene(void) { static float i = 0; i += 0.01f; if (i > 360) i = 0; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(0, 0, -1.5); glRotatef(i, 1, 1, 1); Box(0.3f, 0.3f, 0.3f); glutSwapBuffers(); } void changeSize(int w, int h) { if (h == 0) h = 1; float ratio = 1.0* w / h; glMatrixMode(GL_PROJECTION);// 单位化投影矩阵。 glLoadIdentity(); glViewport(0, 0, w, h);// 设置视口大小为整个窗体大小 gluPerspective(45, ratio, 1, 1000);// 设置正确的投影矩阵 glMatrixMode(GL_MODELVIEW);//以下是设置模型视图矩阵 glLoadIdentity(); gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, -1.0, 0.0f, 1.0f, 0.0f);//设置观測点 } int main(int argc, char * argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(320, 320); glutCreateWindow("Hello OpenGL"); glutDisplayFunc(renderScene); glutIdleFunc(renderScene); //指定程序空暇时调用函数 glutReshapeFunc(changeSize); //指定窗体形状变化时的回调函数 glEnable(GL_DEPTH_TEST); glutMainLoop(); return 0; }
效果如图