Presentation is loading. Please wait.

Presentation is loading. Please wait.

Institute for Computer Graphics1 The Institute for Computer Graphics An Introduction to OpenGL Programming Dongho Kim An Introduction to OpenGL Programming.

Similar presentations


Presentation on theme: "Institute for Computer Graphics1 The Institute for Computer Graphics An Introduction to OpenGL Programming Dongho Kim An Introduction to OpenGL Programming."— Presentation transcript:

1 Institute for Computer Graphics1 The Institute for Computer Graphics An Introduction to OpenGL Programming Dongho Kim An Introduction to OpenGL Programming Dongho Kim

2 Institute for Computer Graphics2 About Today’s Lecture Based on the material used for Graphics Tools class last year Schedule of lectures Introduction to OpenGL (this week)Introduction to OpenGL (this week) Introduction to DirectX (next week)Introduction to DirectX (next week) Two weeks laterTwo weeks later –Stuffs related to Game Programming –Advanced features, such as Vertex / Pixel shader Based on the material used for Graphics Tools class last year Schedule of lectures Introduction to OpenGL (this week)Introduction to OpenGL (this week) Introduction to DirectX (next week)Introduction to DirectX (next week) Two weeks laterTwo weeks later –Stuffs related to Game Programming –Advanced features, such as Vertex / Pixel shader

3 Institute for Computer Graphics3 Overview OpenGL Introduction Elementary Rendering Display Lists Graphics TransformationsLighting Texture Mapping Additional Rendering Attributes Imaging OpenGL Introduction Elementary Rendering Display Lists Graphics TransformationsLighting Texture Mapping Additional Rendering Attributes Imaging

4 Institute for Computer Graphics4 What Is OpenGL? Graphics Rendering API high-quality color images composed of geometric and image primitiveshigh-quality color images composed of geometric and image primitives window system independentwindow system independent operating system independentoperating system independent Graphics Rendering API high-quality color images composed of geometric and image primitiveshigh-quality color images composed of geometric and image primitives window system independentwindow system independent operating system independentoperating system independent

5 Institute for Computer Graphics5 OpenGL as a Renderer Geometric primitives points, lines and polygonspoints, lines and polygons Image Primitives images and bitmapsimages and bitmaps separate pipelines for images and geometryseparate pipelines for images and geometry –linked through texture mapping Rendering depends on state Colors, materials, light sources, etc.Colors, materials, light sources, etc. Geometric primitives points, lines and polygonspoints, lines and polygons Image Primitives images and bitmapsimages and bitmaps separate pipelines for images and geometryseparate pipelines for images and geometry –linked through texture mapping Rendering depends on state Colors, materials, light sources, etc.Colors, materials, light sources, etc.

6 Institute for Computer Graphics6 Related APIs AGL, GLX, WGL glue between OpenGL and windowing systemsglue between OpenGL and windowing systems GLU (OpenGL Utility Library) Part of OpenGLPart of OpenGL NURBS, tessellators, quadric shapes, etc.NURBS, tessellators, quadric shapes, etc. GLUT (OpenGL Utility Toolkit) Portable windowing APIPortable windowing API Not officially part of OpenGLNot officially part of OpenGL AGL, GLX, WGL glue between OpenGL and windowing systemsglue between OpenGL and windowing systems GLU (OpenGL Utility Library) Part of OpenGLPart of OpenGL NURBS, tessellators, quadric shapes, etc.NURBS, tessellators, quadric shapes, etc. GLUT (OpenGL Utility Toolkit) Portable windowing APIPortable windowing API Not officially part of OpenGLNot officially part of OpenGL

7 Institute for Computer Graphics7 OpenGL and Related APIs application program X, Win32, Mac O/S software and/or hardware GL GLX, AGL Or WGL OpenGL Motif widget or similar GLU GLUT

8 Institute for Computer Graphics8 Preliminaries Header Files #include #include Libraries Enumerated Types OpenGL defines numerous types for compatibilityOpenGL defines numerous types for compatibility GLfloat, GLint, GLenum, etc. Header Files #include #include Libraries Enumerated Types OpenGL defines numerous types for compatibilityOpenGL defines numerous types for compatibility GLfloat, GLint, GLenum, etc.

9 Institute for Computer Graphics9 GLUT Basics Application Structure Configure and open windowConfigure and open window Initialize OpenGL stateInitialize OpenGL state Register input callback functionsRegister input callback functions –render –resize –input: keyboard, mouse, etc. Enter event processing loopEnter event processing loop Application Structure Configure and open windowConfigure and open window Initialize OpenGL stateInitialize OpenGL state Register input callback functionsRegister input callback functions –render –resize –input: keyboard, mouse, etc. Enter event processing loopEnter event processing loop

10 Institute for Computer Graphics10 Sample Program void main( int argc, char** argv ) { int mode = GLUT_RGB|GLUT_DOUBLE; GLUTInitDisplayMode( mode ); glutCreateWindow( argv[0] ); init(); glutDisplayFunc( display ); glutReshapeFunc( resize ); glutKeyboardFunc( key ); glutIdleFunc( idle ); glutMainLoop(); } void main( int argc, char** argv ) { int mode = GLUT_RGB|GLUT_DOUBLE; GLUTInitDisplayMode( mode ); glutCreateWindow( argv[0] ); init(); glutDisplayFunc( display ); glutReshapeFunc( resize ); glutKeyboardFunc( key ); glutIdleFunc( idle ); glutMainLoop(); }

11 Institute for Computer Graphics11 OpenGL Initialization Set up whatever state you’re going to use void init( void ) { glClearColor( 0.0, 0.0, 0.0, 1.0 ); glClearDepth( 1.0 ); glEnable( GL_LIGHT0 ); glEnable( GL_LIGHTING ); glEnable( GL_DEPTH_TEST ); } Set up whatever state you’re going to use void init( void ) { glClearColor( 0.0, 0.0, 0.0, 1.0 ); glClearDepth( 1.0 ); glEnable( GL_LIGHT0 ); glEnable( GL_LIGHTING ); glEnable( GL_DEPTH_TEST ); }

