Вы находитесь на странице: 1из 34

CSE 640 Computer Graphics

OpenGL Lab Manual

Computer Science and Engineering Department Auburn University


Spring 1999

Table of Contents
INTRODUCTION..........................................................................................................................3 INTRODUCTION..........................................................................................................................3 CHAPTER 1 GETTING STARTED............................................................................................6 CHAPTER 1 GETTING STARTED............................................................................................6 CHAPTER 2 DRAWING WITH OPENGL..............................................................................13 CHAPTER 2 DRAWING WITH OPENGL..............................................................................13 2.4 THREE-DIMENSIONAL OBJECTS..................................................................................17 2.4 THREE-DIMENSIONAL OBJECTS..................................................................................17 FOLLOWING DRAWING ROUTINES ARE INCLUDED IN GLUT TO DRAW 3DIMENSIONAL OBJECTS. EACH MODEL COMES IN TWO FLAVORS:WIREFRAMES WITHOUT SURFACE NORMALS, AND SOLID WITH SHADING AND SURFACE NORMALS. USE THE SOLID VERSION WHEN YOU ARE APPLYING LIGHTING.............................................................................................................17 FOLLOWING DRAWING ROUTINES ARE INCLUDED IN GLUT TO DRAW 3DIMENSIONAL OBJECTS. EACH MODEL COMES IN TWO FLAVORS:WIREFRAMES WITHOUT SURFACE NORMALS, AND SOLID WITH SHADING AND SURFACE NORMALS. USE THE SOLID VERSION WHEN YOU ARE APPLYING LIGHTING.............................................................................................................17 CHAPTER 3 OPENGL TRANSFORMATIONS......................................................................18 CHAPTER 3 OPENGL TRANSFORMATIONS......................................................................18 CHAPTER 4 DISPLAY LISTS...................................................................................................24

2 CHAPTER 4 DISPLAY LISTS...................................................................................................24 CHAPTER 5 COLOR.................................................................................................................26 CHAPTER 5 COLOR.................................................................................................................26 CHAPTER 6 TEXT....................................................................................................................28 CHAPTER 6 TEXT....................................................................................................................28 APPENDIX - USING OPENGL IN MICROSOFT VISUAL C++ ........................................30 APPENDIX - USING OPENGL IN MICROSOFT VISUAL C++ ........................................30
GLUT on PC................................................................................................................................................................31

REFERENCES.............................................................................................................................33 REFERENCES.............................................................................................................................33

Introduction
OpenGL is a graphics library developed by Silicon Graphics, Inc. It was originally developed in the early 80s for use with the companys IRIS GL graphics workstations. Since then the library has been ported to other platforms and has become a standard library for creating threedimensional (3D) scenes.

About This Manual


This manual introduces Mesa 2.3. Mesa is a 3D graphics library very similar to the OpenGL graphics library. It is not a licensed implementation of OpenGL, but for the purposes of the lab it is close enough. In this manual OpenGL and Mesa will be used interchangeably. It has been written as a guide for students enrolled in the Auburn University Computer Science and Engineering Departments Computer Graphics course. For those who want to do assignments on PCs, please refer to the Appendix. Much of the text is adapted from OpenGL Programming Guide : The Official Guide to Learning OpenGL, Release 1.1 and some is adapted from 3-D Graphics Programming with OpenGL.

OpenGL
The OpenGL library consists of over 115 functions all beginning with the letters gl. There is also a utility library consisting of 43 functions that begin with glu and an auxiliary library of 31 functions whose names begin with aux. In addition, there is a utility tool kit, start with glut, consisting of 32 functions. The core set of 115 functions represents that basic functions that should be implemented on an OpenGL platform. These functions allow the programmer to create various types of shapes, produce lighting effects, incorporate antialiasing and texture mapping, perform matrix transformations, and much more. The utility library includes functions that use the core functions to perform higher level drawing. These functions simplify the use of texture images, perform high-level coordinate transformations, support polygon tessellation, and render spheres, cylinders, spheres and other quadric surfaces. The auxiliary library is a set of special functions used to simplify programming examples in the OpenGL Programming Guide. These platform-independent functions perform window management, I/O and drawing of several 3D objects.

The utility tool kit, GLUT, has become a popular library for OpenGL programmers, because it standardizes and simplifies window and event management. GLUT has been ported atop a variety of OpenGL implementations, including both the X Window Systems and Microsoft Windows NT. In our Mesa environment, the utility tool kit library has not been installed yet. OpenGL supports the following concepts: Geometric Primitives Wireframes Depth Cueing Antialiasing Flatshading Hidden surface removal Light sources & smooth shading Texture mapping Motion blurring and many more

Book
The reference book for the class is OpenGL Programming Guide. Note this is a second edition written for the OpenGL 1.1 specification. The implementation of OpenGL on the engineering network is Mesa 2.3 which adheres to the 1.1 specification. The OpenGL specification provides some platform independent routines that allow the user to practice with OpenGL without concerning himself with the details of manipulating windows. These routines are not meant to be used in developing full-featured applications but are useful for learning. It is recommended that you do use these routines in your assignments. In the book these routines are referred to as the GLUT library. All routines in this library start with glut (e.g. glutInitWindowPosition.)

Demos
Demos of OpenGL can be found in /opt/mesa2.3/ in the subdirectories book, demos, and samples. Demos for the CSE 640 lab and for this lab can be found in ~ftp/pub/kchang (makefile, executables and some sources). Also in this directory is this MS Word 7.0 version of the CSE640 Lab Manual which you might find useful.

To run the demos and any other OpenGL program, you will need to add the following directories to you LD_LIBRARY_PATH environment variable:

5 /usr/dt/lib /opt/mesa2.3/lib or setenv LD_LIBRARY_PATH /usr/dt/lib: /opt/mesa2.3/lib

Chapter 1 Getting Started


1.0 Setup your environment

To run the program, you have to have the motif module installed from user-setup before running the OpenGL program. Sample programs can be found at ~ftp/pub/kchang. 1.1 Create a New File

In this class, programs will be written in C. Use any text editor to create your program file and save it with a .c extension. For example, a program named sample may be stored as sample.c. 1.2 Linking With The OpenGL Libraries

In order for an application to use the OpenGL functions, it must link with the Mesa libraries. To do this, get a copy of the Mesa makefile and place it in the directory in which you will work on your OpenGL programs. Makefile can be retrieved from ~ftp/pub/kchang. 1.3 Compiling The Application

To compile the application, at a command prompt go to the directory that contains your program and type make program. For example, to compile the program sample.c in a directory named cse640, type: cd cse640 make sample Again the Mesa makefile must be in the same directory as your program. 1.4 Include files The following header files must be included with any application using Mesa.
#include <glut.h> /* utility toolkit library */

When compiling using MS Visual C++, following files must be included.


#include <windows.h> /* #include <gl\glut.h> /* windows library */ utility toolkit library */

Note that glut.h includes both gl.h and glu.h automatically, so including those files is redundant.

7 1.5 Program Structure

The structure of your OpenGL program should look similar to this:


#include <glut.h> /* utility toolkit library */

void init() { /* initialization code */ } void reshape(GLsizei w, GLsizei h) { /* code to execute if the window is resized */ } void display(void) { /* code to display the scene */ } void main() { /* code to setup window */ }

1.6

Data Types

Following is a list of the OpenGL data types which can be found in <gl\gl.h>.
typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef typedef unsigned int unsigned char unsigned int signed char short int int unsigned char unsigned short unsigned int float float double double void GLenum; GLboolean; GLbitfield; GLbyte; GLshort; GLint; GLsizei; GLubyte; GLushort; GLuint; GLfloat; GLclampf; GLdouble; GLclampd; GLvoid;

1.7

A Simple Mesa Program


/* utility toolkit library */

#include <glut.h> #include <math.h> #define PI 3.14159265359

void init() { glClearColor(0.0f,0.0f,0.0f,0.0f); glShadeModel(GL_FLAT); }

/*see Chapter 5*/ /*see Chapter 5*/

void reshape(GLsizei w, GLsizei h) { glViewport(0,0,w,h); /*see Chapter 3*/ glMatrixMode(GL_PROJECTION); /*see Chapter 3*/ glLoadIdentity(); /*see Chapter 3*/ glOrtho(-50.0,50.0,-50.0,50.0,-1.0,1.0); /*see Chapter 3*/ glMatrixMode(GL_MODELVIEW); /*see Chapter 3*/ glLoadIdentity(); } void display(void) { double j; glClear(GL_COLOR_BUFFER_BIT); glColor3d(1.0,0.0,0.0); /*see Chapter 5*/

/*draw a circle with radius 5*/ glBegin(GL_POLYGON); /*see Chapter 2 */ for (j=360.0;j>=0.0;j-=20.0) glVertex2d(5*sin(j*PI/180),5*cos(j*PI/180)); /*see Ch. 2 */ glEnd(); /*see Chapter 2 */ glFinish(); } void main(int argc, char** argv) { glutInit (&argc, argv);

9
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);/*see below for */ glutInitWindowPosition(50,50); /*brief summary of */ glutInitWindowSize (500,500); /*glut functions */ glutCreateWindow(Sample Program); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMainLooop(); }

1.8

The GLUT Library

The glut library contains functions that allow you to easily create a window to display your OpenGL drawings. The following glut functions are particularly useful:
void glutInit(int *argc, char **argv);

Initializes GLUT and processes any command line arguments, and should be called before any other GLUT routine. Table 1-1 glutInit() Function Description
void glutInitDisplayMode(unsigned int mode);

