Graphics Programming Open GL Katia Oleinik koleinikbu edu
Graphics Programming Open. GL Katia Oleinik: koleinik@bu. edu
Graphics Programming Open. GL • Low-level API • cross-language • cross-platform • 2 D, 3 D computer graphics
GLUT - The Open. GL Utility Toolkit • simple, easy and small • window system independent toolkit for writing Open. GL programs; • implements a simple windowing API; • makes it considerably easier to learn and explore Open. GL; • provides portable API – you can write a single Open. GL program; • designed for constructing small sized Open. GL programs; • is not a full-featured toolkit for large applications that requires sophisticated user interface • has C/C++ and FORTRAN programming bindings • available on nearly all platforms
Step 0. c Simple GLUT program Log on to katana % cp –r /scratch/ogltut/ogl. % cd ogl Note that after tutorial, examples will be available via the web, but not in the location above. Go to http: //scv. bu. edu/documentation/presentations/intro_to_Open. GL/ogltut/
Step 0. c Simple GLUT program #include <stdio. h> #include <stdlib. h> #include <GL/glut. h> void display(void); void init(void); int main(int argc, char **argv){ glut. Init(&argc, argv); // GLUT Configuration glut. Create. Window("Sample GL Window"); // Create Window and give a title glut. Display. Func(display); /* Set display as a callback for the current window */ init(); /* Set basic open. GL states */ /* Enter GLUT event processing loop, which interprets events and calls respective callback routines */ glut. Main. Loop(); return 0; }
Step 0. c Simple GLUT program /* called once to set up basic opengl state */ void init( ){ } /* display is called by the glut main loop once for every animated frame */ void display( ){ }
Steps to edit, compile and run the program • Edit the source file in the editor, save it and exit • >make file_name • >file_name • For step 0. c: • >make step 0 • >step 0
Step 1. c More GLUT functions int main(int argc, char **argv){ glut. Init(&argc, argv); // GLUT Configuration glut. Init. Display. Mode ( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ); glut. Init. Window. Size ( 500, 500 ); // Set size and position of the window glut. Window. Position ( 200, 200 ); glut. Create. Window(“GL Primitives"); // Create Window and give a title glut. Display. Func(display); /* Set a callback for the current window */ init(); /* Set basic open. GL states */ /* Enter GLUT event processing loop */ glut. Main. Loop(); return 0; }
Step 1. c Initialize open. GL scene /* called once to set up basic open. GL state */ void init(void){ gl. Enable(GL_DEPTH_TEST); /* Use depth buffering for hidden surface removal*/ gl. Matrix. Mode(GL_PROJECTION); /* Set up the perspective matrix */ gl. Load. Identity(); /* left, right, bottom, top, near, far */ /* near and far values are the distances from the camera to the front and rear clipping planes */ gl. Ortho(-4. 0, 1. , 10. 0); // orthgraphic view gl. Matrix. Mode(GL_MODELVIEW); /* Set up the model view matrix */ gl. Load. Identity(); /* Camera position */ /* By the default, the camera is situated at the origin, points down the negative z-axis, and has an upper vector (0, 1, 0)*/ glu. Look. At(0. , 5. , 0. , 1. , 0. ); }
Step 1. c More GLUT functions /* drawing routine, called by the display function every animated frame */ void mydraw( ){ gl. Color 3 f( 1. 0, 0. 0); // red color glut. Solid. Sphere(1. , 24); // draw a sphere of radius 1. } /* display is called by the glut main loop once for every animated frame */ void display( ){ /* initialize color and depth buffers */ gl. Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); /* call the routine that actually draws what you want */ mydraw(); glut. Swap. Buffers(); /* show the just-filled frame buffer */ }
GLUT primitives • void glut. Solid. Sphere(GLdouble radius, GLint slices, GLint stacks); • void glut. Wire. Sphere(GLdouble radius, GLint slices, GLint stacks); • void glut. Solid. Cube(GLdouble size); • void glut. Solid. Cone(GLdouble base, GLdouble height, GLint slices, GLint stacks); • void glut. Solid. Torus(GLdouble inner. Radius, GLdouble outer. Radius, GLint nsides, GLint rings); • void glut. Solid. Dodecahedron(void); // radius sqrt(3) • void glut. Solid. Tetrahedron(void); // radius sqrt(3) • void glut. Solid. Icosahedron(void) // radius 1 • void glut. Solid. Octahedron(void); // radius 1
Step 1. c Interactive Exercise #1: working with GLUT primitives • Run interactive exercise #1 • >int_gl_prim • Use up and down arrows to explore different GLUT primitives • Use w/s keys to switch between wire and solid state
Step 1. c GLUT primitives • • • glut. Solid. Sphere glut. Solid. Cube glut. Solid. Cone glut. Solid. Torus glut. Solid. Dodecahedron glut. Solid. Octahedron glut. Solid. Tetrahedron glut. Solid. Icosahedron glut. Solid. Teapot glut. Wire. Sphere glut. Wire. Cube glut. Wire. Cone glut. Wire. Torus glut. Wire. Dodecahedron glut. Wire. Octahedron glut. Wire. Tetrahedron glut. Wire. Icosahedron glut. Wire. Teapot • More info: http: //www. opengl. org/documentation/specs/glut/spec 3/node 80. html
Colors: RGBA vs. Color-Index Color mode RGBA mode Color-Index Mode
Step 1. c Interactive Exercise #2: Exploring open. GL colors • Run interactive exercise • >int_gl_color • Press c/s keys to switch between object/background mode • Use r/g/b keys to switch between red/green/blue components • Use arrow keys to modify the value of color component
Step 1. c Setting up the scene and adding color /* display is called by the glut main loop once for every animated frame */ void display( ){ /* initialize background color and clear color and depth buffers */ gl. Clear. Color(0. 7 f, 0. 7, 0. 0 f); gl. Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); mydraw(); glut. Swap. Buffers(); }
Step 1. c Setting up the scene and adding color void mydraw() { gl. Color 3 f( 1. 0, 0. 0); /* red color */ glut. Solid. Teapot(. 5); /* draw teapot */ } More information about gl color routines: http: //www. opengl. org/sdk/docs/man/xhtml/gl. Color. xml
Step 1. c Open GL transformation
Step 1. c Viewing: Camera Analogy Positioning the Camera Viewing Transformation Positioning the Modeling Transformation Choose a camera lens and adjust zoom Projection Transformation Mapping to screen Viewport Transformation
Step 1. c Viewport transformation • • • indicates the shape of the available screen area into which the scene is mapped Since viewport specifies the region the image occupies on the computer screen, you can think of the viewport transformation as defining the size and location of the final processed photograph - for example, whether the photograph should be enlarged or shrunk. if the window changes size, the viewport needs to change accordingly void gl. Viewport( int x, int y, int width, int height);
Step 1. c Viewport transformation gl. Viewport( 0, 0, width, height);
Step 1. c Projection Perspective vs. Orthographic Objects which are far away are smaller than those nearby; All objects appear the same size regardless the distance; Does not preserve the shape of the objects. Orthographic views make it much easier to compare sizes of the objects. It is possible to accurately measure the distances Perspective view points give more information about depth; Easier to view because you use perspective views in real life. Useful in architecture, game design, art etc. All views are at the same scale Very useful for cartography, engineering drawings, machine parts.
Step 1. c Projection transformation gl. Matrix. Mode(GL_PROJECTION); gl. Load. Identity(); //perspective projection gl. Frustum(left, right, bottom, top, near, far); Or //orthographic projection gl. Ortho (left, right, bottom, top, near, far);
Step 1. c Perspective Transformation //perspective projection void gl. Frustum(double left, double right, double bottom, double top, double near, double far);
Step 1. c Perspective Transformation Four sides of the frustum, its top, and its base correspond to the six clipping planes of the viewing volume. Objects or parts of objects outside these planes are clipped from the final image Does not have to be symmetrical
Step 1. c Perspective Transformation //perspective projection void glu. Perspective( double fovy, double aspect, double near, double far);
Step 1. c Orthographic Transformation //orthographic projection void gl. Ortho( double left, double right, double bottom, double top, double near, double far);
Step 1. c Modelview Matrix //perspective projection void glu. Look. At(double eye. X, double eye. Y, double eye. Z, double center. X, double center. Y, double center. Z, double up. X, double up. Y, double up. Z);
Step 1. c Setting up the scene void init(void) { /* called once to set up basic opengl state */ gl. Enable(GL_DEPTH_TEST); gl. Matrix. Mode(GL_PROJECTION); /* Set up the projection matrix */ gl. Load. Identity(); // left, right, bottom, top, near, far gl. Frustum(-1. 0, 1. 0, 1. , 10. 0); // perspective view // gl. Ortho (-1. 0, 1. 0, 1. , 10. 0); // orthographic view // glu. Perspective(45. 0 f, 1. , 10. ); // perspective view gl. Matrix. Mode(GL_MODELVIEW); /* Set up the model view matrix */ gl. Load. Identity(); eye center up-direction glu. Look. At(0. , 2. , 0. , 1. , 0. ); /* Camera position */ }
Step 1. c Interactive exercise #3: setting up the camera • Run interactive exercise • >int_gl_camera • Use a/ n/ f keys to choose angle/ near/ far modes. • Use ex/ ey/ ez keys to choose x, y, z values for eye location. • Use cx/ cy/ cz keys to choose x, y, z values for center location.
step 1. c Assignment #1: setting up the scene • Modify input file step 1. c 1) Draw a ball with the color of your choice 2) Set orthographic projection, so that the diameter of the ball would be about 20% of the width of the screen. 3) Set up camera on z axis 5 units away from the origin
step 2. c Additional GLUT callback routines GLUT supports many different callback actions, including: glut. Display. Func()defines the function that sets up the image on the screen glut. Reshape. Func() function is called when the size of the window is changed glut. Key. Board. Func() callback routine to respond on keyboard entry glut. Mouse. Func() callback to respond on pressing the mouse button glut. Motion. Func() callback to respond mouse move while a mouse button is pressed glut. Passive. Mouse. Func() callback to respond to mouse motion regardless state of mouse button glut. Idle. Func() callback routine for idle state, usually used for animation More info: http: //www. opengl. org/resources/libraries/glut/spec 3/node 45. html
step 2. c Additional GLUT callback routines int main(int argc, char **argv) { . . . /* Set callback function that responds on keyboard pressing */ glut. Keyboard. Func (keypress); . . . } /* keyboard callback routine */ void keypress( unsigned char key, int x, int y) { if (key == 'q' || key =='Q' || key ==27)exit(0); // exit }
Step 2. c Callback routines & Window Resizing int main(int argc, char **argv) { . . . /* Set display as a callback for the current window */ glut. Display. Func(display); /* Set callback function that respond to resizing the window */ glut. Reshape. Func(resize); /* Set callback function that responds on keyboard pressing */ glut. Keyboard. Func(keypress); /* Set callback function that responds on the mouse click */ glut. Mouse. Func(mousepress); . . . }
Step 2. c Callback routines & Window Resizing void keypress( unsigned char key, int x, int y) { … } void mousepress( int button, int state, int x, int y) { … } void resize(int width, int height) { double aspect; gl. Viewport(0, 0, width, height); /* Reset the viewport */ aspect = (double)width / (double)height; /* compute aspect ratio*/ gl. Matrix. Mode(GL_PROJECTION); gl. Load. Identity(); //reset projection matrix if (aspect < 1. 0) { gl. Ortho(-4. , -4. /aspect, 1. , 10. ); } else { gl. Ortho(-4. *aspect, -4. , 10. ); } gl. Matrix. Mode(GL_MODELVIEW); gl. Load. Identity(); glu. Look. At(0. , 5. , 0. , 1. , 0. ); }
step 2. c Assignment #2: callback routines and viewport • Modify input file step 2. c 1) Enable a Keyboard callback routine that prints the pressed key in the command window 2) Make the program exit, when ESC (ascii=27), "q" or "Q" are pressed 3) Enable a Mouse callback routine that prints on the screen the information about which mouse button was pressed
step 3. c Geometric Primitives Points Lines Polygons Coordinates Vertices Size Width Outline/solid Stippling Normals
step 3. c Open. GL Primitives gl. Begin(GL_LINES); gl. Vertex 3 f(10. 0 f, 0. 0 f); gl. Vertex 3 f(20. 0 f, 0. 0 f); gl. Vertex 3 f(10. 0 f, 5. 0 f, 0. 0 f); gl. Vertex 3 f(20. 0 f, 5. 0 f, 0. 0 f); gl. End(); http: //www. opengl. org/sdk/docs/man/xhtml/gl. Begin. xml
step 3. c Define a box void box. Def( float length, float height, float width) { gl. Begin(GL_QUADS); /* you can color each side or even each vertex in different color */ gl. Color 3 f(0. , . 35, 1. ); gl. Vertex 3 f(-length/2. , height/2. , width/2. ); gl. Vertex 3 f( length/2. , height/2. , -width/2. ); gl. Vertex 3 f(-length/2. , height/2. , -width/2. ); /* add here other sides */ …. . gl. End(); }
step 3. c Open. GL Transformations Vertex Data Model. View Matrix Projection Matrix Object Coordinates Perspective Division Eye Coordinates Clip Coordinates Viewport Transformation Device Coordinates Window Coordinates
step 3. c Model View Transformations gl. Matrix. Mode(GL_MODELVIEW); gl. Load. Identity(); gl. Translate(x, y, z); /* transformation L */ gl. Rotate (angle, x, y, z); /* transformation M */ gl. Scale (x, y, z); /* transformation N */ Order of operations: L * M * N * v Draw Geometry
step 3. c Model View Transformations View from a plane Orbit an object void pilot. View( … ) { gl. Rotatef(roll, 0. 0, 1. 0); gl. Rotatef(pitch, 0. 0, 1. 0, 0. 0); gl. Rotatef(heading, 1. 0, 0. 0); gl. Translatef(-x, -y, -z); } void polar. View( … ) { gl. Translatef(0. 0, -distance); gl. Rotated(-twist, 0. 0, 1. 0); gl. Rotated(-elevation, 1. 0, 0. 0); gl. Rotated(azimuth, 0. 0, 1. 0); } http: //www. opengl. org/sdk/docs/man/xhtml/gl. Rotate. xml
step 3. c Assignment #3: GL primitives and transformations • Modify input file step 3. c 1) Create a thin box, centered around 0, using GL_QUADS type. This box should be. 01 thick (along y axis), 2. 0 units in length (in x axis), . 4 units in width (along z axis). 2) Define a different (from your sphere) color for the box. Remember you can assign a different color for each quad or even to each vertex(!). 3) Move your sphere 1 unite up along y axis. 4) Move box down y axis, so its upper plane is on the level y=0. 5) Modify your keypress callback function to respond on pressing "w" and "s" keys to switch between wire and solid states: The GL constants are GL_FILL and GL_LINE
step 4. c Open. GL Display Lists // create one display list index = gl. Gen. Lists(1); // compile the display list gl. New. List(index, GL_COMPILE); gl. Begin(GL_TRIANGLES); gl. Vertex 3 fv(v 0); gl. Vertex 3 fv(v 1); gl. Vertex 3 fv(v 2); gl. End(); gl. End. List(); . . . // draw the display list gl. Call. List(index); . . . // delete it if it is not used any more gl. Delete. Lists(index, 1);
step 4. c Assignment #4: using GL lists • Modify input file step 4. c 1) use gl. Scale to scale down the ball. Try to place gl. Scale command before gl. Translate and then after. Compare the results. 2) Add to the key. Press callback routine: if user presses "<" and ">" (or left, right) buttons, the platform (box) moves to the left and to the right accordingly. 3) Remember it should not go beyond the clipping planes, so x coordinate for the translation can not exceed plus/minus 4
step 5. c Lighting Ambient Light has no source, considered to be everywhere. • gl. Lightfv(GL_LIGHT 0, GL_AMBIENT, light_amb) Diffuse Light Ambient & Diffuse shines upon an object indirectly • gl. Lightfv(GL_LIGHT 0, GL_DIFFUSE, light_diff) Specular Light Ambient Diffuse highlights an object with a reflective color. • gl. Lightfv(GL_LIGHT 0, GL_SPECULAR, light_spec) Diffuse & Specular Ambient, Diffuse & Specular
step 5. c Light(s) Position At least 8 lights available. Light Positional / Spotlight Directional GLfloat light_pos[] = { x, y, z, w } // 4 th value: w=1 – for positional, w=0 – for directional gl. Lightfv (GL_LIGHT 0, GL_POSITION, light_pos) http: //www. opengl. org/sdk/docs/man/xhtml/gl. Light. xml
step 5. c Material Properties Ambient default = (0. 2, 1. 0) • GLfloat mat_amb [] = {0. 1, 0. 5, 0. 8, 1. 0}; • gl. Materialfv(GL_FRONT_AND_BACK, GL_AMBIENT, mat_amb); Diffuse In real life diffuse and ambient colors are set to the same value default = (0. 8, 1. 0) • GLfloat mat_diff [] = {0. 1, 0. 5, 0. 8, 1. 0}; • gl. Materialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, mat_diff); Specular default = (0. 0, 1. 0) • GLfloat mat_spec [] = {1. 0, 1. 0}; • gl. Materialfv(GL_FRONT, GL_SPECULAR, mat_spec); Shininess controls the size and brightness of the highlight, value range (0. to 128. ) default =0. 0 • GLfloat low_shininess [] = {5. }; // the higher value the smaller and brighter (more focused) the highlight • gl. Materialfv(GL_FRONT, GL_SHININESS, low_shininess); Emission emissive color of material (usually to simulate a light source), • GLfloat mat_emission[] = {0. 3, 0. 2, 0. 0}; • gl. Materialfv(GL_FRONT, GL_EMISSION, mat_emission); default = (0. 0, 1. 0)
step 5. c Default Lighting values Parameter Name Default Value Meaning GL_AMBIENT (0. 0, 1. 0) ambient RGBA intensity of light GL_DIFFUSE (1. 0, 1. 0) diffuse RGBA intensity of light GL_SPECULAR (1. 0, 1. 0) specular RGBA intensity of light GL_POSITION (0. 0, 1. 0, 0. 0) (x, y, z, w) position of light GL_SPOT_DIRECTION (0. 0, -1. 0) (x, y, z) direction of spotlight
step 5. c Default Material values Parameter Name Default Value Meaning GL_AMBIENT (0. 2, 1. 0) ambient color of material GL_DIFFUSE (0. 8, 1. 0) diffuse color of material GL_AMBIENT_AND_DIFFUSE ambient and diffuse color of material GL_SPECULAR (0. 0, 1. 0) specular color of material GL_SHININESS 0. 0 specular exponent in the range of 0. 0 to 128. 0 GL_EMISSION (0. 0, 1. 0) emissive color of material (to simulate a light)
step 5. c A simple way to define light • Light: o set diffuse to the color you want the light to be o set specular equal to diffuse o set ambient to 1/4 of diffuse. • Material: o set diffuse to the color you want the material to be o set specular to a gray (white is brightest reflection, black is no reflection) o set ambient to 1/4 of diffuse
step 5. c Enable Lighting • • • /* Enable a single Open. GL light. */ gl. Lightfv(GL_LIGHT 0, GL_DIFFUSE, light_diffuse); gl. Lightfv(GL_LIGHT 0, GL_POSITION, light_position); gl. Enable(GL_LIGHT 0); gl. Enable(GL_LIGHTING); • • gl. Clear. Color (0. 0, 0. 0); // background color gl. Shade. Model (GL_SMOOTH); // shading algorithm • • gl. Materialfv(GL_FRONT, GL_SPECULAR, mat_specular); gl. Materialfv(GL_FRONT, GL_SHININESS, mat_shininess); • • • gl. Enable(GL_NORMALIZE); //enable normalizing to avoid problems with light! … gl. Begin(GL_QUADS); // specify a normal either per vertex or per polygon gl. Normal 3 f(0, 0, 1); gl. Vertex 3 fv(a); gl. Vertex 3 fv(b); gl. Vertex 3 fv(c); gl. Vertex 3 fv(d); gl. End();
step 5. c Assignment #5: add lights to the scene and explore transformations • Modify input file step 5. c 1) Enable open. GL lighs. Use directional light with the direction coming diagonaly from the upper right corner toward the origin. 2) Calculate normals for the sides of the platform 3) Add to the keyboard events the handling of pressing X, Y, Z, keys - they will change the axis of the rotation. And pressing keys F and B will rotate the object for 10 degrees. Apply this rotations to the platform only.
step 6. c Assignment #6: putting it all together for a game! • Modify input file step 6. c 1) move the platform down the screen, so it would move along the y=-4 level 2) make ball "bounce" from the wall, left and right walls and the platform 3) if the ball misses the platform, it should "fall" beneath the "floor" and a new ball should appear from the "ceiling".
Open. GL Helpful Materials Online documentation • Open. GL: http: //www. opengl. org • GLUT: http: //www. freeglut. org • Reference: http: //www. glprogramming. com/blue/ Examples: • From Open. GL. org (examples and tutorials): http: //www. opengl. org/code Books: • “Red book”: Open. GL Programming Guide. Woo, Neider, Davis, Shreiner. ISBN 0 -201 -60458 -2. • “Blue book”: Open. GL Reference Manual. Shreiner. ISBN 0 -201 -65765 -1
Thank you! Final Notes: • Please fill out an online evaluation of this tutorial: scv. bu. edu/survey/tutorial_evaluation. html • System help@twister. bu. edu, help@katana. bu. edu • Web-based tutorials www. bu. edu/tech/research/tutorials • Consultation by appointment Katia Oleinik(koleinik@bu. edu)
- Slides: 56