opengl 2 angel: chapter 2 opengl programming and reference guides, other sources. ppt from angel,...

90
OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Upload: ezra-wilcox

Post on 30-Dec-2015

243 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

OpenGL 2Angel: Chapter 2

OpenGL Programming and Reference Guides, other sources.ppt from Angel, AW, etc.

CSCI 6360

Page 2: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

But first … Homework

• (get the environment set up)• Create some objects

• “Extra Credit”

Page 3: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

OpenGL objects - 2015

Uses fns for shapes, draws scene. Shapes plus t-fan and trig for star.

Shapes plus rotates on click. Different poly d-s for each.

Page 4: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

OpenGL objects - 2015

Figs start cntr, rnd move to edge – bounce. Diff. side with mouse clicks.

Page 5: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

OpenGL objects - 2013

User interaction tochange camera view

“Simple Clock”, like is says

Rotates

Page 6: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

OpenGL objects - 2013

Page 7: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

OpenGL objects - 2010

Page 8: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Introduction

• Recall from last time:

– Angel takes a “top down” approach …• vs. the “old school” approach, where you understand what you’re doing

– E.g., complicated line drawing algorithms first

– OpenGL is pretty complicated …

– Especially, in that programmer has access to “inner workings” of (graphics) system

• “Don’t touch the switches …”

• Will continue in that vein

• Will talk a fair amount about software architecture … interactive systems generally

• Will wander around in the trees – GLUT functions

Page 9: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Overview

• Event driven software architectures– Different paradigm for control flow – vs. “top to bottom”, object-oriented, etc.

• In commercial software, “user interface code” is typically > 50% of code!

• Will be talking about such “user interface programming” – At least as much as needed to write interactive graphics programs using GLUT

• Input devices

• Programming event input with GLUT

• Working with callbacks– Interactive programs using GLUT callbacks

• E.g., Mouse, Keyboard, Reshape

• Menus in GLUT

Page 10: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Next Time …more interaction

• Other interactive program techniques and elements:

– Double buffering (maybe tonight)• For animation and smooth display

– Picking• Select objects from the display

– Rubberbanding• Interactive drawing of lines and rectangles

– Display Lists

• Retained mode graphics– Text

• Bitmap and stroke

– Multiple and sub- windows

Page 11: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Recall, Project Sketchpad

• Yet again, Angel reminds us of Sutherland’s seminal work– Ivan Sutherland (MIT 1963)

• New interaction paradigm– Established basic interactive

paradigm that characterizes interactive computer graphics:

• User sees object on display• User points to (picks) object with

an input device– light pen, mouse, trackball

• Object changes moves, rotates, morphs

• Repeat

Sketchpad in 1963 - CRT monitor, light pen and function-key panel.

Page 12: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Graphical Input

• Devices described either by– Physical properties

• Mouse• Keyboard• Trackball

– Logical Properties• What is returned to program

via API– A position– An object identifier

• Modes– How and when input is

obtained• Request or event

mouse trackball

data tabletjoy stick

light pen space ball

Page 13: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Incremental (Relative) Devices

• Devices such as data tablet return a position directly to the operating system

• Devices such as the mouse, trackball, and joy stick return incremental inputs (or velocities) to the operating system– Must integrate these inputs to

obtain an absolute position• Rotation of cylinders in mouse• Roll of trackball• Difficult to obtain absolute position• Can get variable sensitivity

mouse

trackball

data tablet

joy stick

light pen space ball

Page 14: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Logical Devices• Consider the C and C++ code:

– C++: cin >> x;– C: scanf (“%d”, &x);

• What is the input device?– Can’t tell from the code - could be keyboard, file, output from another program

• The code provides logical input– A number (an int) is returned to the program regardless of the physical device

• Graphical Logical Devices– Graphical input more varied than input to standard programs (characters) – Six types of logical input (also, general terms for interaction):

• Locator: return a position• Pick: return ID of an object• Keyboard: return strings of characters• Stroke: return array of positions• Valuator: return floating point number• Choice: return one of n items

Page 15: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

X Window Input

• Historically important terminology

• X Window System introduced client-server model for network of workstations– Client:

• OpenGL program– Graphics Server:

• bitmap display with a pointing device and a keyboard

Page 16: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Recall, Software Architecture

Page 17: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Recall, Software Architecture

“Application Progs” E.g., student programs MS Excel, etc.

Tools: Graphic Maya, 3ds

Tools: UI Program. MFC, Swing, Qt (widget toolkit and more)

Graphics API OpenGl (no win sys func) DirectX

GLUTOpenGL Utility Toolkit

Window system API MS windows X tools

CPU GPUGraphics Processing Unit

Tools: Vis. Program. VTK

Page 18: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT

GLU

GL

GLX, AGLor WGL

X, MS Windows, Mac os

software and/or hardware

application program

OpenGL Motifwidget or similar

Recall, Software ArchitectureWindow systems and graphics systems examples

• Window system controls/manages window creation, appearance, messages (event queue), etc.

– Has its own API for programming, with and without accessing OpenGL

• Graphics system controls graphics display hardware– Here, OpenGL – GL and its utilities, GLU

window system

graphics system

Page 19: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT

GLU

GL

GLX, AGLor WGL

X, Win32, Mac O/S

software and/or hardware

application program

OpenGL Motifwidget or similar

Recall, Software ArchitectureWindow systems and graphics systems examples

• Window system controls/manages window creation, appearance, messages (event queue), etc.

– Has its own API for programming, with and without accessing OpenGL

• Graphics system controls graphics display hardware– Here, OpenGL – GL and its utilities, GLU

window system

graphics system

Page 20: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT

GLU

GL

GLX, AGLor WGL

X, Win32, Mac O/S

software and/or hardware

application program

OpenGL Motifwidget or similar

Software Org. – Window & Graphics Systems

• GLUT - layer for access to both window and graphics systems– GLUT uses GLU and GL for graphics

• Controls operating and window systems primarily through GLX, AGL, WGL

• Callback functions are means GLUT uses to “shield programmer from intricacies of direct event loop programming”

window system

graphics system

Page 21: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT, Qt

GLU

GL

GLX, AGLor WGL

X, Win32, Mac O/S

software and/or hardware

application program

OpenGL Motifwidget or similar

Software Org. – Window & Graphics Systems

• Qt also provides access to both window and graphics system– Widely used and robust, e.g., Google Earth– Many more widgets– Tradeoff:

• Flexibility (not all window system calls available)

window system

graphics system

Page 22: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360
Page 23: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

From last time: Glut - Event LoopWhat’s a callback function? … we’ll see

• Recall, “…, more about GLUT next time”

– Now, it’s next time …

• Program defines a display callback function– Here, named mydisplay

• Every glut program must have a display callback

– Executed whenever OpenGL indicates display must be refreshed,

• (much more later)• E.g., when window

opened, mouse clicked• Here, just draw polygon

– The main function ends with program entering an event loop

#include <GL/glut.h>

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();

}

int main(int argc, char** argv){ glutCreateWindow("simple"); glutDisplayFunc(mydisplay); glutMainLoop();}

Page 24: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

About Input Modes• Input devices contain a trigger used to send signal to operating system

– Button on mouse– Pressing or releasing a key

• When triggered, input devices return information (measure) to system– Mouse returns position information– Keyboard returns ASCII code

• Returned by: 1. Request mode (familiar) vs. 2. Event mode (next slide)– “when” input is present for interactive program

• 1. Request mode– Input provided to program only when user triggers the device– Typical of keyboard input

• Can erase, edit, etc. until enter return key (the trigger) is depressed

Page 25: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Event Mode – this is new

Page 26: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Event Mode – this is new

• Most systems have more than one input device, each of which can be triggered at an arbitrary time by a user

• Each trigger generates an event whose measure is put in an event queue which can be examined by the user program

• Event types … and these may not all be what you think of as “events”– Mouse: click one or more buttons– Keyboard: press or release a key– Motion: move mouse– Window: resize, expose, iconify– Idle: “nonevent” (for heavens sake), or, the “null event”

• Define what should be done if no other event is in queue

Page 27: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Event Driven Architecture

• Different paradigm for control flow

• Have written “while (true)” loops– Continues in loop until something terminates, e.g., menus

• Also, have written polling loops– I.e., continue looping and constantly getting value (will see example)

• Will look at details of event driven (software) architecture as relate to interactive systems generally

• Essential challenge is the handling of asynchronous events– E.g., button presses, mouse movement, …– Whatever user does, … and whenever he or she does it

• GLUT will make use of callback functions – but there are other ways– And, will look at MS Windows API to handle events, as GLUT is “abstraction”

Page 28: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

About Interaction Handling, Polling

• Sampling (polling) vs. event-driven software architectures– Basic issue of how to get and act upon user actions– Entails “looking at” (getting information from) input devices– Readln (...) -- get character information, “sits and waits” – With several asynchronous devices (mouse loc & button) need new method(s)

• Polling to detect mouse: // use past and current values of some event indicator to see if (new) input 

old_val = get_val_of (mouse_button_1) 

WHILE (!quit){new_val = get_val_of (mouse_button_1)if (new_val != old_val)

{// do whatever to do with mouse clickold_val = new_val}

  // check other devices too, and act if need to }

• This is process intensive as always checking

Page 29: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

About Interaction Handling, Event Driven

• Event Driven 

WHILE (!quit){// program waits for user actionwait_on (user_action) // just sit there until event occurs, sort of a magic function, … we’ll

see 

switch (user_action) {case mouse_button_1_clicked:

// do whatever to do with mouse click 

// other cases to handle user input:case mouse_button_2_clicked:

.}

• When > 1 user action occurs before processing of another event, put events in queue

– event queue:

• This is basic manner in which window manager (system) handles user input:– There is an event for everything (click, resize window, move mouse into window, ...)!

• and a message is generated for each, so in fact the messages are held in a queue: window’s event, or message, queue

e1 e2 e3 e4 e5 ……

Page 30: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Window Manager Distributes Events to Appropriate Program Event Queues

• E.g., mouse move across multiple programs– Information about input event distributed to all programs, e.g., mouse x, y– Every program has an event queue

program 1

queue 1

wndproc(){}

program n

queue n

wndproc(){}

Windows - distributes eventsProgram 1 Program 2 Program 3

Event queue 1 Event queue 2 Event queue 3

Wndproc 1 Wndproc 2 Wndproc 3

Page 31: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Again, Event Driven

• Event driven control flow architecture: 

WHILE (!quit){:// program waits for user actionwait_on (user_action) // just sit there until event occurs

 switch (user_action) {

:case mouse_button_1_clicked: // do whatever to do with mouse click

 // other cases to handle user input:case mouse_move:

// … and other window system eventscase window_resized:

.}

• There is an event for everything (click, resize window, window, ...)!• and a message is generated for each, so in fact the messages are held in a

queue: window’s message queue

Page 32: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

E.g., MS Windows Callback Functionlike GLUT Callback Function, but handles everything! - separate functions for GLUT

WndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) // front message of event queue { switch (iMsg) // note switch structure – handles and

returns {

case WM_CREATE : // message when program starts:

case WM_SIZE : // message when window size changed

case WM_MOUSEMOVE :x = LOWORD (lParam); y = HIWORD (lParam); // “decode” lParam to get x and y locations

: return 0 ;

  case WM_LBUTTONDOWN : // myMouse (button, state, x, y);

x = LOWORD (lParam); y = HIWORD (lParam); TextOut (hdc, 20, 200, szBuffer, nLength); // write x and y locations return 0 ;

  case WM_DESTROY : // window closed

PostQuitMessage (0) ; return 0 ;

}return DefWindowProc (hwnd, iMsg, wParam, lParam) ; // default handling of events, if not here

}

Page 33: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

MS Windows Callback Functionlike GLUT Callback Function, but handles everything! - separate functions for GLUT

WndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) // front message of event queue { switch (iMsg) // note switch structure – handles and

returns {

case WM_CREATE : // message when program starts:

case WM_SIZE : // message when window size changed

case WM_MOUSEMOVE :x = LOWORD (lParam); y = HIWORD (lParam); // “decode” lParam to get x and y locations

: return 0 ;

  case WM_LBUTTONDOWN : // myMouse (button, state, x, y);

x = LOWORD (lParam); y = HIWORD (lParam); TextOut (hdc, 20, 200, szBuffer, nLength); // write x and y locations return 0 ;

  case WM_DESTROY : // window closed

PostQuitMessage (0) ; return 0 ;

}return DefWindowProc (hwnd, iMsg, wParam, lParam) ; // default handling of events, if not here

}

glutMouseFunc encapsulates several “raw” window events in a nice function with parameters

glutReshapeFunc

Page 34: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Software Org. – GL, GLU, GLUT(again)

• GLUT provides another layer for access to window manager/system– GLUT uses GLU and GL for graphics

• Controls operating and window systems primarily through GLX, AGL, WGL

• Callback functions means GLUT uses to “shield programmer from intricacies of direct event loop programming” - Angel

GLUT

GLU

GL

GLX, AGLor WGL

X, Win32, Mac O/S

software and/or hardware

application program

OpenGL Motifwidget or similar

Page 35: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT Resources – “Manual”Saw for OpenGL last time

• The OpenGL Utility Toolkit (GLUT) Programming Interface API Version 3

– http://www.opengl.org/documentation/specs/glut/spec3/spec3.html

Page 36: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT Callback Functions

• GLUT callback function is called when various events occur

• E.g., WM_LBUTTON_DOWN– glutMouseFunc callback

encapsulates several “raw” window events in a nice function with parameters

• Some used all the time– glutDisplayFunc

• More later

From manual:

7.1 glutDisplayFunc

7.2 glutOverlayDisplayFunc

7.3 glutReshapeFunc

7.4 glutKeyboardFunc

7.5 glutMouseFunc

7.6 glutMotionFunc, glutPassiveMotionFunc

7.7 glutVisibilityFunc

7.8 glutEntryFunc

7.9 glutSpecialFunc

7.10 glutSpaceballMotionFunc

7.11 glutSpaceballRotateFunc

7.12 glutSpaceballButtonFunc

7.13 glutButtonBoxFunc

7.14 glutDialsFunc

7.15 glutTabletMotionFunc

7.16 glutTabletButtonFunc

7.17 glutMenuStatusFunc

7.18 glutIdleFunc

7.19 glutTimerFunc

Page 37: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT Callback Functions

• Callback function is called when various events occur

• E.g., WM_LBUTTON_DOWN

• glutMouseFunc callback– encapsulates several “raw” window events

in nice function with parameters

glutMouseFunc (myMouse);

void myMouse(int button, int state, int x, int y)

{

if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)

exit(0);

}

Page 38: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Again, Window Manager Distributes Events to Appropriate Event Queues

• E.g., mouse move across multiple programs– Information about input event distributed to all programs, e.g., mouse x, y– Every program has an event queue

program 1

queue 1

wndproc(){}

program n

queue n

wndproc(){}

Windows - distributes eventsProgram 1 Program 2 Program 3

Event queue 1 Event queue 2 Event queue 3

Wndproc 1 Wndproc 2 Wndproc 3

Page 39: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

MS Windows Callback Functionlike GLUT Callback Function, but handles everything! - separate functions for GLUT

WndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) // front message of event queue { switch (iMsg) // note switch structure – handles and

returns {

case WM_CREATE : // message when program starts:

case WM_SIZE : // message when window size changed

case WM_MOUSEMOVE :x = LOWORD (lParam); y = HIWORD (lParam); // “decode” lParam to get x and y locations

: return 0 ;

  case WM_LBUTTONDOWN : // myMouse (button, state, x, y);

x = LOWORD (lParam); y = HIWORD (lParam); TextOut (hdc, 20, 200, szBuffer, nLength); // write x and y locations return 0 ;

  case WM_DESTROY : // window closed

PostQuitMessage (0) ; return 0 ;

}return DefWindowProc (hwnd, iMsg, wParam, lParam) ; // default handling of events, if not here

}

glutMouseFunc encapsulates several “raw” window events in a nice function with parameters

glutReshapeFunc

Page 40: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT Resources – ExamplesExamples are good, … very good

• Examples– http://www.opengl.org/resources/

code/samples/glut_examples/examples/examples.html

Page 41: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT Callback Functions

• GLUT callback function is called when various events occur

• E.g., WM_LBUTTON_DOWN– glutMouseFunc callback

encapsulates several “raw” window events in a nice function with parameters

• Some used all the time– glutDisplayFunc

7.1 glutDisplayFunc