12 Institute for Computer Graphics12 GLUT Callback Functions Routine to call when something happens window resize of redrawwindow resize of redraw user inputuser input animationanimation “Register” callbacks with GLUT glutDisplayFunc( display ); glutIdleFunc( idle ); glutKeyboardFunc( key ); Routine to call when something happens window resize of redrawwindow resize of redraw user inputuser input animationanimation “Register” callbacks with GLUT glutDisplayFunc( display ); glutIdleFunc( idle ); glutKeyboardFunc( key );

13 Institute for Computer Graphics13 Rendering Callback Do all of your drawing here glutDisplayFunc( render ); void render( void ) { glClear( GL_COLOR_BUFFER_BIT ); glBegin( GL_TRIANGLE_STRIP ); glVertex3fv( v[0] ); glVertex3fv( v[1] ); glVertex3fv( v[2] ); glVertex3fv( v[3] ); glEnd(); glutSwapBuffers(); } Do all of your drawing here glutDisplayFunc( render ); void render( void ) { glClear( GL_COLOR_BUFFER_BIT ); glBegin( GL_TRIANGLE_STRIP ); glVertex3fv( v[0] ); glVertex3fv( v[1] ); glVertex3fv( v[2] ); glVertex3fv( v[3] ); glEnd(); glutSwapBuffers(); }

14 Institute for Computer Graphics14 Idle Callbacks Use for animation and continuous update glutIdleFunc( idle ); void idle( void ) { t += dt; glutPostRedisplay(); } Use for animation and continuous update glutIdleFunc( idle ); void idle( void ) { t += dt; glutPostRedisplay(); }

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

16 Institute for Computer Graphics16 Elementary Rendering

17 Institute for Computer Graphics17 Elementary Rendering Geometric Primitives Managing OpenGL State OpenGL Buffers Geometric Primitives Managing OpenGL State OpenGL Buffers

18 Institute for Computer Graphics18 OpenGL Geometric Primitives All geometric primitives are specified by vertices

19 Institute for Computer Graphics19 Simple Example void drawRhombus( Glfloat color[] ) { glBegin( GL_QUADS ); glColor3fv( color ); glVertex2f( 0.0, 0.0 ); glVertex2f( 1.0, 0.0 ); glVertex2f( 1.5, 1.118 ); glVertex2f( 0.5, 1.118 ); glEnd(); } void drawRhombus( Glfloat color[] ) { glBegin( GL_QUADS ); glColor3fv( color ); glVertex2f( 0.0, 0.0 ); glVertex2f( 1.0, 0.0 ); glVertex2f( 1.5, 1.118 ); glVertex2f( 0.5, 1.118 ); glEnd(); }

20 Institute for Computer Graphics20 OpenGL Command Formats 2 – (x,y) 3 – (x,y,z) 4 – (x,y,z,w) b – byte ub – unsigned byte s – short us – unsigned short i – int ui – unsigned int f – float d - double Omit “v” for Scalar form glVertex2f( x, y ) Number of Components Data TypeVector glVertex3fv( v )

21 Institute for Computer Graphics21 Primitives are specified using glBegin( primType ); glEnd(); primType determines how vertices are combinedprimType determines how vertices are combined Primitives are specified using glBegin( primType ); glEnd(); primType determines how vertices are combinedprimType determines how vertices are combined Specifying Geometric Primitives GLfloat red, green, blue; GLfloat coords[3]; glBegin( primType ); for ( i = 0; i < nVerts; ++i) { glColor3f( red, green, blue ); glVertex3f( coords ); } glEnd();

22 Institute for Computer Graphics22 OpenGL Color Models RGBA or Color Index glColor*()glColor*() glIndex*()glIndex*() RGBA or Color Index glColor*()glColor*() glIndex*()glIndex*() Frame Buffer RGB 0 1 2 3 … color index mode Display RGBA mode

23 Institute for Computer Graphics23 Shapes Tutorial Run shapes tutorial Run shapes tutorial Run shapes tutorial Run shapes tutorial

24 Institute for Computer Graphics24 Advanced Primitives Vertex Arrays Bernstein Polynomial Evaluators basis for GLU NURBSbasis for GLU NURBS –NURBS (Non-Uniform Rational B-Spline) GLU Quadric Objects spheresphere cylinder (or cone)cylinder (or cone) disk (circle)disk (circle) Vertex Arrays Bernstein Polynomial Evaluators basis for GLU NURBSbasis for GLU NURBS –NURBS (Non-Uniform Rational B-Spline) GLU Quadric Objects spheresphere cylinder (or cone)cylinder (or cone) disk (circle)disk (circle)

25 Institute for Computer Graphics25 OpenGL’s State Machine All rendering attributes are encapsulated in the OpenGL State rendering stylesrendering styles shadingshading lightinglighting texture mappingtexture mapping All rendering attributes are encapsulated in the OpenGL State rendering stylesrendering styles shadingshading lightinglighting texture mappingtexture mapping

26 Institute for Computer Graphics26 Manipulating OpenGL State Appearance is controlled by current state for each ( primitive to render ) { update OpenGL state update OpenGL state render primitive render primitive} Manipulating vertex attributes is most common way to manipulate state glColor*() / glIndex*() glNormal*() glTexCoord*() Appearance is controlled by current state for each ( primitive to render ) { update OpenGL state update OpenGL state render primitive render primitive} Manipulating vertex attributes is most common way to manipulate state glColor*() / glIndex*() glNormal*() glTexCoord*()

27 Institute for Computer Graphics27 Controlling current state Setting State glPointSize( size ); glLineStipple( repeat, pattern ); glShadeModel( GL_SMOOTH ); Enabling Features glEnable( GL_LIGHTING ); glDisable( GL_TEXTURE_2D ); Setting State glPointSize( size ); glLineStipple( repeat, pattern ); glShadeModel( GL_SMOOTH ); Enabling Features glEnable( GL_LIGHTING ); glDisable( GL_TEXTURE_2D );

28 Institute for Computer Graphics28 OpenGL Buffers Color for double buffering, divided into front and backfor double buffering, divided into front and backAlphaDepthStencilAccumulationColor AlphaDepthStencilAccumulation

