Friday 15 March 2013

3D Transformation

4: Write a program in C/C++ using OpenGL to perform a 3-Dimensional transformation, such as translation ,rotation and reflection, on a given triangle.

#include <GL/glut.h> // GLUT stuff, includes OpenGL headers as well
#include <windows.h>
#include <math.h>

// Point class to keep it a little cleaner.
class Point {
public:
    float x, y, z;
    void setxy(float x2, float y2, float z2) { x = x2; y = y2; z=z2; }
    const Point & operator=(const Point &rPoint) {
         x = rPoint.x;
         y = rPoint.y;
         z = rPoint.z;
         return *this;
      }

};

void drawTriangle(Point p1, Point p2,Point p3) {       
    glBegin(GL_TRIANGLES);           
      glVertex3f(p1.x,p1.y,p1.z);//left of window
      glVertex3f(p2.x,p2.y,p2.z);
      glVertex3f(p3.x,p3.y,p3.z);     
    glEnd();//end drawing of line loop
    glFlush();   
}

void myDisplay() {
    Point abc[3];   
    glMatrixMode(GL_MODELVIEW); 
    glClearColor(0.0,0.0,0.0,0.0);     
    glClear(GL_COLOR_BUFFER_BIT);       
    glLoadIdentity();          
    abc[0].x=1.0,abc[0].y=-0.25,abc[0].z=0.0;
    abc[1].x=0.0,abc[1].y=-0.25,abc[1].z=0.0;
    abc[2].x=0.0,abc[2].y=0.25,abc[2].z=0.0;           
    drawTriangle(abc[0],abc[1],abc[2]);                   
    glTranslatef(0.0f,-0.6f,0.0f);
    drawTriangle(abc[0],abc[1],abc[2]);           
    glRotatef(180.0,0.0f,0.0f,1.0f);
    drawTriangle(abc[0],abc[1],abc[2]);   
   
}

int main(int argc, char *argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
    glutInitWindowSize(640,480);
    glutInitWindowPosition(100,150);
    glutCreateWindow("3D Transformation");   
    glutDisplayFunc(myDisplay);
    glutMainLoop();
    return 0;
}

1 comment: