Develop a program to demonstrate 3D transformation on 3D objects

Develop a program to demonstrate 3D transformation on 3D objects

Program:

#include <GL/glut.h>
#include <cmath>

// Transformation parameters
GLfloat tx = 0.0, ty = 0.0, tz = -5.0; // Translation
GLfloat sx = 1.0, sy = 1.0, sz = 1.0; // Scaling
GLfloat angleX = 0.0, angleY = 0.0;   // Rotation angles

void drawCube() {
    glutWireCube(1.0); // Draw a wireframe cube
}

void drawSphere() {
    glutWireSphere(0.5, 20, 20); // Draw a wireframe sphere
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    // Apply transformations and draw cube
    glPushMatrix();
    glTranslatef(-1.0, 0.0, 0.0);
    glTranslatef(tx, ty, tz);
    glRotatef(angleX, 1.0, 0.0, 0.0);
    glRotatef(angleY, 0.0, 1.0, 0.0);
    glScalef(sx, sy, sz);
    glColor3f(1.0, 0.0, 0.0); // Red color for cube
    drawCube();
    glPopMatrix();

    // Apply transformations and draw sphere
    glPushMatrix();
    glTranslatef(1.0, 0.0, 0.0);
    glTranslatef(tx, ty, tz);
    glRotatef(angleX, 1.0, 0.0, 0.0);
    glRotatef(angleY, 0.0, 1.0, 0.0);
    glScalef(sx, sy, sz);
    glColor3f(0.0, 0.0, 1.0); // Blue color for sphere
    drawSphere();
    glPopMatrix();

    glutSwapBuffers();
}

void init() {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glColor3f(1.0, 1.0, 1.0);
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    gluPerspective(45.0, 1.0, 1.0, 10.0);
    glMatrixMode(GL_MODELVIEW);
    gluLookAt(0.0, 0.0, 0.0, 0.0, 0.0, -5.0, 0.0, 1.0, 0.0);
}

void keyboard(unsigned char key, int x, int y) {
    switch (key) {

        case 'd': tx += 0.1; break; // Translate right

        case 'i': sy += 0.1; sx += 0.1; break; // Scale 

        case 'u': sz += 0.1; sz -= 0.1; break; // Scale up depth

        case 27: exit(0); // ESC key to exit
    }
    glutPostRedisplay();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("3D Transformations");
    init();
    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutMainLoop();
    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *