SlideShare a Scribd company logo
Introduction to
OpenGL Programming
What is OpenGL
   OpenGL is a software API to graphics hardware.
       designed as a streamlined, hardware-independent
        interface to be implemented on many different hardware
        platforms
       Intuitive, procedural interface with c binding
       No windowing commands !
       No high-level commands for describing models of three-
        dimensional objects
       The OpenGL Utility Library (GLU) provides many of the
        modeling features, such as quadric surfaces and NURBS
        curves and surfaces
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
  platform-independent 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
OpenGL Evolution
 Controlled        by an Architectural Review Board
 (ARB)
    Members include SGI, Microsoft, Nvidia, HP,
     3DLabs, IBM,…….
    Relatively stable (present version 2.0)
        Evolution reflects new hardware capabilities
            3D texture mapping and texture objects
            Vertex and fragment programs
    Allows for platform specific features through
     extensions
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
   Links with window system
     GLX for X window systems, WGL for Windows

     Cross-platform GUI libraries: GLUT, SDL, FLTK, QT,
       …
Windowing with OpenGL
 OpenGL  is independent of any specific
  window system
 OpenGL can be used with different window
  systems
    X windows (GLX)
    MFC
    …
 GLUTprovide a portable API for creating
 window and interacting with I/O devices
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
           No slide bars, buttons, …
Software Organization

                   application program

     OpenGL Motif
    widget or similar     GLUT
               GLX, AGL
                or WGL             GLU

   X, Win32, Mac O/S                     OpenGL

               software and/or hardware
OpenGL Architecture
        Immediate Mode                           geometry
                                                  pipeline
                              Per Vertex
        Polynomial           Operations &
         Evaluator             Primitive
                              Assembly



      Display                                      Per Fragment   Frame
CPU     List
                                 Rasterization
                                                    Operations    Buffer



                                 Texture
                                 Memory
                  Pixel
                Operations
OpenGL as a state machine
   GL State Variables- can be set and queried by OpenGL. Remains
    unchanged until the next change.
       Projection and viewing matrix
       Color and material properties
       Lights and shading
       Line and polygon drawing modes
       …
   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 Syntax
   Functions have prefix gl and initial capital letters for each word
       glClearColor(), glEnable(), glPushMatrix()            …
   glu for GLU functions
       gluLookAt(), gluPerspective()       …
   Constants begin with GL_, use all capital letters
       GL_COLOR_BUFFER_BIT, GL_PROJECTION, GL_MODELVIEW …
   Extra letters in some commands indicate the number and type of
    variables
       glColor3f(), glVertex3f()       …
   OpenGL data types
       GLfloat, GLdouble, GLint, GLenum,         …
   Underlying storage mode is the same
   Easy to create overloaded functions in C++ but issue is efficiency
OpenGL function format
                        function name
                                          dimensions

                glVertex3f(x,y,z)


                              x,y,z are floats
belongs to GL library


         glVertex3fv(p)

                              p is a pointer to an array
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,….
GLUT
 Developed  by Mark Kilgard
 Hides the complexities of differing window
  system APIs
     Default user interface for class projects
 Glut   routines have prefix glut
     glutCreateWindow() …
 Has  very limited GUI interface
 Glui is the C++ extension of glut
Glut Routines
   Initialization: glutInit() processes (and removes) command-line
    arguments that may be of interest to glut and the window system and
    does general initialization of Glut and OpenGL
       Must be called before any other glut routines
   Display Mode: The next procedure, glutInitDisplayMode(),
    performs initializations informing OpenGL how to set up the frame
    buffer.
       Display Mode         Meaning
       GLUT_RGB             Use RGB colors
       GLUT_RGBA            Use RGB plus alpha (for transparency)
       GLUT_INDEX           Use indexed colors (not recommended)

       GLUT_DOUBLE          Use double buffering (recommended)
       GLUT_SINGLE          Use single buffering (not recommended)

       GLUT_DEPTH           Use depth-buffer (for hidden surface removal.)
Glut Routines
 Window    Setup
    glutInitWindowSize(int width, int height)
    glutInitWindowPosition(int x, int y)
    glutCreateWindow(char* title)
A Simple Program
Generate a square on a solid background
simple.c
 #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** argv){
        glutInit(&argc, argv);
        glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
        glutInitWindowSize(500,500);
        glutInitWindowPosition(0,0);
        glutCreateWindow("simple");
        glutDisplayFunc(mydisplay);
        init();
        glutMainLoop();
 }
Closer Look at the main()
 #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();                         display callback
                        set OpenGL state
     glutMainLoop();
 }
                            enter event loop
init.c
                                black clear color