Specifies whether to create an RGBA or color-index window, or a single- or double-buffered window, You can also specify that the window have an associated depth, stencil, and/or accumulation buffer. The mode argument is a bitwise ORed combination of GLUT_RGB or GLUT_INDEX, GLUT _SINGLE or GLUT _DOUBLE, and any of the buffer-enabling flags: GLUT _DEPTH, GLUT _STENCIL, or GLUT _ACCUM. For example, for a double-buffered, RGBA-mode window with a depth and stencil buffer, use GLUT _RGBA | GLUT _DOUBLE | GLUT _DEPTH | GLUT _STENCIL. The default value is GLUT _INDEX | GLUT _SINGLE, or a color-indexed, single-buffered window. Table 1-2 glutInitDisplayMode() Function Description
void glutCreateWindow(char *titleSting);

Opens a window with the characteristics specified OpenGL context. The string titleString appears in the title bar, if your window system does that sort of thing. The window is not displayed until glutMainLoop() is called. Table 1-3 glutCreateWindow() Function Description

10

void glutInitWindowPosition(int x, int y);

Tells glutCreateWindow() where to position a window on the screen. The arguments (x, y) indicate the location of the upper left corner of the window. Table 1-4 glutInitWindowPosition() Function Description
void glutInitWindowSize(int width, int size);

Tells glutCreateWindow() the size of a window in pixel on the screen. Table 1-5 glutInitWindowSize() Function Description
void glutDisplayFunc(void (*func)(void));

Whenever GLUT determines the contents of the window need to be redisplayed, the callback function registered by glutDisplayFunc() is executed. Therefore, you should put all the routines you need to redraw the scene in the display callback function. Table 1-6 glutDisplayFunc() Function Description
void glutReshapeFunc(void (*func)(int w, int h));

Specifies the function, func, thats called whenever the window is resized, moved, or exposed. The argument func is a pointer to a function that expects two arguments, the new width and height of the window. Typically, func calls glViewport(), so that the display is clipped to the new size, and it redefines the projection matrix so that the aspect ratio of the projected image matches the viewport, avoiding aspect ratio distortion. If you dont call glutReshapeFunc(), a default reshape function is called, which assumes a two-dimensional orthographic projection. With this call, the window is automatically redrawn after every reshaping event. Table 1-7 glutReshapeFunc() Function Description
void glutKeyboardFunc(void (*func)(unsigned char key, int x, int y));

Specifies the function, func, thats called when the keyboard key indicated by key is pressed. The key parameter is the generated ASCII value. The x and y callback parameters indicate the location of the mouse (in window-relative coordinates) when the key was pressed. With this call, the window is automatically redrawn after every processed key event, although in a real appliction, you might wait for several events to be completed before drawing. Table 1-8 glutKeyboardFunc() Function Description

11
void glutMouseFunc(void (*func)(int button, int s, int x, int y));

Specifies the function, func, thats called when the mouse button is pressed or released. The button parameter is one of GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON, or GLUT_RIGHT_BUTTON. The s parameter is either GLUT_UP or GLUT_DOWN, depending upon whether the mouse has been released or pressed. The x and y callback parameters indicate the location of the mouse (in window-relative coordinates) when the event occurred. Table 1-9 glutMouseFunc() Function Description
void glutMotionFunc(void (*func)(int x, int y));

Specifies the function, func, thats called when the mouse pointer moves within the window while one or more mouse button is pressed. The x and y callback parameters indicate the location of the mouse (in window-relative coordinates) when the event occurred. Table 1-10 glutMotionFunc() Function Description
void glutIdleFunc(void *func);

Specifies the function, func, to be executed if no other events are pending. If zero is passed in, execution of func is disabled. Table 1-11 glutIdleFunc() Function Description
void glutMainLoop(void);

Enters the GLUT processing loop, never to return. Registered callback functions will be called when the corresponding events instigate them. Table 1-12 glutMainLoop() Function Description 1.9 Animation and Key Commands

The general idea behind animation is that a scene is drawn, erased, and redrawn with a few minor changes. If this is done continuously and at an appropriate speed, objects will appear to move. There are two methods that can be used to create a program loop for animation when using the glut library. First you can simply create your own loops in the display function specified by glutDisplayFunc(). For example, if you wanted to make an object spin, you could set up a loop that clears the screen, draws the object to the screen, and then rotate a few degrees. The problem with this is that key commands setup with the glutKeyboardFunc() will only be evaluated when the system is idle. This means that the display function must be completed before key commands will be accepted. This creates a problem when combining user input and animation.

12 This can be solved by using the second method of looping. Use glutIdleFunc() and pass your display function to it as an argument. This way the system will continuously call your display function and global variables can be used to modify the display. For example, I could use the function glTranslated(x++,2.0,3.0) where x is a global variable to move an object across the screen. Key command functions can be used to modify the global variables and therefore the display.

13

Chapter 2 Drawing With OpenGL


2.1 Drawing OpenGL Primitive Geometric Types

