OpenGL Training/Tutorial

                 Jayant Mukherjee



1                     February 13, 2013
Part01: Introduction

    Introduction of OpenGL with code samples.



2                  Part 01 - Introduction   February 13, 2013
Part01 : Topics
       About OpenGL
       OpenGL Versions
       OpenGL Overview
       OpenGL Philosophy
       OpenGL Functionality
       OpenGL Usage
       OpenGL Convention
       OpenGL Basic Concepts
       OpenGL Rendering Pipeline
       Primitives (Points, Lines, Polygon)
       Environment Setup
       Code Samples (Win32/glut)
    3                                Part 01 - Introduction   February 13, 2013
Part01 : About OpenGL
       History
           OpenGL is relatively new (1992) GL from Silicon Graphics
           IrisGL - a 3D API for high-end IRIS graphics workstations
           OpenGL attempts to be more portable
           OpenGL Architecture Review Board (ARB) decides on all
            enhancements
       What it is…
           Software interface to graphics hardware
           About 120 C-callable routines for 3D graphics
           Platform (OS/Hardware) independent graphics library
       What it is not…
           Not a windowing system (no window creation)
           Not a UI system (no keyboard and mouse routines)
           Not a 3D modeling system (Open Inventor, VRML, Java3D)
                                     http://en.wikipedia.org/wiki/OpenGL

    4                                      Part 01 - Introduction   February 13, 2013
Part01 : OpenGL Versions
Version            Release Year
OpenGL 1.0         January, 1992
OpenGL 1.1         January, 1997
OpenGL 1.2         March 16, 1998
OpenGL 1.2.1       October 14, 1998
OpenGL 1.3         August 14, 2001
OpenGL 1.4         July 24, 2002
OpenGL 1.5         July 29, 2003
OpenGL 2.0         September 7, 2004
OpenGL 2.1         July 2, 2006
OpenGL 3.0         July 11, 2008
OpenGL 3.1         March 24, 2009 and updated May 28, 2009
OpenGL 3.2         August 3, 2009 and updated December 7, 2009
OpenGL 3.3         March 11, 2010
OpenGL 4.0         March 11, 2010
OpenGL 4.1         July 26, 2010

5                 Part 01 - Introduction   February 13, 2013
Part01 : Overview
       OpenGL is a procedural graphics language
       programmer describes the steps involved to achieve a
        certain display
       “steps” involve C style function calls to a highly portable
        API
       fairly direct control over fundamental operations of two
        and three dimensional graphics
       an API not a language
       What it can do?
           Display primitives
           Coordinate transformations (transformation matrix
            manipulation)
           Lighting calculations
           Antialiasing
           Pixel Update Operations
           Display-List Mode
    6                                    Part 01 - Introduction   February 13, 2013
Part01 : Philosophy
       Platform independent
       Window system independent
       Rendering only
       Aims to be real-time
       Takes advantage of graphics hardware where it
        exists
       State system
       Client-server system
       Standard supported by major companies


    7                           Part 01 - Introduction   February 13, 2013
Part01 : Functionality
       Simple geometric objects
        (e.g. lines, polygons, rectangles, etc.)
       Transformations, viewing, clipping
       Hidden line & hidden surface removal
       Color, lighting, texture
       Bitmaps, fonts, and images
       Immediate- & Retained- mode graphics
           An immediate-mode API is procedural. Each time a new
            frame is drawn, the application directly issues the drawing
            commands.
           A retained-mode API is declarative. The application
            constructs a scene from graphics primitives, such as
    8       shapes and lines.           Part 01 - Introduction February 13, 2013
Part01 : Usage
       Scientific Visualization
       Information
        Visualization
       Medical Visualization
       CAD
       Games
       Movies
       Virtual Reality
       Architectural
        Walkthrough

    9                              Part 01 - Introduction   February 13, 2013
Part01 : Convention
    Constants:
        prefix GL + all capitals (e.g. GL_COLOR_BUFER_BIT)
    Functions:
        prefix gl + capital first letter (e.g. glClearColor)
            returnType glCommand[234][sifd] (type value, ...);
            returnType glCommand[234][sifd]v (type *value);
    Many variations of the same functions
        glColor[2,3,4][b,s,i,f,d,ub,us,ui](v)
            [2,3,4]: dimension
            [b,s,i,f,d,ub,us,ui]: data type
            (v): optional pointer (vector) representation

                                                 Example:
                                                 glColor3i(1, 0, 0)
                                                 or
                                                 glColor3f(1.0, 1.0, 1.0)
                                                 or
                                                 GLfloat color_array[] = {1.0, 1.0, 1.0};
                                                 glColor3fv(color_array)
    10                                           Part 01 - Introduction   February 13, 2013