void init()                                opaque window
{
  glClearColor (0.0, 0.0, 0.0, 1.0);

    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
Event Handling
   Virtually all interactive graphics programs are even
    driven
   GLUT uses callbacks to handle events
       Windows system invokes a particular procedure when an
        event of particular type occurs.
       MOST IMPORTANT: display event
         Signaled when window first displays and whenever portions
          of the window reveals from blocking window
         glutDisplayFunc(void (*func)(void)) registers
          the display callback function
   Running the program: glutMainLoop()
       Main event loop. Never exit()
More Callbacks
   glutReshapeFunc(void (*func)(int w, int h)) indicates
    what action should be taken when the window is resized.
   glutKeyboardFunc(void (*func)(unsigned char key, int
    x, int y)) and glutMouseFunc(void (*func)(int button,
    int state, int x, int y)) allow you to link a keyboard key or a
    mouse button with a routine that's invoked when the key or mouse
    button is pressed or released.
   glutMotionFunc(void (*func)(int x, int y)) registers a
    routine to call back when the mouse is moved while a mouse button is
    also pressed.

   glutIdleFunc(void (*func)(void)) registers a function that's to
    be executed if no other events are pending - for example, when the
    event loop would otherwise be idle
Compilation on Windows
  See  class web site on how to set up a project
   with OpenGL
  Visual C++
      Get glut.h, glut32.lib and glut32.dll from web
      Create a console application
      Add opengl32.lib, glut32.lib, glut32.lib to project
       settings (under link tab)
Simple Animation
 Animation
    Redraw + swap buffers
    What looks like if using single buffer
    Example program
 More   on the glut documentation
    Chapter 2 of textbook
    OpenGL redbook
    Links in the class resources page
OpenGL Drawing
   We have learned how to create a window
   Steps in the display function
       Clear the window
       Set drawing attributes
       Send drawing commands
       Swap the buffers
   OpenGL coordinate system has different origin from
    the window system
       Uses lower left corner instead of upper left corner as origin
Clear the Window
 glClear(GL_COLOR_BUFFER_BIT)
    clears the frame buffer by overwriting it with the
     background color.
    Background color is a state set by
     glClearColor(GLfloat r, GLfloat g,
     GLfloat b, GLfloat a) in the init().
Drawing Attributes: Color
   glColor3f(GLfloat r, GLfloat g, GLfloat b)            sets the
    drawing color
       glColor3d(), glColor3ui() can also be used
       Remember OpenGL is a state machine
       Once set, the attribute applies to all subsequent defined
        objects until it is set to some other value
       glColor3fv() takes a flat array as input
   There are more drawing attributes than color
       Point size: glPointSize()
       Line width: glLinewidth()
       Dash or dotted line: glLineStipple()
       Polygon pattern: glPolygonStipple()
       …
Drawing Commands
   Simple Objects glRectf()
   Complex Objects
       Use construct
        glBegin(mode) and
        glEnd() and a list of
        vertices in between
           glBegin(mode)
              glVertex(v0);
               glVertex(v1);
               ...
            glEnd();
   Some other commands can
    also be used between
    glBegin() and glEnd(), e.g.
    glColor3f().
   Example
Projection and Viewport
Orthographic projection
   Orthographic View
       glOrtho(left,
        right, bottom,
        top, front, back)
           Specifies the
            coordinates of 3D
            region to be projected
                                      z=0
            into the image space.
           Any drawing outside the
            region will be
            automatically clipped
            away.
Viewports
 Do not have use the entire window for the
  image: glViewport(x,y,w,h)
 Values in pixels (screen coordinates)
Window to Viewport mapping


Aspect Ratio: Height/Width
If the aspect ratio of the window
Is different from that of the
viewport, the picture will be
distorted.
Sierpinski Gasket (2D)
   Start with a triangle




   Connect bisectors of sides and remove central
    triangle




   Repeat
Example
 Five   subdivisions
Gasket Program
#include <GL/glut.h>
/* initial triangle */
GLfloat v[3][2]={{-1.0, -0.58},
           {1.0, -0.58}, {0.0, 1.15}};
int n; /* number of recursive steps */
void triangle( GLfloat *a, GLfloat *b, GLfloat *c)
/* display one triangle */
{
      glVertex2fv(a);
      glVertex2fv(b);
      glVertex2fv(c);
}
Triangle Subdivision
void divide_triangle(GLfloat *a, GLfloat *b, GLfloat *c, int
    m)
{
/* triangle subdivision using vertex numbers */
     point2 v0, v1, v2;
     int j;
     if(m>0)
       {
         for(j=0; j<2; j++) v0[j]=(a[j]+b[j])/2;
         for(j=0; j<2; j++) v1[j]=(a[j]+c[j])/2;
         for(j=0; j<2; j++) v2[j]=(b[j]+c[j])/2;
         divide_triangle(a, v0, v1, m-1);
         divide_triangle(c, v1, v2, m-1);
         divide_triangle(b, v2, v0, m-1);
     }
     else(triangle(a,b,c));
  /* draw triangle at end of recursion */
}
Gasket Display Functions
void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_TRIANGLES);
    divide_triangle(v[0], v[1], v[2], n);
    glEnd();
    glFlush();
}

•   By having the glBegin and glEnd in the display callback rather
    than in the function triangle and using GL_TRIANGLES rather
    than GL_POLYGON in glBegin, we call glBegin and glEnd
    only once for the entire gasket rather than once for each triangle