29 Institute for Computer Graphics29 Clearing Buffers Setting clear values glClearColor( r, g, b, a ); glClearDepth( 1.0 ); Clearing buffers glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); Setting clear values glClearColor( r, g, b, a ); glClearDepth( 1.0 ); Clearing buffers glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

30 Institute for Computer Graphics30 Animation Using Double Buffering 1) Request a double buffered color buffer glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE ); 2) Clear color buffer glClear( GL_COLOR_BUFFER_BIT ); 3) Render Scene 4) Request swap of front and back buffers glutSwapBuffers(); Repeat steps 2-4 for animation 1) Request a double buffered color buffer glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE ); 2) Clear color buffer glClear( GL_COLOR_BUFFER_BIT ); 3) Render Scene 4) Request swap of front and back buffers glutSwapBuffers(); Repeat steps 2-4 for animation

31 Institute for Computer Graphics31 Depth Buffering Using OpenGL 1) Request a double buffered color buffer glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ); 2) Enable depth buffering glEnable( GL_DEPTH_TEST ); 3) Clear color buffer glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 4) Render Scene 5) Swap color buffers 1) Request a double buffered color buffer glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH ); 2) Enable depth buffering glEnable( GL_DEPTH_TEST ); 3) Clear color buffer glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 4) Render Scene 5) Swap color buffers

32 Institute for Computer Graphics32 A Program Template void main( int argc, char** argv ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow( “Tetrahedron” ); init(); glutIdleFunc( drawScene ); glutMainLoop(); } void main( int argc, char** argv ) { glutInit( &argc, argv ); glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow( “Tetrahedron” ); init(); glutIdleFunc( drawScene ); glutMainLoop(); }

33 Institute for Computer Graphics33 A Program Template (cont.) void init( void ) { glClearColor( 0.0, 0.0, 1.0, 1.0 ); } void init( void ) { glClearColor( 0.0, 0.0, 1.0, 1.0 ); }

34 Institute for Computer Graphics34 A Program Template (cont.) void drawScene( void ) { GLfloat vertices[] = { … }; GLfloat colors[] = { … }; glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glBegin( GL_TRIANGLE_STRIP ); /* calls to glColor*() and glVertex*() */ glEnd(); glutSwapBuffers(); } void drawScene( void ) { GLfloat vertices[] = { … }; GLfloat colors[] = { … }; glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glBegin( GL_TRIANGLE_STRIP ); /* calls to glColor*() and glVertex*() */ glEnd(); glutSwapBuffers(); }

35 Institute for Computer Graphics35 Immediate Mode and Display Lists Graphics Immediate Mode and Display Lists Graphics

36 Institute for Computer Graphics36 Immediate vs Retained Mode Immediate Mode Graphics Primitive are sent to pipeline and display right awayPrimitive are sent to pipeline and display right away No memory of graphical entitiesNo memory of graphical entities Retained Mode Graphics Primitives placed in display listsPrimitives placed in display lists Display lists kept on graphics serverDisplay lists kept on graphics server Can be redisplayed with different stateCan be redisplayed with different state Can be shared among OpenGL graphics contextsCan be shared among OpenGL graphics contexts Immediate Mode Graphics Primitive are sent to pipeline and display right awayPrimitive are sent to pipeline and display right away No memory of graphical entitiesNo memory of graphical entities Retained Mode Graphics Primitives placed in display listsPrimitives placed in display lists Display lists kept on graphics serverDisplay lists kept on graphics server Can be redisplayed with different stateCan be redisplayed with different state Can be shared among OpenGL graphics contextsCan be shared among OpenGL graphics contexts

37 Institute for Computer Graphics37 Display Lists steps: create it, then call it GLuint id; void init( void ) { id = glGenLists( 1 ); glNewList( id, GL_COMPILE ); /* other OpenGL routines */ glEndList(); } void display( void ) { glCallList( id ); } steps: create it, then call it GLuint id; void init( void ) { id = glGenLists( 1 ); glNewList( id, GL_COMPILE ); /* other OpenGL routines */ glEndList(); } void display( void ) { glCallList( id ); }

38 Institute for Computer Graphics38 Modeling with Display Lists #define BOX 1 /* or any other integer */ glNewList( BOX, GL_COMPILE ); glBegin( GL_QUADS ); glVertex3d( … ); … glEnd(); glEndList(); #define BOX 1 /* or any other integer */ glNewList( BOX, GL_COMPILE ); glBegin( GL_QUADS ); glVertex3d( … ); … glEnd(); glEndList();

39 Institute for Computer Graphics39 Creating Instances glPushMatrix(); glTranslatef( x, y, z ); glRotated( theta, axisx, axisy, axisz ); glScaled( sx, sy, sz ); glCallList( BOX ); glPopMatrix(); glPushMatrix(); glTranslatef( x, y, z ); glRotated( theta, axisx, axisy, axisz ); glScaled( sx, sy, sz ); glCallList( BOX ); glPopMatrix();

40 Institute for Computer Graphics40 Display Lists Not all OpenGL routines can be stored in display lists State changes persist, even after a display list is finished Display lists can call other display lists Display lists are not editable, but you can fake it make a list (A) which calls other lists (B, C, and D)make a list (A) which calls other lists (B, C, and D) delete and replace B, C, and D, as neededdelete and replace B, C, and D, as needed Not all OpenGL routines can be stored in display lists State changes persist, even after a display list is finished Display lists can call other display lists Display lists are not editable, but you can fake it make a list (A) which calls other lists (B, C, and D)make a list (A) which calls other lists (B, C, and D) delete and replace B, C, and D, as neededdelete and replace B, C, and D, as needed

41 Institute for Computer Graphics41 Display Lists and Hierarchy Consider model of a car Create display list for chassisCreate display list for chassis Create display list for wheelCreate display list for wheel glNewList( CAR, GL_COMPILE ); glCallList( CHASSIS ); glTranslatef( … ); glCallList( WHEEL ); glTranslatef( … ); glCallList( WHEEL ); … glEndList(); Consider model of a car Create display list for chassisCreate display list for chassis Create display list for wheelCreate display list for wheel glNewList( CAR, GL_COMPILE ); glCallList( CHASSIS ); glTranslatef( … ); glCallList( WHEEL ); glTranslatef( … ); glCallList( WHEEL ); … glEndList();

