21CSL66 Program 4

4. Develop a program to demonstrate 2D transformation on basic objects.

#include <GL/glut.h>

float angle = 0.0f;
float scaleX = 1.0f;
float scaleY = 1.0f;
float translateX = 0.0f;
float translateY = 0.0f;

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

    // Apply transformations
    glTranslatef(translateX, translateY, 0.0f); // Translation
    glRotatef(angle, 0.0f, 0.0f, 1.0f);         // Rotation
    glScalef(scaleX, scaleY, 1.0f);             // Scaling

    // Set color to green
    glColor3f(0.0f, 1.0f, 0.0f); // Green color

    // Draw your object here (e.g., a square)
    glBegin(GL_QUADS);
    glVertex2f(-0.5f, -0.5f);
    glVertex2f(0.5f, -0.5f);
    glVertex2f(0.5f, 0.5f);
    glVertex2f(-0.5f, 0.5f);
    glEnd();

    glFlush();
}


void reshape(int w, int h)
{
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(-1.0f, 1.0f, -1.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);
}

void keyboard(unsigned char key, int x, int y)
{
    switch(key)
    {
    case 'r':
        angle += 5.0f;  // Rotate clockwise by 5 degrees
        break;
    case 'd':
        scaleX += 0.1f; // Scale up by 10%
        scaleY += 0.1f;
        break;
    case 's':
        scaleX -= 0.1f; // Scale down by 10%
        scaleY -= 0.1f;
        break;
    case 'f':
        translateX += 0.1f; // Translate 0.1 units to the right
        break;
    case 'a':
        translateX -= 0.1f; // Translate 0.1 units to the left
        break;
    case 'e':
        translateY += 0.1f; // Translate 0.1 units upwards
        break;
    case 'x':
        translateY -= 0.1f; // Translate 0.1 units downwards
        break;
    }
    glutPostRedisplay(); // Redraw the scene
}

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("vtucode | 2D Transformation");
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutKeyboardFunc(keyboard);
    glutMainLoop();
    return 0;
}

OUTPUT:

braham@braham:~/Desktop/program$ g++ program4.cpp -lGL -lGLU -lglut -o program4
braham@braham:~/Desktop/program$ ./program4
program4 output

Leave a Reply

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