An Interactive Introduction To Opengl Programming
An Interactive Introduction To Opengl Programming
An Interactive Introduction To Opengl Programming
OpenGL Programming
Ed Angel
Dave Shreiner
Vicki Shreiner
Welcome
http://www.opengl-redbook.com/s2006/
• Executables and Source Code available
– Microsoft Windows
– Linux
– Apple (as soon as we can)
What Is OpenGL, and What
Can It Do for Me?
• OpenGL is a computer graphics rendering API
– Generate high-quality color images by rendering with
geometric and image primitives
– Create interactive applications with 3D graphics
– OpenGL is
• operating system independent
• window system independent
Related APIs
application program
OpenGL Motif
widget or similar GLUT
GLX, AGL
or WGL GLU
Configure
and open a
Initialize
window
OpenGL’s
state Process
user events
Draw an
image
An OpenGL Program
#include <GL/glut.h>
#include "cube.h"
glBegin( GL_QUADS );
for ( i = 0; i < NUM_CUBE_FACES; ++i ) { Have OpenGL
glColor3fv( faceColor[i] ); draw a cube
for ( j = 0; j < NUM_VERTICES_PER_FACE; ++j ) {
glVertex3fv( vertex[face[i][j]] );
from some
} 3D points
} (vertices)
glEnd();
glFlush();
}
OpenGL Command Formats
glVertex3fv( v )
• Libraries
• Enumerated Types
– OpenGL defines numerous types for compatibility
• GLfloat, GLint, GLenum, etc.
GLUT Basics
• Application Structure:
– Configure and open window
– Initialize OpenGL state
– Register input callback functions
– Enter event processing loop
GLUT Callback Functions
• Geometric primitives
– points, lines and polygons
• Image Primitives
– images and bitmaps
– separate pipeline for images and geometry
• linked through texture mapping
• Rendering depends on state
– colors, materials, light sources, etc.
OpenGL Geometric Primitives
GL_POINTS GL_POLYGON
GL_LINES GL_LINE_STRIP
GL_LINE_LOOP
GL_TRIANGLES
GL_QUAD_STRIP
GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
GL_QUADS
Specifying Geometric
Primitives
• Primitives are specified using
glBegin( primType );
glEnd();
• primType determines how vertices are combined
glBegin( primType );
for ( i = 0; i < n; ++i ) {
glColor3f( red[i], green[i], blue[i] );
glVertex3fv( coords[i] );
}
glEnd();
How OpenGL Works:
The Conceptual Model
Configure
how OpenGL
Draw stuff
should draw
stuff
Controlling OpenGL’s
Drawing
• Set OpenGL’s rendering state
– State controls how things are drawn
• shading – lighting
• texture maps – line styles (stipples)
• polygon patterns – transparency
The Power of Setting OpenGL
State
Appearance is
controlled by
setting
OpenGL’s
state.
Setting OpenGL State
glMaterialfv()
OpenGL and Color
camera
tripod model
Camera Analogy and
Transformations
• Projection transformations
– adjust the lens of the camera
• Viewing transformations
– tripod–define position and orientation of the viewing volume
in the world
• Modeling transformations
– moving the model
• Viewport transformations
– enlarge or reduce the physical photograph
Coordinate Systems and
Transformations
• Steps in forming an image
1. specify geometry (world coordinates)
2. specify camera (camera coordinates)
3. project (window coordinates)
4. map to viewport (screen coordinates)
• Each step uses transformations
• Every transformation is equivalent to a change in
coordinate systems (frames)
Homogeneous Coordinates
– each vertex is a column vector
x
y
v
z
w
– w is usually 1.0
– all operations are matrix multiplications
– directions (directed line segments) can be represented
with w = 0.0
3D Transformations
• A vertex is transformed by 4 x 4 matrices
– all affine operations are matrix multiplications
– all matrices are stored column-major in OpenGL
– matrices are always post-multiplied
– product of matrix and vector is Mv
m0 m4 m8 m12
m m5 m9 m13
M 1
m2 m6 m10 m14
m3 m7 m11 m15
Specifying Transformations
• Move object
glTranslate{fd}( x, y, z )
• Rotate object around arbitrary axis x y z
glRotate{fd}( angle, x, y, z )
– angle is in degrees
• Dilate (stretch or shrink) or mirror object
glScale{fd}( x, y, z )
Transformation Tutorial
Connection: Viewing and
Modeling
• Moving camera is equivalent to moving every
object in the world towards a stationary
camera
• Viewing transformations are equivalent to
several modeling transformations
– gluLookAt() has its own command
– can make your own polar view or pilot view
Compositing Modeling
Transformations
• Problem: hierarchical objects
– one position depends upon a previous position
– robot arm or hand; sub-assemblies
• Solution: moving local coordinate system
– modeling transformations move coordinate system
– post-multiply column-major matrices
– OpenGL post-multiplies matrices
Compositing Modeling
Transformations (cont’d.)
• Problem: objects move relative to absolute world origin
– my object rotates around the wrong origin
• make it spin around its center or something else
• Solution: fixed coordinate system
– modeling transformations move objects around fixed
coordinate system
– pre-multiply column-major matrices
– OpenGL post-multiplies matrices
– must reverse order of operations to achieve desired effect
Additional Clipping Planes
1 1
2 2
4 4
Front 8 8 Back
16 16
Buffer Buffer
Display
Animation Using Double
Buffering
Request
Request aa double
double buffered
buffered color
color buffer
buffer
glutInitDisplayMode(
glutInitDisplayMode( GLUT_RGB GLUT_DOUBLE );
GLUT_RGB || GLUT_DOUBLE );
Clear
Clear color
color buffer
buffer
glClear(
glClear( GL_COLOR_BUFFER_BIT
GL_COLOR_BUFFER_BIT );
);
Render
Render scene
scene
Request
Request swap
swap of
of front
front and
and back
back buffers
buffers
glutSwapBuffers();
glutSwapBuffers();
• Repeat
Repeat steps
steps 22 -- 44 for
for animation
animation
–– Use
Use aa glutIdleFunc()
glutIdleFunc() callback
callback
Depth Buffering and
Hidden Surface Removal
1 1
2 2
4 4
Color 8 8 Depth
16 16
Buffer Buffer
Display
Depth Buffering Using
OpenGL
Request
Request aa depth
depth buffer
buffer
glutInitDisplayMode(
glutInitDisplayMode( GLUT_RGB
GLUT_RGB || GLUT_DOUBLE
GLUT_DOUBLE ||
GLUT_DEPTH
GLUT_DEPTH );
);
Enable
Enable depth
depth buffering
buffering
glEnable(
glEnable( GL_DEPTH_TEST
GL_DEPTH_TEST );
);
Clear
Clear color
color and
and depth
depth buffers
buffers
glClear(
glClear( GL_COLOR_BUFFER_BIT
GL_COLOR_BUFFER_BIT ||
GL_DEPTH_BUFFER_BIT
GL_DEPTH_BUFFER_BIT );
);
Render
Render scene
scene
Swap
Swap color
color buffers
buffers
Lighting
Lighting Principles
– properties
• colors
• position and type
• attenuation
Light Sources (cont'd.)
• Bitmaps
– 2D array of bit masks for pixels
• update pixel color based on current color
• Images
– 2D array of pixel color information
• complete color information for each pixel
• OpenGL does not understand image formats
Pixel Pipeline
TextureM glCopyTex*Image();
emory
glReadPixels(), glCopyPixels()
Positioning Image Primitives
glRasterPos3f( x, y, z )
glWindosPos3f( x, y, z )
– raster position transformed like geometry
– discarded if raster position
is outside of viewport
• may need to fine tune
viewport for desired
results
Raster Position
Rendering Images
z x
geometry screen
t
image
s
Texture Mapping and the
OpenGL Pipeline
• Images and geometry flow through separate
pipelines that join at the rasterizer
– “complex” textures do not affect geometric
complexity
c (0.4, 0.2)
b
B C
0, 0 1, 0 s (0.8, 0.4)
Generating Texture
Coordinates
• Automatically generate texture coords
glTexGen{ifd}[v]()
• specify a plane Ax By Cz D 0
– generate texture coordinates based upon distance from
plane
• generation modes
– GL_OBJECT_LINEAR
– GL_EYE_LINEAR
– GL_SPHERE_MAP
Texture Tutorial
Texture Mapping
Part 2
Applying Textures II
–– specify
specify textures
textures inin texture
texture objects
objects
–– set
set texture
texture filter
filter
–– set
set texture
texture function
function
–– set
set texture
texture wrap
wrap mode
mode
–– set
set optional
optional perspective
perspective correction
correction hint
hint
–– bind
bind texture
texture object
object
–– enable
enable texturing
texturing
–– supply
supply texture
texture coordinates
coordinates for
for vertex
vertex
•• coordinates
coordinates can
can also
also be
be generated
generated
Texture Application Methods
• Filter Modes
– minification or magnification
– special mipmap minification filters
• Wrap Modes
– clamping or repeating
• Texture Functions
– how to mix primitive’s color with texture’s color
• blend, modulate or replace texels
Filter Modes
Example:
glTexParameteri( target, type, mode );
• Example:
glTexParameteri( GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP )
glTexParameteri( GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_REPEAT )
s
GL_REPEAT GL_CLAMP
texture wrapping wrapping
Texture Functions
Per Vertex
Polynomial Operations &
Evaluator Primitive
Assembly
Display Listed
Texture
Memory
Pixel
Operations
Display Lists
•• Vertex
Vertex Arrays
Arrays
•• Bernstein
Bernstein Polynomial
Polynomial Evaluators
Evaluators
–– basis
basis for
for GLU
GLU NURBS
NURBS
•• NURBS
NURBS (Non-Uniform
(Non-Uniform Rational
Rational B-Splines)
B-Splines)
•• GLU
GLU Quadric
Quadric Objects
Objects
–– sphere
sphere
–– cylinder
cylinder (or
(or cone)
cone)
–– disk
disk (circle)
(circle)
Alpha: the 4th Color
Component
• Measure of Opacity
– simulate translucent objects
• glass, water, etc.
– composite images
– antialiasing
– ignored if blending is not enabled
glEnable( GL_BLEND )
Blending
Example of bump-mapping
done with a multi-pass
OpenGL algorithm
Antialiasing
Scissor
Scissor Alpha
Alpha Stencil
Stencil
Test
Test Test
Test Test
Test
Framebuffer
Depth
Depth Logical
Logical
Blending
Blending Dithering
Dithering
Test
Test Operations
Operations
Alpha Test
Geometry Fragment
Rasterization Processing
Processing
pixels
Frame
Buffer
Geometry Processing
• Coordinate Transformations
• Primitive Assembly
• Clipping
• Per-vertex lighting
• Programmable through a vertex program or
vertex shader
Rasterizer
Ed Angel
Dave Shreiner
Vicki Shreiner
On-Line Resources
– http://www.opengl.org
• start here; up to date specification and lots of sample code
– news:comp.graphics.api.opengl
– http://www.sgi.com/software/opengl
– http://www.mesa3d.org/
• Brian Paul’s Mesa 3D
– http://www.cs.utah.edu/~narobins/opengl.html
• very special thanks to Nate Robins for the OpenGL Tutors
• source code for tutors available here!
Books