42 Institute for Computer Graphics42 TransformationsTransformations

43 Institute for Computer Graphics43 Transformations Prior to rendering, view, locate, and orient eye/camera positioneye/camera position 3D geometry3D geometry Manage the matrices including matrix stackincluding matrix stack Combine (composite) transformations Prior to rendering, view, locate, and orient eye/camera positioneye/camera position 3D geometry3D geometry Manage the matrices including matrix stackincluding matrix stack Combine (composite) transformations

44 Institute for Computer Graphics44 3D Mathematics A vertex is transformed by matrices each vertex is a column vector v, ( x, y, z, w ) T where w is usually 1.0each vertex is a column vector v, ( x, y, z, w ) T where w is usually 1.0 all operations are matrix multiplicationsall operations are matrix multiplications all matrices are column-majorall matrices are column-major matrices are always post-multipliedmatrices are always post-multiplied product of matrix and vector is Mvproduct of matrix and vector is Mv Programmer does not have to remember the exact matrices A vertex is transformed by matrices each vertex is a column vector v, ( x, y, z, w ) T where w is usually 1.0each vertex is a column vector v, ( x, y, z, w ) T where w is usually 1.0 all operations are matrix multiplicationsall operations are matrix multiplications all matrices are column-majorall matrices are column-major matrices are always post-multipliedmatrices are always post-multiplied product of matrix and vector is Mvproduct of matrix and vector is Mv Programmer does not have to remember the exact matrices

45 Institute for Computer Graphics45 Camera Analogy Projection transformations adjust the lens of the cameraadjust the lens of the camera Viewing transformations tripod-define position and orientation of the viewing volume in the worldtripod-define position and orientation of the viewing volume in the world Modeling transformations moving the modelmoving the model Viewport transformations enlarge or reduce the physical photographenlarge or reduce the physical photograph Projection transformations adjust the lens of the cameraadjust the lens of the camera Viewing transformations tripod-define position and orientation of the viewing volume in the worldtripod-define position and orientation of the viewing volume in the world Modeling transformations moving the modelmoving the model Viewport transformations enlarge or reduce the physical photographenlarge or reduce the physical photograph

46 Institute for Computer Graphics46 Transformation Pipeline VertexVertex VertexVertex Modelview Matrix Modelview Matrix Modelview Projection Matrix Projection Matrix Projection Perspective Division Perspective Division Viewport Transform Viewport Transform objectwindoweye normalized device clip

47 Institute for Computer Graphics47 Matrix Operations Specify Current Matrix Stack glMatrixMode(GL_MODELVIEW or GL_PROJECTION) Other Matrix or Stack Operations glLoadIdentity() glPushMatrix() glPopMatrix() Specify Current Matrix Stack glMatrixMode(GL_MODELVIEW or GL_PROJECTION) Other Matrix or Stack Operations glLoadIdentity() glPushMatrix() glPopMatrix()

48 Institute for Computer Graphics48 Transformation hierarchy example glLoadIdentity() Transformation 1 Draw something (T1) glPushMatrix() Transformation 2 glPushMatrix() Transformation 3 Draw something (T1*T2*T3) glLoadIdentity() Draw something (I) glPopMatrix() Draw something (T1*T2) glPopMatrix() Draw something (T1) glLoadIdentity() Transformation 1 Draw something (T1) glPushMatrix() Transformation 2 glPushMatrix() Transformation 3 Draw something (T1*T2*T3) glLoadIdentity() Draw something (I) glPopMatrix() Draw something (T1*T2) glPopMatrix() Draw something (T1)

49 Institute for Computer Graphics49 Viewport Transformation Viewport Usually same as window sizeUsually same as window size Viewport aspect ratio should be same as projection transformation or resulting image may be distortedViewport aspect ratio should be same as projection transformation or resulting image may be distorted glViewport( x, y, width, height );Viewport Usually same as window sizeUsually same as window size Viewport aspect ratio should be same as projection transformation or resulting image may be distortedViewport aspect ratio should be same as projection transformation or resulting image may be distorted glViewport( x, y, width, height );

50 Institute for Computer Graphics50 Projection Transformation Shape of viewing frustum Perspective projection gluPerspective( fovy, aspect, zNear, zFar ) glFrustum( left, right, bottom, top, zNear, zFar ) Orthographic parallel projection glOrtho( left, right, bottom, top, zNear, zFar ) gluOrtho2D( left, right, bottom, top ) calls glOrtho with z values near zerocalls glOrtho with z values near zero Shape of viewing frustum Perspective projection gluPerspective( fovy, aspect, zNear, zFar ) glFrustum( left, right, bottom, top, zNear, zFar ) Orthographic parallel projection glOrtho( left, right, bottom, top, zNear, zFar ) gluOrtho2D( left, right, bottom, top ) calls glOrtho with z values near zerocalls glOrtho with z values near zero

51 Institute for Computer Graphics51 Viewing Transformations Position the camera/eye in the scene place the tripod down; aim cameraplace the tripod down; aim camera To “fly through” a scene change viewing transformation and redraw scenechange viewing transformation and redraw scene gluLookAt( eyex, eyey, eyez, aimx, aimy, aimz, upx, upy, upz ) up vector determines unique orientationup vector determines unique orientation careful of degenerate positionscareful of degenerate positions Position the camera/eye in the scene place the tripod down; aim cameraplace the tripod down; aim camera To “fly through” a scene change viewing transformation and redraw scenechange viewing transformation and redraw scene gluLookAt( eyex, eyey, eyez, aimx, aimy, aimz, upx, upy, upz ) up vector determines unique orientationup vector determines unique orientation careful of degenerate positionscareful of degenerate positions

52 Institute for Computer Graphics52 Projection Tutorial Run projection tutorial Run projection tutorial Run projection tutorial Run projection tutorial