7.2 glutOverlayDisplayFunc

7.3 glutReshapeFunc

7.4 glutKeyboardFunc

7.5 glutMouseFunc

7.6 glutMotionFunc, glutPassiveMotionFunc

7.7 glutVisibilityFunc

7.8 glutEntryFunc

7.9 glutSpecialFunc

7.10 glutSpaceballMotionFunc

7.11 glutSpaceballRotateFunc

7.12 glutSpaceballButtonFunc

7.13 glutButtonBoxFunc

7.14 glutDialsFunc

7.15 glutTabletMotionFunc

7.16 glutTabletButtonFunc

7.17 glutMenuStatusFunc

7.18 glutIdleFunc

7.19 glutTimerFunc

Page 42: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT Callback FunctionWndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) // front message of event queue { switch (iMsg) // note switch structure – handles and

returns {

case WM_CREATE : // message when program starts:

case WM_SIZE : // message when window size changed

case WM_MOUSEMOVE :x = LOWORD (lParam); y = HIWORD (lParam); // “decode” lParam to get x and y locations

: return 0 ;

  case WM_LBUTTONDOWN : // myMouse (button, state, x, y);

x = LOWORD (lParam); y = HIWORD (lParam); TextOut (hdc, 20, 200, szBuffer, nLength); // write x and y locations return 0 ;

  case WM_DESTROY : // window closed

PostQuitMessage (0) ; return 0 ;

}return DefWindowProc (hwnd, iMsg, wParam, lParam) ; // default handling of events, if not here

}

Page 43: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

OpengGL Event Driven Control StructureCallback functions … said another way

• Something happens– An “event”– GLUT callback may handle, if used

• E.g., mousemotion

– May cause redraw• E.g., move window off• GLUT display function called

• Update any signals (values) that creating the display depends on

– Often, display needs to be redrawn– Program indicates this by

postRedisplay ()• Which actually causes system to

indicate call to GLUT dislay function

• Draw display– GLUT display function

DrawDisplay

Event – user, system, program

Program’s GLUT callback may changes state of program for redraw

PostRedisplay()

Page 44: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Sum: GLUT Callback Funcs. for Events(summary, as needed)

• Callback functions are GLUT’s programming interface for event-driven input– Avoids handling input in “raw” terms of window manager/systems– Handles most events of interest, but for full control must deal with full event stream though

window manager/system api

• Define a callback function for each type of event the GLUT recognizes– This user-supplied function is executed when the event occurs

• Example: glutMouseFunc(mymouse)- for mouse clicks– “mymouse” is name of function called when mouse event occurs– Note function name as a parameter!

• GLUT recognizes a subset of the events recognized by any particular window system (Windows, X, Macintosh)

– glutDisplayFunc– glutMouseFunc– glutReshapeFunc– glutKeyboardFunc– glutMotionFunc, glutPassiveMotionFunc

Page 45: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT and C ProgrammingBriefly …

• Not what you learned in (most) other classes …– But it’s real …– Recall, use of globals – just don’t have parameter (message) passing facilities in

GLUT functions that might like to have– Also note, C use of #define (or enum)

• E.g., #define iCircle 1

• Typical opengl program structure– Init– Display

• Other encapsulation, as in other control structures, e.g., drawSquare or drawFigure (IFigureType, iColor)

– Handle menu(s)– main

Page 46: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

From last time: “simple.c revisited” GLUT functions in detail now…

• GLUT library calls in main:

• glutInit – allows application to get

command line arguments and initializes system

• gluInitDisplayMode – requests properties for window – rendering context

• RGB color• Single buffering• Properties logically ORed

together

• glutWindowSize (pixels)

• glutWindowPosition – from top-left corner of display

• glutCreateWindow – Window has title “simple”

• glutDisplayFunc – Name of display callback function

• glutMainLoop – enter infinite event loop

