Introduction to Computer Graphics with...

Post on 16-Jun-2018

219 views 0 download

transcript

Introduction to Computer

Graphics with OpenGL/GLUT

What is OpenGL?

• OpenGL (Open Graphics Library)

• A software interface to graphics hardware

• a standard specification defining a cross-language,

cross-platform graphics rendering API for writing

applications that produce 2D/3D computer graphics.

• the industry's most widely used, supported and best

documented 2D/3D graphics API.

2

OpenGL and GLUT

• GLUT (OpenGL Utility Toolkit)• An auxiliary library

• A portable windowing API

• Easier to show the output of your OpenGL application

• Not officially part of OpenGL

• Handles:• Window creation,

• OS system calls

• Mouse buttons, movement, keyboard, etc…

How to install GLUT?

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

• Copy the files to following folders:• glut.h VC/include/gl/

• glut32.lib VC/lib/

• glut32.dll windows/system32/

• Header Files:• #include <GL/glut.h>

• #include <GL/gl.h>

• Include glut automatically includes other header files

GLUT Basics

• Application Structure• Configure and open window

• Initialize OpenGL state

• Register input callback functions• render

• resize

• input: keyboard, mouse, etc.

• Enter event processing loop

6

Event Handling in OpenGL/GLUT

• You tell OpenGL which user-defined function to call

when certain events occur.

• OpenGL monitors the input devices. When

something happens (mouse down, key press, etc. )

OpenGL calls your code.

• Can provide functions for

• window resizing

• mouse button presses

• mouse button releases

• mouse motion

• keyboard presses …

Events in OpenGL

Event Example OpenGL Callback Function

Keypress KeyDown

KeyUp

glutKeyboardFunc

Mouse leftButtonDown

leftButtonUp

glutMouseFunc

Motion With mouse press

Without

glutMotionFunc

glutPassiveMotionFunc

Window Moving

Resizing

glutReshapeFunc

System Idle

Timer

glutIdleFunc

glutTimerFunc

Software What to draw glutDisplayFunc

GLUT Callback functions

• Event-driven: Programs that use windows

• Input/Output

• Wait until an event happens and then execute

some pre-defined functions according to the user’s

input

• Events – key press, mouse button press and

release, window resize, etc.

• Your OpenGL program will be in infinite loop

9

Window Resizing

void glutReshapeFunc(void (*func)(int w, int h))

• func is a pointer to a function that takes two arguments,

the new width w and new height h of the window.

OpenGL calls this function whenever the window is

resized.

• func typically makes a call to glViewport() so that

the display is clipped to the new size, and redefines the

projection matrix so that the aspect ratio of the projected

image matches the viewport.

10

Mouse Events

void glutMouseFunc(

void (*func)(int button, int state,

int x, int y));

•func is a pointer to a function that takes 4 integer parameters. func is called by OpenGL whenever a mouse button is pressed or released.

•button specifies which mouse button was pressed, and is either:

GLUT_LEFT_BUTTON,

GLUT_RIGHT_BUTTON, or

GLUT_MIDDLE_BUTTON

11

Mouse Events

•state specifies the state of the mouse button, and

is either:

GLUT_UP, or

GLUT_DOWN

•x and y specify the location (in window-

relative coordinates) of the mouse when the event occurred.

12

Mouse Motion

glutMotionFunc( void (*func)(int x, int y));

• func is called by OpenGL when the mouse pointer moves

within the window while one or more mouse buttons are

pressed.

• x and y specify the location of the mouse when

the event occurred.

13

Keyboard Events

void glutKeyboardFunc(

void (*func)(unsigned char key,

int x, int y));

• func is a pointer to a function that takes 3 parameters. func is called by OpenGL whenever a key is pressed.

• key is the ASCII value of the key that was pressed

• x and y specify the location of the mouse when the key was pressed .

14

Idle Function

glutIdleFunc( void (*func)());

• func is called by OpenGL when no other events are

pending, when it would otherwise be idle.

• Pass in Null (0) to disable the function.

15

Example Code using OpenGL Input

int main( int argc, char** argv)