53 Institute for Computer Graphics53 Modeling Transformations Move Object glTranslate{fd}( x, y, z ) Rotate object around arbitrary axis (x, y, z) glRotate{fd}( angle, x, y, z ) angle in degreesangle in degrees Dilate (stretch or shrink) or mirror object glScale{fd}( x, y, z ) Move Object glTranslate{fd}( x, y, z ) Rotate object around arbitrary axis (x, y, z) glRotate{fd}( angle, x, y, z ) angle in degreesangle in degrees Dilate (stretch or shrink) or mirror object glScale{fd}( x, y, z )

54 Institute for Computer Graphics54 Transformation Tutorial Run transformation tutorial Run transformation tutorial Run transformation tutorial Run transformation tutorial

55 Institute for Computer Graphics55 Connection: Viewing and Modeling Moving camera is equivalent to moving every object in the world towards a stationary camera Moving camera is equivalent to moving every object in the world towards a stationary camera Viewing transformations are equivalent to several modeling transformations Viewing transformations are equivalent to several modeling transformations gluLookAt() has its own command can make your own polar view or pilot view Moving camera is equivalent to moving every object in the world towards a stationary camera Moving camera is equivalent to moving every object in the world towards a stationary camera Viewing transformations are equivalent to several modeling transformations Viewing transformations are equivalent to several modeling transformations gluLookAt() has its own command can make your own polar view or pilot view

56 Institute for Computer Graphics56 Projection is left handed Projection transformations ( gluPerspective, glOrtho ) are left handed think of zNear and zFar as distance from view pointthink of zNear and zFar as distance from view point Everything else is right handed, including the vertices to be rendered Projection transformations ( gluPerspective, glOrtho ) are left handed think of zNear and zFar as distance from view pointthink of zNear and zFar as distance from view point Everything else is right handed, including the vertices to be rendered

57 Institute for Computer Graphics57 LightingLighting

58 Institute for Computer Graphics58 Lighting Principles Lighting simulates how objects reflect light material property of objectmaterial property of object light’s color and positionlight’s color and position global lighting parametersglobal lighting parameters –ambient light –two sided lighting available in both color index and RGBA modeavailable in both color index and RGBA mode Lighting simulates how objects reflect light material property of objectmaterial property of object light’s color and positionlight’s color and position global lighting parametersglobal lighting parameters –ambient light –two sided lighting available in both color index and RGBA modeavailable in both color index and RGBA mode

59 Institute for Computer Graphics59 How OpenGL Simulates Lights Phong lighting model Computed at verticesComputed at vertices Lighting contributors Surface material propertiesSurface material properties Light propertiesLight properties Lighting model propertiesLighting model properties Phong lighting model Computed at verticesComputed at vertices Lighting contributors Surface material propertiesSurface material properties Light propertiesLight properties Lighting model propertiesLighting model properties

60 Institute for Computer Graphics60 Surface Normals Normals define how a surface reflects light glNormal3f( x, y, z ); Current normal is used to compute vertex’s colorCurrent normal is used to compute vertex’s color Use unit normals for proper lightingUse unit normals for proper lighting –scaling affects a normal’s length –glEnable( GL_NORMALIZE ); Normals define how a surface reflects light glNormal3f( x, y, z ); Current normal is used to compute vertex’s colorCurrent normal is used to compute vertex’s color Use unit normals for proper lightingUse unit normals for proper lighting –scaling affects a normal’s length –glEnable( GL_NORMALIZE );

61 Institute for Computer Graphics61 Material Properties Define the surface properties of a primitive glMaterialfv( face, property, value ); Separate materials for front and backSeparate materials for front and back Define the surface properties of a primitive glMaterialfv( face, property, value ); Separate materials for front and backSeparate materials for front and back GL_DIFFUSE GL_DIFFUSE Base color Base color GL_SPECULAR GL_SPECULAR Highlight color Highlight color GL_AMBIENT GL_AMBIENT Low-light color Low-light color GL_EMISSION GL_EMISSION Glow color Glow color GL_SHININESS GL_SHININESS Surface Smoothness Surface Smoothness

62 Institute for Computer Graphics62 Light Properties glLightfv( light, property, value ); light specifies which lightlight specifies which light –Multiple lights, starting with GL_LIGHT0 –glGetIntegerv( GL_MAX_LIGHTS, &n ); propertiesproperties –colors –position and type –attenuation glLightfv( light, property, value ); light specifies which lightlight specifies which light –Multiple lights, starting with GL_LIGHT0 –glGetIntegerv( GL_MAX_LIGHTS, &n ); propertiesproperties –colors –position and type –attenuation

63 Institute for Computer Graphics63 Light Sources (cont.) Light color properties GL_AMBIENTGL_AMBIENT GL_DIFFUSEGL_DIFFUSE GL_SPECULARGL_SPECULAR Light color properties GL_AMBIENTGL_AMBIENT GL_DIFFUSEGL_DIFFUSE GL_SPECULARGL_SPECULAR

64 Institute for Computer Graphics64 Types of Lights OpenGL supports two types of Lights Local (Point) light sourcesLocal (Point) light sources Infinite (Directional) light sourcesInfinite (Directional) light sources Type of light controlled by w coordinate w = 0 Infinite Light directed along (x y z) w  0 Local Light positioned at (x/w y/w z/w) OpenGL supports two types of Lights Local (Point) light sourcesLocal (Point) light sources Infinite (Directional) light sourcesInfinite (Directional) light sources Type of light controlled by w coordinate w = 0 Infinite Light directed along (x y z) w  0 Local Light positioned at (x/w y/w z/w)

65 Institute for Computer Graphics65 Turning on the Lights Flip each light’s switch glEnable( GL_LIGHTn );glEnable( GL_LIGHTn ); Turn on the power glEnable( GL_LIGHTING );glEnable( GL_LIGHTING ); Flip each light’s switch glEnable( GL_LIGHTn );glEnable( GL_LIGHTn ); Turn on the power glEnable( GL_LIGHTING );glEnable( GL_LIGHTING );

66 Institute for Computer Graphics66 Light Material Tutorial Run Light Material tutorial Run Light Material tutorial Run Light Material tutorial Run Light Material tutorial

