Unit 2: Graphics Programming The Opengl: by Shubha Raj K.B
Unit 2: Graphics Programming The Opengl: by Shubha Raj K.B
Unit 2: Graphics Programming The Opengl: by Shubha Raj K.B
Objectives
2.1 The Sierpinski Gasket 2.2 Programming 2D Applications Co-ordinate systems 2.3 The OpenGL API Graphics Functions The Graphics pipelines and state machines The OpenGL Interface 2.4 Primitives and Attributes 2.5 Color 2.6 Viewing 2.7 Control Functions 2.8 The Gasket program 2.9 Polygons and Recursion 2.10 The 3d Gasket 2.11 Plotting Implicit Functions
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
2
Use pen-plotter API. P=(x,y,0) or p=(x,y) Or P can be represented by column matrix glVertex*() *= ntv
void display( void ) { /* define a point data type */ typedef GLfloat point2[2]; point2 vertices[3]={{0.0,0.0},{250,400.0},{400.0,0.0}}; /* A triangle */ int i, j, k; int rand(); /* standard random number generator */ point2 p ={75,50.0}; /* An arbitrary initial point inside traingle */ /* compute and plots 5000 new points */ for( k=0; k<5000; k++) { j=rand()%3; /* pick a vertex at random */ /* Compute point halfway between selected vertex and old point */ p[0] = (p[0]+vertices[j][0])/2.0; p[1] = (p[1]+vertices[j][1])/2.0; /* plot new point */ glBegin(GL_POINTS); glVertex2fv(p); glEnd(); } glFlush(); /* clear buffers */
Device-independent graphics
- World or object co-ordinates - Device or Window or Screen co-ordinates
Application program
function calls
output
Data
Graphics System
Input
Input/output devices
Attributes (HOW) Viewing (CAMERA) Transformations Control (GLUT) Input (GLUT) Query (Device independent programs- 2 color)
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
12
Primitive function
Define the low level objects or atomic entities that our system can display. Depending on the API, the primitives can include
- points, line segments, polygons, pixels, text , and various type of curves and surfaces.
Attribute function
To perform operations ranging from choosing the color with which we display a line segment.
- Eg glColor3f(1.0,0.0,0.0); glLineWidth(width);
To picking a pattern with which to fill the inside of a polygon. To selecting a typesafe for the title on a graph.
Input function Allows us to deal with the diverse forms of input that characterize modern graphics systems.
- void glutKeyboardFunc(void (*func) (unsigned char key, int x, int y));
Control function Enable us to communicate with the window system, to initialize our programs and to deal with any errors that take place during the execution of our programs. - glutInitWindowSize(500,500);
Query function How many color are supported or The size of the display. Camera parameters or values in the frame buffer.
- State changing
Transformation functions Attribute functions
19
2. Those that either changes the state inside the machine or return state information.
Underlying storage mode is the same Easy to create overloaded functions in C++ but issue is efficiency
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
21
GLU
- This library uses only GL functions but contains code for creating common objects and simplifying viewing. - Functions in the GLU library begin with the letter glu. GLUT To interface with the window system and to get input from external devices into our programs, we need at least one more library.
AGL
- for the macintosh it is agl or(Apple graphics library).
Rather than using a different library for each system,we use a readily available library called the openGL utility Toolkit(GLUT). GLUT provides minimum functionality that should be expected in any modern windowing system.
Glut uses GLX and the X libraries. GL_FILL and GL_POINTS are defined in the header file(.h) #include<GL/glut.h> or #include<GLUT/glut.h> Is sufficient to read in glut.h,gl.h,glu.h
26
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)
30
OpenGL Primitives
GL_POINTS
GL_LINES GL_LINE_STRIP
GL_POLYGON
GL_LINE_LOOP GL_TRIANGLES
GL_QUAD_STRIP GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
31
32
Geometric Primitives can be used as building blocks for other geometric objects. Raster primitives such as arrays of pixels pass through a separate parallel pipeline. The basic OpenGL geometric primitives are specified by sets of vertices.
glBegin(type);
glVertex*(); . . glVertex*(); glEnd();
35
The value of type specifies how OpenGL assembles the vertices to define geometric objects. Other code and OpenGL function calls can occur between glBegin and glEnd. Major difference between the geometric types
- Whether or not they have interiors.
LINE SEGMENTS Finite sections of lines between two vertices called line segments.
USES Use line segments to define approximations to curves. you can use a sequence of line segments to connect data values for a graph. You can also use line segments for the edges of closed objects, such as polygon that have interiors.
Line segments(GL_LINES):
- Successive pairs of vertices to be interpreted as the endpoints of individual segments.
Polylines(GL_LINE_STRIP,GL_LINE_LOOP):
GL_LINE_STRIP - If successive vertices are to be connected, we can use the line strip or polyline form. GL_LINE_LOOP - will draw a line segment from the final vertex to the first, thus creating a closed path.
Polygon Basics
Polygon has a border and has a well defined interior.
- It can be described by line loop.
Polygons play a special role in CG. The performance of graphics systems is characterized by the
- number of polygons per second that can be rendered.
Polygon rendering Render only its edges. Render its interior with a solid color or a pattern. we can render or not render the edges
Filled objects
Three properties will ensure that a polygon will be displayed correctly. It must be simple,convex and flat. Simple
in 2D ,as long as no two edges of a polygon cross each other,we have a simple polygon. Well defined interiors.
Convex
An object is convex if all points on the line segment between any two points inside the object or on its boundary are inside the object. p1 and p2 are arbitrary points inside a polygon and the entire line segment connecting them is inside the polygon. Convex objects include
triangle, tetrahedra, rectangles, circles, spheres, parallepipeds.
Simple: edges cannot cross Convex: All points on line segment between two points in a polygon are also in the polygon
Polygon Issues
OpenGL will only display polygons correctly that are
- Simple: edges cannot cross - Convex: All points on line segment between two points in a polygon are also in the polygon - Flat: all vertices are in the same plane
nonsimple polygon
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
Convexity
Convex objects
Polygon types
2.4.4 TEXT
There are two forms of text:
- Stroke - Raster
Stroke text
Defining a full 128 or 256 character stroke font can be complex. It takes significant memory and processing time. standard postscript fonts
Raster text simple and fast. Characters are defined as rectangles of bit called bit blocks. Each block defines a single character by the pattern of 0 and 1 bits in the block. Bit-block-transfer
- A raster character can be placed in the frame buffer rapidly by a bit-block-transfer(bitblt) operation,which moves the block of bits using a single call.
a)Raster text
Replicating you can increase the size of raster characters by replicating or duplicating pixels, a process that gives larger characters a blocky appearance. GLUT library provides a few predefined bitmap and stroke character sets .
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, c) - Where c is the number of the ASCII character that we wish to be placed on the display
Tessellation
- We approximate a curves surfaces by a mesh of convex polygons- Tessellation - which can occur either at the
rendering stage or within the user programs
2.4.6 Attributes
Color Thinkness of a line Pattern used to fill a polygon
63
Attributes
An Attributes is any property that determines how a geometric primitive is to be rendered - point (color, size), line (color,thickness, type), polygon (pattern types, etc). - text (height, width, font, style (bold, italic, underlined)) immediate mode primitives are not stored in the display system but rather passed through the system for possible rendering as soon as they are defined. no memory once erased from the display,it is lost. display list keep objects in memory so that these objects can be redisplayed.
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
65
2.5 COLOR
A visible color can be characterized by a function C(l) that occupies wavelengths from about 350 to 780nm. Tristimulus values
- Our Brain receive three values. Color theory If two colors produce the same tristimulus values,then they are visually indistinguishable.
Additive color
Subtractive color
68
Color formation
Additive color Subtractive color
Color solid
Color solid
Draw Solid using a coordinate system corresponding to the three primaries. Principal diagonal of the cube connects the origin(black) with white. All colors along this line have shades of gray.
Each pixel has separate red, green and blue components that correspond to locations in memory. Each pixel consist of 24 bits(3 bytes).
1 byte for each red, green and blue.
Color components between 0.0 and 1.0, where 1.0 denotes the maximun(saturated value).
- glColor3f(1.0,0.0,0.0);
RGBA SYSTEM A-alpha The alpha value will be treated by OpenGL as either an opacity or transparency. A=0.0 - Fully transparent A=1.0 - Fully opaque
Must clear the window whenever we want to draw a new frame. glClearColor(1.0,1.0,1.0,1.0); defines an RGB color clearing color that is white.
It gives less no of color. Indexed color provide solution that allowed applications to display a wide range of color.
Images are called indexed color because the actual image color data for each pixel is the index into this palette . Analogy with an artist who paints in oil.
256 entries in the table constitute the users color palette. fig:color lookup table
Fig:Indexed color
Suppose that our frame has k bits per pixel. Each pixel value or index is an integer between 0 and
We handle the specification through a user defined color lookup table that is of size 2k *3m. The user program fills the 2k entries of the table with the desired colors ,
- using m bits for each of red ,green and blue.
The first RGB color in the table is index 0, the second RGB color is index 1, etc.
- There can be at most only 256 colors in the palette.
Advantage
- Less memory - Fewer other hardware components.
2.6 VIEWING
Camera forms an image by exposing a film. The computer system forms an image
- by carrying out a sequence of operations in its pipeline.
Slide the projection plane along the z-axis without changing where the projectors intersect the plane.
Orthographic Projection
Projectors are orthogonal to projection surface
There is reference point in the projection plane from which we can make measurements of a view volume and a direction of projection. Reference point -origin. camera points in the negative z-direction.
Viewing volume
It takes a point(x,y,z) and projects it into the point(x,y,0). In openGL, an orthographic projection with a right parallelepiped viewing volume is specified via the following
void glOrtho(GLdouble left, GLdouble right, GLdouble bottom,GLdouble top, Gldouble near,GLdouble far);
The orthographic projection sees only those objects in the volume specified by viewing volume.
2.6.2 2D viewing
void gluOrtho2D (GLdouble left, Gldouble right, GLdouble bottom, GLdouble top)
Take a rectangular area of our two dimensional world and transferring its contents to the display.
The area of the world that we image is known as viewing rectangle or clipping rectangle. Objects inside the rectangle are in the image.
- objects outside are clipped out.
2D viewing
a) objects before clipping. b) objects after clipping
Matrics
Two things to specify:
- Physical location of camera in the scene (MODELVIEW matrix in OpenGL). - Projection properties of the camera (PROJECTION matrix in OpenGL):
96
Perspective projection
void glFrustum(GLdouble left, GLdouble right, GLdouble bottom,GLdouble top, GLdouble near, GLdouble far);
Orthographic projection
void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble near, GLdouble far);
Window
- has height and width - it displays the contents of the frame buffer. - Positions in the window measured in terms pixels.
Screen resolution-1280 x1024 Frame buffer must have resolution equal to screen size.
If they differ, objects are distorted on the screen. To avoid this distortion if we ensure that
- the clipping rectangle and display window have the same aspect ratio.
Viewports
Do not have use the entire window for the image: glViewport(x,y,w,h) Values in pixels (screen coordinates)
105
Interaction between windowing system and OpenGL is initialized by the following function.
glutInit(int *argc,char **argv) Argument is same as main.
Use following GLUT functions before window creation to specify these parameters.
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(640,480); glutInitWindowPosition(0,0);
A Simple Program
Generate a square on a solid background
107
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){ glutCreateWindow("simple"); glutDisplayFunc(mydisplay); glutMainLoop(); }
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
108
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
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
109
main.c
#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"); define window properties glutDisplayFunc(mydisplay);
init();
glutMainLoop(); }
init.c
black clear color opaque window
glMatrixMode (GL_PROJECTION); glLoadIdentity (); glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0); }
viewing volume
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
111
- callbacks
Display function Input and window functions
112
simple.c 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
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
113
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
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
114
Coordinate Systems
The units in glVertex are determined by the application and are called
- object or problem coordinates
Internally, OpenGL will convert to camera (eye) coordinates and later to screen coordinates OpenGL also uses some internal representations that usually are not visible to the application
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
115
void display( void ) { /* define a point data type */ typedef GLfloat point2[2]; point2 vertices[3]={{0.0,0.0},{250,400.0},{400.0,0.0}}; /* A triangle */ int i, j, k; int rand(); /* standard random number generator */ point2 p ={75,50.0}; /* An arbitrary initial point inside traingle */ glClear(GL_COLOR_BUFFER_BIT); /*clear the window */ /* compute and plots 5000 new points */ for( k=0; k<1000; k++) { j=rand()%3; /* pick a vertex at random */ /* Compute point halfway between selected vertex and old point */ p[0] = (p[0]+vertices[j][0])/2.0; p[1] = (p[1]+vertices[j][1])/2.0; /* plot new point */ glBegin(GL_POINTS); glVertex2fv(p); glEnd(); } glFlush(); /* clear buffers */ }
117
Repeat
118
Example
subdivisions
119
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 */
121
122
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 */ }
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
123
main Function
int main(int argc, char **argv) { n=4; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowSize(500, 500); glutCreateWindow(2D Gasket"); glutDisplayFunc(display); myinit(); glutMainLoop(); }
125
Efficiency Note
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
126
Objectives
Develop a more sophisticated threedimensional example
- Sierpinski gasket: a fractal
127
Going to 3D
- Not much changes - Use glVertex3*( ) - Have to worry about the order in which polygons are drawn or use hidden-surface removal - Polygons should be simple, convex, flat
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
128
dimensions
belongs to GL library
130
Appears as if we remove a solid tetrahedron from the center leaving four smaller tetrahedra
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
131
triangle code
void triangle( GLfloat *a, GLfloat *b, GLfloat *c) { glVertex3fv(a); glVertex3fv(b); glVertex3fv(c); }
132
subdivision code
void divide_triangle(GLfloat *a, GLfloat *b, GLfloat *c, int m) { GLfloat v1[3], v2[3], v3[3]; int j; if(m>0) { for(j=0; j<3; j++) v1[j]=(a[j]+b[j])/2; for(j=0; j<3; j++) v2[j]=(a[j]+c[j])/2; for(j=0; j<3; j++) v3[j]=(b[j]+c[j])/2; divide_triangle(a, v1, v2, m-1); divide_triangle(c, v2, v3, m-1); divide_triangle(b, v3, v1, m-1); } else(triangle(a,b,c)); }
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
133
tetrahedron code
void tetrahedron( int m) { glColor3f(1.0,0.0,0.0); divide_triangle(v[0], v[1], glColor3f(0.0,1.0,0.0); divide_triangle(v[3], v[2], glColor3f(0.0,0.0,1.0); divide_triangle(v[0], v[3], glColor3f(0.0,0.0,0.0); divide_triangle(v[0], v[2], }
v[2], m);
v[1], m);
v[1], m);
v[3], m);
134
Almost Correct
Because the triangles are drawn in the order they are defined in the program,
- the front triangles are not always rendered in front of triangles behind them
get this
want this
135
136
Keeping only these tetrahedrons removes a volume in the middle See text for code
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
138
Volume Subdivision
139
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
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
141
MATRIX MODE
Using glMatrixMode function you chose which matrix you want to change. OpenGL works with 3 matrices: GL_MODELVIEW:
- this one is used to move vertex to model space.
- By default, the matrix mode is GL_MODELVIEW, which assumes everything you draw will be in one 3Dspace.
GL_PROJECTION:
- this one is used to convert 3D coordinate to 2D coordinate for final pixel position.
A computer monitor is a 2D surface. We need to transform 3D scene into 2D image in order to display it. GL_PROJECTION matrix is for this projection transformation GL_TEXTURE: this one is used to alter texture coordinates.
Matrix mode
Pipeline graphics system depends on
- multiplying together or Concatenating a number of transformation matrices to achieve the desired image of a primitive
Marching Squares
- Solve the problem for sampled data by a technique called marching Squares
Angel: Interactive Computer Graphics 5E Addison-Wesley 2009
145
Summary of UNIT2
GKS
- 2D, Pen-Plotter Model - GKS-3D
Recently Sun Microsystems recently released their Java bindings for openGL
- Many Java programmer use the JOGL bindings
Modeling-rendering Paradigm
- Focus on Modeling in UNIT2
146