114
Computer Graphics Computer Graphics CSC 830 CSC 830 Lecture notes 2 Lecture notes 2 OpenGL OpenGL

Computer Graphics CSC 830

  • Upload
    kata

  • View
    32

  • Download
    2

Embed Size (px)

DESCRIPTION

Computer Graphics CSC 830. Lecture notes 2 OpenGL. What is OpenGL?. It is NOT a language. It is a Graphics Rendering API (Application Programmer’s Interface) that is a set of function with well defined interface. - PowerPoint PPT Presentation

Citation preview

Page 1: Computer Graphics CSC 830

Computer GraphicsComputer GraphicsCSC 830CSC 830

Computer GraphicsComputer GraphicsCSC 830CSC 830

Lecture notes 2Lecture notes 2OpenGLOpenGL

Page 2: Computer Graphics CSC 830

2

What is OpenGL?• It is NOT a language.• It is a Graphics Rendering API (Application Programmer’s

Interface) that is a set of function with well defined interface.

• Whenever we say that a program is OpenGL-based or OpenGL applications, we mean that it is written in some programming language (such as C/C++ or Java) that makes calls to one or more of OpenGL libraries.

• OpenGL is Not Object-Oriented. OpenGL API does not make use of features such as overloading that are available in object-oriented languages. -> I will show examples with C language bindings.

Page 3: Computer Graphics CSC 830

A History of OpenGL• Was SGI’s Iris GL – basis for “Open”GL• “Open” standard allowing for wide range

hardware platforms• OpenGL v1.0 (1992)• OpenGL v1.1 (1995)• OpenGL v1.5 (latest)

• Governed by OpenGL Architecture Review Board (ARB) which has members from such as Silicon Graphics, IBM, and NVIDIA.

