Introduction to OpenGL

Slides:



Advertisements
Similar presentations
OpenGL CMSC340 3D Character Design & Animation. What is OpenGL? A low-level graphics library specification designed for use with the C and C++ provides…
Advertisements

Chapter 2: Graphics Programming
Computer Graphics CSCE 441
Pemrograman OpenGL Dasar
OpenGL (Graphics Library) Software Interface to graphics software Allows to create interactive programs that produce color images of moving 3D objects.
OpenGL (I). What is OpenGL (OGL)? OGL is a 3D graphics & modeling library Can also use it to draw 2D objects.
CSC 461: Lecture 51 CSC461 Lecture 5: Simple OpenGL Program Objectives: Discuss a simple program Discuss a simple program Introduce the OpenGL program.
1 Angel: Interactive Computer Graphics 4E © Addison-Wesley 2005 Programming with OpenGL Part 2: Complete Programs Ed Angel Professor of Computer Science,
30/1/2006Based on: Angel (4th Edition) & Akeine-Möller & Haines (2nd Edition)1 CSC345: Advanced Graphics & Virtual Environments Lecture 1: Introduction.
CENG477 Introduction to Computer Graphics Introduction to OpenGL, GLUT and GLUI.
Programming with OpenGL Part 1: Background Mohan Sridharan Based on slides created by Edward Angel CS4395: Computer Graphics 1.
Chapter 03: Graphics Primitives Course web page: Chapter #3.
Reference1. [OpenGL course slides by Rasmus Stenholt]
CS380 LAB I OpenGL Donghyuk Kim Reference1. [OpenGL course slides by Rasmus Stenholt] Reference2. [
Computer Graphics Bing-Yu Chen National Taiwan University.
1 GLUT Callback functions Event-driven: Programs that use windows  Input/Output  Wait until an event happens and then execute some pre-defined functions.
Introduction to OpenGL and GLUT GLUT. What is OpenGL? An application programming interface (API) A (low-level) Graphics rendering API Generate high-quality.
Using OpenGL in Visual C++ Opengl32.dll and glu32.dll should be in the system folder Opengl32.dll and glu32.dll should be in the system folder Opengl32.lib.
2 COEN Computer Graphics I Introductions n Brad Grantham lecturer lab dude n Dave Shreiner lecturer slave driver.
Programming with OpenGL Part 1: Background
Lecture 3 OpenGL.
1 Angel: Interactive Computer Graphics 4E © Addison-Wesley 2005 Programming with OpenGL Part 1: Background Ed Angel Professor of Computer Science, Electrical.
1. OpenGL/GLU/GLUT  OpenGL v4.0 (latest) is the “core” library that is platform independent  GLUT v3.7 is an auxiliary library that handles window creation,
1 Figures are extracted from Angel's book (ISBN x) The Human Visual System vs The Pinhole camera Human Visual System Visible Spectrum Pinhole.
1 Angel: Interactive Computer Graphics 5E © Addison-Wesley 2009 Programming with OpenGL Review.
Introduction to OpenGL and GLUT. What’s OpenGL? An Application Programming Interface (API) A low-level graphics programming API – Contains over 250 functions.
C O M P U T E R G R A P H I C S Guoying Zhao 1 / 43 C O M P U T E R G R A P H I C S Guoying Zhao 1 / 43 Computer Graphics Programming with OpenGL I.
CA 302 Computer Graphics and Visual Programming Lecture 2: Introduction to OpenGL Aydın Öztürk
Chun-Yuan Lin Introduction to OpenGL 2015/12/19 1 CG.
NoufNaief.net TA: Nouf Al-harbi.
GLUT functions glutInit allows application to get command line arguments and initializes system gluInitDisplayMode requests properties for the window.
Doç. Dr. Cemil Öz SAÜ Bilgisayar Mühendisliği Dr. Cemil Öz.
CSCE 441: Computer Graphics
OpenGL Basic Drawing 2003 Spring Keng Shih-Ling
1 Programming with OpenGL Part 2: Complete Programs.
OpenGL API 2D Graphic Primitives Angel Angel: Interactive Computer Graphics5E © Addison-Wesley
31/1/2006Based on: Angel (4th Edition) & Akeine-Möller & Haines (2nd Edition)1 CSC345: Advanced Graphics & Virtual Environments Lecture 2: Introduction.
OpenGL: Introduction #include main() { OpenWindow() ; glClearColor(0.0, 0.0, 0.0, 0.0); glClear(GL_COLOR_BUFFER_BIT); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0,
OpenGL Basic Drawing Jian-Liang Lin A Smidgen of OpenGL Code #include main() { InitializeAWindowPlease(); glClearColor (0.0, 0.0, 0.0, 0.0); glClear.
Introduction to OpenGL Muhammad Aamir Khan Lecturer, DCS, UOP.
Introduction to Graphics Programming. Graphics API.
Introduction to Graphics Programming. Graphics: Conceptual Model Real Object Human Eye Display Device Graphics System Synthetic Model Synthetic Camera.
Computer Graphics I, Fall Programming with OpenGL Part 2: Complete Programs.
CSC Graphics Programming Budditha Hettige Department of Statistics and Computer Science.
INTRODUCTION TO OPENGL
Computer Graphics (Fall 2003) COMS 4160, Lecture 5: OpenGL 1 Ravi Ramamoorthi Many slides courtesy Greg Humphreys.
Program Studi S-1 Teknik Informatika FMIPA Universitas Padjadjaran
Introduction to OpenGL (IDE: Eclipse)
The Human Visual System vs The Pinhole camera
Programming with OpenGL Part 1: Background
CS380 Lab Spring Myungbae Son.
Programming with OpenGL Part 1: Background
Programming with OpenGL Part 2: Complete Programs
Materi Anatomi OpenGL Fungsi GLUT Posisi Kamera Proyeksi
OpenGL API 2D Graphic Primitives
Programming with OpenGL Part 2: Complete Programs
OpenGL (Open Graphics Library) Mr. B.A.Swamy Assistant Professor Dept of CSE.
Lab 3 Geometric Drawing Lab 3 Geometric Drawing.
גרפיקה ממוחשבת: מבוא ל-OpenGL
Programming with OpenGL Part 1: Background
Drawing in the plane 455.
Introduction to OpenGL
Computer Graphics, Lee Byung-Gook, Dongseo Univ.
Lecture 12: OpenGL Li Zhang Spring 2008
Programming with OpenGL Part 2: Complete Programs
Programming with OpenGL Part 2: Complete Programs
Programming with OpenGL Part 2: Complete Programs
Programming with OpenGL Part 1: Background
Programming with OpenGL Part 2: Complete Programs
Programming with OpenGL Part 2: Complete Programs
Presentation transcript:

Introduction to OpenGL Computer Graphic Introduction to OpenGL

What is OpenGL? OpenGL is a software interface to graphics hardware. You can use to specify the objects and operations needed to produce interactive three-dimensional applications OpenGL is designed as a hardware-independent interface to be implemented on many different hardware platforms.

What is OpenGL? powerful but primitive set of rendering commands • The most popular raster graphics library, providing a powerful but primitive set of rendering commands • Already supported by every window systems • OpenGL Utility Library (GLU) : higher-level routines, part of OpenGL implementation – Setting up matrices for specific viewing orientations and projections – Performing polygon tessellation and rendering surfaces • OpenGL Utility Toolkit (GLUT): window-system independent high-level library. Need to install this library separately.

What is OpenGL? • Install OpenGL Utility Toolkit (GLUT) for MS Windows – Download GLUT from http://reality.sgi.com/opengl/glut3/glut3.html – Unzip the package – Set “include directory” and “lib directory” in the C Compiler to include the directory containing glut.h, glut.lib – Copy glut32.dll into directory DRIVE:\WINNT\SYSTEM • Add #include <glut.h> to the beginning of the program

OpenGL • OpenGL Programming Guide: – http://www.cs.ucf.edu/dsg/dtran/teaching/cps5 60/openGL/install/theredbook.zip • Nate Robins’ OpenGL Tutors – http://www.cs.utah.edu/~narobins/opengl.html

OpenGL Libraries In order to write a VC++ application using GLUT you'll need three files: 1- glut.h - You'll have to include This is the file in your source code. The common place to put this file is in C:\Program Files\Microsoft Visual\ Studio\VC98 \ Include \GL folder. 2- glut.lib and glut32.lib This file must be linked to your application so make sure to put it your lib folder. 3- glut32.dll and glut.dll - choose one according to the OpenGL you're using. If using Microsoft's version then you must choose glut32.dll. You should place the dll file in your system folder.

Setup In the "Project options" textbox replace "subsystem:console" With "subsystem:windows" The following files to the Object/library modules: opengl32.lib glut32.lib glu32.lib

Compilation on Windows Visual C++ – Get glut.h, glut32.lib and glut32.dll from web – Create a console application – Add opengl32.lib, glut32.lib, glut32.lib to project settings (under link tab)

Programming with OpenGL Part 1: Background

OpenGL Functions Primitives Attributes : color ,texture, and font size Points Line Segments Polygons Attributes : color ,texture, and font size Transformations Viewing Modeling Control Input (GLUT)

GLUT Basics Application Structure Configure and open window Initialize OpenGL state Register input callback functions render resize input: keyboard, mouse, etc. Enter event processing loop Here’s the basic structure that we’ll be using in our applications. This is generally what you’d do in your own OpenGL applications. The steps are: 1) Choose the type of window that you need for your application and initialize it. 2) Initialize any OpenGL state that you don’t need to change every frame of your program. This might include things like the background color, light positions and texture maps. 3) Register the callback functions that you’ll need. Callbacks are routines you write that GLUT calls when a certain sequence of events occurs, like the window needing to be refreshed, or the user moving the mouse. The most important callback function is the one to render your scene, which we’ll discuss in a few slides. 4) Enter the main event processing loop. This is where your application receives events, and schedules when callback functions are called.

