CS100433 Introduction to OpenGL Junqiao Zhao 赵君峤 Department of Computer Science and Technology College of Electronics and Information Engineering Tongji University
Before OpenGL Let s think what is need to produce an image physically?
Image Formation In computer graphics, we form images which are generally two dimensional using a process analogous to how images are formed by physical imaging systems Cameras Microscopes Telescopes Human visual system
Synthetic Camera Model projector p image plane projection of p center of projection
Pinhole Camera Use trigonometry to find projection of point at (x,y,z) x p = -x/z/d y p = -y/z/d z p = d These are equations of simple perspective
Elements of Image Formation Objects Viewer Light source(s) Attributes (Materials) Attributes that govern how light interacts with the materials in the scene Note the independence of the objects, the viewer, and the light source(s)
How to design a Graphics API Can we mimic the synthetic camera model to design graphics hardware software? Application Programmer Interface (API) Need only specify Objects Viewer Lights Materials But how is the API implemented?
API Contents Functions that specify what we need to form an image Objects Viewer Light Source(s) Materials Other information Input from devices such as mouse and keyboard Capabilities of system
Object Specification Most APIs support a limited set of primitives including Points (0D object) Line segments (1D objects) Polygons (2D objects) Some curves and surfaces Quadrics Parametric polynomials All are defined through locations in space or vertices
Example type of object 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( ); location of vertex end of object definition
Camera Specification Six degrees of freedom Position of center of lens Orientation Lens Film size Orientation of film plane
Lights and Materials Types of lights Point sources vs distributed sources Spot lights Near and far sources Color properties Material properties Absorption: color properties Scattering Diffuse Specular
Rendering
Physical Approaches Ray tracing: follow rays of light from center of projection until they either are absorbed by objects or go off to infinity Can handle global effects Multiple reflections Translucent objects Slow Must have whole data base available at all times Radiosity: Energy based approach Very slow
Global vs Local Lighting Cannot compute color or shade of each object independently Some objects are blocked from light Light can reflect from object to object Some objects might be translucent
Practical Approach Process objects once at a time in the order they are generated by the application Can consider only local lighting Pipeline architecture All steps can be implemented in hardware on the graphics card OpenGL
SGI and GL Silicon Graphics (SGI) revolutionized the graphics workstation by implementing the pipeline in hardware (1982) To access the system, application programmers used a library called GL With GL, it was relatively simple to program three dimensional interactive applications
OpenGL The success of GL lead to OpenGL (1992), a platformindependent API that was Easy to use Close enough to the hardware to get excellent performance Focus on rendering Omitted windowing and input to avoid window system dependencies At present OpenGL 5
What is OpenGL? Open Graphics Library that creates an interface to graphics hardware Hardware and OS independent Windows/Mac OS/Linux/FreeBSD C/C++/Java APIs for rendering 2D and 3D scene Low-level interface Polygon based OpenGL vs D3D CAD virtual reality Games
OpenGL Libraries OpenGL core library OpenGL32 on Windows GL on most unix/linux systems (libgl.a) OpenGL Utility Library (GLU) Provides functionality in OpenGL core but avoids having to rewrite code Viewing transformation, 3D models, etc. Links with window system GLX for X window systems WGL for Windows AGL for Macintosh
GLUT OpenGL Utility Toolkit (GLUT) Provides functionality common to all window systems Open a window Get input from mouse and keyboard Menus Event-driven Code is portable but GLUT lacks the functionality of a good toolkit for a specific platform
OpenGL Rendering Pipeline
A metaphor for transformation Coordinate system - the local coordinate - the world coordinate - the camera coordinate
OpenGL State OpenGL is a state machine OpenGL functions are of two types Primitive generating Can cause output if primitive is visible How vertices are processed and appearance of primitive are controlled by the state State changing Transformation functions Attribute functions
OpenGL: A State Machine As a primitive is drawn each vertex is affected by current OpenGL states States stay in effect until changed. All states have a default value
OpenGL: A State Machine State machine Color:red Linewidth:1.0 Matrix:modelview Light pos1 Color:blue Linewidth: 5.0 Matrix:projection Light pos2
Types of OpenGL States On/Off States glenable(...), gldisable(...), glisenabled(...) E.g: GL_POINT_SMOOTH, GL_LINE_STIPPLE,... Mode States State Values may be one of options E.g. glshademodel(gl_smooth), glshademodel(gl_flat) Query by: glget(gl_shade_model)
OpenGL: A State Machine Value States Assign relevant values to states. Query values by: glgetboolean(...), glgetdouble(...),... Set values by, e.g.: Color: glcolor3f(glfloat r, GLFloat g GLFloat b) Point Size : glpointsize(glfloat size); Line Width : gllinewidth(glfloat width);
OpenGL Basics Commands : prefix gl and initial capital letters for each word e.g. glclearcolor() Constants: begin with GL_, all capital, underscores for word separation e.g. GL_COLOR_BUFFER_BIT Replace gl & GL_ with glut & GLUT_ for glut and with glu & GLU_ for glu
OpenGL #defines Most constants are defined in the include files gl.h, glu.h and glut.h Note #include <GL/glut.h> should automatically include the others Examples glbegin(gl_polygon) glclear(gl_color_buffer_bit) include files also define OpenGL data types: GLfloat, GLdouble,.
OpenGL Basics Basic Command: glvertex*# Same format used in other commands such as: glcolor*#, glrasterpos*#, glnormal*# Sometimes v added to pass a vector(array) function name dimensions glvertex3f(x,y,z) belongs to GL library x,y,z are floats
Example 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( );
Lack of Object Orientation OpenGL is not object oriented so that there are multiple functions for a given logical function glvertex3f glvertex2i glvertex3dv Underlying storage mode is the same Easy to create overloaded functions in C++ but issue is efficiency
OpenGL Primitives glbegin(glenum mode); glvertex3f(0., 0., 0.); glvertex3f(0., 3., 0.); glvertex3f(4., 3., 0.);... glvertex3f(5., 2., 0.); glvertex3f(4., 0., 0.); glend();
OpenGL Primitives glbegin(glenum mode)
Vertex Attributes glbegin(glenum mode); glcolor( ); glnormal( ); gltexcoord( ); glvertex3f();... glend(); All need to come before call to glvertex to affect that vertex
OpenGL Polygons should be Valid Simple: no self-intersection Convex Planar
OpenGL Pipeline
OpenGL Pipeline Initial Vertex Data: vertices, polygon, lines Initial Pixel Data: pixels, bitmaps
OpenGL Pipeline Store static geometry + attributes for current (immediate mode) or later use
OpenGL Pipeline From: Parametric Curves and Surfaces defined using control points To: Vertices
OpenGL Pipeline 42 Vertex transformations Compute tex coords Computer vertex lighting Angel: Interactive Computer Graphics 4E Addison-Wesley 2005
OpenGL Pipeline Vertices -> Primitives Perspective division Viewport operation Clipping: points, line, polygon Culling
OpenGL Pipeline Unpacking <-> Pixel map
OpenGL Pipeline Texture objects for switching Texture memory
OpenGL Pipeline Geometric/pixel data -> Fragments Each fragment corresponds a pixel in the frame buffer Fragment is potential pixel : color, depth, etc.
OpenGL Pipeline Modify/delete fragments before drawing e.g.: depth buffer, fog, stencil, alpha, blending operation
OpenGL Pipeline Draw onto frame buffer, then be rendered on screen
Summary Vertices Transformations, lighting, coloring, tex coords Fragments Clipping, culling, projection, rasterization Each point in an image with relevant info: color, depth, texture Fragments tests, blending/dithering Pixels Primitives Points, line segments, polygons with relevant edge flag, color and texture info per vertex In frame buffer a set of logical buffers: color, depth, stencil
Programmable pipeline Shaders Vertex shader Geometry shader Fragment shader
Programmable pipeline
GLUT Basics OpenGL Utilities Toolkit Basic window and interaction management (GLUI an option for somewhat more complex user interface) glutinit(&argc, argv) - initialize GLUT glutinitdisplaymode(unsigned int mode) Many alternatives GLFW Freeglut
A Simple Program Generate a square on a solid background
simple.cpp #include <GL/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 const *argv[]) { glutcreatewindow("simple"); glutdisplayfunc(mydisplay); glutmainloop(); return 0; }
Event Loop Note that the program defines a display callback function named mydisplay Every glut program must have a display callback The display callback is executed whenever OpenGL decides the display must be refreshed, for example when the window is opened The main function ends with the program entering an event loop
Program Structure Most OpenGL programs have a similar structure that consists of the following functions main(): defines the callback functions opens one or more windows with the required properties enters event loop (last executable statement) init(): sets the state variables Viewing Attributes Callbacks Display function Input and window functions
simple.cpp revisited In this version, we shall see the same output but we have defined all the relevant state values through function calls using the default values In particular, we set Colors Viewing conditions Window properties
main.cpp #include <GL/glut.h> includes gl.h int main(int argc, char *argv[]) { glutinit(&argc,argv); glutinitdisplaymode(glut_single GLUT_RGB); glutinitwindowsize(500,500); glutinitwindowposition(0,0); glutcreatewindow("simple"); glutdisplayfunc(mydisplay); define window properties } init(); glutmainloop(); return 0; set OpenGL state enter event loop display callback
GLUT functions glutinit allows application to get command line arguments and initializes system gluinitdisplaymode requests properties for the window (the rendering context) 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 loop
Void init() black clear color void init() { glclearcolor (0.0, 0.0, 0.0, 1.0); opaque window glcolor3f(1.0, 1.0, 1.0); fill/draw with white } glmatrixmode (GL_PROJECTION); glloadidentity (); glortho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); viewing volume
OpenGL Camera OpenGL places a camera at the origin in object space pointing in the negative z direction The default viewing volume is a box centered at the origin with a side of length 2 (-1, 1)
mydisplay() 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(); }
Attributes Attributes are part of the OpenGL state and determine the appearance of objects Color (points, lines, polygons) Size and width (points, lines) Stipple pattern (lines, polygons) Polygon mode Display as filled: solid color or stipple pattern Display edges Display vertices
RGB color Each color component is 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), whereas in glcolor3ub the values range from 0 to 255
Color and State The color as set by glcolor becomes part of the state and will be used until changed Colors and other attributes are not part of the object but are assigned when the object is rendered We can create conceptual vertex colors by code such as glcolor glvertex glcolor glvertex
Smooth Color Default is smooth shading OpenGL interpolates vertex colors across visible polygons Alternative is flat shading Color of first vertex determines fill color glshademodel (GL_SMOOTH) or GL_FLAT
Viewports Do not have use the entire window for the image: glviewport(x,y,w,h) Values in pixels (screen coordinates)
OpenGL References web: OpenGL official website:http://www.opengl.org OpenGL Reference Manual:http://www.opengl.org/sdk/docs/ GLUT:http://www.opengl.org/resources/libraries/glut/ Nate Robin: http://user.xmission.com/~nate/tutors.html NEHE:http://nehe.gamedev.net specification : The OpenGL Utility Toolkit (GLUT) Programming Interface (PDF/HTML) for Windows book: OpenGL Programming Guide (seventh edition), Addison Wesley OpenGL SuperBible (third edition), Waite Group Press OpenGL Shading Language
References Ed Angel, CS/EECE 433 Computer Graphics, University of New Mexico Steve Marschner, CS4620/5620 Computer Graphics, Cornell Tom Thorne, COMPUTER GRAPHICS, The University of Edinburgh Elif Tosun, Computer Graphics, The University of New York Lin Zhang, Computer Graphics, Tongji Unviersity
Questions?
Contents-modelview transformation View transformation - where the camera is located - glulookat, gltranslate, glrotate Model transformation - the position, scale and direction of model - gltranslate, glscale, glrotate Why together? - share the same effect
Contents-projection transformation Define a viewing volume - perspective projection - glfrustum, gluperspective - animation, application for realistic effect - Orthographic Projection - glortho - CAD, architecture Viewing Volume Clipping
Contents-viewport transformation viewport transformation - the size of the image on the screen - glviewport notice: the aspect ratio of a viewport = that of the viewing volume