OpenGL uses 10 primitive geometric types as the building blocks of all models. These primitives include points, lines, line strips, line loops, polygon, quads, quad strips, triangles, triangle strips and triangle fans. For the complete set of OpenGL function, you may refer to the following WWW page: http://wildsau.idv.uni-linz.ac.at/~gjenichl/OpenGL/ With OpenGL, all geometric objects are ultimately described as an ordered set of vertices. You use the glVertex*() function to specify a vertex. Table 2-1 describes the glVertex*() function.
void glVertex{234}{sifd}[v](TYPE coords);

Specifies a vertex for use in describing a geometric object. You can supply up to four coordinates (x, y, z, w) for a particular vertex or as few as two (x, y) by selecting the appropriate version of the function. If you use a version that doesnt explicitly specify z or w, z is understood to be 0 and w is understood to be 1. Calls to glVertex*() should be executed between a glBegin() and glEnd() pair. s = short i = integer f = float d = double v = vector (or array) of either s,i,f or d Table 2-1 glVertex*() Function Description Here are some examples of using glVertex*() :
glVertex3d(5.0, 5.0, 5.0); int vertex[2] = { 5, 5 }; glVertex2iv(vertex); struct Vertex { double x, y, z; }; struct Vertex v = { 5.0, 5.0, 5.0 }; glVertex3fv((double*)&v);

14 OpenGL must be told how to interpret the list of vertices. To do this, you bracket each set of vertices between a call to glBegin() and a call to glEnd(). The argument passed to glBegin() determines what sort of geometric primitive is constructed form the vertices. For example, the following code specifies the vertices for a 5-sided polygon:
glBegin(GL_POLYGON); glVertex2d( 0.0, 0.0); glVertex2d(0.0, 3.0); glVertex2d(3.0, 3.0); glVertex2d(4.0, 1.5); glVertex2d(3.0, 0.0); glEnd();

Table 2-2 gives a description of the glBegin function and allowed parameters.
void glBegin(GLenum mode)

Marks the beginning of a vertex list that describes a geometric primitive. The type of primitive is indicated by mode, which can be one of the following values: Value
GL_POINTS GL_LINES GL_POLYGON GL_TRIANGLES GL_QUADS GL_LINE_STRIP GL_LINE_LOOP GL_TRIANGLE_STRIP GL_TRIANGLE_FAN GL_QUAD_STRIP

Meaning individual points pairs of vertices interpreted as individual line segments boundary of a simple, convex polygon triples of vertices interpreted as triangles quadruples of vertices interpreted as four-sided polygons series of connected line segments same as above, with a segment added between last and first vertices linked strip of triangles linked fan of triangles linked strip of quadrilaterals

Table 2-2 Geometric Primitive Names and Meanings Figure 2-1 show a graphical representation of each primitive type.

15

Figure 2-1 Geometric Primitive Types 2.2 Line Stippling

To make stippled lines, i.e. dashed or dotted lines, use the glLineStipple() function. This function defines the stipple pattern when line stippling has been enabled.. Table 2-3 gives a description of the glLineStipple() function.
void glLineStipple(GLint factor, GLushort pattern);

Sets the current stippling pattern for lines. The pattern argument is a 16-bit series of 0s and 1s and is repeated to stipple a line. A 1 indicates that drawing occurs and a 0 indicates that it does not, on a pixel-by-pixel basis beginning with the low-order bits of the pattern. To enable line stippling, call glEnable(GL_LINE_STIPPLE). Call glDisable(GL_LINE_STIPPLE) to

16 disable line stippling. Table 2-3 glLineStipple() Function Description 2.3 Polygon Details

The polygons that make up all the primitive types except points and lines can either be drawn as points, lines, or filled surfaces. Use the glPolygonMode() function to set the current polygon mode. Table 2-4 gives a description of the glPolygonMode() function.
void glPolygonMode(GLenum face, GLenum mode);

Controls the drawing mode for a polygons front and back faces. The parameter face can be GL_FRONT, GL_BACK, or GL_FRONT_AND_BACK; mode can be GL_POINT, GL_LINE, or GL_FILL to indicate whether the polygon should be drawn as points, outlined, or filled. By default, both front and back faces are drawn filled. Table 2-4 glPolygonMode() Function Description The front of a polygon is determined by the direction the polygon is drawn. Polygons whose vertices appear in a counterclockwise order on the screen are said to be front-facing. If all your polygons have the same facing, drawing speed can be increased by discarding opposite facing polygons. Another way to determine a polygons facing is to look at the normal vector of the surface. A vector that is perpendicular to a surface is call a normal to that surface. If the angle between the camera and the normal to a surface is greater than or equal to 90 degrees, that surface is said to be back-facing. If the angle is less than 90 degrees it is front-facing. OpenGL can be instructed not to draw these types of polygons by using the glCullFace() function as described in Table 2-5.
void glCullFace(GLenum mode);