Part01 : Basic Concepts
    OpenGL as a state machine (Once the value of a
     property is set, the value persists until a new value is
     given).
    Graphics primitives going through a “pipeline” of
     rendering operations
    OpenGL controls the state of the pipeline with many state
     variables (fg & bg colors, line thickness, texture
     pattern, eyes, lights, surface material, etc.)
    Binary state: glEnable & glDisable
    Query: glGet[Boolean,Integer,Float,Double]
    Coordinates :
     XYZ axis follow Cartesian system.
    11                           Part 01 - Introduction   February 13, 2013
Part01 : Rendering Pipeline
            Primitives               Transformation            Clipping                 Shading           Projection          Rasterisation




        Primitives                 Transformation              Clipping             Shading/Texturing           Projection          Rasterisation




• Lines, Polygons, Triangles   • Modeling Transform   • Parallel/Orthographic     • Material, Lights    • Viewport location    • Images in buffer
• Vertices                       (Transform Matrix)   • Perspective               • Color               • Transformation       • Viewport Transformation
                               • Viewing Transform                                                                             • Images on screen
                                 (Eye, Lookat)




    12                                                                          Part 01 - Introduction         February 13, 2013
Part01 : Primitives (Points, Lines…) - I
    All geometric objects in OpenGL are created from a set of basic
     primitives.
    Certain primitives are provided to allow optimization of geometry for
     improved rendering speed.
    Primitives specified by vertex calls (glVertex*) bracketed by
     glBegin(type) and glEnd()
    Specified by a set of vertices
        glVertex[2,3,4][s,i,f,d](v) (TYPE coords)
 Grouped together by glBegin() & glEnd()
                                                       glBegin(GLenum mode)
glBegin(GL_POLYGON)                                        mode includes
                                                               GL_POINTS
   glVertex3f(…)                                               GL_LINES, GL_LINE_STRIP, GL_LINE_
                                                                LOOP
    glVertex3f(…)                                              GL_POLYGON
   glVertex3f(…)                                               GL_TRIANGLES, GL_TRIANGLE_STRI
                                                                P
glEnd                                                          GL_QUADS, GL_QUAD_STRIP

    13                                       Part 01 - Introduction   February 13, 2013
Part01 : Primitives (Points, Lines…) - II
    Point Type
        GL_POINTS

    Line Type
        GL_LINES
        GL_LINE_STRIP
        GL_LINE_LOOP

    Triangle Type
        GL_TRIANGLES
        GL_TRIANGLE_STRI
         P
        GL_TRIANGLE_FAN

    Quad Type
        GL_QUADS
        GL_QUAD_STRIP

    Polygon Type
        GL_POLYGON


Ref : Drawing Primitives in OpenGL


    14                               Part 01 - Introduction   February 13, 2013
