Develop A Program To Demonstrate 2D Transformation On Basic Objects
Develop A Program To Demonstrate 2D Transformation On Basic Objects
#include <GL/glut.h>
void init(void) {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-5.0, 5.0, -5.0, 5.0);
}
void drawSquare() {
glBegin(GL_POLYGON);
glVertex2f(-1.0, -1.0);
glVertex2f(1.0, -1.0);
glVertex2f(1.0, 1.0);
glVertex2f(-1.0, 1.0);
glEnd();
}
void display(void) {
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
glTranslatef(translateX, translateY, 0.0);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
glScalef(scaleX, scaleY, 1.0f);
glutSwapBuffers();
}
1. **Initialization**:
- OpenGL headers are included using `<GL/glut.h>`.
- Global variables are declared to hold transformation parameters such as translation (`translateX`,
`translateY`), rotation (`angle`), and scaling (`scaleX`, `scaleY`).
2. **Init Function**:
- The `init` function initializes OpenGL settings.
- It sets the clear color to black.
- The projection matrix is set to an orthographic projection using `gluOrtho2D`, defining the coordinate
system of the window.
3. **Drawing Function**:
- The `drawSquare` function defines the vertices of a square using `glBegin(GL_POLYGON)` and
`glEnd()`. This function will draw a square centered at the origin with side length 2.
4. **Display Function**:
- The `display` function is called whenever the contents of the window need to be redrawn.
- It clears the color buffer.
- It loads the identity matrix and applies the desired transformations using `glTranslatef` for translation,
`glRotatef` for rotation, and `glScalef` for scaling.
- It then draws the square with the specified transformations applied.
5. **Keyboard Function**:
- The `keyboard` function handles keyboard input for controlling the transformations.
- Each key press ('w', 's', 'a', 'd', 'q', 'e', 'z', 'x') triggers a specific transformation:
- 'w' and 's': Translate up and down along the Y-axis.
- 'a' and 'd': Translate left and right along the X-axis.
- 'q' and 'e': Rotate clockwise and counterclockwise.
- 'z' and 'x': Scale up and down.
- After updating the transformation parameters, it requests a redraw using `glutPostRedisplay`.
6. **Main Function**:
- The `main` function is the entry point of the program.
- It initializes GLUT, sets the display mode, window size, position, and creates the main window.
- Callback functions for display and keyboard events are registered.
- Finally, it enters the GLUT main loop with `glutMainLoop`, which continuously processes events
until the program exits.
This program creates a window where you can see a square object. Using keyboard inputs, you can
control translation, rotation, and scaling of the square in 2D space.