{

glutInit(&argc, argv);

glutInitDisplayMode( GLUT_RGB || GLUT_SINGLE );

glutInitWindowSize ( 250, 250 );

glutInitWindowPosition ( 100, 100 );

glutCreateWindow (argv[0]);

init ();

glutDisplayFunc ( display );

glutReshapeFunc (reshape );

glutMouseFunc ( mouse );

glutMotionFunc ( motion );

glutKeyboardFunc ( keyboard );

glutMainLoop ();

return 0;

}

16

Example Code Using OpenGL Input

void display ( void )

{

glClear ( GL_COLOR_BUFFER_BIT );

glColor3f (1.0, 1.0, 1.0);

glBegin (GL_POINTS);

glVertex3f (0.5, 0.25, 0.0);

glVertex3f (0.75, 0.5, 0.0);

glVertex3f (0.75, 0.75, 0.0);

glVertex3f (0.25, 0.75, 0.0);

glEnd();

glFlush();

}

17

Example Code Using OpenGL Input

void reshape ()

{

// called when window is resized.

// typically set viewport,

//set projection matrix, etc.

}

18

Example Code Using OpenGL Input

void mouse (int button, int state, int x, int y)

{

switch (button)

case GLUT_LEFT_BUTTON:

if (state == GLUT_DOWN)

// do something

case GLUT_RIGHT_BUTTON:

// etc., etc.

}

19

Example Code Using OpenGL Input

void motion (int x, int y)

{

// do whatever is appropriate,

// e.g., move object to point (x, y)

}

20

Example Code Using OpenGL Input

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

{

switch (key) {

case ‘s’:

// do something

break;

case ‘S’:

// do something here too

break;

case ‘t’:

case ‘T’: // If you don’t want to be case sensitive.

// do something here too

break;

.

.

.

}

}

21

Matrix Operations

• OpenGL has 4 matrices it uses:• GL_MODELVIEW

• contains the composite modeling and viewing matrices

• GL_PROJECTION• contains a matrix for the projection transformation

• GL_TEXTURE• used for performing operations on the texture (stretching,

moving, rotating, etc.)

• GL_COLOR• used for color space conversions

• Make sure the appropriate matrix is current when you do modeling, viewing, or projections

22

Setting the Current Matrix

void glMatrixMode(Glenum mode);

• sets the current matrix to be mode

•mode is GL_MODELVIEW, GL_PROJECTION,

GL_TEXTURE, or GL_COLOR

23

Loading the Current Matrix

void glLoadMatrix{fd}( TYPE *m)

• loads the array m of TYPE GLfloat or GLdouble to

the current matrix

24

Multiplying the Current Matrix

void glMultMatrix{fd}(TYPE *m)

• Postmultiplies the current matrix by m, which is of

TYPE GLfloat or GLdouble

25

Transformations

• Translation:

void glTranslate{fd}( TYPE dx, TYPE dy, TYPE dz)

•TYPE is GLfloat or GLdouble

• The translation is applied to the current matrix – make sure the appropriate matrix is current, e.g.,

glMatrixMode(GL_MODELVIEW);

glTranslate(0.3, 0.2, 1.5);

• Distances are in world coordinates

26

Transformations

• Rotation:

void glRotate{fd}(TYPE angle, TYPE dx,

TYPE dy, TYPE dz)

• rotates angle about the axis given by (dx, dy,

dz) and the origin

•TYPE is GLfloat or GLdouble

27

Transformations

• Scale:

void glScale{fd}( TYPE sx, TYPE sy, TYPE

sz)

• scales about the origin by (sx, sy, sz)

•TYPE is GLfloat or GLdouble

28

Viewing - Parallel

• Setting an orthographic view

glOrtho(GLdouble left, GLdouble right,

GLdouble bottom, GLdouble top,

GLdouble zNear, GLdouble zFar)

• produces a parallel projection with the clipping volume being

• [left, right] in the x direction

• [bottom, top] in the y direction

• [zNear, zFar] in the z direction

• Only objects falling in this region will be drawn.

• Make sure you call • glMatrixMode (GL_PROJECTION);

• and usually glLoadIdentity();

• before calling glOrtho()

29

Viewing - Perspective