Example: 3D Gasket
    after 5 iterations
Tetrahedron Code
void tetrahedron( int m)
{
    glColor3f(1.0,0.0,0.0);
    divide_triangle(v[0], v[1],   v[2], m);
    glColor3f(0.0,1.0,0.0);
    divide_triangle(v[3], v[2],   v[1], m);
    glColor3f(0.0,0.0,1.0);
    divide_triangle(v[0], v[3],   v[1], m);
    glColor3f(0.0,0.0,0.0);
    divide_triangle(v[0], v[2],   v[3], m);
}

More Related Content

What's hot

Baiscs of OpenGL
Baiscs of OpenGLBaiscs of OpenGL
Baiscs of OpenGL
Mrinmoy Dalal
 
OpenGL Basics
OpenGL BasicsOpenGL Basics
OpenGL Basics
Sandip Jadhav
 
4. THREE DIMENSIONAL DISPLAY METHODS
4.	THREE DIMENSIONAL DISPLAY METHODS4.	THREE DIMENSIONAL DISPLAY METHODS
4. THREE DIMENSIONAL DISPLAY METHODS
SanthiNivas
 
Monitors & workstation,Donald ch-2
Monitors & workstation,Donald ch-2Monitors & workstation,Donald ch-2
Monitors & workstation,Donald ch-2
Iftikhar Ahmad
 
Graphics software and standards
Graphics software and standardsGraphics software and standards
Graphics software and standards
Mani Kanth
 
Computer animation
Computer animationComputer animation
Computer animation
shusrusha
 
Opengl presentation
Opengl presentationOpengl presentation
Opengl presentation
elnaqah
 
JPEG Image Compression
JPEG Image CompressionJPEG Image Compression
JPEG Image Compression
Aishwarya K. M.
 
Rendering Algorithms.pptx
Rendering Algorithms.pptxRendering Algorithms.pptx
Rendering Algorithms.pptx
SherinRappai
 
Applications of cg
Applications of cgApplications of cg
Applications of cg
Ankit Garg
 
Simplifies and normal forms - Theory of Computation
Simplifies and normal forms - Theory of ComputationSimplifies and normal forms - Theory of Computation
Simplifies and normal forms - Theory of Computation
Nikhil Pandit
 
Polygon clipping
Polygon clippingPolygon clipping
Polygon clippingMohd Arif
 
Character generation
Character generationCharacter generation
Character generation
Ankit Garg
 
Illumination Models & Shading
Illumination Models & ShadingIllumination Models & Shading
I/O devices - Computer graphics
I/O devices -  Computer graphicsI/O devices -  Computer graphics
I/O devices - Computer graphics
Amritha Davis
 
Video display devices
Video display devicesVideo display devices
Video display devicesMohd Arif
 
Hidden surface removal
Hidden surface removalHidden surface removal
Hidden surface removal
Punyajoy Saha
 

What's hot (20)

Baiscs of OpenGL
Baiscs of OpenGLBaiscs of OpenGL
Baiscs of OpenGL
 
OpenGL Basics
OpenGL BasicsOpenGL Basics
OpenGL Basics
 
4. THREE DIMENSIONAL DISPLAY METHODS
4.	THREE DIMENSIONAL DISPLAY METHODS4.	THREE DIMENSIONAL DISPLAY METHODS
4. THREE DIMENSIONAL DISPLAY METHODS
 
Monitors & workstation,Donald ch-2
Monitors & workstation,Donald ch-2Monitors & workstation,Donald ch-2
Monitors & workstation,Donald ch-2
 
Graphics software and standards
Graphics software and standardsGraphics software and standards
Graphics software and standards
 
Computer animation
Computer animationComputer animation
Computer animation
 
Opengl presentation
Opengl presentationOpengl presentation
Opengl presentation
 
JPEG Image Compression
JPEG Image CompressionJPEG Image Compression
JPEG Image Compression
 
Shading
ShadingShading
Shading
 
Rendering Algorithms.pptx
Rendering Algorithms.pptxRendering Algorithms.pptx
Rendering Algorithms.pptx
 
Applications of cg
Applications of cgApplications of cg
Applications of cg
 
Simplifies and normal forms - Theory of Computation
Simplifies and normal forms - Theory of ComputationSimplifies and normal forms - Theory of Computation
Simplifies and normal forms - Theory of Computation
 
Notes on a Standard: Unicode
Notes on a Standard: UnicodeNotes on a Standard: Unicode
Notes on a Standard: Unicode
 
Polygon clipping
Polygon clippingPolygon clipping
Polygon clipping
 
Character generation
Character generationCharacter generation
Character generation
 
Illumination Models & Shading
Illumination Models & ShadingIllumination Models & Shading
Illumination Models & Shading
 
I/O devices - Computer graphics
I/O devices -  Computer graphicsI/O devices -  Computer graphics
I/O devices - Computer graphics
 