OpenGL State OpenGL is a state machine OpenGL functions are of two types Primitive generating Can cause output if primitive is visible How vertices are processes and appearance of primitive are controlled by the state State changing Transformation functions Attribute functions

Lack of Object Orientation OpenGL is not object oriented so that there are multiple functions for a given logical function, e.g. glVertex3f, glVertex2i, glVertex3dv,….. Underlying storage mode is the same Easy to create overloaded functions in C++ but issue is efficiency

Preliminaries Headers Files Libraries Enumerated Types #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> Libraries Enumerated Types OpenGL defines numerous types for compatibility GLbyte, GLshort, GLushort, GLint, GLuint, GLsizei, GLfloat, GLdouble, GLclampf, GLclampd, GLubyte, GLboolean, GLenum, GLbitfield All of our discussions today will be presented in the C computer language. For C, there are a few required elements which an application must do: Header files describe all of the function calls, their parameters and defined constant values to the compiler. OpenGL has header files for GL (the core library), GLU (the utility library), and GLUT (freeware windowing toolkit). Note: glut.h includes gl.h and glu.h. On Microsoft Windows, including only glut.h is recommended to avoid warnings about redefining Windows macros. Libraries are the operating system dependent implementation of OpenGL on the system you’re using. Each operating system has its own set of libraries. For Unix systems, the OpenGL library is commonly named libGL.so and for Microsoft Windows, it’s named opengl32.lib. Finally, enumerated types are definitions for the basic types (i.e. float, double, int, etc.) which your program uses to store variables. To simplify platform independence for OpenGL programs, a complete set of enumerated types are defined. Use them to simplify transferring your programs to other operating systems.