void init(){

// black clear color - 1.0 – opaque window glClearColor (0.0, 0.0, 0.0, 1.0);

// fill/draw with white glColor3f(1.0, 1.0, 1.0);

glMatrixMode (GL_PROJECTION); // more laterglLoadIdentity ();

// view volume glOrtho(-1.0,1.0,-1.0,1.0,-1.0,1.0); }

void mydisplay () { ….} // before …

int main(int argc, char** argv){

glutInit(&argc,argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize (500,500); // win prop glutInitWindowPosition (0,0); glutCreateWindow ("simple"); glutDisplayFunc (mydisplay); // display callback

init(); //set OGl state

glutMainLoop(); // enter event loop

}

Page 47: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT Event Loop - Detail• Recall , last line in main.c must be:

– glutMainLoop();– puts program in an “infinite event loop”

• In each pass through event loop, GLUT – looks at events in event queue– for each event in the queue that GLUT

recognizes, GLUT executes appropriate callback function, if one is defined

• E.g., glutMouseFunc– if no callback is defined for the event, the

event is ignored

• Here, only “display” function handled events dealt with

– Will see mouse, etc. handling later

int main(int argc, char** argv){

glutInit(&argc,argv);

glutInitDisplayMode(GLUT_SING|GLUT_RGB);

// define win prop glutInitWindowSize(500,500);

glutInitWindowPosition(0,0);

glutCreateWindow("simple");

// display callback glutDisplayFunc(mydisplay);

// set OpenGl stateinit();

// enter event loopglutMainLoop();

}

Page 48: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Display Callback: glutDisplayFunc(<fn>)“redraw all when needed”, man page next slide

• Lots of things go on that require that content of window needs to be redrawn

– E.g., when the window is first opened, reshaped, exposed, another window moved across

• Also, when program itself determines time to change display

• Display callback is executed whenever GLUT determines that window should be refreshed

• In main.c– glutDisplayFunc(mydisplay)

identifies function to be executed– Every GLUT program must have a

display callback

int main(int argc, char** argv){

glutInit(&argc,argv);

glutInitDisplayMode(GLUT_SING|GLUT_RGB);

// define win prop glutInitWindowSize(500,500);

glutInitWindowPosition(0,0);

glutCreateWindow("simple");

// display callback glutDisplayFunc(mydisplay);

// set OpenGl stateinit();

// enter event loopglutMainLoop();

}

Page 49: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Display Callback: glutDisplayFunc(<fn>)

• x

Page 50: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Display Callback:glutPostRedisplayFunc(<fn>)

• “Posting redisplays” … Controlling program flow yourself

• Use glutPostRedisplay()for API/programmer control of execution– “Forces redraw”– Actually, “sets flag” or otherwise indicates that window needs to be redrawn

• Just as when another window is moved off

– Consider this as an “event” to be handled– Program handles “event” by calling display callback function, defined in glutDisplayFunc()– Many events may invoke the display callback function

• Can lead to multiple executions of display callback on a single pass through event loop

• Useful, e.g., for control of drawing in execution

• Do note how this is a different paradigm of control, i.e., based on events, than simply “top to bottom”, etc.

– It’s, well, event driven, but, it’s your event!

• Again, GLUT checks to see if flag is set the end of event loop– If set, then the display callback function is executed

Page 51: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

BTW, Using globals

• Note that example programs make extensive use of global variables, which has its disadvantages…

– However, that is the typical (and required) programming style with OpenGL

• The form of all GLUT callbacks is fixed, e.g.,– void mydisplay()– void mymouse(GLint button, GLint state, GLint x, GLint y)

• Therefore, must use globals to pass information to callbacks, ex.:

float n; /*global */

void mydisplay()

{

/* draw something that depends on n

}

Page 52: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Angel’s mouse position example

Page 53: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Mouse Callback: glutMouseFunc(<fn>)

• In practice, mouse is primary pointing device and means for interaction

– Here, function for returning, as C constants, information

– In main: glutMouseFunc(mymouse);

– Function prototype: void mymouse(GLint button, GLint state, GLint x, GLint y);

• Returns :– button (GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, GLUT_RIGHT_BUTTON) – state of that button (GLUT_UP, GLUT_DOWN)– position of button press in window, x, y coordinates

• Position in window (system) coordinates, not screen coordinates– Window system 0,0 is at top left of window

Page 54: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Screen and OGL Coordinate Systems“Programming is a craft …”

• Different coordinate systems for screen and world

• Position in screen window is usually measured in pixels with origin at top-left corner

• Consequence of refresh done from top to bottom

• OGL world coordinate system origin at bottom left• Must invert y coordinate returned by callback by

height of window• y = h – y;

• To invert y position we need window height• Height can change during program execution• Track with a global variable

– New height returned to reshape callback– Can also use GL query functions (glGet …) to obtain

any value that is part of state• glGetIntv• glGetFloatv

(0,0) – screen window

h

w(0,0) – OGL

Page 55: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

glutGet (<const>)

• Lots of states can be queried

• Here,– glutGet(GLUT_WINDOW_HEIGHT)

Page 56: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Ex: Using Mouse Position (Angel)

• Example:– Draw small square at location of mouse

each time left mouse button clicked– glutMouseFunc(mymouse) in main– mymouse called each time button clicked

• Not use display callback - not good practice!

– But one is required by GLUT;– Can use empty display callback function

• mydisplay(){}

void mymouse( int btn, int state, int x, int y){

if (btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN)

exit(0);if (btn==GLUT_LEFT_BUTTON &&

state==GLUT_DOWN)drawSquare(x, y);

}

void drawSquare(int x, int y){ y = w - y; // invert y position glColor3ub( (char) rand()%256, // rnd col

(char) rand )%256, (char) rand()%256);

glBegin(GL_POLYGON); glVertex2f(x+size, y+size); glVertex2f(x-size, y+size); glVertex2f(x-size, y-size); glVertex2f(x+size, y-size); glEnd();}

Page 57: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Mouse Motion Callback: glutMotionFunc(<fn>)

• Also, …

• Can draw squares (or anything else) continuously as long as a mouse button is depressed by using the motion callback

– glutMotionFunc(drawSquare)

• Can draw squares without depressing a button using the passive motion callback

– glutPassiveMotionFunc(drawSquare)

Page 58: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Keyboard Callback: glutKeyboardFunc(<fn>)

• GLUT function - returns ASCII code of key depressed and mouse loc

– glutKeyboardFunc(mykey)– void mykey(unsigned char key, int x, int y)

void mykey(){

if(key == ‘Q’ | key == ‘q’) exit(0);

}

• Special and modifier keys – can do a fair number of things with GLUT– GLUT defines the special keys in glut.h

• Function key 1: GLUT_KEY_F1• Up arrow key: GLUT_KEY_UP

– if(key == GLUT_KEY_F1 ……

– Can also check of one of the modifiers• GLUT_ACTIVE_SHIFT• GLUT_ACTIVE_CTRL• GLUT_ACTIVE_ALT

is depressed byglutGetModifiers()

– Allows emulation of three-button mouse with one- or two-button mice

Page 59: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Toolkits and Widgets

• Most window systems provide a toolkit or library of functions for building user interfaces that use special types of windows called widgets

• Widget sets include tools such as:– Menus– Slidebars– Dials– Input boxes

• Toolkits tend to be platform dependent

• GLUT provides a few widgets including menus

• Again, GLUT is bare minimum, will see qt as full set

Page 60: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Menus glutCreateMenu(<fn>), etc.

• GLUT supports “pop-up” menus– These really pop-up – in graphic display!– A menu can have submenus

• To create a menu (really easy):1. Register callback function associated with menu2. Define menu entries with id used by callback 3. Link/attach menu to a mouse button

• To use menu1. Write callback function that uses menu id’s to

select what action to perform

clear screen

exit

// “create” menu shown at right in main:

// create menu with callback menu_id = glutCreateMenu (myMenu);

// string when/btn pressed, id valglutAddMenuEntry (“clear Screen”, 1);glutAddMenuEntry (“exit”, 2); // specify btn to invoke menuglutAttachMenu (GLUT_RIGHT_BUTTON);

:

// callback function for actionvoid myMenu (int choice){ switch (choice) { case 1: glClear(0); break; case 2: exit(0); break; } // draw screen again //without menu glutPostRedisplay();}

Page 61: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Hierarchical Menus:glutAddSubMenu (<fn>)

• Note: each menu has an id that is returned when created

• Add submenus by:

– glutAddSubMenu(char *submenu_name, submenu id)

• Callbacks color_menu and top_menu, as before

// create the top level menu – is by defaultglutCreateMenu (top_menu);glutAddMenuEntry (“Wire”, 1);glutAddMenuEntry (“(Solid)”, 2);

// create a menu – will use as submenusub_menu = glutCreateMenu (color_menu);glutAddMenuEntry (“(Red)”, 3);glutAddMenuEntry (“Yellow”, 4)

// specify this 3rd element of top menu has submenuglutAddSubMenu (“Torus Color”, sub_menu);

glutAttachMenu(GLUT_RIGHT_BUTTON);

Page 62: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Programming in the Dark“Programming is a craft …”

• One disadvantage of “top down” programming approach (or, design it all, or “good software engineering practice” is writing code that don’t understand details of makes all this somewhat circular

• Can lead to “unintended consequences”

• When debugging reaches stage of “let me guess” (relatively “uneducatedly”), this is not a good thing– Combinatorics – 32 things with 64 possibilities

• Idea is that details will be filled in … and need to use from outset– “get basic program schema working, then fill in the details”

Page 63: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

• Ok, let’s see a switch or two…

Page 64: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Reshaping the Display Window(fine, if not get all details first time through)

• Can reshape and resize OGL display window by dragging corner of window, of course

• In terms of event driven architecture,

– “Needs redraw”, when this “event” occurs– (or flag is set, or state, or …)– Causes “display function” to be called to

(re)draw the window

• What happens to display on resize?– Must redraw from application– Possibilities:

• Display whole world but force to fit in new window

• Display part of world• Display whole, alter aspect ratio to fit

– Ratio of width to height– E.g, 1000 to 800 = .8

Page 65: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Reshape Callback: glutReshapeFunc(<fn>), 1

• Another GLUT function: glutReshapeFunc (myreshape)

– Sets reshape callback for curr win

• void myreshape (int w, int h)– Returns width and height of new

window (in pixels)– Executes whatever you put in it– A redisplay (event) is posted

automatically at end of execution of the callback

– GLUT has a default reshape callback but probably want to define own

• Doesn’t, e.g., deal with change of aspect ratio

• Good place to put viewing functions because invoked when window is first opened

• Example follows (will see glViewport and gluOrtho2d)

Page 66: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Reshape Callback: glutReshapeFunc(<fn>), 2

• Quick look ---- Example (will see glViewport and gluOrtho2d shortly)

– preserves shapes by making viewport and world window have same aspect ratio– (will see glViewport and gluOrtho2d shortly)– gluOrtho specifies viewing rectangle (for the world)– glViewport specifies viewing rectangle (for that which is viewed on the display)

void myReshape(int w, int h){ glViewport(0, 0, w, h); // viewport will be 0, 0 lower left and w, h as right and top glMatrixMode(GL_PROJECTION); // switch matrix mode (more later) … it’s all a series of matrix mults. glLoadIdentity(); // (more later)

if (w <= h) // set ortho view vol to correspond to viewport gluOrtho2D(-2.0, 2.0, -2.0 * (GLfloat)h / (GLfloat)w, 2.0 * (GLfloat) h / (GLfloat) w); else gluOrtho2D(-2.0 * (GLfloat)w / (GLfloat)h, 2.0 * (GLfloat)w / (GLfloat)h, -2.0, 2.0);

glMatrixMode(GL_MODELVIEW); // return to modelview mode (more later)}

z=0

Page 67: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Recall, OpenGL Camera and View Volume Defaults

• OpenGL places a camera at origin in object/world space pointing in negative z direction

• Default view volume is a box centered at the origin with a side of length 2

Page 68: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Recall, Orthographic Viewing is Default

• Orthographic vs. perspective– Later will examine projection on view

plane for differing distances– Angel suggests thinking of orthographic

view as camera at infinite/far distance w/telephoto lens

• In the default orthographic view, points are projected forward along the z axis onto the plane z=0

z=0

z=0

Page 69: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

gluOrtho2D• From online reference …

• gluOrtho2D – – define a 2-D orthographic projection matrix, more about matrices later– (recall, “it’s all series of matrix multiplications, and we’ll get to that later” – here, it sets one)

• void gluOrtho2D(left, right, bottom, top)

• left, right – Specify the coordinates for the left and right vertical clipping planes.

• bottom, top – Specify the coordinates for the bottom and top horizontal clipping planes

z=0

z=0

Page 70: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Viewports• Do not have to use entire graphics window for viewing area

– Left below, mapping of clipping window to viewport - Right, aspect ratio mismatch

• Use function glViewport(x, y, width, height) to modify– Values in pixels (screen coordinates)– x, y specify lower left of viewport rectangle (relative to lower left of window)

• default 0,0– width, height specify those of viewport

• Can adjust height and width of viewport to match aspect ratio of clipping rectangle

– Prevents “distortion”, as in right figure

Page 71: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Ex: Reshape and Aspect Ratio• Below preserves shapes by making viewport and world window

have same aspect ratio

void myReshape(int w, int h){ glViewport(0, 0, w, h);

// switch matrix mode glMatrixMode(GL_PROJECTION); glLoadIdentity();

// if wider than high, then scale top and right to fit viewport // else higher than wide, so scale bottom and left to viewport if (w <= h) // glOrtho2d (left, right, top, bottom) gluOrtho2D(-2.0, 2.0, -2.0 * (GLfloat)h / (GLfloat)w, 2.0 * (GLfloat) h / (GLfloat) w); // else higher than wide, so scale bottom and left to viewport else gluOrtho2D(-2.0 * (GLfloat)w / (GLfloat)h, 2.0 * (GLfloat)w / (GLfloat)h, -2.0, 2.0);

// return to modelview mode glMatrixMode(GL_MODELVIEW); /* return to modelview mode */}

Page 72: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

BTW, Terminating a Program

• In our original programs, no way to terminate them through OGL

• Can use the simple mouse callback:

void mymouse (int btn, int state, int x, int y){If (btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN)

exit(0); }

Page 73: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Control Structure Review

Page 74: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Control Structure Review, 1/51. Event driven control flow – vs. “stop every thing and wait for a, e.g.,

keyboard char”

2. Practical thing most different is that all drawing in one function so can handle “redraw” (or refresh) at any time

– Vs., e.g., doing drawing when handle menu input– At first exposure to event driven programming, this is new – at least degree to which

it is done• Seems somehow “inefficient” to redraw EVERYTHING

• BUT, given that there is no way of know what part of screen needs to be redrawn, that’s what it takes

– Requires, then, some signal (message, event) to redraw

3. Either event from window system or Postredisplay() is signal to redraw

4. GLUT isolates programmer from window system details through callback functions

– Recall, example with MS Windows

Page 75: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Review – Events, 2/5Events, events, events, … from many things

• Events – from input devices– Most systems have more than one input device, each of which can be triggered

at an arbitrary time by a user– Mouse: click one or more buttons– Motion: move mouse– Keyboard: press or release a key

• Events – from system– Window: resize, expose, iconify– Idle: nonevent

• Define what should be done if no other event is in queue

• Events – from your program– postRedisplay

• Each event is put in an event queue, examined by the user program

Page 76: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Review – Glut Event Loop, 3/5• Program defines a display

callback function– Here, named mydisplay

• Every glut program must have a display callback

– Executed whenever OpenGL decides display must be refreshed,

• E.g., when window opened

– The main function ends with program entering an event loop

#include <GL/glut.h>

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();

}

int main(int argc, char** argv){ glutCreateWindow("simple"); glutDisplayFunc(mydisplay); glutMainLoop();}

Page 77: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Paradigm Control Structure, 4/5

1. Something happens– An “event”– GLUT callback may handle, if used

• E.g., mousemotion– May cause redraw

• E.g., move window off• GLUT display function called

2. Update any signals (values) that creating the display depends on

– Often, display needs to be redrawn– Program indicates this by

postRedisplay ()• Which actually causes system to

indicate call to GLUT dislay function

3. Draw display– GLUT display function– Everything drawn in one function Draw

Display

Event – user, system, program

Program’s GLUT callback may changes state of program for redraw

PostRedisplay()

Page 78: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

GLUT and C Programming, 5/5

• Maybe not what you learned about best practices …– But it’s real …– Recall, use of globals – just don’t have parameter (message) passing facilities in

GLUT functions that might like to have– Also note, C use of #define (or enum)

• E.g., #define iCircle 1

• Functions found in typical OpenGL programs:– Init– Display

• Other encapsulation, as in other control structures, e.g., drawSquare or drawFigure (IFigureType, iColor)

– Handle menu(s)– main

Page 79: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Program 2: Menus, Figures, Saving and Restoring

• In this second programming assignment in Open GL you will create a program to allow user interaction through a menu to draw objects (polygons). 

• The program should allow user through a menu with submenus to – 1) display at least five objects selected from at least four different types, e.g.,