Video display devices
Video display devicesVideo display devices
Video display devices
 
Hidden surface removal
Hidden surface removalHidden surface removal
Hidden surface removal
 
Object representations
Object representationsObject representations
Object representations
 

Viewers also liked

Introduction of openGL
Introduction  of openGLIntroduction  of openGL
Introduction of openGL
Gary Yeh
 
OpenGL Starter L01
OpenGL Starter L01OpenGL Starter L01
OpenGL Starter L01
Mohammad Shaker
 
OpenGL L01-Primitives
OpenGL L01-PrimitivesOpenGL L01-Primitives
OpenGL L01-Primitives
Mohammad Shaker
 
OpenGL Introduction
OpenGL IntroductionOpenGL Introduction
OpenGL Introduction
Yi-Lung Tsai
 
Flying machine Business Profile
Flying machine Business ProfileFlying machine Business Profile
Flying machine Business Profile
Sandeep Malkar
 
Opengl (1)
Opengl (1)Opengl (1)
Opengl (1)
ch samaram
 
Protein structure by Pauling & corey
Protein structure by Pauling & coreyProtein structure by Pauling & corey
Protein structure by Pauling & corey
CIMAP
 
OpenGL (ES) debugging
OpenGL (ES) debuggingOpenGL (ES) debugging
OpenGL (ES) debugging
Leszek Godlewski
 
Opengl lec 3
Opengl lec 3Opengl lec 3
Opengl lec 3elnaqah
 
3 d graphics with opengl part 2
3 d graphics with opengl  part 23 d graphics with opengl  part 2
3 d graphics with opengl part 2
Sardar Alam
 
Web gl game development
Web gl game developmentWeb gl game development
Web gl game development
webglgame
 
cloud conference 2013 - Infrastructure as a Service in Amazon Web Services
cloud conference 2013 - Infrastructure as a Service in Amazon Web Servicescloud conference 2013 - Infrastructure as a Service in Amazon Web Services
cloud conference 2013 - Infrastructure as a Service in Amazon Web Services
VMEngine
 
Getting Started with WebGL
Getting Started with WebGLGetting Started with WebGL
Getting Started with WebGLChihoon Byun
 
CG OpenGL polar curves & input display color-course 4
CG OpenGL polar curves & input display color-course 4CG OpenGL polar curves & input display color-course 4
CG OpenGL polar curves & input display color-course 4
fungfung Chen
 
SIGGRAPH 2012: NVIDIA OpenGL for 2012
SIGGRAPH 2012: NVIDIA OpenGL for 2012SIGGRAPH 2012: NVIDIA OpenGL for 2012
SIGGRAPH 2012: NVIDIA OpenGL for 2012
Mark Kilgard
 
OpenGL Transformation
OpenGL TransformationOpenGL Transformation
OpenGL Transformation
Sandip Jadhav
 
Chapter02 graphics-programming
Chapter02 graphics-programmingChapter02 graphics-programming
Chapter02 graphics-programming
Mohammed Romi
 
WebGL and three.js
WebGL and three.jsWebGL and three.js
WebGL and three.js
Anton Narusberg
 
OpenGL Starter L02
OpenGL Starter L02OpenGL Starter L02
OpenGL Starter L02
Mohammad Shaker
 

Viewers also liked (20)

Introduction of openGL
Introduction  of openGLIntroduction  of openGL
Introduction of openGL
 
OpenGL Starter L01
OpenGL Starter L01OpenGL Starter L01
OpenGL Starter L01
 
OpenGL L01-Primitives
OpenGL L01-PrimitivesOpenGL L01-Primitives
OpenGL L01-Primitives
 
OpenGL Introduction
OpenGL IntroductionOpenGL Introduction
OpenGL Introduction
 
Flying machine Business Profile
Flying machine Business ProfileFlying machine Business Profile
Flying machine Business Profile
 
Opengl (1)
Opengl (1)Opengl (1)
Opengl (1)
 
Protein structure by Pauling & corey
Protein structure by Pauling & coreyProtein structure by Pauling & corey
Protein structure by Pauling & corey
 
OpenGL (ES) debugging
OpenGL (ES) debuggingOpenGL (ES) debugging
OpenGL (ES) debugging
 
Opengl lec 3
Opengl lec 3Opengl lec 3
Opengl lec 3
 
3 d graphics with opengl part 2
3 d graphics with opengl  part 23 d graphics with opengl  part 2
3 d graphics with opengl part 2
 
Web gl game development
Web gl game developmentWeb gl game development
Web gl game development
 
cloud conference 2013 - Infrastructure as a Service in Amazon Web Services
cloud conference 2013 - Infrastructure as a Service in Amazon Web Servicescloud conference 2013 - Infrastructure as a Service in Amazon Web Services
cloud conference 2013 - Infrastructure as a Service in Amazon Web Services
 
Getting Started with WebGL
Getting Started with WebGLGetting Started with WebGL
Getting Started with WebGL
 