67 Institute for Computer Graphics67 Controlling a Light’s Position ModelView matrix affects a light’s position Different effects based on when position is specifiedDifferent effects based on when position is specified –eye coordinates –world coordinates –model coordinates Push and pop matrices to uniquely control a light’s positionPush and pop matrices to uniquely control a light’s position ModelView matrix affects a light’s position Different effects based on when position is specifiedDifferent effects based on when position is specified –eye coordinates –world coordinates –model coordinates Push and pop matrices to uniquely control a light’s positionPush and pop matrices to uniquely control a light’s position

68 Institute for Computer Graphics68 Light Position Tutorial Run Light Position tutorial Run Light Position tutorial Run Light Position tutorial Run Light Position tutorial

69 Institute for Computer Graphics69 Advanced Lighting Features Spotlights localize lighting effectslocalize lighting effects –GL_SPOT_DIRECTION –GL_SPOT_CUTOFF –GL_SPOT_EXPONENT Spotlights localize lighting effectslocalize lighting effects –GL_SPOT_DIRECTION –GL_SPOT_CUTOFF –GL_SPOT_EXPONENT

70 Institute for Computer Graphics70 Advanced Lighting Features Light Attenuation decrease light intensity with distancedecrease light intensity with distance –GL_CONTANT_ATTENUATION –GL_LINEAR_ATTENUATION –GL_QUADRIC_ATTENUATION Light Attenuation decrease light intensity with distancedecrease light intensity with distance –GL_CONTANT_ATTENUATION –GL_LINEAR_ATTENUATION –GL_QUADRIC_ATTENUATION

71 Institute for Computer Graphics71 Tips for Better Lighting Recall lighting computed only at vertices model tessellation heavily affects lighting resultsmodel tessellation heavily affects lighting results –better results but more geometry to process Use a single infinite light for fastest lighting minimal computation per vertexminimal computation per vertex Recall lighting computed only at vertices model tessellation heavily affects lighting resultsmodel tessellation heavily affects lighting results –better results but more geometry to process Use a single infinite light for fastest lighting minimal computation per vertexminimal computation per vertex

72 Institute for Computer Graphics72 Texture Mapping

73 Institute for Computer Graphics73 Texture Mapping Apply a 1D, 2D, or 3D image to geometric primitives Uses of Texturing simulating materialssimulating materials reducing geometric complexityreducing geometric complexity image warpingimage warping reflectorsreflectors Apply a 1D, 2D, or 3D image to geometric primitives Uses of Texturing simulating materialssimulating materials reducing geometric complexityreducing geometric complexity image warpingimage warping reflectorsreflectors

74 Institute for Computer Graphics74 Applying Textures specify textures in texture objectsspecify textures in texture objects set texture filterset texture filter set texture functionset texture function set texture wrap modeset texture wrap mode bind texture objectbind texture object enable texturingenable texturing supply texture coordinates for vertexsupply texture coordinates for vertex –coordinates can also be generated specify textures in texture objectsspecify textures in texture objects set texture filterset texture filter set texture functionset texture function set texture wrap modeset texture wrap mode bind texture objectbind texture object enable texturingenable texturing supply texture coordinates for vertexsupply texture coordinates for vertex –coordinates can also be generated

75 Institute for Computer Graphics75 Texture Objects Like display lists for texture images one image per texture objectone image per texture object may be shared by several graphics contextsmay be shared by several graphics contexts Generate texture names glGenTexture( n, *texIds ); Like display lists for texture images one image per texture objectone image per texture object may be shared by several graphics contextsmay be shared by several graphics contexts Generate texture names glGenTexture( n, *texIds );

76 Institute for Computer Graphics76 Texture Objects (cont’d) Create texture objects with texture data and state glBindTexture( target, id ); Bind textures for using glBindTexture( target, id ); target: GL_TEXTURE_{123}D Create texture objects with texture data and state glBindTexture( target, id ); Bind textures for using glBindTexture( target, id ); target: GL_TEXTURE_{123}D

77 Institute for Computer Graphics77 Specify Texture Image Define a texture image from an array of texels in CPU memory glTexImage2D( target, level, components, w, h, border, format, type, *texels ); dimensions of image must be powers of 2dimensions of image must be powers of 2 Define a texture image from an array of texels in CPU memory glTexImage2D( target, level, components, w, h, border, format, type, *texels ); dimensions of image must be powers of 2dimensions of image must be powers of 2

78 Institute for Computer Graphics78 Converting a Texture Image If dimensions of image are not power of 2 gluScaleImage( format, w_in, h_in, type_in, *data_in, w_out, h_out, type_out, *data_out ); *_in is for source image*_in is for source image *_out is for destination image*_out is for destination image Image interpolated and filtered during scaling If dimensions of image are not power of 2 gluScaleImage( format, w_in, h_in, type_in, *data_in, w_out, h_out, type_out, *data_out ); *_in is for source image*_in is for source image *_out is for destination image*_out is for destination image Image interpolated and filtered during scaling

79 Institute for Computer Graphics79 Specifying a Texture: Other Methods Use frame buffer as source of texture image uses current buffer as source imageuses current buffer as source imageglCopyTexImage2D(…)glCopyTexImage1D(…) Modify part of a defined texture glTexSubImage2D(…)glTexSubImage1D(…) Do both with glColyTexSubImage2D(…), etc. Use frame buffer as source of texture image uses current buffer as source imageuses current buffer as source imageglCopyTexImage2D(…)glCopyTexImage1D(…) Modify part of a defined texture glTexSubImage2D(…)glTexSubImage1D(…) Do both with glColyTexSubImage2D(…), etc.

80 Institute for Computer Graphics80 Mapping a Texture Based on parametric texture coordinatesBased on parametric texture coordinates glTexCoord*() specified at each vertexglTexCoord*() specified at each vertex Based on parametric texture coordinatesBased on parametric texture coordinates glTexCoord*() specified at each vertexglTexCoord*() specified at each vertex