Indicates which polygons should be discarded (culled) before theyre converted to screen coordinates. The mode is either GL_FRONT, GL_BACK or GL_FRONT_AND_BACK to indicate front-facing, back-facing, or all polygons. To take effect, culling must be enabled using glEnable(GL_CULL_FACE). It can be disabled using glDisable(GL_CULL_FACE). Table 2-5 glCullFace() Function Description

17

2.4

Three-Dimensional Objects

Following drawing routines are included in GLUT to draw 3-dimensional objects. Each model comes in two flavors:wireframes without surface normals, and solid with shading and surface normals. Use the solid version when you are applying lighting.

void void void void void void void void void void void void void void void void void void

glutWireSphere (GLdouble radius, GLint slices, GLint stacks); glutSolidSphere (GLdouble radius, GLint slices, GLint stacks); glutWireCube (GLdouble size); glutSolidCube (GLdouble size); glutWireTorus (GLdouble inRadius, GLdouble outRadius, GLint nsides, GLint rings); glutSolidTorus (GLdouble inRadius, GLdouble outRadius, GLint nsides, GLint rings); glutWireIcosahedron (void); glutSolidIcosahedron (void); glutWireOctahedron (void); glutSolidOctahedron (void); glutWireTetrahedron (void); glutSolidTetrahedron (void); glutWireDodecahedron (GLdouble radius); glutSolidDodecahedron (GLdouble radius); glutWireCone (GLdouble radius, GLdouble height, GLint slices, GLint stacks); glutSolidCone (GLdouble radius, GLdouble height, GLint slices, GLint stacks); glutWireTeapot (GLdouble size); glutSolidTeapot (GLdouble size);

18

Chapter 3 OpenGL Transformations


There are four important transformations that occur in OpenGL. The first is the viewing transformation which is used to specify the camera position and orientation. The second is the modeling transformation which are used to move, rotate or scale the model. The third is the projection transformation which specifies how the scene should be projected onto the OpenGL window. The fourth is the viewport transformation which, in conjunction with the viewing and projection transformation, is used to determine how the scene is mapped onto the OpenGL window. The viewing transformation must precede the modelling transformations in your code, but you can specify the projection and viewport transformation at any point before drawing occurs. Figure 3-1 shows the order in which these operations occur on your computer. Vertex Coordinate View Matrix Model Matrix Projection Matrix

3.1

Viewing transformation

Viewing transformation is analogous to positioning and aiming a camera. The viewing transformation is specified with gluLookAt().
void gluLookAt(GLdouble eyex, GLdouble eyey, GLdouble eyez, GLdouble centerx, GLdouble centery, GLdouble centerz, GLdouble upx, GLdouble upy, GLdouble upz);

Defines a viewing matrix and multiplies it to the right of the current matrix. The desired viewpoint is specified by eyex, eyey and eyez. The centerx, centery and centerz arguments specify any point along the desired line of sight, but typically theyre some point in the center of the scene being looked at. The upx, upy and upz arguments indicate which direction is up (that is, the direction from the bottom to the top of the viewing volume). Table 3-1 gluLookAt() Function Description 3.2 Projection transformation

19

Specifying the projection transformation is like choosing a lens for a camera. You can think of this transformation as determining what the field of view or viewing volume is and therefore what objects are inside it and to some extent how they look. Setting Up Orthographic Projection To set up orthographic (or parallel) projection, first specify which matrix stack is being modified. In this case, the projection matrix stack is used. Call glMatrixMode() to specify which matrix stack to modify as described in Table 3-2. Next call glLoadIdentity() to initialize the matrix. Then call the glOrtho() function described in table 3-3 to create the viewing volume. Finally, call glViewPort() (described in Table 3-4) to specify how the viewing volume is to be mapped to the OpenGL drawing window.
void glMatrixMode(GLenum mode);

Specifies whether the modelview, projection, or texture matrix will be modified. The mode argument can be one of GL_MODELVIEW, GL_PROJECTION, or GL_TEXTURE. Subsequent transformation commands affect the specified matrix. Note that only one matrix can be modified at a time. By default, the modelview matrix is modifiable and all three matrices contain the identity matrix. Table 3-2 glMatrixMode() Function Description
void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far);

Creates a matrix for an orthographic parallel viewing volume and multiplies the current matrix by it. The near clipping plane is a rectangle with the lower left corner at (left, bottom, -near) and the upper right corner at (right, top, -near). The far clipping plane is a rectangle with corners at (left, bottom, -far) and (right, top, -far). Both near and far can be positive or negative. Table 3-3 glOrtho() Function Description

void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);