• Setting a perspective view

gluPerspective (GLdouble fovy, GLdouble aspect

GLdouble near, GLdouble far)

•fovy is the angle of the field of view in the xzplane, and must be between 0 and 180.

•aspect is the aspect ratio (width / height)

•near is the distance from the viewpoint to the

near clipping plane (always positive).

•far is the distance from the viewpoint to the far

clipping plane (always positive).

30

Camera Set-Up

• Used to specify camera position and parameters

void gluLookAt( GLdouble eyex, GLdouble eyey, GLdouble eyez, GLdouble atx, GLdouble aty, GLdoubleatz, GLdouble upx, GLdouble upy, GLdouble upz)

The eye point (eyex, eyey, eyez) is the lookFrom pointThe at point (atx, aty, atz) is the lookAt pointThe up point (upx, upy, upz) is the View Up Vector This call creates the appropriate matrix and applies it to the current

matrix. Hence, we need to set the current matrix mode:

glMatrixMode(GL_MODELVIEW);

glLoadIdentity();

gluLookAt(0.0, 0.0, 1.0, 0.0, 0.0,

0.0, 0.0, 1.0, 0.0);

31

Creating a Normal Vector

glNormal3{dfi}(TYPE nx, TYPE ny, TYPE nz )

•TYPE is GLdouble, GLfloat, or GLint

• (nx, ny, nz) are the coordinates of the normal vector

• If GL_RESCALE_NORMAL is enabled, normals do not have to be unit size. The system will normalize them for you.

• Normalization is disabled by default

• Can enable by calling either glEnable(GL_NORMALIZE)

or glEnable(GL_RESCALE_NORMAL)

32

Setting the Normals

glBegin (GL_POLYGON);

glNormal3fv(n0);

glVertex3fv(v0);

glNormal3fv(n1);

glVertex3fv(v1);

glNormal3fv(n2);

glVertex3fv(v2);

glEnd();

33

Lighting

To enable lighting in the scene:

glEnable(GL_LIGHTING )

• This enables lighting in the scene, but does

not enable individual lights

• To enable each light source:

glEnable(GL_LIGHTi )

where 0 ≤ i < GL_MAX_LIGHTS

34

Lighting

To set the value of a light source parameter:glLight{if}v(GLenum light, GLenum pname,

TYPE params )

• light is the light number of the form GL_LIGHTi,

where 0 ≤ i < GL_MAX_LIGHTS

• pname specifies the light source parameter to set, and is one ofGL_AMBIENT (RGBA)GL_DIFFUSE (RGBA)GL_SPECULAR (RGBA)GL_POSITION (x, y, z, w) – if w = 0, it is a directional lightGL_SPOT_DIRECTION (x, y, z)

• params is a pointer to an array that contains the data

35

Lighting

To set the ambient lighting in the scene:

glLightModel{if}{v}(

GLenum GL_LIGHT_MODEL_AMBIENT,

TYPE params )

•params contains a pointer to 4 int or float values that

specify the ambient RGBA intensity of the entire scene.

36

Shading

To set the shading type for the scene:glShadeModel (GLenum mode )

•mode specifies the type of shading to be done, and is either

GL_FLAT

GL_SMOOTH (Gouraud shading)

The default is GL_SMOOTH

37

Setting Material Properties

To set the material properties for the current material:

glMaterial{fi}{v}(GLenum face, GLenum

pname, TYPE params )

•face specifies which face the properties should be

applied to and is:GL_FRONT

GL_BACK

GL_FRONT_AND_BACK

GL_BACK is used for shading back-facing

polygons when two-sided lighting is enabled

38

Setting Material Properties•pname specifies which parameter is to be set and is:

GL_AMBIENT

• The ambient reflectance of the material. (RGBA)

GL_DIFFUSE

• The diffuse reflectance of the material. (RGBA)

GL_SPECULAR

• The specular reflectance of the material. (RGBA)

GL_EMISSION

• The emitted light intensity of the material. (RGBA)

GL_SHININESS

• The specular exponent of the material. (int or float)

39

Texture Mapping

• Steps in using textures in OpenGL:

1. Create a texture.