81 Institute for Computer Graphics81 Generating Texture Coordinates Automatically generate texture coordinates glTexGen{ifd}[v]() specify a plane Ax+By+Cz+D = 0 generate texture coordinates based on distance from planegenerate texture coordinates based on distance from plane generation modes GL_OBJECT_LINEARGL_OBJECT_LINEAR GL_EYE_LINEARGL_EYE_LINEAR GL_SPHERE_MAPGL_SPHERE_MAP Automatically generate texture coordinates glTexGen{ifd}[v]() specify a plane Ax+By+Cz+D = 0 generate texture coordinates based on distance from planegenerate texture coordinates based on distance from plane generation modes GL_OBJECT_LINEARGL_OBJECT_LINEAR GL_EYE_LINEARGL_EYE_LINEAR GL_SPHERE_MAPGL_SPHERE_MAP

82 Institute for Computer Graphics82 Texture Application Methods Filter Modes minification or magnificationminification or magnification special mipmap minification filtersspecial mipmap minification filters Wrap Modes clamping or repeatingclamping or repeating Texture Functions how to mix primitive’s color with texture’s colorhow to mix primitive’s color with texture’s color –blend, modulate, or replace texels Filter Modes minification or magnificationminification or magnification special mipmap minification filtersspecial mipmap minification filters Wrap Modes clamping or repeatingclamping or repeating Texture Functions how to mix primitive’s color with texture’s colorhow to mix primitive’s color with texture’s color –blend, modulate, or replace texels

83 Institute for Computer Graphics83 Filter Modes Example: glTexParameteri( target, type, mode ); GL_NEARESTGL_LINEARGL_NEAREST_MIPMAP_NEARESTGL_NEAREST_MIPMAP_LINEARGL_LINEAR_MIPMAP_NEARESTGL_LINEAR_MIPMAP_LINEARExample: GL_NEARESTGL_LINEARGL_NEAREST_MIPMAP_NEARESTGL_NEAREST_MIPMAP_LINEARGL_LINEAR_MIPMAP_NEARESTGL_LINEAR_MIPMAP_LINEAR

84 Institute for Computer Graphics84 Mipmapped Textures Mipmap allows prefiltered texture maps of decreasing resolutions Lessens interpolation errors for smaller textured objects Declare mipmap level during texture definition glTexImage*D( GL_TEXTURE_*D, level, … ) GLU mipmap builder routines gluBuild*DMipmaps( … ) gluBuild*DMipmaps( … ) Mipmap allows prefiltered texture maps of decreasing resolutions Lessens interpolation errors for smaller textured objects Declare mipmap level during texture definition glTexImage*D( GL_TEXTURE_*D, level, … ) GLU mipmap builder routines gluBuild*DMipmaps( … ) gluBuild*DMipmaps( … )

85 Institute for Computer Graphics85 Wrapping Mode Example: glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ) Example: glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP ) glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )

86 Institute for Computer Graphics86 Texture Functions Controls how texture is applied GL_TEXTURE_ENV_MODE modes GL_MODULATEGL_MODULATE GL_BLENDGL_BLEND GL_REPLACEGL_REPLACE Set blend color with GL_TEXTURE_ENV_COLOR Controls how texture is applied GL_TEXTURE_ENV_MODE modes GL_MODULATEGL_MODULATE GL_BLENDGL_BLEND GL_REPLACEGL_REPLACE Set blend color with GL_TEXTURE_ENV_COLOR

87 Institute for Computer Graphics87 Texture Tutorial Run Texture tutorial Run Texture tutorial Run Texture tutorial Run Texture tutorial

88 Institute for Computer Graphics88 2D Operations

89 Institute for Computer Graphics89 Alpha: the 4 th Color Component Measure of Opacity simulate translucent objectssimulate translucent objects –glass, water, etc. composite imagescomposite images antialiasingantialiasing ignored if blending is not enabledignored if blending is not enabled Measure of Opacity simulate translucent objectssimulate translucent objects –glass, water, etc. composite imagescomposite images antialiasingantialiasing ignored if blending is not enabledignored if blending is not enabled

90 Institute for Computer Graphics90 Alpha Blending Combine pixels with what’s in already in the framebuffer glBlendFunc( src, dst ); C o = src * C i + dst * C f GL_ONE GL_ZERO GL_SRC_ALPHAGL_ONE_MINUS_SRC_ALPHA Combine pixels with what’s in already in the framebuffer glBlendFunc( src, dst ); C o = src * C i + dst * C f GL_ONE GL_ZERO GL_SRC_ALPHAGL_ONE_MINUS_SRC_ALPHA

91 Institute for Computer Graphics91 Pixel-based primitives Bitmaps 2D array of bit masks for pixels2D array of bit masks for pixels –update pixel color based on current color Images 2D array of pixel color information2D array of pixel color information –complete color information for each pixel OpenGL doesn’t understand image formats Bitmaps 2D array of bit masks for pixels2D array of bit masks for pixels –update pixel color based on current color Images 2D array of pixel color information2D array of pixel color information –complete color information for each pixel OpenGL doesn’t understand image formats

92 Institute for Computer Graphics92 Positioning Image Primitives glRasterPos3f( x, y, z ) raster position transformed like geometryraster position transformed like geometry discarded if raster position is outside of viewportdiscarded if raster position is outside of viewport glRasterPos3f( x, y, z ) raster position transformed like geometryraster position transformed like geometry discarded if raster position is outside of viewportdiscarded if raster position is outside of viewport

93 Institute for Computer Graphics93 Rendering Bitmaps glBitmap( width, height, xorig, yorig, xmove, ymove, bitmap ) Render bitmap in current color at ( xorig, yorig )Render bitmap in current color at ( xorig, yorig ) Advance raster position by ( xmove, ymove ) after renderingAdvance raster position by ( xmove, ymove ) after rendering OpenGL uses bitmaps for font rendering each character is stored in a display list containing a bitmapeach character is stored in a display list containing a bitmap glBitmap( width, height, xorig, yorig, xmove, ymove, bitmap ) Render bitmap in current color at ( xorig, yorig )Render bitmap in current color at ( xorig, yorig ) Advance raster position by ( xmove, ymove ) after renderingAdvance raster position by ( xmove, ymove ) after rendering OpenGL uses bitmaps for font rendering each character is stored in a display list containing a bitmapeach character is stored in a display list containing a bitmap