square, triangle, – 2) specify the color of an object from at least four different colors, – 3) save the objects and their colors to a file, – 4) read those objects and colors from a file for display at the same locations, – 5) discard the current object set, and – 6) exit.

Page 80: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Program 2: Menus (and submenus), Figures, Saving and Restoring

1) display at least five objects selected from at least four different types, e.g., square, triangle, sphere,

– Note: It would make sense and be appropriate (in real life or something like it – and in the next assignment) to allow the user to specify where the object is located and its size, but (for the purposes of this program) just go ahead and put it at a location and with a size of your choosing. However, do not put it “on top of” another object.

2) specify the color of an object when it is created by the user’s selecting one color from at least four different colors,

 

3) save all the object types and colors to a file,

Note: No need to prompt for a file name, etc.

4) read the objects and colors from a file and display them at the same locations,

5) discard the current object set, allowing the user to “start over” with no object

6) exit.

For extra credit have the program handle change in window sizes and aspect ratios, keeping the relative positioning the same for objects.

Page 81: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Program 2: Menus (and submenus), Figures, Saving and Restoring

• When complete, please upload to the class Blackboard site: – 1) a short description (100-200 words) of what the program does – 2) a screen capture showing the display when five objects have been created, – 3) source code and – 4) executable.

• Note: Hopefully, the locations in which you installed any element used by the system on which you developed the program will be “compatible” with the system on which the program is to be executed.