Part01 : Environment Setup
    Using Windows SDK
        OpenGL and OpenGL Utility (GLU) ships with Microsoft SDK.
         Add SDK Path to IDE Project Directories.
        Add Headers: gl.h, glu.h
         Found @ <SDKDIR>Windowsv6.0Aincludegl
        Add Libs for linking: opengl32.lib, glu32.lib
         Found @ <SDKDIR>Windowsv6.0Alib
        Required DLLs: opengl32.dll, glu32.dll
         Found @ <WINDIR> System32
    Using GLUT (www.xmission.com/~nate/glut.html or http://freeglut.sourceforge.net)
        Store the Binaries at appropriate location and reference it properly
        Add Header: glut.h
         Found @ <GLUTPATH>include
        Add Lib for linking: glut32.lib
         Found @ <GLUTPATH>lib
        Required DLL: glut32.dll
         Found @ <GLUTPATH>bin


    15                                         Part 01 - Introduction   February 13, 2013
Part01 : Code Samples
    Using Windows SDK
        Create Basic Window from the Windows Base Code.
        Add Headers & Libs.
        Modify the Windows Class Registration.
        Modify the Window Creation Code.
            Setup PixelFormat.
            Create Rendering Context and set it current.
        Add Cleanup code where remove rendering context.
        Add Event Handlers
            Add Display function handler for rendering OpenGL stuff.
            Add Resize function handler for window resizing.
    Using GLUT
        Add Headers and Libs.
        Initialize the GLUT system and create basic window.
        Add Event Handlers
            Add Display, Resize, Idle, Keyboard, Mouse handlers.

    16                                         Part 01 - Introduction   February 13, 2013
Part02: Basics

     Introduction of OpenGL with code samples.



17                     Part 02 - Basics   February 13, 2013
Part02 : Topics
    Transformations
        Modeling
            Concept of Matrices.
            Scaling, Rotation, Translation
        Viewing
            Camera
            Projection: Ortho/Perspective
    Code Samples (Win32/glut)




    18                                        Part 02 - Basics   February 13, 2013
Part02 : Transformations-Modeling I
    Concept of Matrices.
        All affine operations are matrix multiplications.
        A 3D vertex is represented by a 4-tuple (column) vector.
        A vertex is transformed by 4 x 4 matrices.
        All matrices are stored column-major in OpenGL
        Matrices are always post-multiplied. product of matrix and
         vector is Mv. OpenGL only multiplies a matrix on the
         right, the programmer must remember that the last matrix
         specified is the first applied.
                                             x
                                                             m0    m4     m8     m12
                                             y
                                      v            M
                                                             m1    m5     m9     m13
                                             z               m2    m6     m10    m14
                                             w               m3    m7     m11    m15
    19                                    Part 02 - Basics   February 13, 2013
Part02 : Transformations-Modeling II
 OpenGL uses stacks to maintain transformation matrices
  (MODELVIEW stack is the most important)
 You can load, push and pop the stack
 The current transform is applied to all graphics primitive until it is
  changed
2 ways of specifying Transformation Matrices.
    Using crude Matrices.                 Using built-in routines.
        Specify current Matrix                glTranslate[f,d](x,y,z)
         glMatrixMode(GLenum mode)             glRotate[f,d](angle,x,y,z)
        Initialize current Matrix             glScale[f,d](x,y,z)
         glLoadIdentity(void)                  Order is important
         glLoadMatrix[f,d](const TYPE
         *m)
        Concatenate current Matrix
         glMultMatrix(const TYPE *m)



    20                                      Part 02 - Basics   February 13, 2013
Part02 : Transformations-Viewing I
    Camera.
        Default: eyes at origin, looking along -Z
        Important parameters:
            Where is the observer (camera)? Origin.
            What is the look-at direction? -z direction.
            What is the head-up direction? y direction.
        gluLookAt(
         eyex, eyey, eyez, aimx, aimy, aimz, upx, upy, upz )
            gluLookAt() multiplies itself onto the current matrix, so it usually
             comes after glMatrixMode(GL_MODELVIEW) and
             glLoadIdentity().




    21                                          Part 02 - Basics   February 13, 2013
Part02 : Transformations-Viewing II
    Projection
        Perspective projection
            gluPerspective( fovy, aspect, zNear, zFar )
            glFrustum( left, right, bottom, top, zNear, zFar )
        Orthographic parallel projection
            glOrtho( left, right, bottom, top, zNear, zFar )
            gluOrtho2D( left, right, bottom, top )
    Projection transformations
     (gluPerspective, glOrtho) are left handed
        Everything else is right handed, including the                          y
         vertexes to be rendered               y     z+

                                                                                          x
                                                                    x
                                                         left handed        z    right
                                                                            +    handed
    22                                          Part 02 - Basics   February 13, 2013
Part02 : Transformations-Viewing III
    glFrustum(left, right, bottom, top, zNear, zFar)




    gluPerspective(fovy, aspect, zNear, zFar)




    glOrtho(left, right, bottom, top, zNear, zFar)




    23                                           Part 02 - Basics   February 13, 2013
Part02 : Code Samples

Ortho              Perspective




24                   Part 02 - Basics   February 13, 2013

OpenGL Introduction

  • 1.
    OpenGL Training/Tutorial Jayant Mukherjee 1 February 13, 2013
  • 2.
    Part01: Introduction Introduction of OpenGL with code samples. 2 Part 01 - Introduction February 13, 2013
  • 3.
    Part01 : Topics  About OpenGL  OpenGL Versions  OpenGL Overview  OpenGL Philosophy  OpenGL Functionality  OpenGL Usage  OpenGL Convention  OpenGL Basic Concepts  OpenGL Rendering Pipeline  Primitives (Points, Lines, Polygon)  Environment Setup  Code Samples (Win32/glut) 3 Part 01 - Introduction February 13, 2013
  • 4.
    Part01 : AboutOpenGL  History  OpenGL is relatively new (1992) GL from Silicon Graphics  IrisGL - a 3D API for high-end IRIS graphics workstations  OpenGL attempts to be more portable  OpenGL Architecture Review Board (ARB) decides on all enhancements  What it is…  Software interface to graphics hardware  About 120 C-callable routines for 3D graphics  Platform (OS/Hardware) independent graphics library  What it is not…  Not a windowing system (no window creation)  Not a UI system (no keyboard and mouse routines)  Not a 3D modeling system (Open Inventor, VRML, Java3D) http://en.wikipedia.org/wiki/OpenGL 4 Part 01 - Introduction February 13, 2013
  • 5.
    Part01 : OpenGLVersions Version Release Year OpenGL 1.0 January, 1992 OpenGL 1.1 January, 1997 OpenGL 1.2 March 16, 1998 OpenGL 1.2.1 October 14, 1998 OpenGL 1.3 August 14, 2001 OpenGL 1.4 July 24, 2002 OpenGL 1.5 July 29, 2003 OpenGL 2.0 September 7, 2004 OpenGL 2.1 July 2, 2006 OpenGL 3.0 July 11, 2008 OpenGL 3.1 March 24, 2009 and updated May 28, 2009 OpenGL 3.2 August 3, 2009 and updated December 7, 2009 OpenGL 3.3 March 11, 2010 OpenGL 4.0 March 11, 2010 OpenGL 4.1 July 26, 2010 5 Part 01 - Introduction February 13, 2013
  • 6.
    Part01 : Overview  OpenGL is a procedural graphics language  programmer describes the steps involved to achieve a certain display  “steps” involve C style function calls to a highly portable API  fairly direct control over fundamental operations of two and three dimensional graphics  an API not a language  What it can do?  Display primitives  Coordinate transformations (transformation matrix manipulation)  Lighting calculations  Antialiasing  Pixel Update Operations  Display-List Mode 6 Part 01 - Introduction February 13, 2013
  • 7.
    Part01 : Philosophy  Platform independent  Window system independent  Rendering only  Aims to be real-time  Takes advantage of graphics hardware where it exists  State system  Client-server system  Standard supported by major companies 7 Part 01 - Introduction February 13, 2013
  • 8.
    Part01 : Functionality  Simple geometric objects (e.g. lines, polygons, rectangles, etc.)  Transformations, viewing, clipping  Hidden line & hidden surface removal  Color, lighting, texture  Bitmaps, fonts, and images  Immediate- & Retained- mode graphics  An immediate-mode API is procedural. Each time a new frame is drawn, the application directly issues the drawing commands.  A retained-mode API is declarative. The application constructs a scene from graphics primitives, such as 8 shapes and lines. Part 01 - Introduction February 13, 2013
  • 9.
    Part01 : Usage  Scientific Visualization  Information Visualization  Medical Visualization  CAD  Games  Movies  Virtual Reality  Architectural Walkthrough 9 Part 01 - Introduction February 13, 2013
  • 10.
    Part01 : Convention  Constants:  prefix GL + all capitals (e.g. GL_COLOR_BUFER_BIT)  Functions:  prefix gl + capital first letter (e.g. glClearColor)  returnType glCommand[234][sifd] (type value, ...);  returnType glCommand[234][sifd]v (type *value);  Many variations of the same functions  glColor[2,3,4][b,s,i,f,d,ub,us,ui](v)  [2,3,4]: dimension  [b,s,i,f,d,ub,us,ui]: data type  (v): optional pointer (vector) representation Example: glColor3i(1, 0, 0) or glColor3f(1.0, 1.0, 1.0) or GLfloat color_array[] = {1.0, 1.0, 1.0}; glColor3fv(color_array) 10 Part 01 - Introduction February 13, 2013
  • 11.
    Part01 : BasicConcepts  OpenGL as a state machine (Once the value of a property is set, the value persists until a new value is given).  Graphics primitives going through a “pipeline” of rendering operations  OpenGL controls the state of the pipeline with many state variables (fg & bg colors, line thickness, texture pattern, eyes, lights, surface material, etc.)  Binary state: glEnable & glDisable  Query: glGet[Boolean,Integer,Float,Double]  Coordinates : XYZ axis follow Cartesian system. 11 Part 01 - Introduction February 13, 2013
  • 12.
    Part01 : RenderingPipeline Primitives Transformation Clipping Shading Projection Rasterisation Primitives Transformation Clipping Shading/Texturing Projection Rasterisation • Lines, Polygons, Triangles • Modeling Transform • Parallel/Orthographic • Material, Lights • Viewport location • Images in buffer • Vertices (Transform Matrix) • Perspective • Color • Transformation • Viewport Transformation • Viewing Transform • Images on screen (Eye, Lookat) 12 Part 01 - Introduction February 13, 2013
  • 13.
    Part01 : Primitives(Points, Lines…) - I  All geometric objects in OpenGL are created from a set of basic primitives.  Certain primitives are provided to allow optimization of geometry for improved rendering speed.  Primitives specified by vertex calls (glVertex*) bracketed by glBegin(type) and glEnd()  Specified by a set of vertices  glVertex[2,3,4][s,i,f,d](v) (TYPE coords)  Grouped together by glBegin() & glEnd()  glBegin(GLenum mode) glBegin(GL_POLYGON)  mode includes  GL_POINTS glVertex3f(…)  GL_LINES, GL_LINE_STRIP, GL_LINE_ LOOP glVertex3f(…)  GL_POLYGON glVertex3f(…)  GL_TRIANGLES, GL_TRIANGLE_STRI P glEnd  GL_QUADS, GL_QUAD_STRIP 13 Part 01 - Introduction February 13, 2013
  • 14.
    Part01 : Primitives(Points, Lines…) - II  Point Type  GL_POINTS  Line Type  GL_LINES  GL_LINE_STRIP  GL_LINE_LOOP  Triangle Type  GL_TRIANGLES  GL_TRIANGLE_STRI P  GL_TRIANGLE_FAN  Quad Type  GL_QUADS  GL_QUAD_STRIP  Polygon Type  GL_POLYGON Ref : Drawing Primitives in OpenGL 14 Part 01 - Introduction February 13, 2013
  • 15.
    Part01 : EnvironmentSetup  Using Windows SDK  OpenGL and OpenGL Utility (GLU) ships with Microsoft SDK. Add SDK Path to IDE Project Directories.  Add Headers: gl.h, glu.h Found @ <SDKDIR>Windowsv6.0Aincludegl  Add Libs for linking: opengl32.lib, glu32.lib Found @ <SDKDIR>Windowsv6.0Alib  Required DLLs: opengl32.dll, glu32.dll Found @ <WINDIR> System32  Using GLUT (www.xmission.com/~nate/glut.html or http://freeglut.sourceforge.net)  Store the Binaries at appropriate location and reference it properly  Add Header: glut.h Found @ <GLUTPATH>include  Add Lib for linking: glut32.lib Found @ <GLUTPATH>lib  Required DLL: glut32.dll Found @ <GLUTPATH>bin 15 Part 01 - Introduction February 13, 2013
  • 16.
    Part01 : CodeSamples  Using Windows SDK  Create Basic Window from the Windows Base Code.  Add Headers & Libs.  Modify the Windows Class Registration.  Modify the Window Creation Code.  Setup PixelFormat.  Create Rendering Context and set it current.  Add Cleanup code where remove rendering context.  Add Event Handlers  Add Display function handler for rendering OpenGL stuff.  Add Resize function handler for window resizing.  Using GLUT  Add Headers and Libs.  Initialize the GLUT system and create basic window.  Add Event Handlers  Add Display, Resize, Idle, Keyboard, Mouse handlers. 16 Part 01 - Introduction February 13, 2013
  • 17.
    Part02: Basics Introduction of OpenGL with code samples. 17 Part 02 - Basics February 13, 2013
  • 18.
    Part02 : Topics  Transformations  Modeling  Concept of Matrices.  Scaling, Rotation, Translation  Viewing  Camera  Projection: Ortho/Perspective  Code Samples (Win32/glut) 18 Part 02 - Basics February 13, 2013
  • 19.
    Part02 : Transformations-ModelingI  Concept of Matrices.  All affine operations are matrix multiplications.  A 3D vertex is represented by a 4-tuple (column) vector.  A vertex is transformed by 4 x 4 matrices.  All matrices are stored column-major in OpenGL  Matrices are always post-multiplied. product of matrix and vector is Mv. OpenGL only multiplies a matrix on the right, the programmer must remember that the last matrix specified is the first applied. x m0 m4 m8 m12  y v M m1 m5 m9 m13 z m2 m6 m10 m14 w m3 m7 m11 m15 19 Part 02 - Basics February 13, 2013
  • 20.
    Part02 : Transformations-ModelingII  OpenGL uses stacks to maintain transformation matrices (MODELVIEW stack is the most important)  You can load, push and pop the stack  The current transform is applied to all graphics primitive until it is changed 2 ways of specifying Transformation Matrices.  Using crude Matrices.  Using built-in routines.  Specify current Matrix  glTranslate[f,d](x,y,z) glMatrixMode(GLenum mode)  glRotate[f,d](angle,x,y,z)  Initialize current Matrix  glScale[f,d](x,y,z) glLoadIdentity(void)  Order is important glLoadMatrix[f,d](const TYPE *m)  Concatenate current Matrix glMultMatrix(const TYPE *m) 20 Part 02 - Basics February 13, 2013
  • 21.
    Part02 : Transformations-ViewingI  Camera.  Default: eyes at origin, looking along -Z  Important parameters:  Where is the observer (camera)? Origin.  What is the look-at direction? -z direction.  What is the head-up direction? y direction.  gluLookAt( eyex, eyey, eyez, aimx, aimy, aimz, upx, upy, upz )  gluLookAt() multiplies itself onto the current matrix, so it usually comes after glMatrixMode(GL_MODELVIEW) and glLoadIdentity(). 21 Part 02 - Basics February 13, 2013
  • 22.
    Part02 : Transformations-ViewingII  Projection  Perspective projection  gluPerspective( fovy, aspect, zNear, zFar )  glFrustum( left, right, bottom, top, zNear, zFar )  Orthographic parallel projection  glOrtho( left, right, bottom, top, zNear, zFar )  gluOrtho2D( left, right, bottom, top )  Projection transformations (gluPerspective, glOrtho) are left handed  Everything else is right handed, including the y vertexes to be rendered y z+ x x left handed z right + handed 22 Part 02 - Basics February 13, 2013
  • 23.
    Part02 : Transformations-ViewingIII  glFrustum(left, right, bottom, top, zNear, zFar)  gluPerspective(fovy, aspect, zNear, zFar)  glOrtho(left, right, bottom, top, zNear, zFar) 23 Part 02 - Basics February 13, 2013
  • 24.
    Part02 : CodeSamples Ortho Perspective 24 Part 02 - Basics February 13, 2013

Editor's Notes

  • #20 Why is a 4-tuple vector used for a 3D (x, y, z) vertex? To ensure that all matrix operations are multiplications. w is usually 1.0If w is changed from 1.0, we can recover x, y and z by division by w. Generally, only perspective transformations change w and require this perspective division in the pipeline.
  • #24 For perspective projections, the viewing volume is shaped like a truncated pyramid (frustum). There is a distinct camera (eye) position, and vertexes of objects are “projected” to camera. Objects which are further from the camera appear smaller. The default camera position at (0, 0, 0), looks down the z-axis, although the camera can be moved by other transformations.ForgluPerspective(), fovyis the angle of field of view (in degrees) in the y direction. fovymust be between 0.0 and 180.0, exclusive. aspect is x/y and should be same as the viewport to avoid distortion. zNearand zFardefine the distance to the near and far clipping planes.glFrustum() is rarely used. Warning: for gluPerspective() or glFrustum(), don’t use zero for zNear!For glOrtho(), the viewing volume is shaped like a rectangular parallelepiped (a box). Vertexes of an object are “projected” towards infinity. Distance does not change the apparent size of an object. Orthographic projection is used for drafting and design (such as blueprints).