• “Mesa” – an Open source (http://www.mesa3d.org)

Page 4: Computer Graphics CSC 830

4

• Official Sitehttp://www.opengl.org

• Non official sites– http://nehe.gamedev.net/

• BOOKS – OpenGL : A Primer– OpenGL Red Book & – OpenGL Blue Book

Useful Websites and Books

Page 5: Computer Graphics CSC 830

5

Useful Links• Online Reference manual sites

• GL and GLUhttp://www.mevis.de/~uwe/opengl/opengl.html

• GLUThttp://pyopengl.sourceforge.net/documentation/manual/

reference-GLUT.html

Page 6: Computer Graphics CSC 830

6

Three View of OpenGL• Programmer’s view

– Specifying a set of objects to render – Describing properties of these objects – Defining how these objects should be viewed

• State machine– Keeps states that affects appearances of input ie. States

determines how the inputs are processed.– Change state (such as color) by using state changing functions

• OpenGL uses Rendering Pipeline Model– Models -> Transformer -> Clipper -> Projector -> Rasterizer ->

Image

Page 7: Computer Graphics CSC 830

7

OpenGL API Functions• OpenGL contains over 200 functions

– Primitive functions : define the elements (eg. A point, line, polygon, etc)

– Attribute functions : control the appearance of primitives (eg. colors, line types, light source, textures.)

– Viewing functions : determine the properties of camera. Transformation

– Windowing functions: not part of core OpenGL

– Other functions

Page 8: Computer Graphics CSC 830

8

Window Management• OpenGL is meant to be platform

independent. i.e. OpenGL is window and operating system independent.

• OpenGL does not include any functions for window management, user interaction, and file I/O.

• Host environment is responsible for window management.

Page 9: Computer Graphics CSC 830

9

Window Management API

• We need additional libraries to handle window management

• GLX/AGL/WGL - glue between OpenGL and windowing systems

• GLUT - OpenGL Window Interface/Utility toolkit

• AUX - OpenGL Utility Toolkit

Page 10: Computer Graphics CSC 830

OpenGL API Hierarchy

Page 11: Computer Graphics CSC 830

11

OpenGL Division of Labor

• GL - “core” library of OpenGL that is platform independent

• GLU - an auxiliary library that handles a variety of graphics accessory functions

• GLUT/AUX - utility toolkits that handle window managements

Page 12: Computer Graphics CSC 830

Libraries and HeadersLibrary Name

Library File Header File

Note

OpenGL opengl32.lib (PC)-lgl (UNIX)

gl.h “core” library

Auxiliary library

glu32.lib (PC)-lglu

glu.h handles a variety of accessory functions

Utility toolkits glut32.lib (PC)-lglut (UNIX)glaux.lib (PC)-lglaux (UNIX)

glut.hglaux.h

window managements

All are presented in the C language

Page 13: Computer Graphics CSC 830

13

Learning OpenGL with GLUT

• GLUT is a Window Manager (handles window creation, user interaction, callbacks, etc)

• http://www.opengl.org/resources/libraries/glut/spec3/spec3.html

• Platform Independent• Makes it easy to learn and write OpenGL

programs without being distracted by your environment

• All of our discussions will be presented in C/C++ language

Page 14: Computer Graphics CSC 830

Include Header files

#include <GL/gl.h> // “core”, the only thing is required

#include <GL/glu.h> // handles accessory functions

#include <GL/glut.h> // handles window managements

void main( int argc, char **argv ){

…..}

Only the “core” library (opengl32.lib, gl.h) are required

Include the necessary header files in your code

Page 15: Computer Graphics CSC 830

Link Libraries

• Link GL library– Link opengl32.lib (PC), or -lgl (UNIX)

• Link GLU library– Link glu32.lib (PC), or -lglu (UNIX)

• Link GLUT library– Link glut32.lib (PC), or -lglut (UNIX)

Link the necessary Libraries to your code

Page 16: Computer Graphics CSC 830

Programming Convention : OpenGL

Data Types

To make it easier to convert OpenGL code from one platform to another, OpenGL defines its own data types that map to normal C data types

GLshort A[10]; short A[10];

GLdouble B; double B;

Page 17: Computer Graphics CSC 830

Programming Convention : OpenGL

Data TypesOpenGL Data Type Representatio

nAs C Type

GLbyte 8-bit integer signed char

GLshort 16-bit integer short

GLint, GLsizei 32-bit integer long

GLfloat 32-bit float float

GLdouble 64-bit float double

GLubyte, GLboolean 8-bit unsigned integer

unsigned char

GLushort 16-bit unsigned short

unsigned short

GLunit, GLenum, GLbitfield

32-bit unsigned integer

unsigned long

Page 18: Computer Graphics CSC 830

Programming Convention : OpenGL

Function Naming

OpenGL functions all follow a naming convention that tells you which library the function is from, and how many and what type of arguments that the function takes

<Library prefix><Root command><Argument count><Argument type>

Page 19: Computer Graphics CSC 830

Programming Convention : OpenGL

Function Naming

glColor3f(…) gl library Root command, # of arguments, type of arguments

gl means OpenGL

glu means GLU

glut means GLUT

f: the argument is float type

i: the argument is integer type

v: the argument requires a vector

Page 20: Computer Graphics CSC 830

20

Programming Convention : OpenGL

Function Naming• Multiple forms of OpenGL functions to

support the variety of data types– glVertex3i(ix, iy, iz)– glVertex3f(x, y, z)– glVertex2i(ix, iy)– glVertex2f(x, y)– ..– We shall use the notation glVertex*() to refer to

all the forms of the vertex function

Page 21: Computer Graphics CSC 830

21

Basic OpenGL Coding Framework

1. Configure GL (and GLUT) - Open window, Display mode, ……

2. Initialize OpenGL state - background color, light, View positions, ……

3. Register callback functions - Render, Interaction (keyboard, mouse), ……

4. Event processing loop - glutMainLoop()

Page 22: Computer Graphics CSC 830

A Sample Programvoid main (int argc, char **argv)

{

glutInit (&argc, argv);

glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);

glutInitWindowSize (500, 500);

glutCreateWindow (“My First Program");

myinit ();

glutDisplayFunc ( display );

glutReshapeFunc ( resize );

glutKeyboardFunc ( key );

glutMainLoop ();

}

1

2

3

4

Page 23: Computer Graphics CSC 830

1: Initializing & Creating Window

void main (int argc, char **argv)

{

glutInit (&argc, argv); // GLUT initialization

glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); // display model

glutInitWindowSize (500, 500); // window size

glutCreateWindow (“My First Program"); // create window

……

}

Set up window/display you’re going to use

Page 24: Computer Graphics CSC 830

GLUT Initializing Functions• Standard GLUT initialization

void glutInit (int *argc, char ** argv)• Display model

void glutInitDisplayMode (unsigned int mode) –Define color model : GLUT_RGB or GLUT_INDEX

–Define buffering: GLUT_SINGLE | GLUT_DOUBLE

• Window size and positionvoid glutInitWindowSize (int width, int height)void glutInitWindowPosition(int x, int y)

- top-left corner of the screen in pixel• Create window

int glutCreateWindow (char *title);

Page 25: Computer Graphics CSC 830

2: Initializing OpenGL State

void myinit(void)

{

glClearColor(1.0, 1.0, 1.0, 1.0); // background color

glColor3f(1.0, 0.0, 0.0); // line color

glMatrixMode(GL_PROJECTION); // followings set up viewing

glLoadIdentity();

gluOrtho2D(0.0, 500.0, 0.0, 500.0);

glMatrixMode(GL_MODELVIEW);

}

Set up whatever state you’re going to use

Page 26: Computer Graphics CSC 830

Event Loops and Callback Functions

• Interactive programs react to the events such as mouse or keyboard events and window events.

• Callback Function - Routine to call when something happens (eg. window resize, redraw, user input, etc)

• GLUT uses a callback mechanism to do its event processing

Page 27: Computer Graphics CSC 830

GLUT Callback Functions• Contents of window need to be refreshed

glutDisplayFunc() • Window is resized or moved

glutReshapeFunc()• Key action

glutKeyboardFunc()• Mouse button action

glutMouseFunc()• Mouse moves while a button is pressed

glutMotionFunc()• Mouse moves regardless of mouse button state glutPassiveMouseFunc()• Called when nothing else is going on

glutIdleFunc()

Page 28: Computer Graphics CSC 830

3: Register Callback Functions

void main (int argc, char **argv)

{

……

glutDisplayFunc ( display ); // display callback

glutReshapeFunc ( resize ); // window resize callback

glutKeyboardFunc ( key ); // keyboard callback

……

}

Set up any callback function you’re going to use

Page 29: Computer Graphics CSC 830

Rendering Callback

void display( void )

{

int k;

glClear(GL_COLOR_BUFFER_BIT);

for( k=0; k<5000; k++)

……

}

It’s here that does all of your OpenGL rendering

Page 30: Computer Graphics CSC 830

Window Resize Callback

void resize(int w, int h)

{

……

display();

}

It’s called when the window is resized or moved

Page 31: Computer Graphics CSC 830

Keyboard Input Callback

void key( char mkey, int x, int y ){ switch( mkey ) { case ‘q’ : exit( EXIT_SUCCESS ); break; …… }}

It’s called when a key is struck on the keyboard

Page 32: Computer Graphics CSC 830

4. Event Process Loop

void main (int argc, char **argv)

{

……

glutMainLoop();

}

This is where your application receives events, and schedules when callback functions are called

Page 33: Computer Graphics CSC 830

33

2D Geometric Primitives

• Primitives – fundamental entities such as point and polygons

• Basic types of geometric primitives– Points– Line segments– Polygons

Page 34: Computer Graphics CSC 830

34

2D Geometric Primitives

GL_POINTS GL_LINES GL_LINE_STRIP

GL_LINE_LOOP

GL_POLYGON

GL_QUADS GL_TRIANGLES

GL_TRIANGLE_FAN

All geometric primitives are specified by vertices

Page 35: Computer Graphics CSC 830

35

Geometry Commands• glBegin(GLenum type)

marks the beginning of a vertex-data list that describes a geometric primitives

• glEnd (void)

marks the end of a vertex-data list

• glVertex*(…)

specifies vertex for describing a geometric object

Page 36: Computer Graphics CSC 830

36

Specifying Geometric Primitives

glBegin( type ); glVertex*(…); …… glVertex*(…);glEnd();

type determines how vertices are combined

Page 37: Computer Graphics CSC 830

37

Types

GL_POINTS GL_LINES GL_LINE_STRIP

GL_LINE_LOOP

GL_POLYGON

GL_QUADS GL_TRIANGLES

GL_TRIANGLE_FAN

Page 38: Computer Graphics CSC 830

38

TypesGL_POINTSGL_LINES : each successive pair for a ling segmentGL_LINE_STRIP: vertices defining a sequence of line segmentsGL_LINE_LOOP: GL_LINE_STRIP + the last vertex connects to

the firstGL_POLYGON : sequence of vertices of polygon, filledGL_QUADS: each successive group of four vertices for a

quadrilateralsGL_TRIANGLES: each successive group of three vertices for a

triangleGL_TRIANGLE_FAN: first three vertices for the first triangle

and each subsequent vertex with the first vertex and the previous vertex for the next triangle

Page 39: Computer Graphics CSC 830

39

Attribute : Linevoid glLineWidth(GLfloat width)

– Set the width in pixel. Default is 1.0

void glLineStripple(GLint factor, GLushort pattern)

Page 40: Computer Graphics CSC 830

40

Rectangles• glRect*() – defines 2D filled

rectangle aligned with the axes.

void glRect{sifd} (TYPE x1, TYPE y1, TYPE x2, TYPE y2);

Page 41: Computer Graphics CSC 830

41

Examplevoid drawSquare (){ glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glVertex2f ( 0.0, 0.0 ); glVertex2f ( 1.0, 0.0 ); glVertex2f ( 1.1, 1.1 ); glVertex2f ( 0.0, 1.0 ); glEnd(); glFlush(); // force the renderer to output the results }

Page 42: Computer Graphics CSC 830

42

OpenGL Color• There are two color models in

OpenGL– RGB Color (True Color)– Indexed Color (Color map)

Page 43: Computer Graphics CSC 830

43

RGB Color Model

•R, G, B components are stored for each pixel

Page 44: Computer Graphics CSC 830

44

RGB Color

Red

Green

Blue

Page 45: Computer Graphics CSC 830

45

How Many Colors?

Color number =For example:

4-bit color

= 16 colors

8-bit color

= 256 colors

24-bit color

= 16.77 million colors

hcolor_dept2

42

82

242

Page 46: Computer Graphics CSC 830

46

How Much Memory?Buffer size = width * height *color depth

For example:

If width = 640, height = 480, color depth = 24 bits

Buffer size = (640 * 480 * 2) bytes

If width = 640, height = 480, color depth = 32 bits

Buffer size = (640 * 480 * 4) bytes

Page 47: Computer Graphics CSC 830

47

Alpha ComponentAlpha value A value indicating the pixels opacity 0 usually represents totally transparent and

the 1 represents completely opaque

Alpha buffer Hold the alpha value for every pixel Alpha values are commonly represented in 8

bits, in which case transparent to opaque ranges from 0 to 255

Page 48: Computer Graphics CSC 830

48

RGB Color Commands• glColor*(…)

specifies vertex colors

• glClearColor(r, g, b, a)

sets current color for cleaning color buffer

Page 49: Computer Graphics CSC 830

49

Examplevoid drawLine (GLfloat *color){ glColor3fv ( color ); glBegin(GL_LINE); glVertex2f ( 0.0, 0.0 ); glVertex2f ( 1.0, 0.0 ); glEnd();}

Page 50: Computer Graphics CSC 830

50

Examplevoid drawLine (GLfloat *color){

glBegin(GL_LINE);glColor3f(1.0,0.0,0.0 );

glVertex2f ( 0.0, 0.0 );glColor3f(0.0,0.0,1.0);

glVertex2f ( 1.0, 0.0 ); glEnd();}

Page 51: Computer Graphics CSC 830

51

Color InterpolationglShadeModel(GL_SMOOTH);

OrglShadeModel(GL_FLAT); - the last

vertex color

• Linear interpolation for a line• Bilinear interpolation for a polygons

Page 52: Computer Graphics CSC 830

52

2D Viewing• Where do we draw the 2D object?

– Assume that we draw objects on an infinite sheet of paper

– Then we need to specify clipping region and project these 2D objects to the screen

void gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top);

Page 53: Computer Graphics CSC 830

53

Coordinate Systems and Transformation

• Identify which matrix we wish to alter• Set the matrix to an identity matrix• Alter the matrix to form the desired

matrix

glMatrixMode(GL_PROJECTION);

glLoadIdentity();

gluOrtho2D(-1.0, 1.0, -1.0, 1.0);

Page 54: Computer Graphics CSC 830

54

Coordinate Systems and Transformation

glMatrixMode(GLenum mode);– Identify which matrix we wish to alter

– The mode is usually GL_MODELVIEW, GL_PROJECTION

glLoadIdentity();– Set the current matrix to an identity

matrix

Page 55: Computer Graphics CSC 830

55

Enabling GL Features• Features – lighting, hidden-surface removal,

texture mapping, etc…• Each feature will slow down the rendering

process.• We can enable/disable each feature individually

void glEnable(GLenum feature)

void glDisable(GLenum feature)

Eg. glEnable(GL_LINE_STRIPPLE);

Page 56: Computer Graphics CSC 830

56

Enabling GL FeaturesGL_ALPHA_TEST

If enabled, do alpha testing. GL_AUTO_NORMAL

If enabled, generate normal vectors when either GL_MAP2_VERTEX_3 or GL_MAP2_VERTEX_4 is used to generate vertices. See glMap2.

GL_BLEND If enabled, blend the incoming RGBA color values with the values in the color buffers..

GL_CLIP_PLANE i If enabled, clip geometry against user-defined clipping plane i..

GL_COLOR_LOGIC_OP If enabled, apply the currently selected logical operation to the incoming RGBA color and color buffer values.

GL_COLOR_MATERIAL If enabled, have one or more material parameters track the current color.

GL_COLOR_TABLE If enabled, preform a color table lookup on the incoming RGBA color values.

GL_CONVOLUTION_1D If enabled, perform a 1D convolution operation on incoming RGBA color values.

GL_CONVOLUTION_2D If enabled, perform a 2D convolution operation on incoming RGBA color values.

……

Page 57: Computer Graphics CSC 830

57

Queries• OpenGL state can be queried by

– void glGet*(GLenum name, Type *value);– Eg. GLfloat color_array[4];

glGetFloatv(GL_CURRENT_COLOR,color_array);

• Check if a feature has been enabled by– GLboolean glIsEnabled(GLenum feature); -

returns GL_TRUE or GL_FALSE

Page 58: Computer Graphics CSC 830

58

Saving the State• State changing functions – overwrites the

state variables• We can store previous state values for later

use– Matrix stacks

void glPushMatrix()void glPopMatrix()

– Attribute stacksvoid glPishAttrib(GLbitfield mask)void glPopAttrib()

Page 59: Computer Graphics CSC 830

59

Saving the StateglMatrix(GL_PROJECTION)

// set projection matrix

// draw scene

glPushMatrix();

// change the project matrix

//draw scene

glPopMatrix();

Page 60: Computer Graphics CSC 830

60

Callback : Reshapevoid glutReshapeFunc(void (*f) (int width, int height));

– invoked whenever the use changes the size of the window using the mouse. width and height is the new window size.

– Usually you want to take care of a new aspect ratio (width-to-height ratio).

Page 61: Computer Graphics CSC 830

61

Callback : Idlevoid glutIdleFunc(void (*)f (void))

– f will be executed whenever there are no other events to be handled.

– necessary for animation

Page 62: Computer Graphics CSC 830

62

Callback : IdleglutIdleFunc(myidle);

void myidle()

{glutPostRedisplay();

}: Request the display callback to be

executed after the current callback returns

Page 63: Computer Graphics CSC 830

63

Double Buffering• Use two buffers :front buffer and back

buffer to guarantee to display a fully redrawn butter image

glutSwapBuffers();

– Replace glFlush() by glutSwapBuffer() in the display callback

Page 64: Computer Graphics CSC 830

64

Keyboard InteractionglutKeyboardFunc(void *f (unsigned char key, int x, int

y))• f is called when any key on the keyboard is pressed. (x, y) is the

position of the mouse in the window given in pixel measured from the upper-left corner of the window.

glutKeyboardFunc(mykey);

void mykey(unsigned char key, int x, int y)

{if(key==‘q’)

exit(0);

}

Page 65: Computer Graphics CSC 830

65

Keyboard Interaction• Special Keys (defined in glut.h)glutSpecialFunc(void *f (int key, int x, int y))

glutSpecialFunc(myskey);

void mykey(unsigned char key, int x, int y){

if(key== GLIT_KEY_F1)..

if(key== GLIT_KEY_UP)…

}

Page 66: Computer Graphics CSC 830

66

Keyboard Interaction• int glutGetModifiers() – returns the

logical AND of GLUT_ACTIVE_SHIFT, GLUT_ACTIVE_CTRL or GLUT_ACTIVE_ALT if that key is pressed at the time a mouse of keyboard event is generated.

if(glutGetModifiers() & GLUT_ACTIVE_CTRL) && (key == ‘c’)) exit(0);