• If not, we will have a go at recompiling it, and if it can be compiled then we’ll execute it.

• If it can’t be compiled, likely it will be straightforward to look at the code and change a path or such, but if not, we will drop you a note to get things straight.

• Usually there are not any significant problems.

Page 82: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Animating Interactive Programs

• .

Page 83: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Animating Interactive Programs

• Animation (movement, etc.) is among most powerful elements of cg– E.g., Today’s movie animations,

tomorrow’s movies …

• Seems straightforward enough:– Draw something at x, y– Maybe change it, move it, etc.– Draw something again at x’, y’

• Let’s see how that algorithm looks (in practice)– Bouncing ball

Page 84: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Animation in Practice

• Well, that sucked …

• “Implementation details” appear to be important in practice

• Recall, frame buffer, “scanning out”, etc.

• In practice, when constantly displaying contents of a (single) frame buffer, new information is being written in, as old information is being displayed

– And display is not what is intended– Display shows part of old and part of new– When running really fast see multiple new

images– Call it “flicker”, “garbage”, or whatever

Page 85: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Double (Frame) Buffers for Animation

• To prevent display of partially complete scene (or scene at location x’, y’):– Write all of scene into frame buffer 1– Display fb 1– Write all of scene into frame buffer 2– Display fb 2– Repeat

