Chapter 2 Graphics Programming Bryson Payne CSCI 3600
Chapter 2: Graphics Programming Bryson Payne CSCI 3600 NGCSU 1
Objectives Development of the Open. GL API Open. GL Architecture n Open. GL as a state machine Functions n n Types Formats Simple program 2
Early History of APIs IFIPS (1973) formed two committees to come up with a standard graphics API n Graphical Kernel System (GKS) w 2 D but contained good workstation model n Core w Both 2 D and 3 D n GKS adopted as IS 0 and later ANSI standard (1980 s) GKS not easily extended to 3 D (GKS-3 D) n Far behind hardware development 3
PHIGS and X Programmers Hierarchical Graphics System (PHIGS) n n Arose from CAD community Database model with retained graphics (structures) X Window System n n DEC/MIT effort Client-server architecture with graphics PEX combined the two n Not easy to use (all the defects of each) 4
SGI and GL Silicon Graphics (SGI) revolutionized the graphics workstation by implementing the pipeline in hardware (1982) To access the system, application programmers used a library called GL With GL, it was relatively simple to program three dimensional interactive applications 5
Open. GL The success of GL lead to Open. GL (1992), a platform-independent API that was n n Easy to use Close enough to the hardware to get excellent performance Focus on rendering Omitted windowing and input to avoid window system dependencies 6
Open. GL Evolution Controlled by an Architectural Review Board (ARB) n n Members include SGI, Microsoft, Nvidia, HP, 3 DLabs, IBM, ……. Relatively stable (present version 2. 0) w Evolution reflects new hardware capabilities n n n 3 D texture mapping and texture objects Vertex programs Allows for platform specific features through extensions 7
Open. GL Libraries Open. GL core library n n Open. GL 32 on Windows GL on most unix/linux systems (lib. GL. a) Open. GL Utility Library (GLU) n Provides functionality in Open. GL core but avoids having to rewrite code Links with window system n n n GLX for X window systems WGL for Windows AGL for Macintosh 8
GLUT Open. GL Utility Toolkit (GLUT) n Provides functionality common to all window systems w w n Open a window Get input from mouse and keyboard Menus Event-driven Code is portable but GLUT lacks the functionality of a good toolkit for a specific platform w No slide bars 9
Software Organization application program Open. GL Motif widget or similar GLX, AGL or WGL X, Win 32, Mac O/S GLUT GLU GL software and/or hardware 10
Open. GL Architecture geometry pipeline Immediate Mode Polynomial Evaluator CPU Display List Per Vertex Operations & Primitive Assembly Rasterization Per Fragment Operations Frame Buffer Texture Memory Pixel Operations 11
Open. GL Functions Primitives n n n Points Line Segments Polygons Attributes Transformations n n Viewing Modeling Control (GLUT) Input (GLUT) Query 12
Open. GL State Open. GL is a state machine Open. GL functions are of two types n Primitive generating w Can cause output if primitive is visible w How vertices are processed and appearance of primitive are controlled by the state n State changing w Transformation functions w Attribute functions 13
Lack of Object Orientation Open. GL is not object oriented so that there are multiple functions for a given logical function n gl. Vertex 3 f gl. Vertex 2 i gl. Vertex 3 dv Underlying storage mode is the same Easy to create overloaded functions in C++ but issue is efficiency 14
Open. GL function format function name dimensions gl. Vertex 3 f(x, y, z) belongs to GL library x, y, z are floats gl. Vertex 3 fv(p) p is a pointer to an array 15
Open. GL #defines Most constants are defined in the include files gl. h, glu. h and glut. h n n Note #include <GL/glut. h> should automatically include the others Examples gl. Begin(GL_POLYGON) gl. Clear(GL_COLOR_BUFFER_BIT) include files also define Open. GL data types: GLfloat, GLdouble, …. 16
A Simple Program Generate a square on a solid background 17
simple. c #include <GL/glut. h> void mydisplay(){ gl. Clear(GL_COLOR_BUFFER_BIT); gl. Begin(GL_POLYGON); gl. Vertex 2 f(-0. 5, -0. 5); gl. Vertex 2 f(-0. 5, 0. 5); gl. Vertex 2 f(0. 5, -0. 5); gl. End(); gl. Flush(); } int main(int argc, char** argv){ glut. Create. Window("simple"); glut. Display. Func(mydisplay); glut. Main. Loop(); } 18
Simple. py – easy translation from Open. GL import * from Open. GLUT import * import sys def mydisplay(): gl. Clear(GL_COLOR_BUFFER_BIT); gl. Begin(GL_POLYGON); gl. Vertex 2 f(-0. 5, -0. 5); gl. Vertex 2 f(-0. 5, 0. 5); gl. Vertex 2 f(0. 5, -0. 5); gl. End(); gl. Flush(); #main glut. Init(sys. argv) glut. Create. Window("simple"); glut. Display. Func(mydisplay); glut. Main. Loop(); 19
Event Loop Note that the program defines a display callback function named mydisplay n n n Every glut program must have a display callback The display callback is executed whenever Open. GL decides the display must be refreshed, for example when the window is opened The main function ends with the program entering an event loop 20
Defaults simple. c is too simple Makes heavy use of state variable default values for n n n Viewing Colors Window parameters Next version will make the defaults more explicit 21
Notes on compilation See website and ftp for examples Unix/linux n n n Include files usually in …/include/GL Compile with –lglut –lglu –lgl loader flags May have to add –L flag for X libraries Mesa implementation included with most linux distributions Check web for latest versions of Mesa and glut 22
Compilation on Windows Forget all the below – we’re usin’ Python!!! Visual C++ n n n Get glut. h, glut 32. lib and glut 32. dll from web Create a console application Add opengl 32. lib, glut 32. lib to project settings (under link tab) Borland C similar Cygwin (linux under Windows) n n Can use gcc and similar makefile to linux Use –lopengl 32 –lglut 32 flags 23
Program Structure Most Open. GL programs have a similar structure that consists of the following functions n main(): w defines the callback functions w opens one or more windows with the required properties w enters event loop (last executable statement) n init(): sets the state variables w Viewing w Attributes n callbacks w Display function w Input and window functions 24
simple. c revisited In this version, we shall see the same output but we have defined all the relevant state values through function calls using the default values In particular, we set n n n Colors Viewing conditions Window properties 25
main. c #include <GL/glut. h> includes gl. h int main(int argc, char** argv) { glut. Init(&argc, argv); glut. Init. Display. Mode(GLUT_SINGLE|GLUT_RGB); glut. Init. Window. Size(500, 500); glut. Init. Window. Position(0, 0); glut. Create. Window("simple"); define window properties glut. Display. Func(mydisplay); init(); } display callback set Open. GL state glut. Main. Loop(); enter event loop 26
GLUT functions glut. Init allows application to get command line arguments and initializes system glu. Init. Display. Mode requests properties for the window (the rendering context) n n n RGB color Single buffering Properties logically ORed together glut. Window. Size in pixels glut. Window. Position from top-left corner of display glut. Create. Window create window with title “simple” glut. Display. Func display callback glut. Main. Loop enter infinite event loop 27
init. c black clear color opaque window void init() { gl. Clear. Color (0. 0, 1. 0); fill/draw with white gl. Color 3 f(1. 0, 1. 0); gl. Matrix. Mode (GL_PROJECTION); gl. Load. Identity (); gl. Ortho(-1. 0, -1. 0, 1. 0); } viewing volume 28
Coordinate Systems The units in gl. Vertex are determined by the application and are called object or problem coordinates The viewing specifications are also in object coordinates and it is the size of the viewing volume that determines what will appear in the image Internally, Open. GL will convert to camera (eye) coordinates and later to screen coordinates Open. GL also uses some internal representations that usually are not visible to the application 29
Open. GL Camera Open. GL places a camera at the origin in object space pointing in the negative z direction The default viewing volume is a box centered at the origin with a side of length 2 30
Orthographic Viewing In the default orthographic view, points are projected forward along the z axis onto the plane z=0 z=0 31
Transformations and Viewing In Open. GL, projection is carried out by a projection matrix (transformation) There is only one set of transformation functions so we must set the matrix mode first gl. Matrix. Mode (GL_PROJECTION) Transformation functions are incremental so we start with an identity matrix and alter it with a projection matrix that gives the view volume gl. Load. Identity(); gl. Ortho(-1. 0, -1. 0, 1. 0); 32
Two- and three-dimensional viewing In gl. Ortho(left, right, bottom, top, near, far) the near and far distances are measured from the camera Two-dimensional vertex commands place all vertices in the plane z=0 If the application is in two dimensions, we can use the function glu. Ortho 2 D(left, right, bottom, top) In two dimensions, the view or clipping volume becomes a clipping window 33
mydisplay. c void mydisplay() { gl. Clear(GL_COLOR_BUFFER_BIT); gl. Begin(GL_POLYGON); gl. Vertex 2 f(-0. 5, -0. 5); gl. Vertex 2 f(-0. 5, 0. 5); gl. Vertex 2 f(0. 5, -0. 5); gl. End(); gl. Flush(); } 34
Open. GL Primitives GL_POINTS GL_LINES GL_POLYGON GL_LINE_STRIP GL_LINE_LOOP GL_TRIANGLES GL_QUAD_STRIP GL_TRIANGLE_FAN 35
Polygon Issues Open. GL will only display polygons correctly that are n n n Simple: edges cannot cross Convex: All points on line segment between two points in a polygon are also in the polygon Flat: all vertices are in the same plane User program can check if above true n Open. GL will produce output if these conditions are violated but it may not be what is desired Triangles satisfy all conditions nonsimple polygon nonconvex polygon 36
Attributes are part of the Open. GL state and determine the appearance of objects n n Color (points, lines, polygons) Size and width (points, lines) Stipple pattern (lines, polygons) Polygon mode w Display as filled: solid color or stipple pattern w Display edges w Display vertices 37
RGB color Each color component is stored separately in the frame buffer Usually 8 bits per component in buffer Note in gl. Color 3 f the color values range from 0. 0 (none) to 1. 0 (all), whereas in gl. Color 3 ub the values range from 0 to 255 38
Indexed Colors are indices into tables of RGB values Requires less memory n n indices usually 8 bits not as important now w Memory inexpensive w Need more colors for shading 39
Color and State The color as set by gl. Color becomes part of the state and will be used until changed n 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 gl. Color gl. Vertex 40
Smooth Color Default is smooth shading n Open. GL interpolates vertex colors across visible polygons Alternative is flat shading n Color of first vertex determines fill color gl. Shade. Model (GL_SMOOTH) or GL_FLAT 41
Viewports Do not have use the entire window for the image: gl. Viewport(x, y, w, h) Values in pixels (screen coordinates) 42
Three-dimensional Applications In Open. GL, two-dimensional applications are a special case of three-dimensional graphics Going to 3 D n n Not much changes Use gl. Vertex 3*( ) Have to worry about the order in which polygons are drawn or use hidden-surface removal Polygons should be simple, convex, flat 43
Sierpinski Gasket (2 D) Start with a triangle Connect bisectors of sides and remove central triangle Repeat 44
Example Five subdivisions 45
The gasket as a fractal Consider the filled area (black) and the perimeter (the length of all the lines around the filled triangles) As we continue subdividing n n the area goes to zero but the perimeter goes to infinity This is not an ordinary geometric object n It is neither two- nor three-dimensional It is a fractal (fractional dimension) object 46
Gasket Program #include <GL/glut. h> /* initial triangle */ GLfloat v[3][2]={{-1. 0, -0. 58}, {0. 0, 1. 15}}; int n; /* number of recursive steps */ 47
Draw one triangle void triangle( GLfloat *a, GLfloat *b, GLfloat *c) /* display one triangle { gl. Vertex 2 fv(a); gl. Vertex 2 fv(b); gl. Vertex 2 fv(c); } */ 48
Triangle Subdivision void divide_triangle(GLfloat *a, GLfloat *b, GLfloat *c, int m) { /* triangle subdivision using vertex numbers */ point 2 v 0, v 1, v 2; int j; if(m>0) { for(j=0; j<2; j++) v 0[j]=(a[j]+b[j])/2; for(j=0; j<2; j++) v 1[j]=(a[j]+c[j])/2; for(j=0; j<2; j++) v 2[j]=(b[j]+c[j])/2; divide_triangle(a, v 0, v 1, m-1); divide_triangle(c, v 1, v 2, m-1); divide_triangle(b, v 2, v 0, m-1); } else(triangle(a, b, c)); /* draw triangle at end of recursion */ } 49
display and init Functions void display() { gl. Clear(GL_COLOR_BUFFER_BIT); gl. Begin(GL_TRIANGLES); divide_triangle(v[0], v[1], v[2], n); gl. End(); gl. Flush(); } void myinit() { gl. Matrix. Mode(GL_PROJECTION); gl. Load. Identity(); glu. Ortho 2 D(-2. 0, 2. 0); gl. Matrix. Mode(GL_MODELVIEW); gl. Clear. Color (1. 0, 1. 0) gl. Color 3 f(0. 0, 0. 0); } 50
main Function int main(int argc, char **argv) { n=4; glut. Init(&argc, argv); glut. Init. Display. Mode(GLUT_SINGLE|GLUT_RGB ); glut. Init. Window. Size(500, 500); glut. Create. Window(“ 2 D Gasket"); glut. Display. Func(display); myinit(); glut. Main. Loop(); } 51
Efficiency Note By having the gl. Begin and gl. End in the display callback rather than in the function triangle and using GL_TRIANGLES rather than GL_POLYGON in gl. Begin, we call gl. Begin and gl. End only once for the entire gasket rather than once for each triangle 52
Moving to 3 D We can easily make the program threedimensional by using GLfloat v[3][3] gl. Vertex 3 f gl. Ortho But that would not be very interesting Instead, we can start with a tetrahedron 53
3 D Gasket We can subdivide each of the four faces Appears as if we remove a solid tetrahedron from the center leaving four smaller tetrahedra 54
Example after 5 iterations 55
triangle code void triangle( GLfloat *a, GLfloat *b, GLfloat *c) { gl. Vertex 3 fv(a); gl. Vertex 3 fv(b); gl. Vertex 3 fv(c); } 56
subdivision code void divide_triangle(GLfloat *a, GLfloat *b, GLfloat *c, int m) { GLfloat v 1[3], v 2[3], v 3[3]; int j; if(m>0) { for(j=0; j<3; j++) v 1[j]=(a[j]+b[j])/2; for(j=0; j<3; j++) v 2[j]=(a[j]+c[j])/2; for(j=0; j<3; j++) v 3[j]=(b[j]+c[j])/2; divide_triangle(a, v 1, v 2, m-1); divide_triangle(c, v 2, v 3, m-1); 57 divide_triangle(b, v 3, v 1, m-1);
tetrahedron code void tetrahedron( int m) { gl. Color 3 f(1. 0, 0. 0); divide_triangle(v[0], v[1], m); gl. Color 3 f(0. 0, 1. 0, 0. 0); divide_triangle(v[3], v[2], m); gl. Color 3 f(0. 0, 1. 0); divide_triangle(v[0], v[3], m); gl. Color 3 f(0. 0, 0. 0); divide_triangle(v[0], v[2], m); v[2], v[1], v[3], 58
Almost Correct Because the triangles are drawn in the order they are defined in the program, the front triangles are not always rendered in front of triangles behindgetthem this want this 59
Hidden-Surface Removal We want to see only those surfaces in front of other surfaces Open. GL uses a hidden-surface method called the z-buffer algorithm that saves depth information as objects are rendered so that only the front objects appear in the image 60
Using the z-buffer algorithm The algorithm uses an extra buffer, the z-buffer, to store depth information as geometry travels down the pipeline It must be n Requested in main. c w glut. Init. Display. Mode (GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH) n Enabled in init. c w gl. Enable(GL_DEPTH_TEST) n Cleared in the display callback w gl. Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) 61
Surface vs Volume Subdvision In our example, we divided the surface of each face We could also divide the volume using the same midpoints The midpoints define four smaller tetrahedrons, one for each vertex Keeping only these tetrahedrons removes a volume in the middle See text for code 62
Volume Subdivision 63
- Slides: 63