Professional Documents
Culture Documents
Computer Graphics: Course Notes
Computer Graphics: Course Notes
COMPUTER GRAPHICS
George Wolberg
Department of Computer Science
City College of New York
New York, NY 10031
wolberg@cs.ccny.cuny.edu
Course Description
Intense introduction to computer graphics.
Intended for advanced undergraduate and
graduate students.
Topics include:
Introduction to Computer
Graphics
Prof. George Wolberg
Dept. of Computer Science
City College of New York
Syllabus
Week
1
2-3
4-5
6
7
8-9
10
11
12-14
Texts
Topic
Introduction, history, vector/raster graphics
OpenGL, GLUT, interaction
Geometry, 2D/3D transformations
Projections, perspective
3D viewing
Midterm, Spring break
Geometric modeling
Shading
Curves and surfaces, texture mapping
Required Text:
- Edward Angel, Interactive Computer Graphics:
A Top-Down Approach Using OpenGL, 4th
Edition, Addison-Wesley, 2006.
Supplementary Text:
- Mason Woo, Jackie Nieder, Tom Davis, and
Dave Shreiner, The OpenGL Programmers
Guide, 3rd Edition, Addison-Wesley,1999.
The definitive OpenGL programming reference
3
Grading
Computer Resources
Contact Information
Objectives
Prof. Wolberg
- Office hours: Tuesday 4-5pm, NAC 8/202I
- Email: wolberg@cs.ccny.cuny.edu
Part 1: Introduction
Text: Chapter 1
Lectures 1-3
- Architecture
- GLUT
- Simple programs in two and three dimensions
- Interaction
Outline: Part 3
10
Outline: Part 4
Part 4: Discrete Methods
Text: Chapter 7-8
Lectures 21-26
- Buffers
- Bitmaps and Pixel Maps
- Texture Mapping
- Compositing and Transparency
- Scan conversion
- Polygon filling
- Hidden surface removal
- Geometry
- Transformations
- Homogeneous Coordinates
- Viewing
- Shading
Outline: Part 2
Outline: Part 1
11
12
Outline: Part 5
Outline: Part 6
- Hierarchical Models
- Animation
- Scene Graphs
13
14
Objectives
In this lecture, we explore what computer
graphics is about and survey some
application areas
But we start with a historical introduction
16
Computer Graphics
Related Fields
Image Processing
Image
- Hardware
- Software
- Applications
Computer
Graphics
Computer
Vision
Scene
Description
17
18
Example
Preliminary Answer
Approaches a Student
Should Bring to a Problem
20
Think Visually
21
22
CRT
Output device
Input devices
Image formed in FB
23
24
- Strip charts
- Pen plotters
- Simple displays using A/D converters to go
from computer to calligraphic CRT
25
Project Sketchpad
26
Display Processor
Rather than have host computer try to refresh
display use a special purpose computer called
a display processor (DPU)
28
Created by Tektronix
Raster Graphics
Beginning of graphics standards
- IFIPS
- Relatively inexpensive
Opened door to use of computer graphics for CAD
community
29
30
Raster Graphics
Raster Graphics
31
32
smooth shading
33
bump mapping
34
Industry-based standards
- PHIGS
- RenderMan
- Texture mapping
- Blending
- Accumulation, stencil buffer
environmental
mapping
35
36
Image Formation
37
Objectives
Image Formation
- Light
- Color
- Perception
- Cameras
- Microscopes
- Telescopes
- Human visual system
39
40
Light
Light is the part of the electromagnetic
spectrum that causes a reaction in our
visual systems
Generally these are wavelengths in the
range of about 350-780 nm (nanometers)
Long wavelengths appear as reds and
short wavelengths as blues
41
42
Luminance
- Monochromatic
- Values are gray levels
- Analogous to working with black and white film
or television
Color
- Has perceptional attributes of hue, saturation,
and lightness
- Do we have to match every frequency in visible
spectrum? No!
43
Three-Color Theory
44
45
46
Pinhole Camera
Additive color
- Form a color by adding amounts of three
primaries
CRTs, projection systems, positive film
Subtractive color
Use trigonometry to find projection of a point
xp= -d(x/z)
Light-material interactions
Printing
Negative film
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
yp= -d(y/z)
zp= -d
48
Advantages
Separation of objects, viewer, light sources
Two-dimensional graphics is a special case
of three-dimensional graphics
Leads to simple software API
projector
p
image plane
projection of p
center of projection
49
50
51
52
Objectives
54
Physical Approaches
Objects
Materials
Viewer
Lights
- Slow
- Need whole data base
- Very slow
55
Practical Approach
56
Pipeline architecture
application
program
display
57
API Contents
58
Object Specification
Most APIs support a limited set of
primitives including
- Objects
- Viewer
- Light Source(s)
- Materials
Quadrics
Parametric polynomial
Other information
- Input from devices such as mouse and keyboard
- Capabilities of system
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
59
60
10
Example
Camera Specification
Six degrees of freedom
type of object
location of vertex
glBegin(GL_POLYGON)
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glEnd( );
Lens
Film size
Orientation of film plane
61
Types of lights
- World coordinates
- Camera coordinates
- Screen coordinates
Material properties
- Absorption: color properties
- Scattering
Diffuse
Specular
63
Clipping
Projection
62
64
65
66
11
Rasterization
If an object is visible in the image, the
appropriate pixels in the frame buffer
must be assigned colors
67
Objectives
Functions
- Core
Both 2D and 3D
- Types
- Formats
Simple program
PHIGS and X
70
SGI and GL
X Window System
- DEC/MIT effort
- Client-server architecture with graphics
71
72
12
OpenGL
OpenGL Evolution
Controlled by an Architectural Review
Board (ARB)
- Easy to use
- Close enough to the hardware to get excellent
performance
- Focused on rendering
- Omitted windowing and input to avoid window
system dependencies
OpenGL Libraries
GLUT
- OpenGL32 on Windows
- GL on most Unix/Linux systems
Slide bars
75
OpenGL Architecture
Geometric
pipeline
Immediate Mode
application program
Polynomial
Evaluator
GLUT
76
Software Organization
GLX, AGL
or WGL
Open a window
Get input from mouse and keyboard
Menus
Event-driven
OpenGL Motif
widget or similar
74
Per Vertex
Operations &
Primitive
Assembly
GLU
GL
CPU
Display
List
Rasterization
Per Fragment
Operations
Frame
Buffer
Texture
Memory
Pixel
Operations
77
78
13
OpenGL Functions
OpenGL State
Primitives
- Points
- Line Segments
- Polygons
- Primitive generating
Can cause output if primitive is visible
How vertices are processed and appearance of primitive
are controlled by the state
Attributes
Transformations
- State changing
- Viewing
- Modeling
Transformation functions
Attribute functions
Control
Input (GLUT)
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
79
80
function name
glVertex3f(x,y,z)
belongs to GL library
glVertex3fv(p)
p is a pointer to an array
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
81
OpenGL #defines
A Simple Program
82
83
84
14
simple.c
Event Loop
#include <glut.h>
void mydisplay(){
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(-0.5,-0.5);
glVertex2f(-0.5, 0.5);
glVertex2f( 0.5, 0.5);
glVertex2f( 0.5,-0.5);
glEnd();
glFlush();
}
int main(int argc, char** argv){
glutCreateWindow("simple");
glutDisplayFunc(mydisplay);
glutMainLoop();
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
85
Defaults
86
Notes on compilation
- Viewing
- Colors
- Window parameters
87
88
Compilation on Windows
Visual C++
- Get glut.h, glut32.lib and glut32.dll from web
- Create a console application
- Add opengl32.lib, glut32.lib, glut32.lib to project
settings (under link tab)
Borland C similar
Cygwin (linux under Windows)
89
15
Objectives
Program Structure
Most OpenGL programs have a similar
structure that consists of the following
functions
-main():
Simple viewing
viewing
Attributes
- callbacks
Display function
Input and window functions
91
92
Simple.c revisited
main.c
includes gl.h
#include <GL/glut.h>
- Colors
- Viewing conditions
- Window properties
init();
display callback
set OpenGL state
glutMainLoop();
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
93
GLUT functions
94
init.c
- RGB color
- Single buffering
- Properties logically ORed together
glutWindowSize in pixels
glutWindowPosition from top-left corner of
display
glutCreateWindow create window with title
simple
glutDisplayFunc display callback
glutMainLoop
enter
infinite event
Angel: Interactive Computer Graphics
4E Addison-Wesley
2006 loop
96
16
Coordinate Systems
OpenGL Camera
Orthographic Viewing
98
glMatrixMode (GL_PROJECTION)
z=0
z=0
glLoadIdentity ();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
99
100
mydisplay.c
101
void mydisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex2f(-0.5,-0.5);
glVertex2f(-0.5, 0.5);
glVertex2f( 0.5, 0.5);
glVertex2f( 0.5,-0.5);
glEnd();
glFlush();
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
102
17
OpenGL Primitives
GL_POINTS
GL_POLYGON
GL_LINES
( x, y ) = ( x0 + r cos , y0 + r sin ),
GL_LINE_STRIP
for 0 2 .
GL_LINE_LOOP
GL_TRIANGLES
GL_QUAD_STRIP
GL_TRIANGLE_STRIP
GL_TRIANGLE_FAN
103
Polygon Issues
nonsimple polygon
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
104
105
Attributes
nonconvex polygon
106
RGB color
Each color component stored separately in the
frame buffer
Usually 8 bits per component in buffer
Note in glColor3f the color values range from
0.0 (none) to 1.0 (all), while in glColor3ub the
values range from 0 to 255
107
108
18
Indexed Color
Memory inexpensive
Need more colors for shading
109
Smooth Color
110
Viewports
glShadeModel
(GL_SMOOTH)
or GL_FLAT
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
111
112
Objectives
Programming with OpenGL
Part 3: Three Dimensions
Prof. George Wolberg
Dept. of Computer Science
City College of New York
114
19
Three-dimensional Applications
Repeat
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
115
116
Example
Five subdivisions
117
Gasket Program
118
Draw a triangle
#include <GL/glut.h>
119
120
20
Triangle Subdivision
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
divide_triangle(v[0], v[1], v[2], n);
glFlush();
}
v0[j]=(a[j]+b[j])/2;
v1[j]=(a[j]+c[j])/2;
v2[j]=(b[j]+c[j])/2;
v0, v1, m-1);
v1, v2, m-1);
v2, v0, m-1);
at end of recursion */
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
121
main Function
122
Moving to 3D
void myinit()
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-2.0, 2.0, -2.0, 2.0);
glMatrixMode(GL_MODELVIEW);
glClearColor (1.0, 1.0, 1.0,1.0)
glColor3f(0.0,0.0,0.0);
}
123
3D Gasket
124
Example
after 5 iterations
125
126
21
triangle code
subdivision code
v1[j]=(a[j]+b[j])/2;
v2[j]=(a[j]+c[j])/2;
v3[j]=(b[j]+c[j])/2;
v1, v2, m-1);
v2, v3, m-1);
v3, v1, m-1);
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
127
tetrahedron code
128
Almost Correct
void tetrahedron(int m)
{
glColor3f(1.0,0.0,0.0);
divide_triangle(v[0], v[1], v[2], m);
glColor3f(0.0,1.0,0.0);
divide_triangle(v[3], v[2], v[1], m);
glColor3f(0.0,0.0,1.0);
divide_triangle(v[0], v[3], v[1], m);
glColor3f(0.0,0.0,0.0);
divide_triangle(v[0], v[2], v[3], m);
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
129
Hidden-Surface Removal
130
- Enabled in init.c
glEnable(GL_DEPTH_TEST)
131
132
22
Example: Drawing a
Sphere
x ( , ) = sin cos
y ( , ) = cos cos
z ( , ) = cos
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
133
134
Subdivision Sphere
We can approximate a sphere to any
desired resolution by recursive
subdivision on a tetrahedron.
/* north pole */
z = 1.0;
glBegin(GL_TRIANGLE_FAN);
glVertex3d(x, y, z);
z = cos(c*80.0);
for(t = -180.0; t <= 180.0; t += 20.0) {
x = sin(c*t) * cos(c*80.0);
y = cos(c*t) * cos(c*80.0);
glVertex3d(x,y,z);
}
glEnd();
135
136
Subdividing a Tetrahedron
Subdividing the triangular faces of the
tetrahedron gives us the desired
approximation.
void tetrahedron(int m) {
/* subdivide the tetrahedron faces */
divide_triangle(v[0], v[1], v[2], m);
divide_triangle(v[3], v[2], v[1], m);
divide_triangle(v[0], v[3], v[1], m);
divide_triangle(v[0], v[2], v[3], m);
}
137
23
Objectives
Project Sketchpad
- Physical Devices
- Logical Devices
- Input Modes
Event-driven input
Introduce double buffering for smooth
animations
Programming event input with GLUT
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
139
140
Graphical Input
Physical Devices
mouse
- Logical Properties
trackball
light pen
Modes
- How and when input is obtained
data tablet
Request or event
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
141
joy stick
space ball
142
Logical Devices
Consider the C and C++ code
- C++: cin >> x;
- C: scanf (%d, &x);
144
24
X Window Input
145
146
Input Modes
Request Mode
- Button on mouse
- Pressing or releasing a key
147
Event Mode
148
Event Types
149
150
25
Callbacks
GLUT callbacks
151
In main.c
-glutDisplayFunc(mydisplay) identifies the
function to be executed
- Every GLUT program must have a display callback
153
Posting redisplays
154
Animating a Display
152
155
156
26
Double Buffering
void myidle() {
/* change something */
t += dt
glutPostRedisplay();
}
Void mydisplay() {
glClear();
/* draw something that depends on t */
glutSwapBuffers();
}
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
157
158
Using globals
The form of all GLUT callbacks is fixed
- void mydisplay()
- void mymouse(GLint button, GLint state,
GLint x, GLint y)
float t; /* global */
void mydisplay()
{
/* draw something that depends on t
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
159
Objectives
glutMouseFunc(mymouse)
void mymouse(GLint button,
GLint state, GLint x, GLint y)
- Mouse
- Keyboard
- Reshape
Returns
- which button (GLUT_LEFT_BUTTON,
GLUT_MIDDLE_BUTTON,
GLUT_RIGHT_BUTTON) caused event
- state of that button (GLUT_UP, GLUT_DOWN)
- Position in window
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
161
162
27
Positioning
(0,0)
glGetIntv
glGetFloatv
163
Terminating a program
165
166
164
167
168
28
glutKeyboardFunc(mykey)
Void mykey(unsigned char key,
int x, int y)
void mykey()
{
if(key == Q | key == q)
exit(0);
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
169
Reshape possibilities
original
reshaped
171
Example Reshape
glutReshapeFunc(myreshape)
void myreshape( int w, int h)
- Returns width and height of new window (in pixels)
- A redisplay is posted automatically at end of
execution of the callback
- GLUT has a default reshape callback but you
probably want to define your own
173
172
174
29
Menus
Three steps
- Define entries for the menu
- Define action for each menu item
Menus
Slidebars
Dials
Input boxes
Menu actions
In main.c
- Menu callback
menu_id = glutCreateMenu(mymenu);
glutAddmenuEntry(clear Screen, 1);
gluAddMenuEntry(exit, 2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
clear screen
identifiers
exit
176
178
Subwindows
Multiple Windows
Changing callbacks during execution
Timers
Portable fonts
-glutBitmapCharacter
-glutStrokeCharacter
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
179
30
Objectives
Picking
Identify a user-defined object on the display
In principle, it should be simple because the
mouse gives the position and we should be able
to determine to which object(s) a position
corresponds
Practical difficulties
- Rubberbanding
Interactive drawing of lines and rectangles
- Display Lists
Retained mode graphics
181
Three Approaches
182
Rendering Modes
Hit list
(default)
183
184
buffer
id is set by application program to identify
objects
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
185
186
31
Example: Picking
187
188
2 names
for(i=0; i<3; i++) {
if(mode == GL_SELECT) glLoadName(i);
/* selection buffer */
/* window dimensions */
/* hit count
*/
glGetIntegerv(GL_VIEWPORT, viewport);
glSelectBuffer(BUFSIZE, buf);
(void) glRenderMode(GL_SELECT);
glInitNames();
results go here
glPushName(0);
}
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
189
190
Processing Hits
hits = glRenderMode(GL_RENDER);
ptr = (GLuint *) buf;
for(i=0; i<hits; i++) { /* for each hit */
names = *ptr; ptr++; /* how many names? */
z1 = (float) *ptr/0x7fffffff); ptr++;
z2 = (float) *ptr/0x7fffffff); ptr++;
for(j=0; j<names; j++) { /* for each name */
if(j == 0)
ii = *ptr; /* set row
*/
else if(j == 1)
jj = *ptr; /* set column */
ptr++;
}
}
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
/* 5x5 picking region near cursor */
gluPickMatrix((GLdouble) x,
(GLdouble) (viewport[3] - y),
5.0, 5.0, viewport);
gluOrtho2D(0.0, 3.0, 0.0, 3.0);
drawSquares(GL_SELECT);
glMatrixMode(GL_PROJECTION);
glPopMatrix();
same as reshape
glFlush();
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
192
32
tools
drawing area
menus
Writing Modes
application
194
XOR write
Usual (default) mode: source replaces
destination (d = s)
frame buffer
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
195
Rubberbanding
Rubberband Lines
second point
196
first point
initial display
198
33
XOR in OpenGL
/* global variables */
float xm, ym, xmm, ymm;
/* in mouse handler */
xm = x/500.;
ym = (500 - y)/500.;
199
200
xmm = x/500.;
ymm = (500 - y)/500.;
glLogicOp(GL_XOR);
glBegin(GL_LINES);
glVertex2f(xm, ym);
glVertex2f(xmm, ymm);
glEnd();
glLogicOp(GL_COPY);
glFlush();
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
201
202
Display Lists
Conceptually similar to a graphics file
- Must define (name, create)
- Add contents
- Close
203
204
34
GLuint id;
void init( void )
{
id = glGenLists( 1 );
glNewList( id, GL_COMPILE );
/* other OpenGL routines */
glEndList();
}
205
206
Geometry
glEndList();
207
Objectives
Basic Elements
Geometry is the study of the relationships
among objects in an n-dimensional space
- Scalars
- Vectors
- Points
- Line segments
- Polygons
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
209
210
35
Coordinate-Free Geometry
Scalars
Vectors
Vector Operations
Every vector has an inverse
- Same magnitude but points in opposite direction
Every vector can be multiplied by a scalar
There is a zero vector
- Zero magnitude, undefined orientation
The sum of any two vectors is a vector
- Use head-to-tail axiom
Examples include
- Force
- Velocity
- Directed line segments
212
-v
v
u
213
214
Expressions such as
v=u+2w-3r
215
216
36
Points
Affine Spaces
Location in space
Operations allowed between points and
vectors
P=v+Q
217
218
Lines
Parametric Form
This form is known as the parametric form
of the line
Two-dimensional forms
- Explicit: y = mx +b
- Implicit: ax + by +c =0
- Parametric:
x() = x0 + (1-)x1
y() = y0 + (1-)y1
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
219
220
Convexity
221
P
P
222
37
Affine Sums
Convex Hull
223
224
Planes
P(,)=R+u+v
P(, )
P()
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
225
Triangles
P(,)=R+(Q-R)+(P-Q)
226
Normals
Every plane has a vector n normal
(perpendicular, orthogonal) to it
convex sum of S() and R
P
227
u
228
38
Objectives
Introduce concepts such as dimension
and basis
Introduce coordinate systems for
representing vectors spaces and frames
for representing affine spaces
Discuss change of frames and basis
Introduce homogeneous coordinates
Representation
Prof. George Wolberg
Dept. of Computer Science
City College of New York
230
Linear Independence
Dimension
231
Representation
Coordinate Systems
232
T 2
a=[1 2 . n] = .
n
233
234
39
Example
Coordinate Systems
V=2v1+3v2-4v3
A=[2 3 4]
Note that this representation is with
respect to a particular basis
For example, in OpenGL we start by
representing vectors using the world
basis but later the system needs a
representation in terms of the camera or
eye basis
Which is correct?
v
v
Frames
Frames II
236
v1
P0
v3
237
238
A Single Representation
If we define 0P = 0 and 1P =P then we can
write
239
240
40
Homogeneous Coordinates
and Computer Graphics
Homogeneous Coordinates
The general form of four dimensional homogeneous
coordinates is
p=[x y z w] T
We return to a three dimensional point (for w0) by
xx/w
yy/w
zz/w
If w=0, the representation is that of a vector
Note that homogeneous coordinates replaces points in
three dimensions by lines through the origin in four
dimensions
242
Change of Coordinate
Systems
Representing second
basis in terms of first
a=[1 2 3 ]
b=[1 2 3]
u1 = 11v1+12v2+13v3
u2 = 21v1+22v2+23v3
u3 = 31v1+32v2+33v3
where
2 2
3 3
243
Change of Frames
Matrix Form
The coefficients define a 3 x 3 matrix
11 12 13
M = 21 22 23
31 32 33
P0
v3
a=MTb
u2
Q0
v1
u3
244
245
246
41
u1 = 11v1+12v2+13v3
u2 = 21v1+22v2+23v3
u3 = 31v1+32v2+33v3
Q0 = 41v1+42v2+43v3 +44P0
defining a 4 x 4 matrix
11
21
M=
31
41
12
13
22
32
23
33
42
43
0
0
0
and
a=MTb
248
Affine Transformations
249
250
1
0
0
0
0 1 d
0 0 1
0 0
Transformations
1 0
251
42
Objectives
General Transformations
- Rotations
- Translation
- Scaling
- Shear
v=T(u)
Q=T(P)
253
Affine Transformations
Pipeline Implementation
Line preserving
Characteristic of many physically
important transformations
255
frame
buffer
T(u)
transformation
rasterizer
T(v)
T(v)
T(v)
T(u)
u
vertices
T(u)
vertices
pixels
Notation
We will be working with both coordinate-free
representations of transformations and
representations within a particular frame
P,Q, R: points in an affine space
u, v, w: vectors in an affine space
, , : scalars
p, q, r: representations of points
-array of 4 scalars in homogeneous
coordinates
u, v, w: representations of points
-array of 4 scalars in homogeneous
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
coordinates
254
256
Translation
Move (translate, displace) a point to a
new location
P
d
P
258
43
Translation Using
Representations
Object Translation
Every point in object is displaced by same vector
object
Object translation
259
Translation Matrix
0 0 dx
1 0 dy
0 1 dz
0 0 1
x = x cos y sin
y = x sin + y cos
x = r cos
y = r sin
260
Rotation (2D)
1
0
261
262
Rotation Matrix
cos sin
cos
0
0
0
0
R = Rz() = sin
0 0
0 0
1 0
0 1
- or in homogeneous coordinates
p=Rz()p
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
263
264
44
Scaling
Expand or contract along each axis (fixed point of origin)
0
0
1
0
x=sxx
y=syy
z=szz
p=Sp
cos
0 sin 0
1
0
0
- sin 0 cos 0
0
0
1
0
R = Ry() = 0
265
0
0
sz
0
0
1
266
Inverses
Although we could compute inverse matrices
by general formulas, we can use simple
geometric observations
original
sx = -1 sy = -1
sx = 1 sy = -1
Concatenation
268
Order of Transformations
0
sy
0
Reflection
sx
0
269
270
45
v
x
271
272
Instancing
Shear
Scale
Orient
Locate
273
274
Example: Plotting a
Function
Shear Matrix
Consider simple shear along x axis
f ( x ) = e x cos 2 x for 0 x 4.
x = x + y cot
y = y
z = z
1 cot
0
1
H() =
0
0
0
0
0 0
0 0
1 0
0 1
275
276
46
Viewport Transformation
A B w / 4 0
C D = h / 2 h / 2
A B x x
C D y = y .
A
B
C
D
=
=
=
=
screenWidth / 4.0;
0.0;
screenHeight / 2.0;
C;
glBegin(GL_POINTS);
for(x = 0.0; x <= 4.0; x += 0.005)
glVertex2f(A*x + B, C*f(x) + D);
glEnd();
277
278
Objectives
Learn how to carry out transformations in
OpenGL
OpenGL Transformations
- Rotation
- Translation
- Scaling
280
Current Transformation
Matrix (CTM)
OpenGL Matrices
-glMatrixMode(GL_MODEL_VIEW);
-glMatrixMode(GL_PROJECTION);
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
p=Cp
vertices
281
CTM
vertices
282
47
CTM operations
The CTM can be altered either by loading a new
CTM or by postmultiplication
Load an identity matrix: C I
Load an arbitrary matrix: C M
Result: C = T -1RT
CTM in OpenGL
284
Multiply on right:
glRotatef(theta, vx, vy, vz)
theta in degrees, (vx, vy, vz) define axis of rotation
glTranslatef(dx, dy, dz)
glScalef( sx, sy, sz)
285
286
Example
Arbitrary Matrices
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(1.0, 2.0, 3.0);
glRotatef(30.0, 0.0, 0.0, .10);
glTranslatef(-1.0, -2.0, -3.0);
287
288
48
Matrix Stacks
glPushMatrix()
glPopMatrix()
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
glGetIntegerv
glGetFloatv
glGetBooleanv
glGetDoublev
glIsEnabled
289
Using Transformations
main.c
291
292
Display callback
void spinCube()
{
theta[axis] += 2.0;
if( theta[axis] > 360.0 ) theta[axis] -= 360.0;
glutPostRedisplay();
}
void mouse(int btn, int state, int x, int y)
{
if(btn==GLUT_LEFT_BUTTON && state == GLUT_DOWN)
axis = 0;
if(btn==GLUT_MIDDLE_BUTTON && state == GLUT_DOWN)
axis = 1;
if(btn==GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
axis = 2;
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
290
293
void display()
{
glClear(GL_COLOR_BUFFER_BIT |
glLoadIdentity();
glRotatef(theta[0], 1.0, 0.0,
glRotatef(theta[1], 0.0, 1.0,
glRotatef(theta[2], 0.0, 0.0,
colorcube();
glutSwapBuffers();
}
GL_DEPTH_BUFFER_BIT);
0.0);
0.0);
1.0);
294
49
295
Motion Control
296
297
Viewing Parameters
void reshape()
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (float) w/h, 1.0, 20.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0., 0., 5., 0., 0., 0., 0., 1., 0.);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0., 0., 5., 0., 0., 0., 0., 1., 0.);
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
299
300
50
Ordering the
Transformations
void display(void) {
glClear (GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glPushMatrix ();
glutWireSphere(1.0, 20, 16);
glRotatef
((GLfloat) year, 0.0, 1.0, 0.0);
glTranslatef (2.0, 0.0, 0.0);
glRotatef
((GLfloat) day, 0.0, 1.0, 0.0);
glutWireSphere(0.2, 10, 8);
glPopMatrix
();
glutSwapBuffers();
}
301
302
Smooth Rotation
void init(void) {
glClearColor(0., 0., 0., 0.);
glShadeModel(GL_FLAT);
}
Incremental Rotation
304
Quaternions
Extension of imaginary numbers from two to
three dimensions
Requires one real and three imaginary
components i, j, k
q=q0+q1i+q2j+q3k
305
306
51
Interfaces
One of the major problems in interactive
computer graphics is how to use twodimensional devices such as a mouse to
interface with three dimensional objects
Example: how to form an instance matrix?
Some alternatives
Building Models
Prof. George Wolberg
Dept. of Computer Science
City College of New York
- Virtual trackball
- 3D input devices such as the spaceball
- Use areas of the screen
Distance from center controls angle, position, scale
depending on mouse button depressed
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
307
Objectives
Representing a Mesh
Consider a mesh e2
v6
- Vertex lists
- Edge lists
e1
v1
e6
e9
v5
e3
e8 v
v4
8
e11
e10
e4
e7 v7
v2 e12
v3
e5
309
310
Simple Representation
List all polygons by their geometric
locations
Leads to OpenGL code such as
The order {v0, v1, v2, v3} and {v1, v2, v3, v0} are
equivalent in that the same polygon will be rendered
by OpenGL but the order {v3, v2, v1, v0} is different
The first two describe inwardly
facing polygons
Use the right-hand rule =
counter-clockwise encirclement
of outward-pointing normal
OpenGL treats inward and
outward facing polygons differently
glBegin(GL_POLYGON);
glVertex3f(x1, y1, z1);
glVertex3f(x6, y6, z6);
glVertex3f(x7, y7, z7);
glEnd();
311
312
52
Geometry vs Topology
Vertex Lists
313
Shared Edges
Edge List
314
315
e2
e1
e2
e3
e4
e5
e6
e7
e8
e9
v1
v6
x1 y1 z1
x2 y2 z2
x3 y3 z3
x4 y4 z4
x5 y5 z5.
x6 y6 z6
x7 y7 z7
x8 y8 z8
v6
e1
v1
e6
e9
v5
e3
e8 v
8
e11
e10
v
e4
e7
7
e
v2 12
v3
e5
316
Modeling a Cube
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
317
318
53
Efficiency
The weakness of our approach is that we
are building the model in the application
and must do many function calls to draw
the cube
Drawing a cube by its faces in the most
straight forward way requires
6
2
4
0
- 6 glBegin, 6 glEnd
- 6 glColor
- 24 glVertex
- More if we use texture and lighting
319
320
Vertex Arrays
Initialization
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
Vertices
Colors
Color indices
Normals
Texture coordinates
Edge flags
data array
3d arrays
stored as floats
data contiguous
321
322
what to draw
number of indices
Method 2:
glDrawElements(GL_QUADS, 24,
GL_UNSIGNED_BYTE, cubeIndices);
323
324
54
326
Objectives
This is an optional lecture that
Virtual Trackball
Physical Trackball
328
329
330
55
Projection of Trackball
Position
Trackball Frame
331
Reversing Projection
Computing Rotations
2
2
2
y = r x z
if r |x| 0, r |z| 0
333
332
334
|n|
| p1 || p 2 |
335
336
56
Example
337
Initialization
winWidth, winHeight;
trackingMouse = false;
redrawContinue = false;
trackballMove = false;
338
339
glutMotionFunc (1)
340
glutMotionFunc (2)
if (dx || dy || dz) {
/* compute theta and cross product */
angle = 90.0 * sqrt(dx*dx + dy*dy + dz*dz);
axis[0] = lastPos[1]*curPos[2] lastPos[2]*curPos[1];
axis[1] = lastPos[2]*curPos[0]
lastPos[0]*curPos[2];
axis[2] = lastPos[0]*curPos[1]
lastPos[1]*curPos[0];
/* update position */
lastPos[0] = curPos[0];
lastPos[1] = curPos[1];
lastPos[2] = curPos[2];
}
voidmouseMotion(int x, int y)
{
float curPos[3],
dx, dy, dz;
/* compute position on hemisphere */
trackball_ptov(x, y, winWidth, winHeight, curPos);
if(trackingMouse) {
/* compute the change in position
on the hemisphere */
dx = curPos[0] - lastPos[0];
dy = curPos[1] - lastPos[1];
dz = curPos[2] - lastPos[2];
}
glutPostRedisplay();
}
341
342
57
Mouse Callback
void spinCube() {
if(redrawContinue) glutPostRedisplay();
}
void display() {
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
if (trackballMove){
glRotatef(angle, axis[0], axis[1], axis[2]);
}
colorcube();
glutSwapBuffers();
}
343
Start Function
344
Stop Function
345
346
Quaternions
Because the rotations are on the surface
of a sphere, quaternions provide an
interesting and more efficient way to
implement the trackball
See code in some of the standard demos
included with Mesa
Classical Viewing
Prof. George Wolberg
Dept. of Computer Science
City College of New York
347
58
Objectives
Classical Viewing
Viewing requires three basic elements
349
350
Classical Projections
351
Taxonomy of Planar
Geometric Projections
Perspective vs Parallel
Computer graphics treats all projections
the same and implements them with a
single pipeline
Classical viewing developed different
techniques for drawing each type of
projection
Fundamental distinction is between
parallel and perspective viewing even
though mathematically parallel viewing is
the limit of perspective viewing
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
352
parallel
perspective
1 point
multiview axonometric oblique
orthographic
isometric
353
dimetric
2 point
3 point
trimetric
354
59
Perspective Projection
Parallel Projection
355
Multiview Orthographic
Projection
Orthographic Projection
Projectors are orthogonal to projection surface
357
Advantages and
Disadvantages
front
side
358
Axonometric Projections
Allow projection plane to move relative to object
356
359
360
60
Types of Axonometric
Projections
Advantages and
Disadvantages
Lines are scaled (foreshortened) but can find
scaling factors
Lines preserved but angles are not
- Projection of a circle in a plane not parallel to the
projection plane is an ellipse
361
362
Advantages and
Disadvantages
Oblique Projection
363
364
Perspective Projection
Vanishing Points
vanishing point
365
366
61
Three-Point Perspective
Two-Point Perspective
367
368
Advantages and
Disadvantages
One-Point Perspective
One principal face parallel to projection plane
One vanishing point for cube
369
370
Objectives
Computer Viewing
372
62
Computer Viewing
There are three aspects of the viewing
process, all of which are implemented in
the pipeline,
- Selecting a lens
Setting the projection matrix
- Clipping
Setting the view volume
Default Projection
374
z=0
375
376
377
378
63
OpenGL code
glMatrixMode(GL_MODELVIEW):
glLoadIdentity();
gluLookAt(1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0., 1.0. 0.0);
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
379
380
381
Projections and
Normalization
382
Homogeneous Coordinate
Representation
xp = x
yp = y
zp = 0
wp = 1
xp = x
yp = y
zp = 0
383
pp = Mp
1
0
M=
0
0 0 0
1 0 0
0 0 0
0 0 1
384
64
Simple Perspective
Perspective Equations
x
z/d
xp =
385
x
z/d
consider q = Mp
where
p=
x
y
z
1
q=
1
0
0
1
0 1/ d
y
z/d
zp = d
386
Homogeneous
Coordinate Form
1
M = 0
0
yp =
Perspective Division
0
0
0
x
y
z / d
x
z/d
yp =
y
z/d
zp = d
OpenGL Orthogonal
Viewing
388
OpenGL Perspective
glOrtho(xmin,xmax,ymin,ymax,near,far)
glOrtho(left,right,bottom,top,near,far)
glFrustum(xmin,xmax,ymin,ymax,near,far)
389
390
65
Projection Matrices
front plane
aspect = w/h
391
Objectives
Normalization
393
Pipeline View
modelview
transformation
projection
transformation
perspective
division
nonsingular
projection
3D 2D
394
Notes
4D 3D
clipping
395
396
66
Orthogonal Normalization
Orthogonal Matrix
glOrtho(left,right,bottom,top,near,far)
normalization find transformation to convert
specified clipping volume to default
Two steps
- Move center to origin
T(-(left+right)/2, -(bottom+top)/2,(near+far)/2))
P = ST =
397
Final Projection
Morth =
0
1
0
0
0
0
0
0
2
top bottom
0
0
2
near far
0
right left
right left
top + bottom
top bottom
far + near
far near
1
398
Oblique Projections
Set z =0
Equivalent to the homogeneous
coordinate transformation
1
0
right left
0
0
0
General Shear
400
Shear Matrix
xy shear (z values unchanged)
1
H(,) = 0
0
0 cot 0
1 cot 0
0
1
0
0
0
1
Projection matrix
top view
P = Morth H(,)
side view
General case:
401
P = Morth STH(,)
402
67
Equivalency
Effect on Clipping
The projection matrix P = STH transforms
the original clipping volume to the default
clipping volume
object
top view
z= 1
DOP
DOP
x = -1
x=1
far plane
z = -1
clipping
volume
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
403
Simple Perspective
near plane
distorted object
(projects correctly)404
Perspective Matrices
1
0
0
0
0 1 0
0 1 0
0
405
Picking and
Generalization
N=
1
0
0
0
0
0 1 0
0
406
If we pick
near + far
far near
2near far
=
near far
x = x/z
y = y/z
z = -(+/z)
which projects orthogonally to the desired point
regardless of and
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
408
68
Normalization
Transformation
Normalization and
Hidden-Surface Removal
Although our selection of the form of the
perspective matrices may appear somewhat
arbitrary, it was chosen so that if z1 > z2 in the
original clipping volume then the for the
transformed points z1 > z2
Thus hidden surface removal works if we first
apply the normalization transformation
However, the formula z = -(+/z) implies that
the distances are distorted by the normalization
which can cause numerical problems especially
if the near distance is small
distorted object
projects correctly
original clipping
volume
original object
new clipping
volume
409
OpenGL Perspective
410
does not)
411
412
Example: Shadows
0
1
0
1
M=
0
0
0 1 / y
0
0
1
0
0
0
0
0
414
69
The Shadow
Transformation
415
/* y_l */
416
Drawing Shadows
After drawing the scene, move the
viewpoint to the light position and apply
the shadow transformation.
Shading
glPushMatrix();
glTranslatef(light[0], light[1],light[2]);
glMultMatrixf(m);
glTranslatef(-light[0], -light[1],-light[2]);
glColor3f(0.0,0.0,0.0); /* shadow color */
drawPolygon();
glPopMatrix();
417
Objectives
But we want
419
420
70
Shading
Scattering
Light strikes A
- Some scattered
- Some absorbed
- Some scattered
- Some absorbed
Light sources
Material properties
Location of viewer
Surface orientation
421
Rendering Equation
422
Global Effects
shadow
translucent surface
- Shadows
- Multiple scattering from object to object
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
423
424
Light-Material Interaction
425
426
71
Light Sources
Point source
- Model with position and color
- Distant source = infinite distance away (parallel)
Spotlight
- Restrict light from ideal point source
Ambient light
- Same amount of light everywhere in scene
- Can model contribution of many sources and
reflecting surfaces
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
427
Surface Types
Phong Model
428
- Diffuse
- Specular
- Ambient
smooth surface
- To source
- To viewer
- Normal
- Perfect reflector
rough surface
429
430
Ideal Reflector
Lambertian Surface
r = 2 (l n ) n - l
431
432
72
Specular Surfaces
shininess coef
reflected
incoming intensity
intensity
absorption coef
specular
highlight
433
Ambient Light
cos
-90
reflection coef
90
435
434
436
Distance Terms
Light Sources
437
438
73
Material Properties
- Shininess coefficient
I =kd Id l n + ks Is (v r ) + ka Ia
For each color component
we add contributions from
all sources
439
440
Example
Shading in OpenGL
Only differences in
these teapots are
the parameters
in the Phong model
441
Objectives
1.
2.
3.
4.
- Flat
- Smooth
- Gouraud
443
444
74
Normals
n
plane
Set by glNormal*()
-glNormal3f(x, y, z);
-glNormal3fv(p);
n = (p1 - p0 ) (p2 - p0 )
normalize n n/ |n|
445
446
-glEnable(GL_LIGHTING)
-glLightModeli(parameter, GL_TRUE)
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightv(GL_LIGHT0, GL_POSITION, light0_pos);
glLightv(GL_LIGHT0, GL_AMBIENT, ambient0);
glLightv(GL_LIGHT0, GL_DIFFUSE, diffuse0);
glLightv(GL_LIGHT0, GL_SPECULAR, specular0);
448
Spotlights
Use glLightv to set
- Direction GL_SPOT_DIRECTION
- Cutoff GL_SPOT_CUTOFF
- Attenuation GL_SPOT_EXPONENT
Proportional to cos
a= 0.80;
glLightf(GL_LIGHT0, GLCONSTANT_ATTENUATION, a);
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
p1
p0
Enabling Shading
p2
n (p - p0 ) = 0
449
450
75
451
452
Material Properties
453
454
Emissive Term
Transparency
455
456
76
Efficiency
Polygonal Shading
-glShadeModel(GL_SMOOTH);
457
Polygon Normals
- Shades at the vertices as computed by the
Phong model can be almost same
- Identical for a distant viewer (default) or if there
is no specular component
459
Mesh Shading
n1 + n 2 + n 3 + n 4
| n1 | + | n 2 | + | n 3 | + | n 4 |
n1 + n 2 + n 3 + n 4
| n1 | + | n 2 | + | n 3 | + | n 4 |
- If centered at origin n = p
460
n=
458
Smooth Shading
461
Gouraud Shading
- Find average normal at each vertex (vertex normals)
- Apply Phong model at each vertex
- Interpolate vertex shades across each polygon
Phong shading
- Find vertex normals
- Interpolate vertex normals across edges
- Find shades along edges
- Interpolate edge shades across polygons
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
462
77
Comparison
If the polygon mesh approximates surfaces with
a high curvatures, Phong shading may look
smooth while Gouraud shading may show edges
Phong shading requires much more work than
Gouraud shading
- Usually not available in real time systems
Both need data structures to represent meshes
so we can obtain vertex normals
Buffers
Prof. George Wolberg
Dept. of Computer Science
City College of New York
463
Objectives
Buffer
Define a buffer by its spatial resolution (n x m) and
its depth k, the number of bits/pixel
pixel
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
465
466
OpenGL Buffers
Color buffers can be displayed
- Front
- Back
- Auxiliary
- Overlay
Depth
Accumulation
- High resolution buffer
Stencil
- Holds masks
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
467
468
78
Writing in Buffers
Writing Model
memory
source
frame buffer
(destination)
Writing Modes
XOR
470
XOR mode
OR
471
472
Raster Position
- Reading pixels
Format conversion
473
474
79
Buffer Selection
Bitmaps
OpenGL treats 1-bit pixels (bitmaps)
differently than multi-bit pixels (pixelmaps)
Bitmaps are masks which determine if the
corresponding pixel in the frame buffer is
drawn with the present raster color
475
Raster Color
476
Drawing Bitmaps
glBitmap(width, height, x0, y0, xi, yi, bitmap)
offset from raster
position
increments in
raster
position after
bitmap drawn
- 0 color unchanged
- 1 color changed based on writing mode
478
Pixel Maps
Three functions
- Draw pixels: processor memory to frame buffer
- Read pixels: frame buffer to processor memory
- Copy pixels: frame buffer to frame buffer
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
479
480
80
Image Formats
glReadPixels(x,y,width,height,format,type,myimage)
type of pixels
size
type of image pointer to processor
memory
GLubyte myimage[512][512][3];
glReadPixels(0,0, 512, 512, GL_RGB,
GL_UNSIGNED_BYTE, myimage);
glDrawPixels(width,height,format,type,myimage)
481
P3
# comment 1
# comment 2
.
#comment n
rows columns maxvalue
pixels
483
FILE *fd;
int k, nm;
char c;
int i;
char b[100];
check for P3
float s;
in first line
int red, green, blue;
printf("enter file name\n");
scanf("%s", b);
fd = fopen(b, "r");
fscanf(fd,"%[^\n] ",b);
if(b[0]!='P'|| b[1] != '3'){
printf("%s is not a PPM file!\n", b);
exit(0);
}
printf("%s is a PPM file\n",b);
484
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
fscanf(fd, "%c",&c);
while(c == '#')
{
fscanf(fd, "%[^\n] ", b);
printf("%s\n",b);
fscanf(fd, "%c",&c);
}
ungetc(c,fd);
nm = n*m;
image=malloc(3*sizeof(GLuint)*nm);
s=255./k;
scale factor
for(i=0;i<nm;i++)
{
fscanf(fd,"%d %d %d",&red, &green, &blue );
image[3*nm-3*i-3]=red;
image[3*nm-3*i-2]=green;
image[3*nm-3*i-1]=blue;
}
482
485
486
81
487
488
Objectives
Introduce Mapping Methods
Texture Mapping
- Texture Mapping
- Environmental Mapping
- Bump Mapping
Modeling an Orange
490
491
492
82
Texture Mapping
- Uses images to fill inside of polygons
Bump mapping
- Emulates altering normal vectors during the
rendering process
493
Texture Mapping
geometric model
494
Environment Mapping
texture mapped
495
496
Bump Mapping
497
498
83
Is it simple?
Coordinate Systems
Parametric coordinates
- May be used to model curved surfaces
Texture coordinates
- Used to identify points in the image to be mapped
World Coordinates
- Conceptually, where the mapping takes place
Screen Coordinates
2D image
Texture Mapping
Mapping Functions
Basic problem is how to find the maps
Consider mapping from texture
coordinates to a point a surface
Appear to need three functions
parametric coordinates
x = x(s,t)
y = y(s,t)
z = z(s,t)
world coordinates
t
s
screen coordinates
501
Backward Mapping
(x,y,z)
texture coordinates
500
502
Two-part mapping
503
504
84
Cylindrical Mapping
Spherical Map
We can use a parametric sphere
parametric cylinder
x = r cos 2 u
y = r sin 2u
z = v/h
x = r cos 2u
y = r sin 2u cos 2v
z = r sin 2u sin 2v
s=u
t=v
maps from texture space
505
Box Mapping
Second Mapping
Map from intermediate object to actual object
- Normals from intermediate to actual
- Normals from actual to intermediate
- Vectors from center of intermediate
actual
507
Aliasing
intermediate
508
Area Averaging
506
preimage
pixel
509
510
85
Objectives
Introduce the OpenGL texture functions
and options
512
Basic Strategy
Texture Mapping
geometry
screen
wrapping, filtering
image
513
514
Texture Example
The texture (below) is a
256 x 256 image that has
been mapped to a
rectangular polygon which
is viewed in perspective
geometry pipeline
rasterizer
image
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
515
pixel pipeline
516
86
Glubyte my_texels[512][512];
- Scan
- Via application code
-glEnable(GL_TEXTURE_2D)
- OpenGL supports 1-4 dimensional texture maps
Converting A Texture
Image
Mapping a Texture
Based on parametric texture coordinates
glTexCoord*() specified at each vertex
0, 1
Texture Space
Object Space
1, 1
(0.4, 0.2)
c
b
518
0, 0
519
B
1, 0 s
Typical Code
C
(0.8, 0.4)
520
Interpolation
glBegin(GL_POLYGON);
glColor3f(r0, g0, b0);
glNormal3f(u0, v0, w0);
glTexCoord2f(s0, t0);
glVertex3f(x0, y0, z0);
glColor3f(r1, g1, b1);
glNormal3f(u1, v1, w1);
glTexCoord2f(s1, t1);
glVertex3f(x1, y1, z1);
.
.
glEnd();
poor selection
of tex coordinates
over trapezoid
showing effects of
bilinear interpolation
521
522
87
Texture Parameters
Wrapping Mode
523
glTexParameteri( GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_CLAMP )
glTexParameteri( GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_REPEAT )
s
texture
GL_REPEAT
wrapping
GL_CLAMP
wrapping
524
Magnification and
Minification
Filter Modes
Modes determined by
-glTexParameteri( target, type, mode )
glTexParameteri(GL_TEXTURE_2D, GL_TEXURE_MAG_FILTER,
GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXURE_MIN_FILTER,
GL_LINEAR);
Texture
Polygon
Magnification
Texture
Polygon
Minification
525
Mipmapped Textures
526
Example
point
sampling
linear
filtering
mipmapped
point
sampling
gluBuild*DMipmaps( )
527
mipmapped
linear
filtering
528
88
Perspective Correction
Hint
Texture Functions
Controls how texture is applied
GL_TEXTURE_ENV_MODE modes
- GL(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,
GL_MODULATE);
529
Generating Texture
Coordinates
glTexGen{ifd}[v]()
specify a plane
- generate texture coordinates based upon distance from
the plane
generation modes
531
Applying Textures II
532
Environmental Maps
- Start with image of environment through a wide
angle lens
Can be either a real scanned image or an image created in
OpenGL t
Multitexturing
- Apply a sequence of textures through cascaded
texture units
-GL_OBJECT_LINEAR
-GL_EYE_LINEAR
-GL_SPHERE_MAP (used for environmental maps)
1.
2.
3.
4.
5.
6.
7.
8.
530
Texture Objects
533
534
89
Objectives
Learn to use the A component in RGBA
color for
536
Physical Models
opaque surface =1
537
538
Writing Model
Blending Equation
blend
destination
component
Color Buffer
539
540
90
Example
glEnable(GL_BLEND)
glBlendFunc(source_factor,
destination_factor)
541
542
Order Dependency
543
544
Fog
545
546
91
Fog Functions
547
548
Line Aliasing
Antialiasing
549
no overlap
overlap
550
Area Averaging
OpenGL Antialiasing
551
552
92
Accumulation Buffer
Applications
Compositing
Image Filtering (convolution)
Whole scene antialiasing
Motion effects
553
554
Basic Implementation
Strategies
A black box graphics system takes as
input a set of vertices and produces as
output set of pixels.
Implementation of a Renderer
Prof. George Wolberg
Dept. of Computer Science
City College of New York
556
for(each_object) render(object);
for(each_pixel) assign_a_color(pixel);
557
558
93
Implementation of
Transformations
The geometric processing stage of the
pipeline involves five coordinate systems:
559
Cohen-Sutherland
Clipping
Line-Segment Clipping
560
561
o1 & o2 = 0
o1 & o2 0
o1 = o2 = 0
563
564
94
Liang-Barsky Clipping
Intersection Tests
x ( ) = (1 ) x1 + x2 ,
y ( ) = (1 ) y1 + y2 ,
- This form is robust and needs no changes for
horizontal or vertical lines.
- As before, we extend the sides of the window to
infinity.
565
Computing Intersections
566
Polygon Clipping
( y2 y1 ) = ymax y1.
All tests are stated in terms of ymax = ymax - y1, which
involves no floating point division.
We compute intersections only when a line needs to be
shortened, and we never shorten a line more than once.
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
567
568
Tessellation
Clipping a convex polygon against a
rectangular window leaves at most one
convex polygon in the window.
x3 = x1 + ( ymax y1 )
x2 x1
,
y2 y1
y3 = ymax .
569
570
95
Pipelining Clipping
Operations
571
572
Clipping in Three
Dimensions
A Pipeline Clipper
The effect of successive clippers on a
polygon:
573
The Cohen-Sutherland
Algorithm in 3D
574
The Liang-Barsky
Algorithm in 3D
Add the equation z ( ) = (1 ) z1 + z2 .
575
576
96
Plane-Line Intersection
Hidden-Surface Removal
n ( p( ) p 0 ) = 0.
is the intersection point.
n ( p0 p1 )
n ( p 2 p1 )
577
The Object-Space
Approach
578
The Object-Space
Algorithm
579
Object-Space Complexity
The Image-Space
Approach
580
581
582
97
Image-Space Complexity
Back-Face Removal
583
584
0
0
v=
1
0
90 90 or cos( ) 0.
We can test the 2nd condition easily by
n v 0.
view direction
surface
ax + by + cz + d = 0
585
586
Basic Algorithm
587
588
98
Incremental Version
behind A
z is constant.
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
589
Depth Sort
590
591
592
Scan Conversion
593
594
99
Plotting Points
y = m x.
595
596
Slope Considerations
revised algorithm
597
Bresenham's Algorithm
598
y = mx + h
for 0 m 1.
599
600
100
Computational
Advantages
d = ( x2 x1 )( a b)
= x ( a b).
d = ab
d is an integer.
601
602
Scan Conversion of
Polygons
An Incremental Approach
Update d based on our last decision.
if d k > 0
2 y
d k +1 = d k
2( y x ) otherwise
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
603
Inside-Outside Testing
604
605
606
101
mytess = gluNewTess();
gluTessBeginPolygon(mytess, NULL);
gluTessBeginContour(mytess);
for(i=0; i<nvertices; i++)
glTessVertex(mytess, vertex[i], vertex[i]);
gluTessEndContour();
gluTessEndPolygon(mytess);
607
OpenGL Tessellation
Options
Flood Fill
610
Scan-Line Algorithms
608
Displaying a Polygon
611
612
102
Generating Intersections
613
Singularities
614
Resolving Singularities
zero or two
edge crossings
one edge
crossing
615
Antialiasing
Area Averaging
616
617
618
103
619
Symbols
Instances
M = TRS
621
Instance Transformation
622
Transformation Tables
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(...);
glRotatef(...);
glScalef(...);
glutSolidCylinder(...); /* symbols follow */
623
624
104
Hierarchical Models
First Attempt
If each wheel has radius r, a 360 rotation
moves the car a distance of 2r.
main() {
float s = ...; /* speed */
float d[3] = {...}; /* direction */
draw_right_front_wheel(s, d);
draw_left_front_wheel(s, d);
draw_right_rear_wheel(s, d);
draw_left_rear_wheel(s, d);
draw_chassis(s, d);
}
625
Graph Representation
626
627
628
A Robot Arm
629
630
105
Incremental
Transformations
Joint Angles
Determine a components position with
respect to the main body of the object.
631
633
move to
leg position
634
Stack-Based Traversal
figure() {
glPushMatrix();
torso();
glTranslate();
glRotate();
head();
glPopMatrix();
glPushMatrix();
glTranslate();
glRotate();
left_upper_leg();
...
632
Tree Traversal
move back
to torso
position
635
636
106
Setting up a Node
637
638
Display Callback
void display(void) {
glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
traverse(&torso_node);
glutSwapBuffers();
}
639
640
Animation
Difficulties
641
642
107
Key-Frame Animation
Graphical Objects
643
644
Scene Graphs
Node Types
645
646
647
648
108
class Node {
public:
Node();
virtual ~Node();
virtual void Render();
void AddChild(Node*);
friend class GLViewer;
}
649
Object Types
enum Enum {
PERSPECTIVE, ORTHO, POSITION, AIMAT,
UPDIRECTION, ASPECT, NEAR, FAR, YANGLE,
BLACK, WHITE, RED, GREEN, YELLOW, BLUE,
MAGENTA, CYAN, GRAY, WIDTH, HEIGHT,
DEPTH, AMBIENT, DIFFUSE, SPECULAR,
SPOT_DIRECTION, DROPOFFRATE, CUTOFFANGLE,
EMISSION, SHININESS, TRANSLATION,
ROTATION, SCALE, BUFFER, SINGLE, DOUBLE,
RADIUS, STYLE, POINTSIZE, LINEWIDTH,
FILLED, LINE, POINT, BACKCOLOR
};
651
Geometry Nodes
652
Camera Class
650
Application Code
653
654
109
Specifying a Perspective
Camera
Lights
How do we turn lights on and off from
within the scene graph?
Materials
myObject->SetMaterial(myMat);
657
658
656
Transformations
659
660
110
Managing Multiple
Windows
GLViewer::~GLViewer() {
if(Root[I]) {
delete Root[I];
Root[I] = NULL;
}
}
661
663
Root[0]->Traverse();
662
void GLViewer::GLInit() {
glutInitDisplayMode(BufType[I] | GLUT_RGB |
GLUT_DEPTH);
glutInitWindowSize(Width[I], Height[I]);
switch(I) {
case 0:
glutReshapeFunc(Reshape0);
glutDisplayFunc(Display0);
break;
...
}
glEnable(GL_DEPTH_TEST);
// other configuration options
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
664
tree traversal
starts here
if(BufType[0] == GLUT_DOUBLE)
glutSwapBuffers();
glFlush();
}
void GLViewer::Reshape0(int w, int h) {
glViewport(0, 0, w, h);
Width[0] = w;
Height[0] = h;
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
void GLViewer::Display0() {
glClear(GL_COLOR_BUFFER_BIT |
GL_DEPTH_BUFFER_BIT);
3 sets of
handlers
calls node
destructor
Initializing OpenGL
GLViewer::GLViewer() {
I = Count++;
Name = "";
BufType[I] = GLUT_SINGLE;
Root[I] = NULL;
}
665
666
111
Node Implementation
Geometry Nodes
void Node::Traverse() {
if(!KeepMatrix) glPushMatrix();
different
for every
node type
Render();
if(LeftChild != NULL)
LeftChild->Traverse();
if(!KeepMatrix) glPopMatrix();
if(RightSibling != NULL)
RightSibling->Traverse();
}
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
667
669
670
CSG Trees
- CSG Trees
- Shade Trees
- BSP Trees
- Quadtrees and Octrees
668
671
672
112
Set Operations
673
Shade Trees
674
I = kd Ld l n + k s Ls (r v ) + k L I .
675
676
BSP Trees
677
678
113
Quadtrees
Octrees
voxel
data
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
679
an octree
680
Representation of Curves
and Surfaces
Three types of object representation:
- explicit:
y = f (x ).
- implicit:
f ( x , y ) = 0.
- parametric:
p(u ) = [ x (u ) y (u ) z (u )]T .
Explicit Representation of
Lines
682
Explicit Representation of
Circles
y = mx + h
y = r2 x2 .
- The other half requires a second equation:
y = r2 x2 .
683
684
114
Explicit Surfaces
Implicit Representations
y = ax + b,
z = cx + d .
- A line: ax + by + c = 0.
- A circle: x2 + y2 - r2 = 0.
z = f ( x, y ).
685
Implicit Surfaces
- A plane: ax + by + cz + d = 0.
- A sphere: x2 + y2 + z2 - r2 = 0.
687
Parametric Form
y = y (u ),
688
Matrix Notation
x = x (u ),
686
Algebraic Surfaces
z = z (u ).
p(u ) = [ x (u ) y ( u ) z (u )]T
689
690
115
Parametric Surfaces
dx (u ) du
dp ( u )
= dy (u ) du .
du
dz (u ) du
x ( u, v )
p(u, v ) = y (u, v ).
z (u, v )
691
x (u, v ) u
x ( u , v ) v
p
p
= y (u, v ) u and
= y (u, v ) v .
u
v
z (u, v ) u
z (u, v ) v
692
693
n=
p p
.
u v
694
Parametric Polynomial
Curves
Implementation Details
p( u ) = u k c k .
k =0
695
696
116
Parametric Polynomial
Surfaces
Design Criteria
Why we prefer parametric polynomials of
low degree:
n m
p(u, v ) = cij ui v j
i = 0 j =0
A surface patch:
- Specify 3(n+1)(m+1) coefficients.
- Let n = m, and let u and v vary over the
rectangle 0 u, v 1.
697
698
Smoothness
Control Points
699
Parametric Cubic
Polynomial Curves
Matrix Notation
3
p( u ) = c k u k = uT c,
k =0
the coefficient
matrix to be
determined
where
control
points
c0
1
c kx
c
u
1
c = , u = 2 , c k = c ky .
c2
u
c kz
c
u 3
3
700
701
702
117
Interpolation
An interpolating polynomial passes
through its control points.
p 0 = p ( 0) = c 0 ,
xk
p k = yk , for 0 k 3.
zk
p1 = p(1 3) = c 0 + 1 3 c1 + (1 3) 2 c 2 + (1 3) 3 c 3 ,
p 2 = p( 2 3) = c 0 + 2 3 c1 + ( 2 3) 2 c 2 + ( 2 3) 3 c 3 ,
p3 = p(1) = c 0 + c1 + c 2 + c 3.
Interpolating Geometry
Matrix
Matrix Notation
In matrix notation p = Ac, where
0
p0
1 0
p
1 1 3 (1 3) 2
1
p = and A =
2
p
2
1 2 3 ( 2 3)
p
1 1
1
3
a column vector
of row vectors
704
(1 3)3
.
( 2 3) 3
1
0
0
0
0
1
5 .5
4.5
9
1
M I = A 1 =
22.5
4.5
18
9
c = M I p.
nonsingular: we
will use its inverse
705
Joining Interpolating
Segments
706
Blending Functions
p(u ) = uT c = uT M I p.
Let
707
708
118
3 3
p(u, v ) = u i v j c ij .
i =0 j =0
709
710
Matrix Notation
In matrix form, the patch is defined by
p(u, v ) = uT Cv,
uT M I P = uT CA T .
- The coefficient matrix C is computed by
16 equations in 16 unknowns.
C = M I PMTI .
- The equation for the surface becomes
p(u, v ) = uT M I PMTI v.
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
711
712
Blending Patches
Extending our use of blending
polynomials to surfaces:
3 3
p(u, v ) = bi (u )b j ( v )pij .
i =0 j =0
p ( 0) = p 0 = c 0 ,
p(1) = p3 = c 0 + c1 + c 2 + c 3.
713
714
119
Additional Conditions
Matrix Form
dx du
p (u ) = dy du = c1 + 2uc 2 + 3u 2c 3.
dz du
call this q
p3 = p (1) = c1 + 2c 2 + 3c 3.
MH
716
Smoothness of the
Hermite Form
Using blending functions p(u)=b(u)Tq,
0
0
0
1
0
0
1
0
.
=
3 3 2 1
2 2 1
1
2u 3 3u 2 + 1
2u 3 + 3u 2
b(u ) = MTH u = 3
.
u 2u 2 + u
3
2
u u
p(u ) = uT M H q.
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
0 0 0
1 1 1
c.
1 0 0
1 2 2
p0 = p (0) = c1,
p 0 1
p 1
3 =
p0 0
p 0
3
717
718
Parametric Continuity
- C0 parametric continuity:
q x ( 0)
p x (1)
p(1) = p y (1) = q(0) = q y (0).
p z (1)
q z (0)
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
719
720
120
Another Approach:
Geometric Continuity
C1 Parametric Continuity
Matching derivatives at the join points
gives us C1 continuity:
p x (1)
q x (0)
p z (1)
q z (0)
different
magnitude
same
direction
721
722
3p1 3p 0 = c1,
0
1
3 3
MB =
3 6
1 3
0 0
0 0
.
3 0
3 1
3p3 3p 2 = c1 + 2c 2 + 3c 3.
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
p(u ) = uT M B p.
723
724
Properties of Bernstein
Polynomials
bkd (u ) =
d!
u k (1 u ) d k .
k!( d k )!
725
726
121
p(u, v ) = bi (u )b j (u )pij
i =0 j =0
= uT M B PMTB v.
727
p
(0,0) = 3( p10 p00 ),
u
p
(0,0) = 3( p01 p 00 ).
v
2p
(0,0) = 9( p00 p01 + p10 p11 ).
uv
729
Cubic B-Splines
730
{pi 2 , pi 1, pi , pi +1}.
728
731
732
122
pi 3
pi 2
p
p
i 1
i 2
and q =
p=
.
pi
pi 1
p
pi +1
i
p(u ) = u Mp,
T
Symmetric
Approximations
1
p(0) = q(1) = ( pi 2 + 4pi 1 + pi ),
6
1
p (0) = q (1) = ( pi pi 2 ),
2
p(u ) = uT c.
735
736
B-Spline Blending
Functions
734
Additional Conditions
4
1
1
3 0
3
1
MS =
6 3 6 3
1 3 3
(1 u )3
2
3
1 4 6u + 3u
6 1 + 3u + 3u 2 3u 3
u3
0
0
.
0
1
737
738
123
Advantages of B-spline
Curves
u i + 2.
0
739
740
Approximating Splines
m 1
p(u ) = Bi (u )pi .
i =1
741
Spline Surfaces
742
General B-Splines
i =0 j =0
p(u, v ) = bi (u )b j (u )pij .
j =0
743
744
124
The Cox-deBoor
Recursion
Recursively Defined
B-Splines
1 uk u uk +1,
Bk 0 =
0 otherwise;
u uk
Bk ,d 1 ( u ) +
Bkd =
uk + d uk
uk + d u
B
(u ).
uk + d +1 uk +1 k +1,d 1
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
745
Uniform Splines
746
Nonuniform B-Splines
{0,0,0,0,1,2,K, n 1, n, n, n, n}
{0,0,0,0,1,1,1,1}.
periodic
uniform
B-spline
often used
747
748
NURBS
Use weights to increase or decrease the
importance of a particular point.
A 4D B-spline
x (u ) n
q(u ) = y (u ) = Bi ,d (u ) wi pi .
i =0
z (u )
xi
y
i
q i = wi .
zi
1
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
w(u ) = Bi ,d (u ) wi .
i =0
749
750
125
Nonuniform Rational
B-Splines
p( u ) =
n
1
B ( u ) wi pi
q(u ) = i =n0 i ,d
.
w( u )
i =0 Bi ,d (u ) wi
Polynomial Evaluation
Methods
( 0)p( uk ) = p(uk ),
p( u ) = c i u , 0 u 1
i
i =0
Horner's method:
752
753
754
compute
these
( m 1) ( pk +1 ) = ( m ) p(uk ) + ( m 1) p(uk ).
Angel: Interactive Computer Graphics 4E Addison-Wesley 2006
755
756
126
757
Efficient Computation of
the Subdivision
758
Using Subdivision
Methods
Curve subdivision extends to surfaces.
l 0 = p0 ,
1
l1 = ( p0 + p1 ),
2
1
1
l1 + ( p1 + p 2 ) ,
2
2
1
l 3 = r0 = (l 2 + r1 ).
2
l2 =
759
760
Rendering Quadric
Surfaces
Algebraic Surfaces
Quadric surfaces are described by
implicit equations of the form
pT Ap + bT p + c = 0.
761
762
127
Quadric Objects in
OpenGL
Creating a 1D evaluator:
glMap1f(type, u_min, u_max, stride,
order, point_array);
GLUquadricObj *qobj;
qobj = gluNewQuadric();
763
Using a 2D evaluator:
765
glMap2f(GL_MAP_VERTEX_3,0,1,3,4,0,1,12,4,data);
...
for(j=0; j<99; j++) {
glBegin(GL_QUAD_STRIP);
for(i=0; i<=100; i++) {
glEvalCoord2f(i/100., j/100.);
glEvalCoord2f((i+1)/100., j/100.);
}
glEnd();
}
766
GLfloat data[32][4][4];
764
767
768
128