– glutSwapBuffers();

• Also, allows “pacing” of displays– Idle function and timer

• With OpenGL and GLUT Will use event based control structure– glutPostRedisplay();

Page 86: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

OpenGL Double Buffering Example

• BTW, all code available at Angel site– “playing with” is good…

• Angel spinning square example

• Will see:– Two windows created– Setup/initialization for double buffering– Display function structuring– Use of postReDisplay to control

drawing– glutIdleFunction– A bit of “trick” coding

int main(int argc, char** argv){ glutInit (&argc,argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); singleb=glutCreateWindow ("single buffered"); myinit (); glutDisplayFunc (displays); glutReshapeFunc (myReshape); glutIdleFunc (spinDisplay); glutMouseFunc (mouse);

glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB); glutInitWindowPosition(500,0); doubleb=glutCreateWindow("double buffered"); myinit (); glutDisplayFunc(displayd); glutReshapeFunc (myReshape); glutIdleFunc (spinDisplay); glutMouseFunc (mouse);

glutMainLoop();

void myinit (){ glClearColor (0.0, 0.0, 0.0, 1.0); glColor3f (1.0, 1.0, 1.0); glShadeModel (GL_FLAT);}

Page 87: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Control Structure• glutDisplayFunc(displayd) and (displays);

– As discussed, called when:

1. Something happens that requires window to be redrawn,

e.g., another window moved off

2. You give command to redraw– glutPostRedisplay()

• Here, displayd and (displays)– Clears window– Draws the figure– Causes buffers to be swapped (or not)

• So far, no movement!

• Angel program actually causes “spin” through somewhat obscure control mechanism

void displayd(){ glClear (GL_COLOR_BUFFER_BIT);

square();

glutSwapBuffers ();}

void displays(){ glClear (GL_COLOR_BUFFER_BIT);

square();

glFlush();}

void square()// x, y are globals{ glBegin(GL_QUADS);

glVertex2f(x,y); glVertex2f(-y,x);

glVertex2f(-x,-y); glVertex2f(y,-x);

glEnd();}

Page 88: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Making the Square Spin

• glutIdleFunc (<fn>)

• User-written function called whenever “nothing is happening”, i.e., idle

• Angel uses button press to set idle-function– Either changing x, y or doing nothing

// Changes global variables x, yvoid spinDisplay (void){ spin = spin + 2.0; if (spin > 360.0) spin = spin - 360.0; x= 25.0*cos(DEGREES_TO_RADIANS * spin); y= 25.0*sin(DEGREES_TO_RADIANS * spin); glutSetWindow (doubleb); glutPostRedisplay (); // set flag to redraw}

void mouse(int btn, int state, int x, int y){if(btn==GLUT_LEFT_BUTTON && state==GLUT_DOWN) glutIdleFunc(spinDisplay);if(btn==GLUT_MIDDLE_BUTTON && state==GLUT_DOWN) glutIdleFunc(NULL);}

Page 89: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

Rest of Square Spin

• Displays called when single buffered display is “current”/selected

– Not the most transparent implementation

• “Old familiar myReshape”– Red book good explication

of openGL matrix use– “duality of model and view

matrices”– Makes more sense when

centrality of matrix transformations to openGL programming is explained

void displays(){ glClear (GL_COLOR_BUFFER_BIT);

square();

glFlush();}

void myReshape(int w, int h){ glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h)

glOrtho (-50.0, 50.0, -50.0*(GLfloat)h/(GLfloat)w, 50.0*(GLfloat)h/(GLfloat)w, -1.0, 1.0);

else glOrtho (-50.0*(GLfloat)w/(GLfloat)h, 50.0*(GLfloat)w/(GLfloat)h, -50.0, 50.0, -1.0, 1.0);

glMatrixMode(GL_MODELVIEW); glLoadIdentity ();

}

Page 90: OpenGL 2 Angel: Chapter 2 OpenGL Programming and Reference Guides, other sources. ppt from Angel, AW, etc. CSCI 6360

End

• .