Program Structure Most OpenGL programs have a similar structure that consists of the following functions main(): defines the callback functions opens one or more windows with the required properties enters event loop (last executable statement) init(): sets the state variables viewing Attributes callbacks Display function Input and window functions

The Main Program We begin with the basic elements of how to create a window. OpenGL was intentionally designed to be independent of any Specific window system. As a result, a number of the basic window operations are not provided in OpenGL. Therefore, a separate library called GLUT or OpenGL Utility Toolkit was created to provide these functions. Basically, GLUT provides the necessary tools for requesting windows to be created and providing interaction with I/O devices

Opening a Window Using GLUT #include<windows.h> #include <GL/glut.h> void main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("simple"); init(); glutDisplayFunc(mydisplay); glutMainLoop(); } includes gl.h Specify the display Mode – RGB or color Index, single or double Buffer define window properties define window starting position set OpenGL state display callback enter event loop

GLUT functions glutInit allows application to get command line arguments and initializes system gluInitDisplayMode requests properties of the window (the rendering context) Int mode= GLUT_SINGLE|GLUT_RGB RGB color Single buffering Properties logically ORed together glutWindowSize in pixels glutWindowPosition from top-left corner of display glutCreateWindow create window with title “simple” glutDisplayFunc display callback glutMainLoop enter infinite event loop