Web Sockets in Java EE 7
Web Sockets in Java EE 7Web Sockets in Java EE 7
Web Sockets in Java EE 7
 
CG OpenGL polar curves & input display color-course 4
CG OpenGL polar curves & input display color-course 4CG OpenGL polar curves & input display color-course 4
CG OpenGL polar curves & input display color-course 4
 
SIGGRAPH 2012: NVIDIA OpenGL for 2012
SIGGRAPH 2012: NVIDIA OpenGL for 2012SIGGRAPH 2012: NVIDIA OpenGL for 2012
SIGGRAPH 2012: NVIDIA OpenGL for 2012
 
OpenGL Transformation
OpenGL TransformationOpenGL Transformation
OpenGL Transformation
 
Chapter02 graphics-programming
Chapter02 graphics-programmingChapter02 graphics-programming
Chapter02 graphics-programming
 
WebGL and three.js
WebGL and three.jsWebGL and three.js
WebGL and three.js
 
OpenGL Starter L02
OpenGL Starter L02OpenGL Starter L02
OpenGL Starter L02
 

Similar to Open gl

openGL basics for sample program (1).ppt
openGL basics for sample program (1).pptopenGL basics for sample program (1).ppt
openGL basics for sample program (1).ppt
HIMANKMISHRA2
 
openGL basics for sample program.ppt
openGL basics for sample program.pptopenGL basics for sample program.ppt
openGL basics for sample program.ppt
HIMANKMISHRA2
 
18csl67 vtu lab manual
18csl67 vtu lab manual18csl67 vtu lab manual
18csl67 vtu lab manual
NatsuDragoneel5
 
Computer Graphics Project Report on Sinking Ship using OpenGL
Computer Graphics Project Report on Sinking Ship using OpenGL Computer Graphics Project Report on Sinking Ship using OpenGL
Computer Graphics Project Report on Sinking Ship using OpenGL
Sharath Raj
 
OpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsOpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI Platforms
Prabindh Sundareson
 
01.Opengl_intro-2.ppt
01.Opengl_intro-2.ppt01.Opengl_intro-2.ppt
01.Opengl_intro-2.ppt
EngrZamaan
 
opengl.ppt
opengl.pptopengl.ppt
opengl.ppt
Subiksha57
 
Intro to Computer Graphics.ppt
Intro to Computer Graphics.pptIntro to Computer Graphics.ppt
Intro to Computer Graphics.ppt
adil104135
 
Advanced Graphics Workshop - GFX2011
Advanced Graphics Workshop - GFX2011Advanced Graphics Workshop - GFX2011
Advanced Graphics Workshop - GFX2011
Prabindh Sundareson
 
Computer Graphics with OpenGL presentation Slides.pptx
Computer Graphics with OpenGL presentation Slides.pptxComputer Graphics with OpenGL presentation Slides.pptx
Computer Graphics with OpenGL presentation Slides.pptx
AnandM62785
 
Convert Your Legacy OpenGL Code to Modern OpenGL with Qt
Convert Your Legacy OpenGL Code to Modern OpenGL with QtConvert Your Legacy OpenGL Code to Modern OpenGL with Qt
Convert Your Legacy OpenGL Code to Modern OpenGL with Qt
ICS
 
Introduction to OpenGL.ppt
Introduction to OpenGL.pptIntroduction to OpenGL.ppt
Introduction to OpenGL.ppt
16118MdFirozAhmed
 
BYO3D 2011: Rendering
BYO3D 2011: RenderingBYO3D 2011: Rendering
BYO3D 2011: Rendering
Matt Hirsch - MIT Media Lab
 
COMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORTCOMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORT
vineet raj
 
Porting the Source Engine to Linux: Valve's Lessons Learned
Porting the Source Engine to Linux: Valve's Lessons LearnedPorting the Source Engine to Linux: Valve's Lessons Learned
Porting the Source Engine to Linux: Valve's Lessons Learned
basisspace
 
Lab Practices and Works Documentation / Report on Computer Graphics
Lab Practices and Works Documentation / Report on Computer GraphicsLab Practices and Works Documentation / Report on Computer Graphics
Lab Practices and Works Documentation / Report on Computer Graphics
Rup Chowdhury
 
Introduction to 2D/3D Graphics
Introduction to 2D/3D GraphicsIntroduction to 2D/3D Graphics
Introduction to 2D/3D Graphics
Prabindh Sundareson
 
State of the Art OpenGL and Qt
State of the Art OpenGL and QtState of the Art OpenGL and Qt
State of the Art OpenGL and Qt
ICS
 

Similar to Open gl (20)

openGL basics for sample program (1).ppt
openGL basics for sample program (1).pptopenGL basics for sample program (1).ppt
openGL basics for sample program (1).ppt
 
openGL basics for sample program.ppt
openGL basics for sample program.pptopenGL basics for sample program.ppt
openGL basics for sample program.ppt
 
18csl67 vtu lab manual
18csl67 vtu lab manual18csl67 vtu lab manual
18csl67 vtu lab manual
 