20 Defines a pixel rectangle in the window into which the final image is mapped. The (x, y) parameter specifies the lower left corner of the viewport, and with and height are the size of the viewport rectangle. By default, the initial viewport values are (0, 0, winWidth, winHeight), where winWidth and winHeight are the size of the window. Table 3-4 glViewPort() Function Description Setting Up Perspective Projection To set up perspective projection, first specify which matrix stack is being modified. In this case, the projection matrix stack is used. Call glMatrixMode() to specify which matrix stack to modify as described in Table 3-2. Next call glLoadIdentity() to initialize the matrix. Then call the gluPerspective() function described in table 3-5 to create the viewing volume. Finally, call glViewPort() (described in Table 3-4) to specify how the viewing volume is to be mapped to the OpenGL drawing window.
void gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar);

Creates a matrix for a symmetric perspective-view frustum and multiplies the current matrix by it. The fovy argument is the angle of the field of view in the x-z plane; its value must be in the range [0.0, 180.0]. The aspect ratio is the width of the frustum divided by its height. The zNear and zFar values are the distances between the viewport and the clipping planes, along the negative z-axis. They should always be positive. Table 3-5 gluPerspective() Function Description Applying rotations and/or translations will change the default orientation of the viewing volume created by gluPerspective(). With no transformations, the viewport remains at the origin, and the line of sight points down the negative z-axis. Once the viewing volume is created with gluPerspective(), the function gluLookAt() can be used to automatically apply the transforms necessary to view the model from a particular point in space. 3.3 Modeling Transformations

The modeling transformations are used to orient and scale the model. The functions glTranslate*(), glRotate*() and glScale*() can be called to create a new modeling transformation. Each call to any of these functions creates a new matrix which is combined with

21 the current modelview matrix to transform all the vertices that follow. Tables 3-6, 3-7 and 3-8 describe these functions.
Void glTranslate{fd}(TYPE x, TYPE y, TYPE z);

Multiplies the current matrix by a matrix that moves (translates) an object by the given x, y, and z values (or moves the local coordinate system by the same amounts). Table 3-6 glTranslate() Function Description
void glRotate{fd}(TYPE angle, TYPE x, TYPE y, TYPE z);

Multiplies the current matrix by a matrix that rotates an object (or the local coordinate system) in a counterclockwise direction about a vector from the origin through the point (x, y, z). The angle parameter specifies the angle of rotation in degrees. Table 3-7 glRotate() Function Description
void glScale{fd}(TYPE x, TYPE y, TYPE z);

Multiplies the current matrix by a matrix that stretches, shrinks, or reflects an object along the axes. Each x, y, and z coordinate of every point in the object is multiplied by the corresponding argument x, y, or z. With the local coordinate system approach, the local coordinate axes are stretched by the x, y, and z factors, and the associated object is stretched with them. Table 3-8 glScale() Function Description 3.4 Matrix Manipulation

Each transformation (i.e, any call to one of the three functions just described) will effect all objects that are drawn after the transformation. Many times this is not desired. To preserve and then recall a previous transformation matrix, the glPushMatrix() and glPopMatrix() functions can be used. These functions should be self explanatory. One pushes the current matrix down the stack, copying the topmost matrix. The other pops the top matrix off the top so that the second-from-the-top matrix becomes the topmost matrix. Following is an example of how to use these functions. In this example I want to draw a car. Each drawing function draws its associated part at the origin. Therefore, the object must be translated to the current location before drawing.

22

DrawCarBody(); /* glPushMatrix(); glTranslated(10.0, DrawWheel(); /* glPopMatrix(); glPushMatrix(); glTranslated(10.0, DrawWheel(); /* glPopMatrix(); . . .

at origin */ 0.0, -5.0); left wheel - relative to origin */ 0.0, 5.0); right wheel - relative to origin */

In this example the wheels are placed relative to the origin since the modelview matrix still holds the identity matrix. Without the calls to push and pop the matrices, the second wheel would have been translated relative to the first wheel drawn. This would have resulted in the second wheel being drawn at (20.0, 0.0, 0.0), not the desired position. Alternatively, we can translate the second wheel relative to the first wheel like this to produce the same result as above:
glPushMatrix(); glTranslated(10.0, 0.0, -5.0); DrawWheel(); glTranslated(0.0, 0.0, 10.0); DrawWheel(); glPopMatrix();

3.5

Depth Checking

When dealing with several objects in 3D space, some objects may be obscured by others. The elimination of the obscured parts is called hidden-surface removal. Hidden-surface removal is automatically handled by OpenGLs depth testing, but it must be enabled. Use the function glEnable(GL_DEPTH_TEST) to do this, and use the function glDepthFunc() to modify how it performs. Also, the depth buffer must be cleared before the scene is drawn. This is done by issuing glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT).
void glDepthFunc(GLenum func);

Sets the comparison function for the depth test. The value for func must be GL_NEVER, GL_ALWAYS, GL_LESS, GL_LEQUAL, GL_EQUAL, GL_GEQUAL, GL_GREATER, or GL_NOTEQUAL. An incoming fragment passes the depth test if its z value has the specified relation to the value already stored in the depth buffer. The default is GL_LESS, which means that an incoming fragment passes the test if its z value is less than that already stored in the depth