1- Initialization glutInit() • All the functions in GLUT have the prefix glut, and those which perform some kind of initialization have the prefix glutInit. • The first thing you must do is call the function glutInit. void glutInit(int *argc, char **argv); Parameters: argc argv are the standard ones for passing information about the command line ( not used here)

Define our window • After initializing GLUT itself, we're going to define our window. First we establish the window's position, i.e. its top left corner.

glutInitWindowPosition(10,50) ; glutInitPosition() This command specifies the location of the upper left corner of the graphics window. The form is glutInitWindowPosition(int x, int y) where the (x, y) coordinates are given relative to the upper left corner of the display. Thus, the arguments (0, 0) places the window in the upper left corner of the display. glutInitWindowPosition(10,50) ;

Window Size Next we'll choose the window size. In order to do this we use the function glutInitWindowSize. This command specifies the desired width and height of the graphics window. The general form is: glutInitWindowSize(int width, int height) glutInitWindowSize(640, 480); The values are given in numbers of pixels.

glutInitDisplayMode() This function performs initializations informing OpenGL how to set up its frame buffer. The argument to glutInitDisplayMode() is a logical-or (using the operator “|”) of a number of possible options, which are given in Table 1. glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);

glutCreateWindow() This command actually creates the graphics window. The general form of the command is glutCreateWindowchar(*title) where title is a character string. Each window has a title, and the argument is a string which specifies the window’s title. glutCreateWindow(“ This is my First Program”);

Colors • Before you start drawing you will want to set the colour of the window (background) and the colour of the drawing (foreground). • The background and foreground can be changed at anytime during the program. • Colours are specified using a mixture of Red, Green and Blue (RGB). • Each amount of colour is specified by a float value between 0 and 1. – 0 = none of this colour – 1 = all of this colour • A colour is specified as (R,G,B) e.g (1, 0.5, 0.2) • Can you guess what R, G and B are set to for black and white?

Color Color in RGBA mode is set by specifying the red, green, blue and alpha intensities. alpha = 1 //opaque alpha = 0 // transparent

RGB color Each color component stored separately in the frame buffer Usually 8 bits per component in buffer Note in glColor3f the color values range from 0.0 (none) to 1.0 (all), while in glColor3ub the values range from 0 to 255

Indexed Color Memory inexpensive Need more colors for shading Colors are indices into tables of RGB values Requires less memory indices usually 8 bits not as important now Memory inexpensive Need more colors for shading

Color and State The color as set by glColor becomes part of the state and will be used until changed Colors and other attributes are not part of the object but are assigned when the object is rendered We can create conceptual vertex colors by code such as glColor glVertex

Setting of color attribute glClearColor(1.0, 1.0, 1.0, 0.0); //Clear color for background glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f);// red // for forground Instead of using one color buffer, two can be used Front Buffer: one that is displayed but not written to Back Buffer: one that is written to but not displayed