Bai 1
Bai 1Bai 1
Bai 1
 
Computer Graphics Project Report on Sinking Ship using OpenGL
Computer Graphics Project Report on Sinking Ship using OpenGL Computer Graphics Project Report on Sinking Ship using OpenGL
Computer Graphics Project Report on Sinking Ship using OpenGL
 
OpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsOpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI Platforms
 
01.Opengl_intro-2.ppt
01.Opengl_intro-2.ppt01.Opengl_intro-2.ppt
01.Opengl_intro-2.ppt
 
opengl.ppt
opengl.pptopengl.ppt
opengl.ppt
 
Intro to Computer Graphics.ppt
Intro to Computer Graphics.pptIntro to Computer Graphics.ppt
Intro to Computer Graphics.ppt
 
Advanced Graphics Workshop - GFX2011
Advanced Graphics Workshop - GFX2011Advanced Graphics Workshop - GFX2011
Advanced Graphics Workshop - GFX2011
 
Computer Graphics with OpenGL presentation Slides.pptx
Computer Graphics with OpenGL presentation Slides.pptxComputer Graphics with OpenGL presentation Slides.pptx
Computer Graphics with OpenGL presentation Slides.pptx
 
Convert Your Legacy OpenGL Code to Modern OpenGL with Qt
Convert Your Legacy OpenGL Code to Modern OpenGL with QtConvert Your Legacy OpenGL Code to Modern OpenGL with Qt
Convert Your Legacy OpenGL Code to Modern OpenGL with Qt
 
Introduction to OpenGL.ppt
Introduction to OpenGL.pptIntroduction to OpenGL.ppt
Introduction to OpenGL.ppt
 
BYO3D 2011: Rendering
BYO3D 2011: RenderingBYO3D 2011: Rendering
BYO3D 2011: Rendering
 
COMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORTCOMPUTER GRAPHICS PROJECT REPORT
COMPUTER GRAPHICS PROJECT REPORT
 
Open gles
Open glesOpen gles
Open gles
 
Porting the Source Engine to Linux: Valve's Lessons Learned
Porting the Source Engine to Linux: Valve's Lessons LearnedPorting the Source Engine to Linux: Valve's Lessons Learned
Porting the Source Engine to Linux: Valve's Lessons Learned
 
Lab Practices and Works Documentation / Report on Computer Graphics
Lab Practices and Works Documentation / Report on Computer GraphicsLab Practices and Works Documentation / Report on Computer Graphics
Lab Practices and Works Documentation / Report on Computer Graphics
 
Introduction to 2D/3D Graphics
Introduction to 2D/3D GraphicsIntroduction to 2D/3D Graphics
Introduction to 2D/3D Graphics
 
State of the Art OpenGL and Qt
State of the Art OpenGL and QtState of the Art OpenGL and Qt
State of the Art OpenGL and Qt
 

More from ch samaram

Syllabus r10-ecm-42-network security and cryptography
 Syllabus r10-ecm-42-network security and cryptography Syllabus r10-ecm-42-network security and cryptography
Syllabus r10-ecm-42-network security and cryptographych samaram
 
Restaurant billing application
Restaurant billing applicationRestaurant billing application
Restaurant billing applicationch samaram
 
Spintronics
SpintronicsSpintronics
Spintronics
ch samaram
 
Spintronics (1)
Spintronics (1)Spintronics (1)
Spintronics (1)
ch samaram
 
Shore
ShoreShore
Shore
ch samaram
 
Presentation
PresentationPresentation
Presentation
ch samaram
 
Computer forensics law and privacy
Computer forensics   law and privacyComputer forensics   law and privacy
Computer forensics law and privacy
ch samaram
 
Blue gene
Blue geneBlue gene
Blue gene
ch samaram
 
Blue gene
Blue geneBlue gene
Blue gene
ch samaram
 
Wearable (1)
Wearable (1)Wearable (1)
Wearable (1)
ch samaram
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoftch samaram
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
 

More from ch samaram (17)

Syllabus r10-ecm-42-network security and cryptography
 Syllabus r10-ecm-42-network security and cryptography Syllabus r10-ecm-42-network security and cryptography
Syllabus r10-ecm-42-network security and cryptography
 
Restaurant billing application
Restaurant billing applicationRestaurant billing application
Restaurant billing application
 
Spintronics
SpintronicsSpintronics
Spintronics
 
Spintronics (1)
Spintronics (1)Spintronics (1)
Spintronics (1)
 
Shore
ShoreShore
Shore
 
Presentation
PresentationPresentation
Presentation
 
Computer forensics law and privacy
Computer forensics   law and privacyComputer forensics   law and privacy
Computer forensics law and privacy
 
Blue gene
Blue geneBlue gene
Blue gene
 
Blue gene
Blue geneBlue gene
Blue gene
 
Wearable (1)
Wearable (1)Wearable (1)
Wearable (1)
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Html siva
Html sivaHtml siva
Html siva
 
Css siva
Css sivaCss siva
Css siva
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Ajax
AjaxAjax
Ajax
 