23 buffer. In this case, the z value represents the distance from the object to the viewpoint, and smaller values mean the corresponding objects are closer to the viewpoint. Table 3-9 glDepthFunc() Function Description ex. glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); . . . glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawObject();

24

Chapter 4 Display Lists


Display lists can be used to optimize performance since you can use them to store OpenGL commands for later execution. It is often a good idea to cache commands in a display list if you plan to redraw the same geometry multiple times, or it you have a set of state changes that need to be applied multiple times. A display list is created by placing drawing and transformation functions between calls to glNewList() and glEndList() functions. The list must be given a unique integer that identifies the display list. The glNewList() function is described in Table 4-1.
void glNewList(GLuint list, GLenum mode);

Specifies the start of a display list. OpenGL routines that are called subsequently (until glEndList() is called) are stored in a display list, except for a few restricted OpenGL routines that cant be stored. The list parameter is a unique positive integer that identifies the display list. The possible values for the mode parameter are GL_COMPILE and GL_COMPILE_AND_EXECUTE. Use GL_COMPILE if you dont want the following OpenGL commands to be executed as they are placed in the display list; to cause the commands to be executed immediately as well as placed in the display list for later use, specify GL_COMPILE_AND_EXECUTE. Table 4-1 glNewList() Function Description To execute a display list, call the glCallList() function and pass as an argument the unique integer used when the list was created. To have OpenGL generate the unique integers for you, use the glGenLists() function as described in Table 4-2.
GLuint glGenLists(GLsizei range);

Allocates range number of contiguous, previously unallocated display-list indices. The integer returned is the index that marks the beginning of a contiguous block of empty display-list indices. The returned indices are all marked as empty and used, so subsequent calls to glGenLists() will not return these indices until they are deleted. Zero is returned if the requested number of indices are not available, or if range is zero. Table 4-2 glGenLists() Function Description

25 Delete a list with glDeleteLists(GLuint list, GLsizei range). Once a OpenGL command has been stored in a list it is not possible to remove it. Niether can you add any new commands to the list after it has been defined. You can delete the entire display list and create a new one, but you cant edit it. Also display lists can not be defined in a nested way. Instead, display lists can be hierarchical referencing other display lists. This is useful for the display of composite objects that are made up of many other objects. Not all OpenGL commands can be stored and executed from within a display list. For example, commands that set client state and commands that retrieve state values arent stored in a display list. (Many of these commands are easily identifiable because they return values in parameters passed by reference or returen a value directly.) Following are some OpenGL commands that are not stored in a display list; glColorPointer() glGenLists() glReadPixels() glFlush() glPixelStore() glFinish() glNormalPointer() glDisableClientState() etc... glDeleteLists() glGet*()

You also have to be cautious not to use display list with auxShape* functions such as auxSolidWire() since these functions also contain the display lists inside.

26

Chapter 5 Color
5.1 Specifying a Shading Model

A line or a filled polygon primitive can be drawn with a single color (flat shading) or with many different colors (smooth shading, also called Gouraud shading). You can specify the desired shading technique with the glShadeModel() function, passing either GL_FLAT or GL_SMOOTH as a parameter. 5.2 Specifying a Background Color

Before you draw your OpenGL objects, you should clear the window. This is especially important when you are attempting animation because the screen must be cleared between shots. A window is cleared by using the function glClear() described in 5-1. The glClear() function blanks the screen to a some default color. This background color can be set using the function glClearColor() described in 5-2.
void glClear(Glbitfield mask);

Clears the specified buffers to their current clearing values. The mask argument is a bitwiseORed combination of the values listed in the table below. Buffer Color buffer Depth buffer Accumulation buffer Stencil buffer Name GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT GL_ACCUM_BUFFER_BIT GL_STENCIL_BUFFER_BIT Table 5-1 glClear*() Function Description
void glClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha);

Sets the current clearing color for use in clearing color buffers in RGBA mode. The red, green, blue, and alpha values are clamped if necessary to the range [0,1]. The default clearing color is (0,0,0,0), which is black. Table 5-2 glClearColor*() Function Description

27 5.3 Specifying a Color

In RGBA mode, use the glColor*() function to select a current color. This function is described in Table 5-3. All objects are colored using the current color.
Void void void void glColor3{b glColor4{b glColor3{b glColor4{b s s s s i i i i f f f f d d d d ub ub ub ub us us us us ui}(TYPE r, TYPE g, TYPE b); ui}(TYPE r, TYPE g, TYPE b); ui}v(const TYPE *v); ui}v(const TYPE *v);

Sets the current red, green, blue, and alpha values. This command can have up to three suffixes, which differentiate variations of the parameters accepted. The first suffix is either 3 or 4, to indicate whether you supply an alpha value in addition to the red, green, and blue values. If you dont supply an alpha value, its automatically set to 1.0. The second suffix indicates the data type for parameters: byte, short, integer, float, double, unsigned byte, unsigned short, or unsigned integer. The third suffix is an optional v, which indicates that the argument is a pointer to an array of values of the given data type. Table 5-3 glColor*() Function Description