OpenGL Initalization We’ll use the init() routine for our one-time OpenGL state initialization call after window has been created, but before first rendering call void init( void ) { // set the background color // glClearColor( R, G, B, α ); glClearColor( 1.0, 0.0, 0.0, 1.0 ); }

Setting the Background Colour glClearColor(R, G, B, α); glClearColor(1,0,0,0); glClearColor(0,1,0,0); glClearColor(0,0,1,0);

init.c black clear color opaque window void init() { glClearColor (0.0, 0.0, 0.0, 1.0); ////////////////////////////////////////// glMatrixMode (GL_PROJECTION); glLoadIdentity (); // Viewing in 2D gluOrtho2D(0.0 ,// Left 2.0, // Right 0.0, // Bottom 2.0 // Top); } black clear color opaque window

Specifying a Vertex’s Color Use the OpenGL color command glColor3f( r, g, b ); Where you specify the color determines how the primitive is shaded points only get one color

Setting the Foreground Colour glClear(GL_COLOR_BUFFER_BIT); glColor3f(R, G, B); glColor4f(R, G, B, α);

Example of setting color glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0f, 0.0f, 0.0f);//no alpha value form glBegin( GL_TRIANGLEs); glVertex3f( -1.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f); glEnd(); Note that the glColor*() function can be placed inside a glBegin()/glEnd() pair. Therefore you can specify individual colors for each individual vertex

OpenGL Command Notation (1/2) void glSomeFunction {3} {bsifd} {v} (arguments); the first optional term in curly braces indicates that this function takes 3 arguments. the second sets of braces indicates that this function takes 5 possible argument types b = byte, s = short, I = integer, f = float, d = double the last term in curly braces indicate that a vector form of the command also exists.

OpenGL Command Notation (2/2) glVertex3fv( ... ) Number of components Data Type Vector b - byte ub - unsigned byte s - short us - unsigned short i - int ui - unsigned int f - float d - double omit “v” for scalar form glVertex2f( x, y ) 2 - (x,y) 3 - (x,y,z) 4 - (x,y,z,w)

OpenGL function format function name dimensions glVertex3f(x,y,z) x,y,z are floats belongs to GL library glVertex3fv(p) p is a pointer to an array

Specifying an OpenGL Vertex Recall OpenGL specifies geometric primitives by its vertices glVertex3f( x, y, z ); Different primitives require different numbers of vertices

OpenGL Command Syntax OpenGL commands use the prefix gl and initial capital letters for each word making up the command name glClearColor( ) Similarly, OpenGL defined constants begin with GL_, use all capital letters, and used underscores to separate words

Command Suffixes and Argument Data Types

OpenGL drawing To draw a primitive, call glBegin(Primitive) glEnd() encloses a list of vertices and their attributes Coordinates of a primitive are given counter-clockwise order

OpenGL drawing Between glBegin/ glEnd, those opengl commands are allowed: glVertex*() : set vertex coordinates glColor*() : set current color glIndex*() : set current color index glNormal*() : set normal vector coordinates (Light.) glTexCoord*() : set texture coordinates (Texture)

Constructive Primitives The glBegin() / glEnd() Wrappers all OpenGL descriptions of primitives start with glBegin(xxx), where xxx is an OpenGL-defined constant that identifies the OpenGL primitive.

Specifying Geometric Primitives Primitives are specified using glBegin( primType ); glEnd(); primType determines how vertices are combined GLfloat red, greed, blue; Glfloat coords[3]; glBegin( primType ); for ( i = 0; i < nVerts; ++i ) { glColor3f( red, green, blue ); glVertex3fv( coords ); } glEnd(); OpenGL organizes vertices into primitives based upon which type is passed into glBegin(). The possible types are: GL_POINTS GL_LINE_STRIP GL_LINES GL_LINE_LOOP GL_POLYGON GL_TRIANGLE_STRIP GL_TRIANGLES GL_TRIANGLE_FAN GL_QUADS GL_QUAD_STRIP

OpenGL Primitives GL_POINTS GL_POLYGON GL_LINE_STRIP GL_LINES GL_LINE_LOOP GL_TRIANGLES GL_QUAD_STRIP GL_TRIANGLE_STRIP GL_TRIANGLE_FAN

Simple Example Drawing Single Point glBegin(GL_POINTS); glVertex3f(0.0f, 0.0f, 0.0f); glEnd(); Draw triangle The drawRhombus() routine causes OpenGL to render a single quadrilateral in a single color. The rhombus is planar, since the z value is automatically set to 0.0 by glVertex2f(). glBegin(GL_TRIANGLES); glVertex3f(0.0f, 1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 0.0f); glEnd();

Drawing Polygon void mydisplay(){ glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glFlush(); }

Draw a triangle with different colors : glBegin(GL_TRIANGLES); glColor3f(1.0f, 0.0f, 0.0f); //pure red glVertex3f(0.0f, 1.0f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); //pure green glVertex3f(-1.0f, -1.0f, 0.0f); glColor3f(0.0f, 0.0f, 1.0f); //pure blue glVertex3f(1.0f, -1.0f, 0.0f); glEnd();

Rendering Callback Callback function where all our drawing is done Every GLUT program must have a display callback glutDisplayFunc( my_display_func ); /* this part is in main.c */ void my_display_func (void ) { glClear( GL_COLOR_BUFFER_BIT ); glBegin( GL_TRIANGLE ); glVertex3fv( v[0] ); glVertex3fv( v[1] ); glVertex3fv( v[2] ); glEnd(); glFlush(); }

glClear(GL_COLOR_BUFFER_BIT); glBegin( GL_QUADS ); void dispaly( void) { glClear(GL_COLOR_BUFFER_BIT); glBegin( GL_QUADS ); glColor3f( 1.0f,0.0f,0.0f ); glVertex2f( 0.0, 0.0 ); glVertex2f( 1.0, 0.0 ); glVertex2f( 1.5, 1.118 ); glVertex2f( 0.5, 1.118 ); glEnd(); glFlush( ); glutSwapBuffers(); } Instead of using one color buffer, two can be used Front Buffer: one that is displayed but not written to Back Buffer: one that is written to but not displayed Program then requests a double buffer in main.c glutInitDisplayMode(GL_RGB | GL_DOUBLE) glutSwapBuffers() waits until the current screen refresh period is over so that the previous buffer is completely displayed and then swaps the buffers.

GLUT Callback functions Event-driven: Programs that use windows Input/Output Wait until an event happens and then execute some pre-defined functions according to the user’s input Events – key press, mouse button press and release, window resize, etc. Your OpenGL program will be in infinite loop

GLUT Callback Functions Callback function : Routine to call when an event happens Window resize or redraw User input (mouse, keyboard) Animation (render many frames) “Register” callbacks with GLUT glutDisplayFunc( my_display_func ); glutIdleFunc( my_idle_func ); glutKeyboardFunc( my_key_events_func ); glutMouseFunc ( my_mouse_events_func );

Event Queue Keyboard …. Mouse MainLoop() Window Event queue Mouse_callback() { …. Keypress_callback() { …. window_callback() { ….

Sample Program glutSwapBuffers(); #include <glut.h> void draw(){ glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glVertex2f(-0.5, -0.5); glVertex2f(-0.5, 0.5); glVertex2f(0.5, 0.5); glVertex2f(0.5, -0.5); glEnd(); glFlush(); glutSwapBuffers(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(400, 400); glutCreateWindow(“Sample"); glutDisplayFunc(draw); glutMainLoop(); return 0;

Sample Program void main( int argc, char** argv ) { int mode = GLUT_RGB|GLUT_DOUBLE; glutInitDisplayMode( mode ); glutCreateWindow( argv[0] ); init(); glutDisplayFunc( display ); glutReshapeFunc( resize ); glutKeyboardFunc( key ); glutIdleFunc( idle ); glutMainLoop(); } Here’s an example of the main part of a GLUT based OpenGL application. This is the model that we’ll use for most of our programs in the course. The glutInitDisplayMode() and glutCreateWindow() functions compose the window configuration step. We then call the init() routine, which contains our one-time initialization. Here we initialize any OpenGL state and other program variables that we might need to use during our program that remain constant throughout the program’s execution. Next, we register the callback routines that we’re going to use during our program. Finally, we enter the event processing loop, which interprets events and calls our respective callback routines.

Idle Callback Use for animation and continuous update Can use glutTimerFunc or timed callbacks for animations glutIdleFunc( idle ); void idle( void ) { /* change something */ t += dt; glutPostRedisplay(); }

Posting redisplays Many events may invoke the display callback function Can lead to multiple executions of the display callback on a single pass through the event loop We can avoid this problem by instead using glutPostRedisplay(); which sets a flag. GLUT checks to see if the flag is set at the end of the event loop If set then the display callback function is executed

User Input Callbacks Process user input glutKeyboardFunc( my_key_events ); void my_key_events (char key, int x, int y ) { switch ( key ) { case ‘q’ : case ‘Q’ : exit ( EXIT_SUCCESS); break; case ‘r’ : case ‘R’ : rotate = GL_TRUE; }

Mouse Callback Captures mouse press and release events glutMouseFunc( my_mouse ); void myMouse(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) … }

GLUT Parameters GLUT parameter names associated with mouse events

Events in OpenGL Event Example OpenGL Callback Function Keypress KeyDown KeyUp glutKeyboardFunc Mouse leftButtonDown leftButtonUp glutMouseFunc Motion With mouse press Without glutMotionFunc glutPassiveMotionFunc Window Moving Resizing glutReshapeFunc System Idle Timer glutIdleFunc glutTimerFunc Software What to draw glutDisplayFunc

Shapes Tutorial

glBegin(GL_POLYGON); glVertex3f(0.25, 0.25, 0.0); Program1 .c #include <stdlib.h> #include <GL/glut.h> void display(void) { glColor3f(1.0, 1.0, 1.0); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); glBegin(GL_POLYGON); glVertex3f(0.25, 0.25, 0.0); glVertex3f(0.75, 0.25, 0.0); glVertex3f(0.75, 0.75, 0.0); glVertex3f(0.25, 0.75, 0.0); glEnd( ); glFlush( ); glutSwapBuffers(); }

void init(void){ glClearColor(0.0, 0.0, 0.0); /* Initialize viewing values */ glMatrixMode(GL_PROJECTION); glLoadIdentity( ); glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); } int main (int argc, char **argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(250,250); glutInitWindowPosition(0,0); glutCreateWindow(“hello”); init( ); glutDisplayFunc(display); glutMainLoop( ); return 0;

// Program 2.c #include <stdlib.h> #include <GL/glut.h> static GLfloat spin = 0.0; void init(void){ glClearColor(0.0, 0.0, 0.0, 0.0); glShadeModel(GL_FLAT); } void display(void){ glClear(GL_COLOR_BUFFER_BIT); glPushMatrix( ); glRotatef(spin, 0.0, 0.0, 1.0); glColor3f(1.0, 1.0, 1.0); glRectf(-25.0, -25.0, 25.0, 25.0); glPopMatrix( ); glutSwapBuffers( );

void spinDisplay(void){ spin = spin + 2.0; if(spin > 360.0) spin = spin - 360.0; glutPostRedisplay( ); } void reshape(int w, int h){ glViewport(0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity( ); glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW);

void mouse(int button, int state, int x, int y){ switch(button){ case GLUT_LEFT_BUTTON: if(state == GLUT_DOWN) glutIdleFunc(spinDisplay); break; case GLUT_RIGHT_BUTTON: glutIdleFunc(NULL); default: }

int main(int argc, char ** argv){ glutInit(&argc, argv); // request double buffer mode glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); glutInitWindowSize(250,250); glutInitWindowPosition(100,100); glutCreateWindow(argv[0]); init( ); glutDisplayFunc(display); // register window resize callback glutReshapeFunc(reshape); // register mouse callback glutMouseFunc(mouse); glutMainLoop( ); }