Develop a program to demonstrate basic geometric operations on the 2D object

Develop a program to demonstrate basic geometric operations on the 2D object

Program:

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

// Vertex coordinates of the triangle
GLfloat vertices[3][2] = {
    {0.0, 0.5},
    {-0.5, -0.5},
    {0.5, -0.5}
};

// Transformation parameters
GLfloat tx = 0.0, ty = 0.0; // Translation
GLfloat sx = 1.0, sy = 1.0; // Scaling
GLfloat angle = 0.0;        // Rotation angle

void drawTriangle() {
    glBegin(GL_TRIANGLES);
    for (int i = 0; i < 3; i++) {
        glVertex2fv(vertices[i]);
    }
    glEnd();
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT);
    
    // Apply transformations
    glPushMatrix();
    
    // Translation
    glTranslatef(tx, ty, 0.0);
    
    // Rotation
    glRotatef(angle, 0.0, 0.0, 1.0);
    
    // Scaling
    glScalef(sx, sy, 1.0);
    
    // Draw the triangle
    drawTriangle();
    
    glPopMatrix();
    
    glFlush();
}

void init() {
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glColor3f(1.0, 1.0, 1.0);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(-1.0, 1.0, -1.0, 1.0);
}

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

        case 't': tx += 0.1; break; // Translate right
        case 'r': angle -= 5.0; break; // Rotate clockwise
        case 's': sx += 0.1; sy += 0.1; break; // Scale up horizontally
        case 27: exit(0); // ESC key to exit
    }
    glutPostRedisplay();
}

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

Leave a Reply

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