2. Indicate how the texture is to be applied to each pixel.

3. Enable texture mapping.

4. Draw the scene, specifying both texture and geometric coordinates .

40

Creating a TextureglTexImage2D(GLenum target, GLint level,

GLint internalFormat,

GLsizei width, GLsizei height,

GLint border, GLenum format,

GLenum type, const GLvoid *pixels )

• target should be GL_TEXTURE_2D.• level should be 0.• internalFormat should be GL_RGB.• width is the width of the texture (power of 2).• height is the height of the texture (power of 2).• border should be 0.• format should be GL_RGB.• type specifies the type of data stored, and should be GL_INT,GL_FLOAT, etc.

• pixels is a width by height array of the texture data.

41

Naming a Texture Object

In order to use a texture in OpenGL, you need to name it.The safest way is to have GL provide unused texture

names.

void glGenTextures (GLsizei n, GLuint *textureNames);

• Returns n unused names for texture objects in the array textureNames

• After creating the texture name, it must be bound to the texture.

void glBindTexture (GLenum target, GLuint textureName)

• target should be GL_TEXTURE_2D

• This call creates a new texture object with default values for the texture image and texture properties.

• Subsequent calls to glTexImage*() glTexParameter*(), etc. store data in the texture object.

42

Setting the Texture Environment

void glTexEnvi (GLenum target, GLenum

pname, GLint param);

• This call sets the current texturing environment parameters

•target should be GL_TEXTURE_ENV

•pname should be GL_TEXTURE_ENV_MODE

•param should be GL_DECAL

• Other texturing functions are available - look at an OpenGL book for details

• These are probably the parameters you want.

43

Setting the Texture Parameters

void glTexParameteri (GLenum target,

GLenum pname, GLint param);

• This call sets the current texturing parameters

•target should be GL_TEXTURE_2D

•pname should be GL_TEXTURE_WRAP_S or GL_TEXTURE_WRAP_T

•param should be GL_REPEAT

• Other texturing functions are available, but these are

probably the parameters you want.

44

Texture Coordinates

When you draw an object, you need to specify both geometric coordinates and texture coordinates for each vertex.

Textures are interpolated between vertices.

void glTexCoord2{sifd} (TYPE coords);

e.g.,

void glTexCoord2f(GLFloat s, GLFloat t);

• This call sets the current texture coordinates. Subsequent calls to glVertex*() have those vertices assigned to the set texture coordinate

45

Example of Using Textures

void init (void)

{

glGenTextures(1, &texName);

glBindTexture(GL_TEXTURE_2D, texName);

glTexParameteri(GL_TEXTURE_2D,

GL_TEXTURE_WRAP_S, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D,

GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexImage2D(GL_TEXTURE_2D, GL_RGB,

width,height, 0, GL_RGB, GL_INT,

texImage);

}

46

Example of Using Textures

void display (void)

{

glEnable(GL_TEXTURE_2D);

glTexEnvi(GL_TEXTURE_ENV,

GL_TEXTURE_ENV_MODE, GL_DECAL);

glBindTexture(GL_TEXTURE_2D, texName);

DrawQuad();

glFlush();

glDisable (GL_TEXTURE_2D);

}

47

Example of Using Textures

void DrawQuad(void) {

glBegin(GL_QUADS);

glTexCoord2f (0.0, 0.0);

glVertex3f (-2.0, -1.0, 0.0);

glTexCoord2f (0.0, 1.0);

glVertex3f (-2.0, 1.0, 0.0);

glTexCoord2f (1.0, 1.0);

glVertex3f (0.0, 1.0, 0.0);

glTexCoord2f (1.0, 0.0);

glVertex3f (0.0, -1.0, 0.0);

glTexCoord2f (0.0, 0.0);

glVertex3f (1.0, -1.0, 0.0);

glTexCoord2f (0.0, 1.0);

glVertex3f (1.0, 1.0, 0.0);

glTexCoord2f (1.0, 1.0);

glVertex3f (2.414, 1.0, -1.4.1);

glTexCoord2f (1.0, 0.0);

glVertex3f (-2.414, -1.0, -1.414);

glEnd();

}