#include <GL/glut.h>
#pragma comment(lib, "freeglut.lib")
#include <stdlib.h>
GLfloat vertices[8][3] = {
{-1.0, -1.0, -1.0},
{ 1.0, -1.0, -1.0},
{ 1.0, 1.0, -1.0},
{-1.0, 1.0, -1.0},
{-1.0, -1.0, 1.0},
{ 1.0, -1.0, 1.0},
{ 1.0, 1.0, 1.0},
{-1.0, 1.0, 1.0}
};
GLfloat colors[8][3] = {
{0.0, 0.0, 0.0},
{1.0, 0.0, 0.0},
{1.0, 1.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0},
{1.0, 0.0, 1.0},
{1.0, 1.0, 1.0},
{0.0, 1.0, 1.0}
};
float eyeX = 4.0f;
float eyeY = 4.0f;
float eyeZ = 4.0f;
int projectionMode = 1;
int windowWidth = 800;
int windowHeight = 600;
void polygon(int a, int b, int c, int d) {
glBegin(GL_POLYGON);
glColor3fv(colors[a]);
glVertex3fv(vertices[a]);
glColor3fv(colors[b]);
glVertex3fv(vertices[b]);
glColor3fv(colors[c]);
glVertex3fv(vertices[c]);
glColor3fv(colors[d]);
glVertex3fv(vertices[d]);
glEnd();
}
void colorcube() {
polygon(0, 3, 2, 1);
polygon(2, 3, 7, 6);
polygon(0, 4, 7, 3);
polygon(1, 2, 6, 5);
polygon(4, 5, 6, 7);
polygon(0, 1, 5, 4);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float aspect = (float)windowWidth / (float)windowHeight;
if (projectionMode == 1) {
glOrtho(-3.0 * aspect, 3.0 * aspect, -3.0, 3.0, 1.0, 20.0);
} else {
gluPerspective(60.0, aspect, 1.0, 20.0);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(
eyeX, eyeY, eyeZ,
0.0, 0.0, 0.0,
0.0, 1.0, 0.0
);
colorcube();
glutSwapBuffers();
}
void reshape(int w, int h) {
if (h == 0) h = 1;
windowWidth = w;
windowHeight = h;
glViewport(0, 0, w, h);
}
void keyboard(unsigned char key, int x, int y) {
float step = 0.3f;
switch (key) {
case '1':
projectionMode = 1;
break;
case '2':
projectionMode = 2;
break;
case 'w':
eyeY += step;
break;
case 's':
eyeY -= step;
break;
case 'a':
eyeX -= step;
break;
case 'd':
eyeX += step;
break;
case 'q':
eyeZ += step;
break;
case 'e':
eyeZ -= step;
break;
case 'r':
eyeX = 4.0f;
eyeY = 4.0f;
eyeZ = 4.0f;
break;
case 27:
exit(0);
break;
}
glutPostRedisplay();
}
void init() {
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(windowWidth, windowHeight);
glutCreateWindow("Laboratory Work 4");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMainLoop();
return 0;
}