Monday, June 3, 2019

CG 4 - COLOR CUBE & ALLOW USER TO MOVE

4. Draw a color cube and allow the user to move the camera suitably to experiment with perspective viewing. Positioning of Camera

#include<stdio.h>
#include<math.h>
#include<iostream>
#include<GL/glut.h>
using namespace std;

float v[8][3] = {{-1,-1,-1},{-1,1,-1},{1,1,-1},{1,-1,-1},{-1,-1,1},{-1,1,1},{1,1,1},{1,-1,1}};
float t[] ={0,0,0};
int ax = 2;
float viewer[]={5,0,0};

void init()
{
 glMatrixMode(GL_PROJECTION);
 glFrustum(-2,2,-2,2,2,10);
 glMatrixMode(GL_MODELVIEW);
}

void polygon(int a, int b, int c, int d)
{
 glBegin(GL_QUADS);
 glVertex3fv(v[a]);
 glVertex3fv(v[b]);
 glVertex3fv(v[c]);
 glVertex3fv(v[d]);
 glEnd();
}

void colorcube()
{
 glColor3f(0,0,1);
 polygon(0,1,2,3);
 glColor3f(0,1,0);
 polygon(4,5,6,7);
 glColor3f(1,0,0);
 polygon(0,1,5,4);
 glColor3f(0,0,0);
 polygon(3,2,6,7);
 glColor3f(0,1,1);
 polygon(0,4,7,3);
 glColor3f(1,0,1);
 polygon(1,5,6,2);
}

void spincube()
{
 t[ax] += 1;
 if (t[ax] == 360)
  t[ax] -= 360;
 glutPostRedisplay();
}

void mouse(int btn , int state , int x , int y)
{
 if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
  ax = 0;
 if (btn == GLUT_MIDDLE_BUTTON && state == GLUT_DOWN)
  ax = 1;
 if (btn == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
  ax = 2;
 spincube();
}

void keyboard(unsigned char key, int x, int y)
{
 if(key=='X') viewer[0]+=1;
 if(key=='x') viewer[0]-=1;
 if(key=='Y') viewer[1]+=1;
 if(key=='y') viewer[1]-=1;
 if(key=='Z') viewer[2]+=1;
 if(key=='z') viewer[2]-=1;
 glutPostRedisplay();
}

void display()
{
 glClearColor(1,1,1,1);
 glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
 glLoadIdentity();
 gluLookAt(viewer[0],viewer[1],viewer[2],0,0,0,0,1,0);
 glRotatef(t[0], 1, 0, 0);
 glRotatef(t[1], 0, 1, 0);
 glRotatef(t[2], 0, 0, 1);
 colorcube();
 glutSwapBuffers();
 glFlush();
}

int main (int argc, char ** argv)
{
 glutInit(&argc,argv);
 glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
 glutInitWindowPosition(100,100);
 glutInitWindowSize(500,500);
 glutCreateWindow("Positioning of Camera");
 init();
 glutKeyboardFunc(keyboard);
 glutMouseFunc(mouse);
 glEnable(GL_DEPTH_TEST);
 glutDisplayFunc(display);
 glutMainLoop();
}


OUTPUT :
( click on image to zoom )



No comments:

Post a Comment