2.A] Describe the basic structure of an OpenGL graphics program, including necessary OpenGL functions.
Answer:-
Basic Structure of an OpenGL Graphics Program Using GLUT
1. Initialize the Program
Include Headers:
#include <GL/glut.h> // GLUT library for managing windows and input
Initialize GLUT:
glutInit(&argc, argv); // Prepare GLUT
Set Display Mode and Create Window:
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // Use single buffer and RGB color
glutInitWindowSize(800, 600); // Define window size
glutCreateWindow("OpenGL Window"); // Create the window
2. Define What to Draw
Create Display Function:
void display() {
glClear(GL_COLOR_BUFFER_BIT); // Clear the screen
glBegin(GL_TRIANGLES); // Start drawing a triangle
glVertex2f(-0.5f, -0.5f); // Bottom-left vertex
glVertex2f( 0.5f, -0.5f); // Bottom-right vertex
glVertex2f( 0.0f, 0.5f); // Top vertex
glEnd(); // Finish drawing
glFlush(); // Ensure commands are executed
}
Register Display Function:
glutDisplayFunc(display); // Tell GLUT to call 'display' when needed
3. Main Loop
Start Main Loop:
glutMainLoop(); // Start event processing loop
4. Optional: Handle Input
Handle Keyboard Input:
void handleKeys(unsigned char key, int x, int y) {
if (key == 27) { // ESC key
exit(0); // Exit the program
}
}
glutKeyboardFunc(handleKeys); // Register the keyboard handler
Summary of Functions:
glutInit
: Initializes GLUT.glutInitDisplayMode
: Sets the display mode.glutInitWindowSize
: Defines the window size.glutCreateWindow
: Creates a window.glutDisplayFunc
: Registers the display function.glutMainLoop
: Starts the GLUT event loop.glClear
: Clears the screen.glBegin/glEnd
: Defines the shape (e.g., a triangle).glVertex2f
: Specifies vertex coordinates.glFlush
: Executes drawing commands.glutKeyboardFunc
: Handles keyboard input.