Page 67: Computer Graphics CSC 830

67

Mouse Interactionvoid glutMouseFunc(void (*f) (int button, int state, int x, int y);

– register mouse callback function– Button : GLUT_LEFT_BUTTON,

GLUT_RIGHT_BUTTON, GLUT_MIDDLE_BUTTON

– State: GLUT_UP, GLUT_DOWN

Page 68: Computer Graphics CSC 830

68

Mouse Interactionvoid glutMotionFunc(void (*f) (int x, int y));

-- mouse moved with button downvoid glutPassiveMotionFunc(void (*f) (int x, int y); --

mouse moved without button down– (x,y) is the current position of the mouse

• void glutEntryFunc(void (*f) (int state)) ;

– specifies the mouse entry callback– state : GLUT_ENTERED, GLUT_LEFT

Page 69: Computer Graphics CSC 830

69

Null Callback• When we no longer need a

callback.glutIdleFunc(Null);

Page 70: Computer Graphics CSC 830

70

Camera AnalogyThe graphics transformation process is analogous to taking a photograph with a camera- Place objects

- Position camera

- Adjust camera

- Produce photograph

Page 71: Computer Graphics CSC 830

71

Transformations and Camera Analogy

• Modeling transformation– Positioning and moving the model.

• Viewing transformation– Positioning and aiming camera in the world.

• Projection transformation– Adjusting the lens of the camera.

• Viewport transformation– Enlarging or reducing the physical photograph.

Page 72: Computer Graphics CSC 830

72

OpenGL Transformation Pipeline

Page 73: Computer Graphics CSC 830

73

Transformations in OpenGL

• Transformations are specified by matrix operations. Desired transformation can be obtained by a sequence of simple transformations that can be concatenated together.

• Transformation matrix is usually represented by 4x4 matrix (homogeneous coordinates).

• Provides matrix stacks for each type of supported matrix to store matrices.

Page 74: Computer Graphics CSC 830

74

Programming Transformations

• In OpenGL, the transformation matrices are part of the state, they must be defined prior to any vertices to which they are to apply.

• In modeling, we often have objects specified in their own coordinate systems and must use transformations to bring the objects into the scene.

• OpenGL provides matrix stacks for each type of supported matrix (model-view, projection, texture) to store matrices.

Page 75: Computer Graphics CSC 830

75

Steps in Programming• Define matrices:

– Viewing/modeling, projection, viewport …

• Composite transformations

Page 76: Computer Graphics CSC 830

76

Transformation Matrix Operation

• Current Transformation Matrix (CTM) – The matrix that is applied to any vertex

that is defined subsequent to its setting.

• If change the CTM, we change the state of the system.

• CTM is a 4 x 4 matrix that can be altered by a set of functions.

Page 77: Computer Graphics CSC 830

77

Current Transformation Matrix

The CTM can be set/reset/modify (by post-multiplication) by a matrix

Ex:

C <= M // set to matrix M

C <= CT // post-multiply by T

C <= CS // post-multiply by S

C <= CR // post-multiply by R

Page 78: Computer Graphics CSC 830

78

Current Transformation Matrix

• Each transformation actually creates a new matrix that multiplies the CTM; the result, which becomes the new CTM.

• CTM contains the cumulative product of multiplying transformation matrices.

Ex: If C <= M; C <= CT; C <= CR; C <= CS

Then C = M T R S

Page 79: Computer Graphics CSC 830

79

Ways to Specify Transformations

• In OpenGL, we usually have two styles of specifying transformations:

– Specify matrices ( glLoadMatrix, glMultMatrix )

– Specify operations ( glRotate, glTranslate )

Page 80: Computer Graphics CSC 830

80

Specifying Matrix• Identify current matrix • Modify current matrix• Load current matrix• Multiple current matrix

Page 81: Computer Graphics CSC 830

81

Specifying Matrix (1)• Identify current matrixglMatrixMode (mode)

Specified what transformation matrix is modified.

mode:

GL_MODELVIEW

GL_PROJECTION

Page 82: Computer Graphics CSC 830

82

Specifying Matrix(2)• Modify current matrix

glLoadMatrix{fd} ( Type *m )

Set the 16 values of current matrix to those specified by m.

Note: m is the 1D array of 16 elements arranged by the columns of the desired matrix

Page 83: Computer Graphics CSC 830

83

Specifying Matrix(3)• Modify current matrix

glLoadIdentity ( void )

Set the currently modifiable matrix to the 4x4 identity matrix.

Page 84: Computer Graphics CSC 830

84

Specifying Matrix(4)• Modify current matrix

glMultMatrix{fd} ( Type *m )

Multiple the matrix specified by the 16 values pointed by m by the current matrix, and stores the result as current matrix.

Note: m is the 1D array of 16 elements arranged by the columns of the desired matrix

Page 85: Computer Graphics CSC 830

85

Specifying Operations• Three OpenGL operation routines

for modeling transformations:– Translation– Scale– Rotation

Page 86: Computer Graphics CSC 830

86

Recall

1000

100

010

001

z

y

x

d

d

d

,, zyx dddTTranslation:

1000

000

000

000

z

y

x

s

s

s

,, zyx sssSScale:

• Three elementary 3D transformations

Page 87: Computer Graphics CSC 830

87

Recall

1000

0cossin0

0sincos0

0001

)(Rx

)(Ry

1000

0cos0sin

0010

0sin0cos

1000

0100

00cossin

00sincos

)(

Rz

Rotation )(Rx

Rotation )(Ry

Rotation )(Rz

Page 88: Computer Graphics CSC 830

88

Specifying Operations (1)

• Translation

glTranslate {fd} (TYPE x, TYPE y, TYPE z)

Multiplies the current matrix by a matrix that translates an object by the given x, y, z.

Page 89: Computer Graphics CSC 830

89

Specifying Operations (2)

• Scale

glScale {fd} (TYPE x, TYPE y, TYPE z)

Multiplies the current matrix by a matrix that scales an object by the given x, y, z.

Page 90: Computer Graphics CSC 830

90

Specifying Operations (3)

• Rotate

glRotate {fd} (TPE angle, TYPE x, TYPE y, TYPE z)

Multiplies the current matrix by a matrix that rotates an object in a counterclockwise direction about the ray from origin through the point by the given x, y, z. The angle parameter specifies the angle of rotation in degree.

Page 91: Computer Graphics CSC 830

91

Order of Transformations

• The transformation matrices appear in reverse order to that in which the transformations are applied.

• In OpenGL, the transformation specified most recently is the one applied first.

Page 92: Computer Graphics CSC 830

92

Order of Transformations• In each step:

C <= IC <= CT(4.0, 5.0, 6.0)C <= CR(45, 1.0, 2.0, 3.0)C < = CT(-4.0, -5.0, -6.0)

• FinallyC = T(4.0, 5.0, 6.0) CR(45, 1.0, 2.0, 3.0) CT(-4.0, -

5.0, -6.0)Write it

Read it

Page 93: Computer Graphics CSC 830

93

Matrix Multiplication is Not Commutative

First rotate, then translate =>

First translate, then rotate =>

Page 94: Computer Graphics CSC 830

94

Viewing-Modeling Transformation

• If given an object, and I want to render it from a viewpoint, what information do I have to have?

– Viewing position– Which way I am looking at– Which way is “up”…..

Page 95: Computer Graphics CSC 830

95

Viewing Position

• Translation• Rotation

x

y

z

x

y

z Camera

R, T

Page 96: Computer Graphics CSC 830

96

Where I am and Looking at

x

y

z

x

y

zEyepoint

(eyex, eyey, eyez)

Model

View-up vector

(upx, upy, upz)

Loot at

(atx, aty, atz)

Page 97: Computer Graphics CSC 830

97

Define Coordinate System

+X

+Z

+YIn the default position, the camera is at the origin, looking down the negative z-axis

Page 98: Computer Graphics CSC 830

98

If we use OpenGL• Look-At Function

gluLookAt (eyex, eyey, eyez, atx, aty, atz, upx, upy, upz )

Define a viewing matrix and multiplies it to the right of the current matrix.

Page 99: Computer Graphics CSC 830

99

Matrix Stacks• OpenGL uses matrix stacks

mechanism to manage transformation hierarchy.

• OpenGL provides matrix stacks for each type of supported matrix to store matrices.– Model-view matrix stack– Projection matrix stack– Texture matrix stack

Page 100: Computer Graphics CSC 830

100

Matrix Stacks

Top

Bottom

Popping

Pushing

• Current matrix is always the topmost matrix of the stack

• We manipulate the current matrix is that we actually manipulate the topmost matrix.

• We can control the current matrix by using push and pop operations.

Page 101: Computer Graphics CSC 830

101

Manipulating Matrix Stacks (1)

• Remember where you are

glPushMatrix ( void )

Pushes all matrices in the current stack down one level. The topmost matrix is copied, so its contents are duplicated in both the top and second-from-the top matrix.

Note: current stack is determined by glMatrixModel()

Page 102: Computer Graphics CSC 830

102

Manipulating Matrix Stacks (2)

• Go back to where you were

glPopMatrix ( void )

Pops the top matrix off the stack, destroying the contents of the popped matrix. What was the second-from-the top matrix becomes the top matrix.

Note: current stack is determined by glMatrixModel()

Page 103: Computer Graphics CSC 830

103

Manipulating Matrix Stacks (3)

• The depth of matrix stacks are implementation-dependent.

• The Modelview matrix stack is guaranteed to be at least 32 matrices deep.

• The Projection matrix stack is guaranteed to be at least 2 matrices deep.

glGetIntegerv ( Glenum pname, Glint *parms )

Pname:

GL_MAX_MODELVIEW_STACT_DEPTH

GL_MAX_PROJECTION_STACT_DEPTH

Page 104: Computer Graphics CSC 830

104

Projection Transformation

• Projection & Viewing Volume• Projection Transformation• Viewpoint Transformation

Page 105: Computer Graphics CSC 830

105

OpenGL and Windows Screen

Remember: the Y coordinates of OpenGL screen is the opposite of Windows screen. But same as in the XWindows system.

PositiveX

YPositive

OpenGL Screen Mapping

(50, 50)

(0, 0)

PositiveX

Y Positive

Windows Screen Mapping

(50, 50)

(0, 0)

Page 106: Computer Graphics CSC 830

106

Perspective Projection Volume

Far-plane: zNearNear-plane: zNear

Viewing volume

hw

aspect ratio = w/hy

z

x

fovy

Page 107: Computer Graphics CSC 830

107

Perspective Projection Commands

glFrustum( left, right, bottom, top, zNear, zFar )

Creates a matrix for a perspective viewing frustum and multiplies the current matrix by it.

Page 108: Computer Graphics CSC 830

108

Perspective Projection Commands

gluPerspective( fovy, aspect, zNear, zFar )

Creates a matrix for an perspective viewing frustum and multiplies the current matrix by it.

Note: fovy is the field of view (fov) between the top and bottom planes of the clipping volume. aspect is the aspect ratio

Page 109: Computer Graphics CSC 830

109

Remember to Initialize

glutInitDisplayMode(GLUT_DOUBLE|GLUT_RBG|GLUT_DEPTH);

glClear(GL_DEPTH_BUFFER_BIT)

Clear z (depth) buffer

You can also clear the depth buffer (as we did for color buffer)

Page 110: Computer Graphics CSC 830

110

Viewing a 3D world

View right

View up

ViewUp

ViewRightAspect Ratio

Page 111: Computer Graphics CSC 830

111

Viewport• Viewport

– The region within the window that will be used for drawing the clipping area

– By default, it is set to the entire rectangle of the window that is opened

– Measured in the window coordinates, which reflect the position of pixels on the screen related to the lower-left corner of the window

Page 112: Computer Graphics CSC 830

112

Viewport Transformation

A viewpoint is defined as the same size as the window

A viewpoint is defined as half the size of the window

h

w h

w

Page 113: Computer Graphics CSC 830

113

Aspect Ratio• The Aspect Ratio of a rectangle is the

ratio of the rectangle’s width to its height:

e.g. Aspect Ratio = width/height

• Viewport aspect ratio should be same as projection transformation, or resulting image may be distorted.

Page 114: Computer Graphics CSC 830

114

Viewport Commands• glViewport( x, y, width, height )

Defines a pixel rectangle in the window into which the final image is mapped

(x, y) specifies the lower-left corner of the viewport

(width, height) specifies the size of the viewport rectangle