Html 5
Html 5Html 5
Html 5
 
Css siva
Css sivaCss siva
Css siva
 

Recently uploaded

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

Open gl

  • 2. What is OpenGL  OpenGL is a software API to graphics hardware.  designed as a streamlined, hardware-independent interface to be implemented on many different hardware platforms  Intuitive, procedural interface with c binding  No windowing commands !  No high-level commands for describing models of three- dimensional objects  The OpenGL Utility Library (GLU) provides many of the modeling features, such as quadric surfaces and NURBS curves and surfaces
  • 3. 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
  • 4. OpenGL The success of GL lead to OpenGL (1992), a platform-independent 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
  • 5. OpenGL Evolution  Controlled by an Architectural Review Board (ARB)  Members include SGI, Microsoft, Nvidia, HP, 3DLabs, IBM,…….  Relatively stable (present version 2.0)  Evolution reflects new hardware capabilities  3D texture mapping and texture objects  Vertex and fragment programs  Allows for platform specific features through extensions
  • 6. 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  Links with window system  GLX for X window systems, WGL for Windows  Cross-platform GUI libraries: GLUT, SDL, FLTK, QT, …
  • 7. Windowing with OpenGL  OpenGL is independent of any specific window system  OpenGL can be used with different window systems  X windows (GLX)  MFC  …  GLUTprovide a portable API for creating window and interacting with I/O devices
  • 8. 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  No slide bars, buttons, …
  • 9. Software Organization application program OpenGL Motif widget or similar GLUT GLX, AGL or WGL GLU X, Win32, Mac O/S OpenGL software and/or hardware
  • 10. OpenGL Architecture Immediate Mode geometry pipeline Per Vertex Polynomial Operations & Evaluator Primitive Assembly Display Per Fragment Frame CPU List Rasterization Operations Buffer Texture Memory Pixel Operations
  • 11. OpenGL as a state machine  GL State Variables- can be set and queried by OpenGL. Remains unchanged until the next change.  Projection and viewing matrix  Color and material properties  Lights and shading  Line and polygon drawing modes  …  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
  • 12. OpenGL Syntax  Functions have prefix gl and initial capital letters for each word  glClearColor(), glEnable(), glPushMatrix() …  glu for GLU functions  gluLookAt(), gluPerspective() …  Constants begin with GL_, use all capital letters  GL_COLOR_BUFFER_BIT, GL_PROJECTION, GL_MODELVIEW …  Extra letters in some commands indicate the number and type of variables  glColor3f(), glVertex3f() …  OpenGL data types  GLfloat, GLdouble, GLint, GLenum, …  Underlying storage mode is the same  Easy to create overloaded functions in C++ but issue is efficiency
  • 13. OpenGL function format function name dimensions glVertex3f(x,y,z) x,y,z are floats belongs to GL library glVertex3fv(p) p is a pointer to an array
  • 14. 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,….
  • 15. GLUT  Developed by Mark Kilgard  Hides the complexities of differing window system APIs  Default user interface for class projects  Glut routines have prefix glut  glutCreateWindow() …  Has very limited GUI interface  Glui is the C++ extension of glut
  • 16. Glut Routines  Initialization: glutInit() processes (and removes) command-line arguments that may be of interest to glut and the window system and does general initialization of Glut and OpenGL  Must be called before any other glut routines  Display Mode: The next procedure, glutInitDisplayMode(), performs initializations informing OpenGL how to set up the frame buffer.  Display Mode Meaning  GLUT_RGB Use RGB colors  GLUT_RGBA Use RGB plus alpha (for transparency)  GLUT_INDEX Use indexed colors (not recommended)  GLUT_DOUBLE Use double buffering (recommended)  GLUT_SINGLE Use single buffering (not recommended)  GLUT_DEPTH Use depth-buffer (for hidden surface removal.)
  • 17. Glut Routines  Window Setup  glutInitWindowSize(int width, int height)  glutInitWindowPosition(int x, int y)  glutCreateWindow(char* title)
  • 18. A Simple Program Generate a square on a solid background
  • 19. simple.c #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** argv){ glutInit(&argc, argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500,500); glutInitWindowPosition(0,0); glutCreateWindow("simple"); glutDisplayFunc(mydisplay); init(); glutMainLoop(); }
  • 20. Closer Look at the main() #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(); display callback set OpenGL state glutMainLoop(); } enter event loop
  • 21. init.c black clear color void init() opaque window { glClearColor (0.0, 0.0, 0.0, 1.0); 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
  • 22. Event Handling  Virtually all interactive graphics programs are even driven  GLUT uses callbacks to handle events  Windows system invokes a particular procedure when an event of particular type occurs.  MOST IMPORTANT: display event  Signaled when window first displays and whenever portions of the window reveals from blocking window  glutDisplayFunc(void (*func)(void)) registers the display callback function  Running the program: glutMainLoop()  Main event loop. Never exit()
  • 23. More Callbacks  glutReshapeFunc(void (*func)(int w, int h)) indicates what action should be taken when the window is resized.  glutKeyboardFunc(void (*func)(unsigned char key, int x, int y)) and glutMouseFunc(void (*func)(int button, int state, int x, int y)) allow you to link a keyboard key or a mouse button with a routine that's invoked when the key or mouse button is pressed or released.  glutMotionFunc(void (*func)(int x, int y)) registers a routine to call back when the mouse is moved while a mouse button is also pressed.  glutIdleFunc(void (*func)(void)) registers a function that's to be executed if no other events are pending - for example, when the event loop would otherwise be idle
  • 24. Compilation on Windows  See class web site on how to set up a project with OpenGL  Visual C++  Get glut.h, glut32.lib and glut32.dll from web  Create a console application  Add opengl32.lib, glut32.lib, glut32.lib to project settings (under link tab)
  • 25. Simple Animation  Animation  Redraw + swap buffers  What looks like if using single buffer  Example program  More on the glut documentation  Chapter 2 of textbook  OpenGL redbook  Links in the class resources page
  • 26. OpenGL Drawing  We have learned how to create a window  Steps in the display function  Clear the window  Set drawing attributes  Send drawing commands  Swap the buffers  OpenGL coordinate system has different origin from the window system  Uses lower left corner instead of upper left corner as origin
  • 27. Clear the Window  glClear(GL_COLOR_BUFFER_BIT)  clears the frame buffer by overwriting it with the background color.  Background color is a state set by glClearColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a) in the init().
  • 28. Drawing Attributes: Color  glColor3f(GLfloat r, GLfloat g, GLfloat b) sets the drawing color  glColor3d(), glColor3ui() can also be used  Remember OpenGL is a state machine  Once set, the attribute applies to all subsequent defined objects until it is set to some other value  glColor3fv() takes a flat array as input  There are more drawing attributes than color  Point size: glPointSize()  Line width: glLinewidth()  Dash or dotted line: glLineStipple()  Polygon pattern: glPolygonStipple()  …
  • 29. Drawing Commands  Simple Objects glRectf()  Complex Objects  Use construct glBegin(mode) and glEnd() and a list of vertices in between  glBegin(mode) glVertex(v0); glVertex(v1); ... glEnd();  Some other commands can also be used between glBegin() and glEnd(), e.g. glColor3f().  Example
  • 31. Orthographic projection  Orthographic View  glOrtho(left, right, bottom, top, front, back)  Specifies the coordinates of 3D region to be projected z=0 into the image space.  Any drawing outside the region will be automatically clipped away.
  • 32. Viewports  Do not have use the entire window for the image: glViewport(x,y,w,h)  Values in pixels (screen coordinates)
  • 33. Window to Viewport mapping Aspect Ratio: Height/Width If the aspect ratio of the window Is different from that of the viewport, the picture will be distorted.
  • 34. Sierpinski Gasket (2D)  Start with a triangle  Connect bisectors of sides and remove central triangle  Repeat
  • 35. Example  Five subdivisions
  • 36. Gasket Program #include <GL/glut.h> /* initial triangle */ GLfloat v[3][2]={{-1.0, -0.58}, {1.0, -0.58}, {0.0, 1.15}}; int n; /* number of recursive steps */ void triangle( GLfloat *a, GLfloat *b, GLfloat *c) /* display one triangle */ { glVertex2fv(a); glVertex2fv(b); glVertex2fv(c); }
  • 37. Triangle Subdivision void divide_triangle(GLfloat *a, GLfloat *b, GLfloat *c, int m) { /* triangle subdivision using vertex numbers */ point2 v0, v1, v2; int j; if(m>0) { for(j=0; j<2; j++) v0[j]=(a[j]+b[j])/2; for(j=0; j<2; j++) v1[j]=(a[j]+c[j])/2; for(j=0; j<2; j++) v2[j]=(b[j]+c[j])/2; divide_triangle(a, v0, v1, m-1); divide_triangle(c, v1, v2, m-1); divide_triangle(b, v2, v0, m-1); } else(triangle(a,b,c)); /* draw triangle at end of recursion */ }
  • 38. Gasket Display Functions void display() { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_TRIANGLES); divide_triangle(v[0], v[1], v[2], n); glEnd(); glFlush(); } • By having the glBegin and glEnd in the display callback rather than in the function triangle and using GL_TRIANGLES rather than GL_POLYGON in glBegin, we call glBegin and glEnd only once for the entire gasket rather than once for each triangle
  • 39. Example: 3D Gasket after 5 iterations
  • 40. Tetrahedron Code void tetrahedron( int m) { glColor3f(1.0,0.0,0.0); divide_triangle(v[0], v[1], v[2], m); glColor3f(0.0,1.0,0.0); divide_triangle(v[3], v[2], v[1], m); glColor3f(0.0,0.0,1.0); divide_triangle(v[0], v[3], v[1], m); glColor3f(0.0,0.0,0.0); divide_triangle(v[0], v[2], v[3], m); }