94 Institute for Computer Graphics94 Rendering Images glDrawPixels( width, height, format, type, pixels ) render pixels with lower left of image at current raster positionrender pixels with lower left of image at current raster position numerous formats and data types for specifying storage in memorynumerous formats and data types for specifying storage in memory –best performance by using format and type that matches hardware glDrawPixels( width, height, format, type, pixels ) render pixels with lower left of image at current raster positionrender pixels with lower left of image at current raster position numerous formats and data types for specifying storage in memorynumerous formats and data types for specifying storage in memory –best performance by using format and type that matches hardware

95 Institute for Computer Graphics95 Reading Pixels glReadPixels( x, y, width, height, format, type, pixels ) read pixels from specified ( x,y ) position in framebufferread pixels from specified ( x,y ) position in framebuffer Pixels automatically converted from framebuffer format into requested format and typePixels automatically converted from framebuffer format into requested format and type Framebuffer pixel copy glCopyPixels( x, y, width, height, buffer ) glReadPixels( x, y, width, height, format, type, pixels ) read pixels from specified ( x,y ) position in framebufferread pixels from specified ( x,y ) position in framebuffer Pixels automatically converted from framebuffer format into requested format and typePixels automatically converted from framebuffer format into requested format and type Framebuffer pixel copy glCopyPixels( x, y, width, height, buffer )

96 Institute for Computer Graphics96 From now on…

97 Institute for Computer Graphics97 What we covered so far Not everything on OpenGL Not expert level knowledge General concepts on What OpenGL isWhat OpenGL is What OpenGL can doWhat OpenGL can do How to implement simple featuresHow to implement simple features How to find required informationHow to find required information Not everything on OpenGL Not expert level knowledge General concepts on What OpenGL isWhat OpenGL is What OpenGL can doWhat OpenGL can do How to implement simple featuresHow to implement simple features How to find required informationHow to find required information

98 Institute for Computer Graphics98 Where to start http://www.opengl.org Examples including red book source codesExamples including red book source codes A lot of tips and informationA lot of tips and information Information on recent development and changeInformation on recent development and change http://www.opengl.org Examples including red book source codesExamples including red book source codes A lot of tips and informationA lot of tips and information Information on recent development and changeInformation on recent development and change

99 Institute for Computer Graphics99 Uncovered topics Framebuffer techniquesFramebuffer techniques –masking, stencil, dithering, logical ops, accumulation buffer, … Antialiasing, fog, …Antialiasing, fog, … Curved surfaces (e.g. NURBS)Curved surfaces (e.g. NURBS) Selection and feedbackSelection and feedback Platform dependent techniques (Windows 95/98/NT and X windows)Platform dependent techniques (Windows 95/98/NT and X windows) Framebuffer techniquesFramebuffer techniques –masking, stencil, dithering, logical ops, accumulation buffer, … Antialiasing, fog, …Antialiasing, fog, … Curved surfaces (e.g. NURBS)Curved surfaces (e.g. NURBS) Selection and feedbackSelection and feedback Platform dependent techniques (Windows 95/98/NT and X windows)Platform dependent techniques (Windows 95/98/NT and X windows)

100 Institute for Computer Graphics100 Information Programming guides OpenGL Programming Guide, 3 rd ed.OpenGL Programming Guide, 3 rd ed. OpenGL SuperBible, 2 nd ed.OpenGL SuperBible, 2 nd ed. OpenGL Programming for Windows 95/NTOpenGL Programming for Windows 95/NT http://www.opengl.org/developers/documentation/bo oks.htmlhttp://www.opengl.org/developers/documentation/bo oks.htmlhttp://www.opengl.org/developers/documentation/bo oks.htmlhttp://www.opengl.org/developers/documentation/bo oks.html Programming guides OpenGL Programming Guide, 3 rd ed.OpenGL Programming Guide, 3 rd ed. OpenGL SuperBible, 2 nd ed.OpenGL SuperBible, 2 nd ed. OpenGL Programming for Windows 95/NTOpenGL Programming for Windows 95/NT http://www.opengl.org/developers/documentation/bo oks.htmlhttp://www.opengl.org/developers/documentation/bo oks.htmlhttp://www.opengl.org/developers/documentation/bo oks.htmlhttp://www.opengl.org/developers/documentation/bo oks.html

101 Institute for Computer Graphics101 Assignment (due Feb 26) From the basic shooting game Change flight path of target (1D or 2D)Change flight path of target (1D or 2D) Add explosion of targetAdd explosion of target Different firing (like cannon or whatever)Different firing (like cannon or whatever) Change geometry of gun or targetChange geometry of gun or target More flexible viewMore flexible view Add multiple moving objects to shoot atAdd multiple moving objects to shoot at Add more mouse or keyboard control eventsAdd more mouse or keyboard control events Etc…Etc… From the basic shooting game Change flight path of target (1D or 2D)Change flight path of target (1D or 2D) Add explosion of targetAdd explosion of target Different firing (like cannon or whatever)Different firing (like cannon or whatever) Change geometry of gun or targetChange geometry of gun or target More flexible viewMore flexible view Add multiple moving objects to shoot atAdd multiple moving objects to shoot at Add more mouse or keyboard control eventsAdd more mouse or keyboard control events Etc…Etc…

102 Institute for Computer Graphics102 Information (cont’d) References Online help with Visual C++Online help with Visual C++ man pages on Unix OSman pages on Unix OS WWW information Refer to my OpenGL pageRefer to my OpenGL page –http://www.seas.gwu.edu/~dkim/opengl.html http://www.seas.gwu.edu/~dkim/opengl.html References Online help with Visual C++Online help with Visual C++ man pages on Unix OSman pages on Unix OS WWW information Refer to my OpenGL pageRefer to my OpenGL page –http://www.seas.gwu.edu/~dkim/opengl.html http://www.seas.gwu.edu/~dkim/opengl.html


Download ppt "Institute for Computer Graphics1 The Institute for Computer Graphics An Introduction to OpenGL Programming Dongho Kim An Introduction to OpenGL Programming."

Similar presentations


Ads by Google