28

Chapter 6 Text
OpenGL is designed to be hardware-independent. Because of this there is no easy way to put text into your OpenGL drawings. The most elementary work around is to use lines and polygons to create block letters. Alternatively, you can use some functions from the Mesa library that are Solaris dependent. Place the following code in your program. Note, however, that solaris dependent font utility is not affected by other OpenGL matrix translation.
GLuint base; void makeRasterFont(void) { XFontStruct *fontInfo; Font id; unsigned int first, last; Display *xdisplay; xdisplay = auxXDisplay (); fontInfo = XLoadQueryFont(xdisplay, "-adobe-times-bold-r-normal--14-100-100-100-p-76-iso8859-1"); if (fontInfo == NULL) { printf ("no font found\n"); exit (0); } id = fontInfo->fid; first = fontInfo->min_char_or_byte2; last = fontInfo->max_char_or_byte2; base = glGenLists((GLuint) last+1); if (base == 0) { printf ("out of display lists\n"); exit (0); } glXUseXFont(id, first, last-first+1, base+first);

void printString(char *s) { glPushAttrib (GL_LIST_BIT); glListBase(base); glCallLists(strlen(s), GL_UNSIGNED_BYTE, (GLubyte *)s); glPopAttrib (); }

The bolded line above defines what font will be used. You can get a list of fonts by using the command xlsfonts at a command prompt. Use the function glRasterPos() to set the position for your text and the printString() function to write text.
glRasterPos2i(26,73); printString("Code Cache");

29 Note that some fonts are not available at all engineering labs since each lab uses a different font server. By typing xlsfonts from your command tool, you will get a list of available fonts at your current workstation. If you are using a workstation in Braun Hall, you need to give the following command: xset +fp tcp/braunfonts:7001.

30

Appendix - Using OpenGL in Microsoft Visual C++


Create a New Project Workspace In order to compile a program using Microsoft Visual C++ 4.0, a project workspace must be created. To do this, select New from the File menu. A small pop-up box will appear prompting for the type of object to create. Select Application. Linking With The OpenGL Libraries In order for an application to use OpenGL, it must link with the OpenGL libraries. To do this, perform the following steps after creating a new project workspace. From the Build menu, select Settings Click on the Link tab In the Object/library modules box add opengl32.lib glu32.lib glaux.lib glut32.lib to the beginning of the list (without the quotes of course). Select Output from the Category list. In the Entry-point symbol box, enter mainCRTStartup Click on OK.

Compiling The Application To compile the application, click on the build button, select Build from the Build menu or press F7. The build button is the second button on the second button bar. Include files The following header files should be included with any application using OpenGL.
#include <glut.h> /* utility toolkit library */

Program Structure

31 The structure of your OpenGL program should look like this:


#include <glut.h> #include <win.h> /* utility toolkit library */

void init() { /* initialization code */ } /* CALLBACK is needed for Visual Studio 97 only */ void CALLBACK reshape(GLsizei w, GLsizei h) { /* code to execute if the window is resized */ } /* CALLBACK is needed for Visual Studio 97 only */ void CALLBACK display(void) { /* code to display the scene */ } void main() { /* code to setup window */ }

Running Your Programs in Windows 95 To run your OpenGL programs in Windows 95, you must add 3 files to your windows/system directory. glu32.dll, opengl32.dll, glut32.dll You only need the first two dll files if you do not have Revision 2 of Windows95. These files can be retrieved from ~ftp/pub/foussjd/openGL or ~kchang/pub/graphics/. opengl.exe is a self uncompressing file that contains the above files. In systems where the C drive is not accessible, e.g., Shop 2 PC lab, you can put the ddl files in the same location as the executable.

GLUT on PC

32 Download glutdlls.zip from ~ftp/pub/foussjd/openGL/ or ~kchang/pub/graphics/. This depends on your particular setup. For example, you can put glut.h and glut32.lib in the following directories. Uncompress and place glut.h -> c:\{VC++ install directory}\include\gl glut32.lib -> c:\ {VC++ install directory}\lib glut32.dll -> c:\windows\system For more information on how to set up a PC environment for OpenGL, please check http://reality.sgi.com/mars_corp/foothill/glsetup.html

33

References
1. Neider, Jackie, Tom Davis, and Mason Woo. OpenGL Programming Guide : The Official Guide to Learning OpenGL, Release 1. Addison-Wesley, 1993. 2. Neider, Jackie, Tom Davis, and Mason Woo. OpenGL Programming Guide : The Official Guide to Learning OpenGL, Version 1.1 Addison-Wesley, 1997. 3. Walnum, Calyton. 3-D Graphics Programming with OpenGL. Que Corp., 1995. 4. USENET news group comp.graphics.opengl

Вам также может понравиться