1 / 76

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

candace
Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

    2. opengl objects

    3. Introduction Recall from last time: Angel takes a “top down” approach … vs. the “old school” approach, where you understand what you’re doing 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

    4. Notice anything “unusual”?

    5. You’re flying upside down!

    6. 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

    7. Next Time … 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 qt

    8. 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

    9. 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

    10. 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

    11. 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) Two older APIs (GKS, PHIGS) defined six types of logical input: 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

    12. 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

    13. From last time: Glut - Event Loop 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, E.g., when window opened, mouse clicked The main function ends with program entering an event loop

    14. 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 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

    15. 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 Window: resize, expose, iconify Mouse: click one or more buttons Motion: move mouse Keyboard: press or release a key Idle: nonevent Define what should be done if no other event is in queue

    16. 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 Quick look at MS Windows API to handle events

    17. 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 click old_val = new_val }   // check other devices too, and act if need to  } This is process intensive as always checking

    18. About Interaction Handling, Event Driven Event Driven   WHILE (!quit) { // program waits for user action wait_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_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 message queue

    19. 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

    20. Again, Event Driven Event Driven   WHILE (!quit) { : // program waits for user action wait_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 events case 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

    21. Ex, MSW API: Handle Event Queue Directly 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 : 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 }

    22. GLUT Callback Function 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 }

    23. Software Org. – GL, GLU, GLUT 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 are means GLUT uses to “shield programmer from intricacies of direct event loop programming”

    24. GLUT Resources – “Manual” The OpenGL Utility Toolkit (GLUT) Programming Interface API Version 3 http://www.opengl.org/documentation/specs/glut/spec3/spec3.html

    25. 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

    26. 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) }

    27. GLUT Callback Function 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 }

    28. GLUT Resources - Examples Examples http://www.opengl.org/resources/code/samples/glut_examples/examples/examples.html

    29. 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

    30. GLUT Callback Function 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 }

    31. Paradigm Control Structure 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

    32. Sum: GLUT Callback Funcs. for Events 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

    33. GLUT and C Programming 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 Typical opengl program structure Init Display Other encapsulation, as in other control structures, e.g., drawSquare or drawFigure (IFigureType, iColor) Handle menu(s) main

    34. From last time: “simple.c revisited” GLUT functions in detail now… GLUT library calls: 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 display callback glutMainLoop enter infinite event loop

    35. 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

    36. Display Callback: glutDisplayFunc(<fn>) 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

    37. Display Callback: glutDisplayFunc(<fn>) x

    38. 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

    39. 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 }

    40. Angel’s mouse position example

    41. 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 in window Oops, position is in window system coordinates, not screen coordinates Window system 0,0 is at top left

    42. Screen and OGL Coordinate Systems 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

    43. glutGet(<const>) Lots of states can be queried Here, glutGet(GLUT_WINDOW_HEIGHT)

    44. 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 But one is required by GLUT; Can use empty display callback function mydisplay(){}

    45. 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)

    46. 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 by glutGetModifiers() Allows emulation of three-button mouse with one- or two-button mice

    47. 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

    48. 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 menu 2. Define menu entries with id used by callback 3. Link/attach menu to a mouse button To use menu 1. Write callback function that uses menu id’s to select what action to perform

    49. Hierarchical Menus: glutAddSubMenu (<fn>) Note: each menu has and id that is returned when created Add submenus by: glutAddSubMenu(char *submenu_name, submenu id) Callbacks color_menu and top_menu, as before

    50. Programming in the Dark One disadvantage of “top down” approach is writing code that don’t understand details of Can lead to “unintended consequences” When debugging reaches stage of “let me quess” (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

    51. Ok, let’s see a switch or two…

    52. Reshaping the Display Window 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 Two possibilities Display part of world Display whole world but force to fit in new window Can alter aspect ratio Ratio of width to height E.g, 1000 to 800 = .8

    53. Reshape Callback: glutReshapeFunc(<fn>), 1 Another GLUT function: glutReshapeFunc(myreshape) 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 (will see glViewport and gluOrtho2d shortly)

    54. Reshape Callback: glutReshapeFunc(<fn>), 2 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); glMatrixMode(GL_PROJECTION); /* switch matrix mode */ glLoadIdentity(); if (w <= h) 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 */ }

    55. 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

    56. 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

    57. gluOrtho2D From online reference … gluOrtho2D – define a 2-D orthographic projection matrix (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.

    58. Viewports Do not have to use entire graphics window for viewing area Left, 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

    59. Ex: Reshape and Aspect Ratio Below preserves shapes by making viewport and world window have same aspect ratio

    60. 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); }

    61. Control Structure Review

    62. Control Structure Review Event driven control flow – vs. “stop every thing and wait for a, e.g., keyboard char” 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) to redraw Either an event from window system or Postredisplay() is that signal GLUT isolates programmer from window system details through callback functions

    63. Review - Events 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

    64. Review – Glut Event Loop 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

    65. Paradigm Control Structure 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

    66. GLUT and C Programming 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: Init Display Other encapsulation, as in other control structures, e.g., drawSquare or drawFigure (IFigureType, iColor) Handle menu(s) main

    67. 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. Objects can be displayed at any location, but object visibility should be considered. For extra credit have the program handle change in window sizes and aspect ratios. For even more extra credit, make a cool scene. Never simply copy code and expect good things to happen. The CS Department’s Academic Integrity Policy will be strictly enforced, and it’s more fun to make it all up anyway.

    68. Animating Interactive Programs .

    69. 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

    70. 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

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

    72. OpenGL Double Buffering Example BTW, all code available at class 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

    73. 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

    74. 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

    75. 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

    76. End .

More Related