Institute for Computer Graphi cs 1 The Institute for Computer The Institute for Computer Graphics Graphics An Introduction to An Introduction to OpenGL Programming OpenGL Programming Dongho Kim Dongho Kim
Dec 31, 2015
Institute for Computer Graphics1
The Institute for Computer GraphicsThe Institute for Computer Graphics
An Introduction toAn Introduction to
OpenGL ProgrammingOpenGL Programming
Dongho KimDongho Kim
An Introduction toAn Introduction to
OpenGL ProgrammingOpenGL Programming
Dongho KimDongho Kim
Institute for Computer Graphics2
About Today’s Lecture
Based on the material used for Graphics Tools Based on the material used for Graphics Tools class last yearclass last year
Schedule of lecturesSchedule 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 ProgrammingStuffs related to Game Programming
– Advanced features, such as Vertex / Pixel shaderAdvanced features, such as Vertex / Pixel shader
Based on the material used for Graphics Tools Based on the material used for Graphics Tools class last yearclass last year
Schedule of lecturesSchedule 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 ProgrammingStuffs related to Game Programming
– Advanced features, such as Vertex / Pixel shaderAdvanced features, such as Vertex / Pixel shader
Institute for Computer Graphics3
OverviewOpenGL IntroductionOpenGL Introduction
Elementary RenderingElementary Rendering
Display Lists GraphicsDisplay Lists Graphics
TransformationsTransformations
LightingLighting
Texture MappingTexture Mapping
Additional Rendering AttributesAdditional Rendering Attributes
ImagingImaging
OpenGL IntroductionOpenGL Introduction
Elementary RenderingElementary Rendering
Display Lists GraphicsDisplay Lists Graphics
TransformationsTransformations
LightingLighting
Texture MappingTexture Mapping
Additional Rendering AttributesAdditional Rendering Attributes
ImagingImaging
Institute for Computer Graphics4
What Is OpenGL?
Graphics Rendering APIGraphics Rendering API
• high-quality color images composed of geometric high-quality color images composed of geometric and image primitivesand image primitives
• window system independentwindow system independent
• operating system independentoperating system independent
Graphics Rendering APIGraphics Rendering API
• high-quality color images composed of geometric high-quality color images composed of geometric and image primitivesand image primitives
• window system independentwindow system independent
• operating system independentoperating system independent
Institute for Computer Graphics5
OpenGL as a Renderer
Geometric primitivesGeometric primitives
• points, lines and polygonspoints, lines and polygons
Image PrimitivesImage Primitives
• images and bitmapsimages and bitmaps
• separate pipelines for images and geometryseparate pipelines for images and geometry
– linked through texture mappinglinked through texture mapping
Rendering depends on stateRendering depends on state
• Colors, materials, light sources, etc.Colors, materials, light sources, etc.
Geometric primitivesGeometric primitives
• points, lines and polygonspoints, lines and polygons
Image PrimitivesImage Primitives
• images and bitmapsimages and bitmaps
• separate pipelines for images and geometryseparate pipelines for images and geometry
– linked through texture mappinglinked through texture mapping
Rendering depends on stateRendering depends on state
• Colors, materials, light sources, etc.Colors, materials, light sources, etc.
Institute for Computer Graphics6
Related APIsAGL, GLX, WGLAGL, GLX, WGL• glue between OpenGL and windowing systemsglue between OpenGL and windowing systems
GLU (OpenGL Utility Library)GLU (OpenGL Utility Library)• Part of OpenGLPart of OpenGL
• NURBS, tessellators, quadric shapes, etc.NURBS, tessellators, quadric shapes, etc.
GLUT (OpenGL Utility Toolkit)GLUT (OpenGL Utility Toolkit)• Portable windowing APIPortable windowing API
• Not officially part of OpenGLNot officially part of OpenGL
AGL, GLX, WGLAGL, GLX, WGL• glue between OpenGL and windowing systemsglue between OpenGL and windowing systems
GLU (OpenGL Utility Library)GLU (OpenGL Utility Library)• Part of OpenGLPart of OpenGL
• NURBS, tessellators, quadric shapes, etc.NURBS, tessellators, quadric shapes, etc.
GLUT (OpenGL Utility Toolkit)GLUT (OpenGL Utility Toolkit)• Portable windowing APIPortable windowing API
• Not officially part of OpenGLNot officially part of OpenGL
Institute for Computer Graphics7
OpenGL and Related APIs
application programapplication program
X, Win32, Mac O/SX, Win32, Mac O/S
software and/or hardwaresoftware and/or hardware
GLGL
GLX, AGLOr WGL
OpenGL Motifwidget or similar
GLU
GLUT
Institute for Computer Graphics8
Preliminaries
Header FilesHeader Files
#include <GL/gl.h>#include <GL/gl.h>
#include <GL/glu.h>#include <GL/glu.h>
#include <GL/glut.h>#include <GL/glut.h>
LibrariesLibraries
Enumerated TypesEnumerated Types
• OpenGL defines numerous types for compatibilityOpenGL defines numerous types for compatibility
GLfloat, GLint, GLenumGLfloat, GLint, GLenum,, etc. etc.
Header FilesHeader Files
#include <GL/gl.h>#include <GL/gl.h>
#include <GL/glu.h>#include <GL/glu.h>
#include <GL/glut.h>#include <GL/glut.h>
LibrariesLibraries
Enumerated TypesEnumerated Types
• OpenGL defines numerous types for compatibilityOpenGL defines numerous types for compatibility
GLfloat, GLint, GLenumGLfloat, GLint, GLenum,, etc. etc.
Institute for Computer Graphics9
GLUT Basics
Application StructureApplication Structure
• Configure and open windowConfigure and open window
• Initialize OpenGL stateInitialize OpenGL state
• Register input callback functionsRegister input callback functions
– renderrender
– resizeresize
– input: keyboard, mouse, etc.input: keyboard, mouse, etc.
• Enter event processing loopEnter event processing loop
Application StructureApplication Structure
• Configure and open windowConfigure and open window
• Initialize OpenGL stateInitialize OpenGL state
• Register input callback functionsRegister input callback functions
– renderrender
– resizeresize
– input: keyboard, mouse, etc.input: keyboard, mouse, etc.
• Enter event processing loopEnter event processing loop
Institute for Computer Graphics10
Sample Programvoid 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();}
Institute for Computer Graphics11
OpenGL Initialization
Set up whatever state you’re going to useSet 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 useSet 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 );
}
Institute for Computer Graphics12
GLUT Callback Functions
Routine to call when something happensRoutine to call when something happens• window resize of redrawwindow resize of redraw
• user inputuser input
• animationanimation
““Register” callbacks with GLUTRegister” callbacks with GLUT glutDisplayFunc( display ); glutIdleFunc( idle ); glutKeyboardFunc( key );
Routine to call when something happensRoutine to call when something happens• window resize of redrawwindow resize of redraw
• user inputuser input
• animationanimation
““Register” callbacks with GLUTRegister” callbacks with GLUT glutDisplayFunc( display ); glutIdleFunc( idle ); glutKeyboardFunc( key );
Institute for Computer Graphics13
Rendering CallbackDo all of your drawing hereDo 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 hereDo 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();}
Institute for Computer Graphics14
Idle Callbacks
Use for animation and continuous updateUse for animation and continuous update glutIdleFunc( idle );
void idle( void ){ t += dt; glutPostRedisplay();}
Use for animation and continuous updateUse for animation and continuous update glutIdleFunc( idle );
void idle( void ){ t += dt; glutPostRedisplay();}
Institute for Computer Graphics15
User Input CallbacksProcess user inputProcess 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 inputProcess 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; }}
Institute for Computer Graphics16
Elementary RenderingElementary RenderingElementary RenderingElementary Rendering
Institute for Computer Graphics17
Elementary Rendering
Geometric PrimitivesGeometric Primitives
Managing OpenGL StateManaging OpenGL State
OpenGL BuffersOpenGL Buffers
Geometric PrimitivesGeometric Primitives
Managing OpenGL StateManaging OpenGL State
OpenGL BuffersOpenGL Buffers
Institute for Computer Graphics18
OpenGL Geometric Primitives
All geometric primitives are specified by All geometric primitives are specified by verticesverticesAll geometric primitives are specified by All geometric primitives are specified by verticesvertices
Institute for Computer Graphics19
Simple Examplevoid 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();}
Institute for Computer Graphics20
OpenGL Command Formats
2 – (x,y)3 – (x,y,z)4 – (x,y,z,w)
b – byteub – unsigned bytes – shortus – unsigned shorti – intui – unsigned intf – floatd - double
Omit “v” forScalar form
glVertex2f( x, y )
Number of Components
Data Type Vector
glVertex3fv( v )
Institute for Computer Graphics21
Primitives are specified usingPrimitives are specified usingglBegin( primType );glEnd();
• primTypeprimType determines how vertices are combined determines how vertices are combined
Primitives are specified usingPrimitives are specified usingglBegin( primType );glEnd();
• primTypeprimType determines how vertices are combined 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();
Institute for Computer Graphics22
OpenGL Color ModelsRGBA or Color IndexRGBA or Color Index• glColor*()glColor*()
• glIndex*()glIndex*()
RGBA or Color IndexRGBA or Color Index• glColor*()glColor*()
• glIndex*()glIndex*()
Frame
Buffer
RR GG BB
00
11
22
33
……
color index mode
Display
RGBA mode
Institute for Computer Graphics23
Shapes Tutorial
Run shapes tutorialRun shapes tutorialRun shapes tutorialRun shapes tutorial
Institute for Computer Graphics24
Advanced Primitives
Vertex ArraysVertex Arrays
Bernstein Polynomial EvaluatorsBernstein Polynomial Evaluators
• basis for GLU NURBSbasis for GLU NURBS
– NURBS (Non-Uniform Rational B-Spline)NURBS (Non-Uniform Rational B-Spline)
GLU Quadric ObjectsGLU Quadric Objects
• spheresphere
• cylinder (or cone)cylinder (or cone)
• disk (circle)disk (circle)
Vertex ArraysVertex Arrays
Bernstein Polynomial EvaluatorsBernstein Polynomial Evaluators
• basis for GLU NURBSbasis for GLU NURBS
– NURBS (Non-Uniform Rational B-Spline)NURBS (Non-Uniform Rational B-Spline)
GLU Quadric ObjectsGLU Quadric Objects
• spheresphere
• cylinder (or cone)cylinder (or cone)
• disk (circle)disk (circle)
Institute for Computer Graphics25
OpenGL’s State Machine
All rendering attributes are encapsulated in All rendering attributes are encapsulated in the OpenGL Statethe OpenGL State
• rendering stylesrendering styles
• shadingshading
• lightinglighting
• texture mappingtexture mapping
All rendering attributes are encapsulated in All rendering attributes are encapsulated in the OpenGL Statethe OpenGL State
• rendering stylesrendering styles
• shadingshading
• lightinglighting
• texture mappingtexture mapping
Institute for Computer Graphics26
Manipulating OpenGL StateAppearance is controlled by current stateAppearance is controlled by current state
for each ( primitive to render ) {for each ( primitive to render ) {
update OpenGL stateupdate OpenGL state
render primitiverender primitive
}}
Manipulating vertex attributes is most common Manipulating vertex attributes is most common way to manipulate stateway to manipulate state
glColor*() / glIndex*()
glNormal*()
glTexCoord*()
Appearance is controlled by current stateAppearance is controlled by current state
for each ( primitive to render ) {for each ( primitive to render ) {
update OpenGL stateupdate OpenGL state
render primitiverender primitive
}}
Manipulating vertex attributes is most common Manipulating vertex attributes is most common way to manipulate stateway to manipulate state
glColor*() / glIndex*()
glNormal*()
glTexCoord*()
Institute for Computer Graphics27
Controlling current state
Setting StateSetting StateglPointSize( size );glLineStipple( repeat, pattern );glShadeModel( GL_SMOOTH );
Enabling FeaturesEnabling FeaturesglEnable( GL_LIGHTING );glDisable( GL_TEXTURE_2D );
Setting StateSetting StateglPointSize( size );glLineStipple( repeat, pattern );glShadeModel( GL_SMOOTH );
Enabling FeaturesEnabling FeaturesglEnable( GL_LIGHTING );glDisable( GL_TEXTURE_2D );
Institute for Computer Graphics28
OpenGL Buffers
ColorColor
• for double buffering, divided into front and backfor double buffering, divided into front and back
AlphaAlpha
DepthDepth
StencilStencil
AccumulationAccumulation
ColorColor
• for double buffering, divided into front and backfor double buffering, divided into front and back
AlphaAlpha
DepthDepth
StencilStencil
AccumulationAccumulation
Institute for Computer Graphics29
Clearing Buffers
Setting clear valuesSetting clear valuesglClearColor( r, g, b, a );glClearDepth( 1.0 );
Clearing buffersClearing buffersglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
Setting clear valuesSetting clear valuesglClearColor( r, g, b, a );glClearDepth( 1.0 );
Clearing buffersClearing buffersglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
Institute for Computer Graphics30
Animation Using Double Buffering
1) Request a double buffered color buffer1) Request a double buffered color bufferglutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE );
2) Clear color buffer2) Clear color bufferglClear( GL_COLOR_BUFFER_BIT );
3) Render Scene3) Render Scene
4) Request swap of front and back buffers4) Request swap of front and back buffersglutSwapBuffers();
Repeat steps 2-4 for animationRepeat steps 2-4 for animation
1) Request a double buffered color buffer1) Request a double buffered color bufferglutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE );
2) Clear color buffer2) Clear color bufferglClear( GL_COLOR_BUFFER_BIT );
3) Render Scene3) Render Scene
4) Request swap of front and back buffers4) Request swap of front and back buffersglutSwapBuffers();
Repeat steps 2-4 for animationRepeat steps 2-4 for animation
Institute for Computer Graphics31
Depth Buffering Using OpenGL1) Request a double buffered color buffer1) Request a double buffered color buffer
glutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE |
GLUT_DEPTH );
2) Enable depth buffering2) Enable depth bufferingglEnable( GL_DEPTH_TEST );
3) Clear color buffer3) Clear color bufferglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
4) Render Scene4) Render Scene
5) Swap color buffers5) Swap color buffers
1) Request a double buffered color buffer1) Request a double buffered color bufferglutInitDisplayMode( GLUT_RGB | GLUT_DOUBLE |
GLUT_DEPTH );
2) Enable depth buffering2) Enable depth bufferingglEnable( GL_DEPTH_TEST );
3) Clear color buffer3) Clear color bufferglClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
4) Render Scene4) Render Scene
5) Swap color buffers5) Swap color buffers
Institute for Computer Graphics32
A Program Templatevoid 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();
}
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 );}
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();
}
Institute for Computer Graphics35
Immediate Mode andImmediate Mode and
Display Lists GraphicsDisplay Lists Graphics
Immediate Mode andImmediate Mode and
Display Lists GraphicsDisplay Lists Graphics
Institute for Computer Graphics36
Immediate vs Retained Mode
Immediate Mode GraphicsImmediate 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 GraphicsRetained 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 GraphicsImmediate 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 GraphicsRetained 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
Institute for Computer Graphics37
Display Listssteps: create it, then call itsteps: create it, then call itGLuint 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 itsteps: create it, then call itGLuint id;void init( void ){
id = glGenLists( 1 );glNewList( id, GL_COMPILE );/* other OpenGL routines */glEndList();
}
void display( void ){
glCallList( id );}
Institute for Computer Graphics38
Modeling with Display Lists#define BOX 1 /* or any other integer */
glNewList( BOX, GL_COMPILE );glBegin( GL_QUADS );
glVertex3d( … );glVertex3d( … );
…glEnd();
glEndList();
#define BOX 1 /* or any other integer */
glNewList( BOX, GL_COMPILE );glBegin( GL_QUADS );
glVertex3d( … );glVertex3d( … );
…glEnd();
glEndList();
Institute for Computer Graphics39
Creating InstancesglPushMatrix();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();
Institute for Computer Graphics40
Display Lists
Not all OpenGL routines can be stored in Not all OpenGL routines can be stored in display listsdisplay lists
State changes persist, even after a display list is State changes persist, even after a display list is finishedfinished
Display lists can call other display listsDisplay lists can call other display lists
Display lists are not editable, but you can fake itDisplay 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 Not all OpenGL routines can be stored in display listsdisplay lists
State changes persist, even after a display list is State changes persist, even after a display list is finishedfinished
Display lists can call other display listsDisplay lists can call other display lists
Display lists are not editable, but you can fake itDisplay 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
Institute for Computer Graphics41
Display Lists and Hierarchy
Consider model of a carConsider 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 carConsider 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();
Institute for Computer Graphics42
TransformationsTransformationsTransformationsTransformations
Institute for Computer Graphics43
Transformations
Prior to rendering, view, locate, and orientPrior to rendering, view, locate, and orient
• eye/camera positioneye/camera position
• 3D geometry3D geometry
Manage the matricesManage the matrices
• including matrix stackincluding matrix stack
Combine (composite) transformationsCombine (composite) transformations
Prior to rendering, view, locate, and orientPrior to rendering, view, locate, and orient
• eye/camera positioneye/camera position
• 3D geometry3D geometry
Manage the matricesManage the matrices
• including matrix stackincluding matrix stack
Combine (composite) transformationsCombine (composite) transformations
Institute for Computer Graphics44
3D MathematicsA vertex is transformed by matricesA vertex is transformed by matrices• each vertex is a column vector each vertex is a column vector vv, (, (x, y, z, wx, y, z, w))TT where where ww is usually is usually
1.01.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 product of matrix and vector is MMvv
Programmer does not have to remember the Programmer does not have to remember the exact matricesexact matrices
A vertex is transformed by matricesA vertex is transformed by matrices• each vertex is a column vector each vertex is a column vector vv, (, (x, y, z, wx, y, z, w))TT where where ww is usually is usually
1.01.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 product of matrix and vector is MMvv
Programmer does not have to remember the Programmer does not have to remember the exact matricesexact matrices
151173
141062
13951
12840
mmmm
mmmm
mmmm
mmmm
Institute for Computer Graphics45
Camera AnalogyProjection transformationsProjection transformations• adjust the lens of the cameraadjust the lens of the camera
Viewing transformationsViewing transformations• tripod-define position and orientation of the viewing volume in tripod-define position and orientation of the viewing volume in
the worldthe world
Modeling transformationsModeling transformations• moving the modelmoving the model
Viewport transformationsViewport transformations• enlarge or reduce the physical photographenlarge or reduce the physical photograph
Projection transformationsProjection transformations• adjust the lens of the cameraadjust the lens of the camera
Viewing transformationsViewing transformations• tripod-define position and orientation of the viewing volume in tripod-define position and orientation of the viewing volume in
the worldthe world
Modeling transformationsModeling transformations• moving the modelmoving the model
Viewport transformationsViewport transformations• enlarge or reduce the physical photographenlarge or reduce the physical photograph
Institute for Computer Graphics46
Transformation Pipeline
Vertex
Vertex
Modelview
Matrix
Modelview
Matrix
ModelviewModelview
ModelviewModelview
Projection
Matrix
Projection
Matrix
ProjectionProjection
Perspective
Division
Perspective
Division
Viewport
Transform
Viewport
Transform
object windoweyenormalized
deviceclip
Institute for Computer Graphics47
Matrix Operations
Specify Current Matrix StackSpecify Current Matrix StackglMatrixMode(GL_MODELVIEW or GL_PROJECTION)
Other Matrix or Stack OperationsOther Matrix or Stack OperationsglLoadIdentity()glPushMatrix()glPopMatrix()
Specify Current Matrix StackSpecify Current Matrix StackglMatrixMode(GL_MODELVIEW or GL_PROJECTION)
Other Matrix or Stack OperationsOther Matrix or Stack OperationsglLoadIdentity()glPushMatrix()glPopMatrix()
Institute for Computer Graphics48
Transformation hierarchy exampleglLoadIdentity()glLoadIdentity()Transformation 1Transformation 1Draw something (T1)Draw something (T1)glPushMatrix()glPushMatrix()
Transformation 2 Transformation 2 glPushMatrix()glPushMatrix()
Transformation 3 Transformation 3 Draw something (T1*T2*T3)Draw something (T1*T2*T3)glLoadIdentity()glLoadIdentity()Draw something (I)Draw something (I)
glPopMatrix()glPopMatrix()Draw something (T1*T2)Draw something (T1*T2)
glPopMatrix()glPopMatrix()Draw something (T1)Draw something (T1)
glLoadIdentity()glLoadIdentity()Transformation 1Transformation 1Draw something (T1)Draw something (T1)glPushMatrix()glPushMatrix()
Transformation 2 Transformation 2 glPushMatrix()glPushMatrix()
Transformation 3 Transformation 3 Draw something (T1*T2*T3)Draw something (T1*T2*T3)glLoadIdentity()glLoadIdentity()Draw something (I)Draw something (I)
glPopMatrix()glPopMatrix()Draw something (T1*T2)Draw something (T1*T2)
glPopMatrix()glPopMatrix()Draw something (T1)Draw something (T1)
Institute for Computer Graphics49
Viewport Transformation
ViewportViewport
• Usually same as window sizeUsually same as window size
• Viewport aspect ratio should be same as projection Viewport aspect ratio should be same as projection transformation or resulting image may be distortedtransformation or resulting image may be distorted
glViewport( x, y, width, height );
ViewportViewport
• Usually same as window sizeUsually same as window size
• Viewport aspect ratio should be same as projection Viewport aspect ratio should be same as projection transformation or resulting image may be distortedtransformation or resulting image may be distorted
glViewport( x, y, width, height );
Institute for Computer Graphics50
Projection Transformation
Shape of viewing frustumShape of viewing frustum
Perspective projectionPerspective projectiongluPerspective( fovy, aspect, zNear, zFar )glFrustum( left, right, bottom, top, zNear, zFar )
Orthographic parallel projectionOrthographic parallel projectionglOrtho( left, right, bottom, top, zNear, zFar )gluOrtho2D( left, right, bottom, top )
• calls calls glOrthoglOrtho with with zz values near zero values near zero
Shape of viewing frustumShape of viewing frustum
Perspective projectionPerspective projectiongluPerspective( fovy, aspect, zNear, zFar )glFrustum( left, right, bottom, top, zNear, zFar )
Orthographic parallel projectionOrthographic parallel projectionglOrtho( left, right, bottom, top, zNear, zFar )gluOrtho2D( left, right, bottom, top )
• calls calls glOrthoglOrtho with with zz values near zero values near zero
Institute for Computer Graphics51
Viewing TransformationsPosition the camera/eye in the scenePosition the camera/eye in the scene• place the tripod down; aim cameraplace the tripod down; aim camera
To “fly through” a sceneTo “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 scenePosition the camera/eye in the scene• place the tripod down; aim cameraplace the tripod down; aim camera
To “fly through” a sceneTo “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
Institute for Computer Graphics52
Projection Tutorial
Run projection tutorialRun projection tutorialRun projection tutorialRun projection tutorial
Institute for Computer Graphics53
Modeling Transformations
Move ObjectMove Object
glTranslate{fd}( x, y, z )
Rotate object around arbitrary axis (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 objectDilate (stretch or shrink) or mirror object
glScale{fd}( x, y, z )
Move ObjectMove Object
glTranslate{fd}( x, y, z )
Rotate object around arbitrary axis (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 objectDilate (stretch or shrink) or mirror object
glScale{fd}( x, y, z )
Institute for Computer Graphics54
Transformation Tutorial
Run transformation tutorialRun transformation tutorialRun transformation tutorialRun transformation tutorial
Institute for Computer Graphics55
Connection: Viewing and Modeling
• Moving camera is equivalent to moving Moving camera is equivalent to moving every object in the world towards a every object in the world towards a stationary camerastationary camera
• Viewing transformations are equivalent to Viewing transformations are equivalent to several modeling transformationsseveral modeling transformations
gluLookAt()gluLookAt() has its own command has its own command
can make your own can make your own polar viewpolar view or or pilot viewpilot view
• Moving camera is equivalent to moving Moving camera is equivalent to moving every object in the world towards a every object in the world towards a stationary camerastationary camera
• Viewing transformations are equivalent to Viewing transformations are equivalent to several modeling transformationsseveral modeling transformations
gluLookAt()gluLookAt() has its own command has its own command
can make your own can make your own polar viewpolar view or or pilot viewpilot view
Institute for Computer Graphics56
Projection is left handed
Projection transformations (Projection transformations (gluPerspective, gluPerspective,
glOrthoglOrtho) are left handed) are left handed
• think of think of zNearzNear and and zFarzFar as distance from view point as distance from view point
Everything else is right handed, including Everything else is right handed, including the vertices to be renderedthe vertices to be rendered
Projection transformations (Projection transformations (gluPerspective, gluPerspective,
glOrthoglOrtho) are left handed) are left handed
• think of think of zNearzNear and and zFarzFar as distance from view point as distance from view point
Everything else is right handed, including Everything else is right handed, including the vertices to be renderedthe vertices to be rendered
Institute for Computer Graphics57
LightingLightingLightingLighting
Institute for Computer Graphics58
Lighting Principles
Lighting simulates how objects reflect lightLighting 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 lightambient light
– two sided lightingtwo sided lighting
• available in both color index and RGBA modeavailable in both color index and RGBA mode
Lighting simulates how objects reflect lightLighting 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 lightambient light
– two sided lightingtwo sided lighting
• available in both color index and RGBA modeavailable in both color index and RGBA mode
Institute for Computer Graphics59
How OpenGL Simulates Lights
Phong lighting modelPhong lighting model
• Computed at verticesComputed at vertices
Lighting contributorsLighting contributors
• Surface material propertiesSurface material properties
• Light propertiesLight properties
• Lighting model propertiesLighting model properties
Phong lighting modelPhong lighting model
• Computed at verticesComputed at vertices
Lighting contributorsLighting contributors
• Surface material propertiesSurface material properties
• Light propertiesLight properties
• Lighting model propertiesLighting model properties
Institute for Computer Graphics60
Surface Normals
Normals define how a surface reflects Normals define how a surface reflects lightlight
glNormal3f( glNormal3f( x, y, zx, y, z ); );
• Current normal is used to compute vertex’s colorCurrent normal is used to compute vertex’s color
• Use Use unitunit normals for proper lighting normals for proper lighting
– scaling affects a normal’s lengthscaling affects a normal’s length
– glEnable( GL_NORMALIZE );glEnable( GL_NORMALIZE );
Normals define how a surface reflects Normals define how a surface reflects lightlight
glNormal3f( glNormal3f( x, y, zx, y, z ); );
• Current normal is used to compute vertex’s colorCurrent normal is used to compute vertex’s color
• Use Use unitunit normals for proper lighting normals for proper lighting
– scaling affects a normal’s lengthscaling affects a normal’s length
– glEnable( GL_NORMALIZE );glEnable( GL_NORMALIZE );
Institute for Computer Graphics61
Material Properties
Define the surface properties of a primitiveDefine the surface properties of a primitive
glMaterialfv( glMaterialfv( face, property, valueface, property, value ); );
• Separate materials for front and backSeparate materials for front and back
Define the surface properties of a primitiveDefine the surface properties of a primitive
glMaterialfv( glMaterialfv( face, property, valueface, property, value ); );
• Separate materials for front and backSeparate materials for front and back
GL_DIFFUSEGL_DIFFUSE Base colorBase color
GL_SPECULARGL_SPECULAR Highlight colorHighlight color
GL_AMBIENTGL_AMBIENT Low-light colorLow-light color
GL_EMISSIONGL_EMISSION Glow colorGlow color
GL_SHININESSGL_SHININESS Surface SmoothnessSurface Smoothness
Institute for Computer Graphics62
Light PropertiesglLightfv( glLightfv( light, property, valuelight, property, value ); );
• lightlight specifies which light specifies which light
– Multiple lights, starting with GL_LIGHT0Multiple lights, starting with GL_LIGHT0
– glGetIntegerv( glGetIntegerv( GL_MAX_LIGHTS, &nGL_MAX_LIGHTS, &n ); );
• propertiesproperties
– colorscolors
– position and typeposition and type
– attenuationattenuation
glLightfv( glLightfv( light, property, valuelight, property, value ); );
• lightlight specifies which light specifies which light
– Multiple lights, starting with GL_LIGHT0Multiple lights, starting with GL_LIGHT0
– glGetIntegerv( glGetIntegerv( GL_MAX_LIGHTS, &nGL_MAX_LIGHTS, &n ); );
• propertiesproperties
– colorscolors
– position and typeposition and type
– attenuationattenuation
Institute for Computer Graphics63
Light Sources (cont.)
Light color propertiesLight color properties
• GL_AMBIENTGL_AMBIENT
• GL_DIFFUSEGL_DIFFUSE
• GL_SPECULARGL_SPECULAR
Light color propertiesLight color properties
• GL_AMBIENTGL_AMBIENT
• GL_DIFFUSEGL_DIFFUSE
• GL_SPECULARGL_SPECULAR
Institute for Computer Graphics64
Types of Lights
OpenGL supports two types of LightsOpenGL 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 coordinateType of light controlled by w coordinate
ww = 0 = 0 Infinite Light directed along Infinite Light directed along (x y z)(x y z)
ww 0 0 Local Light positioned at Local Light positioned at (x/w y/w z/w)(x/w y/w z/w)
OpenGL supports two types of LightsOpenGL 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 coordinateType of light controlled by w coordinate
ww = 0 = 0 Infinite Light directed along Infinite Light directed along (x y z)(x y z)
ww 0 0 Local Light positioned at Local Light positioned at (x/w y/w z/w)(x/w y/w z/w)
Institute for Computer Graphics65
Turning on the Lights
Flip each light’s switchFlip each light’s switch
• glEnable( glEnable( GL_LIGHTnGL_LIGHTn ); );
Turn on the powerTurn on the power
• glEnable( glEnable( GL_LIGHTINGGL_LIGHTING ); );
Flip each light’s switchFlip each light’s switch
• glEnable( glEnable( GL_LIGHTnGL_LIGHTn ); );
Turn on the powerTurn on the power
• glEnable( glEnable( GL_LIGHTINGGL_LIGHTING ); );
Institute for Computer Graphics66
Light Material Tutorial
Run Light Material tutorialRun Light Material tutorialRun Light Material tutorialRun Light Material tutorial
Institute for Computer Graphics67
Controlling a Light’s Position
ModelView matrix affects a light’s positionModelView matrix affects a light’s position
• Different effects based on when position is specifiedDifferent effects based on when position is specified
– eye coordinateseye coordinates
– world coordinatesworld coordinates
– model coordinatesmodel coordinates
• Push and pop matrices to uniquely control a light’s Push and pop matrices to uniquely control a light’s positionposition
ModelView matrix affects a light’s positionModelView matrix affects a light’s position
• Different effects based on when position is specifiedDifferent effects based on when position is specified
– eye coordinateseye coordinates
– world coordinatesworld coordinates
– model coordinatesmodel coordinates
• Push and pop matrices to uniquely control a light’s Push and pop matrices to uniquely control a light’s positionposition
Institute for Computer Graphics68
Light Position Tutorial
Run Light Position tutorialRun Light Position tutorialRun Light Position tutorialRun Light Position tutorial
Institute for Computer Graphics69
Advanced Lighting Features
SpotlightsSpotlights
• localize lighting effectslocalize lighting effects
– GL_SPOT_DIRECTIONGL_SPOT_DIRECTION
– GL_SPOT_CUTOFFGL_SPOT_CUTOFF
– GL_SPOT_EXPONENTGL_SPOT_EXPONENT
SpotlightsSpotlights
• localize lighting effectslocalize lighting effects
– GL_SPOT_DIRECTIONGL_SPOT_DIRECTION
– GL_SPOT_CUTOFFGL_SPOT_CUTOFF
– GL_SPOT_EXPONENTGL_SPOT_EXPONENT
Institute for Computer Graphics70
Advanced Lighting Features
Light AttenuationLight Attenuation
• decrease light intensity with distancedecrease light intensity with distance
– GL_CONTANT_ATTENUATIONGL_CONTANT_ATTENUATION
– GL_LINEAR_ATTENUATIONGL_LINEAR_ATTENUATION
– GL_QUADRIC_ATTENUATIONGL_QUADRIC_ATTENUATION
Light AttenuationLight Attenuation
• decrease light intensity with distancedecrease light intensity with distance
– GL_CONTANT_ATTENUATIONGL_CONTANT_ATTENUATION
– GL_LINEAR_ATTENUATIONGL_LINEAR_ATTENUATION
– GL_QUADRIC_ATTENUATIONGL_QUADRIC_ATTENUATION
2
1
dkdkkf
qlci
Institute for Computer Graphics71
Tips for Better Lighting
Recall lighting computed only at verticesRecall lighting computed only at vertices
• model tessellation heavily affects lighting resultsmodel tessellation heavily affects lighting results
– better results but more geometry to processbetter results but more geometry to process
Use a single infinite light for fastest lightingUse a single infinite light for fastest lighting
• minimal computation per vertexminimal computation per vertex
Recall lighting computed only at verticesRecall lighting computed only at vertices
• model tessellation heavily affects lighting resultsmodel tessellation heavily affects lighting results
– better results but more geometry to processbetter results but more geometry to process
Use a single infinite light for fastest lightingUse a single infinite light for fastest lighting
• minimal computation per vertexminimal computation per vertex
Institute for Computer Graphics72
Texture MappingTexture MappingTexture MappingTexture Mapping
Institute for Computer Graphics73
Texture Mapping
Apply a 1D, 2D, or 3D image to geometric Apply a 1D, 2D, or 3D image to geometric primitivesprimitives
Uses of TexturingUses of Texturing
• simulating materialssimulating materials
• reducing geometric complexityreducing geometric complexity
• image warpingimage warping
• reflectorsreflectors
Apply a 1D, 2D, or 3D image to geometric Apply a 1D, 2D, or 3D image to geometric primitivesprimitives
Uses of TexturingUses of Texturing
• simulating materialssimulating materials
• reducing geometric complexityreducing geometric complexity
• image warpingimage warping
• reflectorsreflectors
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 generatedcoordinates 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 generatedcoordinates can also be generated
Institute for Computer Graphics75
Texture Objects
Like display lists for texture imagesLike 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 namesGenerate texture names
glGenTexture( glGenTexture( n, *texIdsn, *texIds ); );
Like display lists for texture imagesLike 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 namesGenerate texture names
glGenTexture( glGenTexture( n, *texIdsn, *texIds ); );
Institute for Computer Graphics76
Texture Objects (cont’d)
Create texture objects with texture data and Create texture objects with texture data and statestate
glBindTexture( glBindTexture( target, idtarget, id ); );
Bind textures for usingBind textures for using
glBindTexture( glBindTexture( target, idtarget, id ); );
target: GL_TEXTURE_{123}Dtarget: GL_TEXTURE_{123}D
Create texture objects with texture data and Create texture objects with texture data and statestate
glBindTexture( glBindTexture( target, idtarget, id ); );
Bind textures for usingBind textures for using
glBindTexture( glBindTexture( target, idtarget, id ); );
target: GL_TEXTURE_{123}Dtarget: GL_TEXTURE_{123}D
Institute for Computer Graphics77
Specify Texture Image
Define a texture image from an array of Define a texture image from an array of texels in CPU memorytexels in CPU memory
glTexImage2D( glTexImage2D( target, level, target, level, components, w, h, border, format, type, components, w, h, border, format, type, *texels*texels ); );
• dimensions of image must be powers of 2dimensions of image must be powers of 2
Define a texture image from an array of Define a texture image from an array of texels in CPU memorytexels in CPU memory
glTexImage2D( glTexImage2D( target, level, target, level, components, w, h, border, format, type, components, w, h, border, format, type, *texels*texels ); );
• dimensions of image must be powers of 2dimensions of image must be powers of 2
Institute for Computer Graphics78
Converting a Texture Image
If dimensions of image are not power of 2If dimensions of image are not power of 2
gluScaleImage( gluScaleImage( format, w_in, h_in, format, w_in, h_in, type_in, *data_in, w_out, h_out, type_in, *data_in, w_out, h_out, type_out, *data_outtype_out, *data_out ); );
• *_in *_in is for source imageis for source image
• *_out *_out is for destination imageis for destination image
Image interpolated and filtered during Image interpolated and filtered during scalingscaling
If dimensions of image are not power of 2If dimensions of image are not power of 2
gluScaleImage( gluScaleImage( format, w_in, h_in, format, w_in, h_in, type_in, *data_in, w_out, h_out, type_in, *data_in, w_out, h_out, type_out, *data_outtype_out, *data_out ); );
• *_in *_in is for source imageis for source image
• *_out *_out is for destination imageis for destination image
Image interpolated and filtered during Image interpolated and filtered during scalingscaling
Institute for Computer Graphics79
Specifying a Texture: Other MethodsUse frame buffer as source of texture imageUse frame buffer as source of texture image• uses current buffer as source imageuses current buffer as source image
glCopyTexImage2D(…)glCopyTexImage2D(…)
glCopyTexImage1D(…)glCopyTexImage1D(…)
Modify part of a defined textureModify part of a defined texture
glTexSubImage2D(…)glTexSubImage2D(…)
glTexSubImage1D(…)glTexSubImage1D(…)
Do both with Do both with glColyTexSubImage2D(…)glColyTexSubImage2D(…), etc., etc.
Use frame buffer as source of texture imageUse frame buffer as source of texture image• uses current buffer as source imageuses current buffer as source image
glCopyTexImage2D(…)glCopyTexImage2D(…)
glCopyTexImage1D(…)glCopyTexImage1D(…)
Modify part of a defined textureModify part of a defined texture
glTexSubImage2D(…)glTexSubImage2D(…)
glTexSubImage1D(…)glTexSubImage1D(…)
Do both with Do both with glColyTexSubImage2D(…)glColyTexSubImage2D(…), etc., etc.
Institute for Computer Graphics80
Mapping a Texture• Based on parametric texture coordinatesBased on parametric texture coordinates
• glTexCoord*()glTexCoord*() specified at each vertex specified at each vertex
• Based on parametric texture coordinatesBased on parametric texture coordinates
• glTexCoord*()glTexCoord*() specified at each vertex specified at each vertex
Institute for Computer Graphics81
Generating Texture CoordinatesAutomatically generate texture coordinatesAutomatically generate texture coordinates
glTexGen{ifd}[v]()glTexGen{ifd}[v]()
specify a plane Ax+By+Cz+D = 0specify a plane Ax+By+Cz+D = 0• generate texture coordinates based on distance from planegenerate texture coordinates based on distance from plane
generation modesgeneration modes• GL_OBJECT_LINEARGL_OBJECT_LINEAR
• GL_EYE_LINEARGL_EYE_LINEAR
• GL_SPHERE_MAPGL_SPHERE_MAP
Automatically generate texture coordinatesAutomatically generate texture coordinates
glTexGen{ifd}[v]()glTexGen{ifd}[v]()
specify a plane Ax+By+Cz+D = 0specify a plane Ax+By+Cz+D = 0• generate texture coordinates based on distance from planegenerate texture coordinates based on distance from plane
generation modesgeneration modes• GL_OBJECT_LINEARGL_OBJECT_LINEAR
• GL_EYE_LINEARGL_EYE_LINEAR
• GL_SPHERE_MAPGL_SPHERE_MAP
Institute for Computer Graphics82
Texture Application Methods
Filter ModesFilter Modes
• minification or magnificationminification or magnification
• special special mipmapmipmap minification filters minification filters
Wrap ModesWrap Modes
• clamping or repeatingclamping or repeating
Texture FunctionsTexture Functions
• how to mix primitive’s color with texture’s colorhow to mix primitive’s color with texture’s color
– blend, modulate, or replace texelsblend, modulate, or replace texels
Filter ModesFilter Modes
• minification or magnificationminification or magnification
• special special mipmapmipmap minification filters minification filters
Wrap ModesWrap Modes
• clamping or repeatingclamping or repeating
Texture FunctionsTexture Functions
• how to mix primitive’s color with texture’s colorhow to mix primitive’s color with texture’s color
– blend, modulate, or replace texelsblend, modulate, or replace texels
Institute for Computer Graphics83
Filter ModesExample:Example:
glTexParameteri( glTexParameteri( target, type, modetarget, type, mode ); );
GL_NEARESTGL_NEAREST
GL_LINEARGL_LINEAR
GL_NEAREST_MIPMAP_NEARESTGL_NEAREST_MIPMAP_NEAREST
GL_NEAREST_MIPMAP_LINEARGL_NEAREST_MIPMAP_LINEAR
GL_LINEAR_MIPMAP_NEARESTGL_LINEAR_MIPMAP_NEAREST
GL_LINEAR_MIPMAP_LINEARGL_LINEAR_MIPMAP_LINEAR
Example:Example:
glTexParameteri( glTexParameteri( target, type, modetarget, type, mode ); );
GL_NEARESTGL_NEAREST
GL_LINEARGL_LINEAR
GL_NEAREST_MIPMAP_NEARESTGL_NEAREST_MIPMAP_NEAREST
GL_NEAREST_MIPMAP_LINEARGL_NEAREST_MIPMAP_LINEAR
GL_LINEAR_MIPMAP_NEARESTGL_LINEAR_MIPMAP_NEAREST
GL_LINEAR_MIPMAP_LINEARGL_LINEAR_MIPMAP_LINEAR
Institute for Computer Graphics84
Mipmapped TexturesMipmap allows prefiltered texture maps of Mipmap allows prefiltered texture maps of decreasing resolutionsdecreasing resolutions
Lessens interpolation errors for smaller textured Lessens interpolation errors for smaller textured objectsobjects
Declare mipmap level during texture definitionDeclare mipmap level during texture definition
glTexImage*D( glTexImage*D( GL_TEXTURE_*D, level, …GL_TEXTURE_*D, level, … ) )
GLU mipmap builder routinesGLU mipmap builder routines
gluBuild*DMipmaps( gluBuild*DMipmaps( …… ) )
Mipmap allows prefiltered texture maps of Mipmap allows prefiltered texture maps of decreasing resolutionsdecreasing resolutions
Lessens interpolation errors for smaller textured Lessens interpolation errors for smaller textured objectsobjects
Declare mipmap level during texture definitionDeclare mipmap level during texture definition
glTexImage*D( glTexImage*D( GL_TEXTURE_*D, level, …GL_TEXTURE_*D, level, … ) )
GLU mipmap builder routinesGLU mipmap builder routines
gluBuild*DMipmaps( gluBuild*DMipmaps( …… ) )
Institute for Computer Graphics85
Wrapping Mode
Example:Example:
glTexParameteri( GL_TEXTURE_2D, glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )GL_TEXTURE_WRAP_S, GL_CLAMP )
glTexParameteri( GL_TEXTURE_2D, glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )GL_TEXTURE_WRAP_T, GL_REPEAT )
Example:Example:
glTexParameteri( GL_TEXTURE_2D, glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP )GL_TEXTURE_WRAP_S, GL_CLAMP )
glTexParameteri( GL_TEXTURE_2D, glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT )GL_TEXTURE_WRAP_T, GL_REPEAT )
Institute for Computer Graphics86
Texture Functions
Controls how texture is appliedControls how texture is applied
GL_TEXTURE_ENV_MODEGL_TEXTURE_ENV_MODE modes modes
• GL_MODULATEGL_MODULATE
• GL_BLENDGL_BLEND
• GL_REPLACEGL_REPLACE
Set blend color with Set blend color with GL_TEXTURE_ENV_COLORGL_TEXTURE_ENV_COLOR
Controls how texture is appliedControls how texture is applied
GL_TEXTURE_ENV_MODEGL_TEXTURE_ENV_MODE modes modes
• GL_MODULATEGL_MODULATE
• GL_BLENDGL_BLEND
• GL_REPLACEGL_REPLACE
Set blend color with Set blend color with GL_TEXTURE_ENV_COLORGL_TEXTURE_ENV_COLOR
Institute for Computer Graphics87
Texture Tutorial
Run Texture tutorialRun Texture tutorialRun Texture tutorialRun Texture tutorial
Institute for Computer Graphics88
2D Operations2D Operations2D Operations2D Operations
Institute for Computer Graphics89
Alpha: the 4th Color Component
Measure of OpacityMeasure of Opacity
• simulate translucent objectssimulate translucent objects
– glass, water, etc.glass, water, etc.
• composite imagescomposite images
• antialiasingantialiasing
• ignored if blending is not enabledignored if blending is not enabled
Measure of OpacityMeasure of Opacity
• simulate translucent objectssimulate translucent objects
– glass, water, etc.glass, water, etc.
• composite imagescomposite images
• antialiasingantialiasing
• ignored if blending is not enabledignored if blending is not enabled
Institute for Computer Graphics90
Alpha Blending
Combine pixels with what’s in already in Combine pixels with what’s in already in the framebufferthe framebuffer
glBlendFunc( glBlendFunc( src, dstsrc, dst ); );
CCoo = = src src * C* Cii + + dst dst * C* Cff
GL_ONE GL_ONE GL_ZEROGL_ZERO
GL_SRC_ALPHAGL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHAGL_ONE_MINUS_SRC_ALPHA
Combine pixels with what’s in already in Combine pixels with what’s in already in the framebufferthe framebuffer
glBlendFunc( glBlendFunc( src, dstsrc, dst ); );
CCoo = = src src * C* Cii + + dst dst * C* Cff
GL_ONE GL_ONE GL_ZEROGL_ZERO
GL_SRC_ALPHAGL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHAGL_ONE_MINUS_SRC_ALPHA
Institute for Computer Graphics91
Pixel-based primitives
BitmapsBitmaps
• 2D array of bit masks for pixels2D array of bit masks for pixels
– update pixel color based on current colorupdate pixel color based on current color
ImagesImages
• 2D array of pixel color information2D array of pixel color information
– complete color information for each pixelcomplete color information for each pixel
OpenGL doesn’t understand image formatsOpenGL doesn’t understand image formats
BitmapsBitmaps
• 2D array of bit masks for pixels2D array of bit masks for pixels
– update pixel color based on current colorupdate pixel color based on current color
ImagesImages
• 2D array of pixel color information2D array of pixel color information
– complete color information for each pixelcomplete color information for each pixel
OpenGL doesn’t understand image formatsOpenGL doesn’t understand image formats
Institute for Computer Graphics92
Positioning Image Primitives
glRasterPos3f( glRasterPos3f( x, y, zx, 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( glRasterPos3f( x, y, zx, 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
Institute for Computer Graphics93
Rendering Bitmaps
glBitmap( glBitmap( width, height, xorig, yorig, width, height, xorig, yorig, xmove, ymove, bitmapxmove, ymove, bitmap ) )
• Render bitmap in current color at (Render bitmap in current color at (xorig, yorigxorig, yorig))
• Advance raster position by (Advance raster position by (xmove, ymovexmove, ymove) after ) after renderingrendering
OpenGL uses bitmaps for font renderingOpenGL uses bitmaps for font rendering
• each character is stored in a display list containing a each character is stored in a display list containing a bitmapbitmap
glBitmap( glBitmap( width, height, xorig, yorig, width, height, xorig, yorig, xmove, ymove, bitmapxmove, ymove, bitmap ) )
• Render bitmap in current color at (Render bitmap in current color at (xorig, yorigxorig, yorig))
• Advance raster position by (Advance raster position by (xmove, ymovexmove, ymove) after ) after renderingrendering
OpenGL uses bitmaps for font renderingOpenGL uses bitmaps for font rendering
• each character is stored in a display list containing a each character is stored in a display list containing a bitmapbitmap
Institute for Computer Graphics94
Rendering Images
glDrawPixels( glDrawPixels( width, height, format, width, height, format, type, pixelstype, pixels ) )
• render pixels with lower left of image at current render pixels with lower left of image at current raster positionraster position
• numerous formats and data types for specifying numerous formats and data types for specifying storage in memorystorage in memory
– best performance by using format and type that best performance by using format and type that matches hardwarematches hardware
glDrawPixels( glDrawPixels( width, height, format, width, height, format, type, pixelstype, pixels ) )
• render pixels with lower left of image at current render pixels with lower left of image at current raster positionraster position
• numerous formats and data types for specifying numerous formats and data types for specifying storage in memorystorage in memory
– best performance by using format and type that best performance by using format and type that matches hardwarematches hardware
Institute for Computer Graphics95
Reading PixelsglReadPixels( x, y, glReadPixels( x, y, width, height, width, height, format, type, pixelsformat, type, pixels ) )
• read pixels from specified (read pixels from specified (x,yx,y) position in ) position in framebufferframebuffer
• Pixels automatically converted from framebuffer Pixels automatically converted from framebuffer format into requested format and typeformat into requested format and type
Framebuffer pixel copyFramebuffer pixel copy
glCopyPixels( x, y, glCopyPixels( x, y, width, height, width, height, buffer buffer ))
glReadPixels( x, y, glReadPixels( x, y, width, height, width, height, format, type, pixelsformat, type, pixels ) )
• read pixels from specified (read pixels from specified (x,yx,y) position in ) position in framebufferframebuffer
• Pixels automatically converted from framebuffer Pixels automatically converted from framebuffer format into requested format and typeformat into requested format and type
Framebuffer pixel copyFramebuffer pixel copy
glCopyPixels( x, y, glCopyPixels( x, y, width, height, width, height, buffer buffer ))
Institute for Computer Graphics96
From now on…From now on…From now on…From now on…
Institute for Computer Graphics97
What we covered so far
Not everything on OpenGLNot everything on OpenGL
Not expert level knowledgeNot expert level knowledge
General concepts onGeneral 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 OpenGLNot everything on OpenGL
Not expert level knowledgeNot expert level knowledge
General concepts onGeneral 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
Institute for Computer Graphics98
Where to start
http://www.opengl.orghttp://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.orghttp://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
Institute for Computer Graphics99
Uncovered topics• Framebuffer techniquesFramebuffer techniques
– masking, stencil, dithering, logical ops, masking, stencil, dithering, logical ops, accumulation buffer, …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 Platform dependent techniques (Windows 95/98/NT and X windows)and X windows)
• Framebuffer techniquesFramebuffer techniques
– masking, stencil, dithering, logical ops, masking, stencil, dithering, logical ops, accumulation buffer, …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 Platform dependent techniques (Windows 95/98/NT and X windows)and X windows)
Institute for Computer Graphics100
Information
Programming guidesProgramming guides
• OpenGL Programming Guide, 3OpenGL Programming Guide, 3rdrd ed. ed.
• OpenGL SuperBible, 2OpenGL SuperBible, 2ndnd ed. ed.
• OpenGL Programming for Windows 95/NTOpenGL Programming for Windows 95/NT
• http://www.http://www.openglopengl.org/developers/documentation/books.html.org/developers/documentation/books.html
Programming guidesProgramming guides
• OpenGL Programming Guide, 3OpenGL Programming Guide, 3rdrd ed. ed.
• OpenGL SuperBible, 2OpenGL SuperBible, 2ndnd ed. ed.
• OpenGL Programming for Windows 95/NTOpenGL Programming for Windows 95/NT
• http://www.http://www.openglopengl.org/developers/documentation/books.html.org/developers/documentation/books.html
Institute for Computer Graphics101
Assignment (due Feb 26)From the basic shooting gameFrom 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 gameFrom 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…
Institute for Computer Graphics102
Information (cont’d)
ReferencesReferences
• Online help with Visual C++Online help with Visual C++
• man pages on Unix OSman pages on Unix OS
WWW informationWWW information
• Refer to my OpenGL pageRefer to my OpenGL page
– http://www.seas.http://www.seas.gwugwu..eduedu/~/~dkimdkim//openglopengl.html.html
ReferencesReferences
• Online help with Visual C++Online help with Visual C++
• man pages on Unix OSman pages on Unix OS
WWW informationWWW information
• Refer to my OpenGL pageRefer to my OpenGL page
– http://www.seas.http://www.seas.gwugwu..eduedu/~/~dkimdkim//openglopengl.html.html