chapter-34-thise
chapter-34-thise
Chapter 3 & 4
Rendering Process
with OpenGL
Computer Graphics
9-Nov-23 Mulugeta G. (BSc) STBC– CS 1
What is OpenGL?
OpenGL (Open Graphics Library)
- an Application Programming Interface (API) that
allows the programmer to create 2D and 3D
graphics images
- generate high-quality color images by rendering with
geometric and image primitives
- It forms many interactive applications
- It is independent of the hardware, operating, and
windowing systems in use
- The fact that it is windowing-system independent, makes it
portable
- a number of windowing toolkits have been developed for
use with OpenGL
What is OpenGL?
OpenGL is based on GL graphics package developed
by the graphics hardware manufacturer Silicon Graphics
- GL was a popular package but it was specific to
Silicon Graphics systems, i.e. code written using GL
would only run on Silicon Graphics hardware
- to overcome this limitation, OpenGL was developed
in the early 1992 as a free platform-independent
version of GL
OpenGL is the core library that contains the majority of
the functionality (around 130 graphics drawing and
operation functions), there are a number of associated
libraries that are also useful
What is OpenGL?
You should make sure that you have access to a
C++ development environment that supports
these two libraries (OpenGL & glut)
Turbo C++ does not support either of them
Two possibilities are:
free Dev-C++ environment (www.bloodshed.net) has
OpenGL built-in and glut can be easily added on as
a separate package
Microsoft Visual C++ also has OpenGL built-in but
not glut. The glut library is available as a free
download from
http://www.xmission.com/~nate/glut.html
GLUT Functions
Primitives
Points
Line Segments
Polygons
Attributes
Transformations
Viewing
Modeling
Control
Input (GLUT)
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 7
GLUT Functions
Every routine provided by OpenGL or associated
libraries follows the same basic rule of syntax:
prefix of the function name is either gl, glu, or glut depending
on which of these 3 libraries the routine is from
main part of the function name indicates the purpose of the
function
suffix of the function name indicates the number and type of
arguments expected by the function
- eg., suffix 3f 3 floating point arguments are expected
Some function arguments can be supplied as predefined
symbolic constants – are always in capital letters, and
have the same prefix convention as function names
- E.g., GL_RGB, GL_POLYGON and GLUT_SINGLE used by
OpenGL and its associated libraries
GLUT Functions
glVertex3fv( ... )
GLUT Functions
OpenGL has a number of built-in data types to help
make it into a platform-independent package
Mostly, they have the same names as C++ data types
but with the prefix GL attached
E.g., GLshort, GLint, GLfloat& GLdouble – are built-in
OpenGL data types
Although you will find that your OpenGL code will still
work on your computer if you do not use these data types,
it will not be as portable to other platforms so it is
recommended that you do use them
#include <GL/glut.h>
- Include glut automatically includes other header files
Sample Program
#include <GL/glut.h>
#include <stdlib.h>
void myInit(void) {
glClearColor(1.0, 1.0, 1.0, 0.0); // white background
glColor3f(0,0,0); // black foreground
glPointSize(4.0); // size of points to be drawn
// establish a coordinate system for the image
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); /* GLUT callback Handlers */
gluOrtho2D(0.0, 640.0, 0.0, 480.0); void display()
} {
glClear(GL_COLOR_BUFFER_BIT); // Clear
Screen
glBegin(GL_POINTS); // draw 4 points
glVertex2f(200,200);
glVertex2f(200,330);
glVertex2f(300,200);
glVertex2f(300,330);
glEnd();
glFlush(); // send all output to the display
}
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 20
Sample Program
int main(int argc, char *argv[])
{
glutInit(&argc, argv); // initialise the glut
library
glutInitWindowSize(640,480); // set size of the
window
glutInitWindowPosition(10,10); // position of
window
glutInitDisplayMode(GLUT_SINGLE |
GLUT_RGB);
glutCreateWindow("GLUT Points demo");
glutDisplayFunc(display); // set display
callback
myInit(); // perform other initialisation
glutMainLoop(); // enter the GL event loop
return EXIT_SUCCESS;
}
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 21
Sample Program
Single or Double Buffering
GLUT_SINGLE & GLUT_DOUBLE specify whether we want to use
single or double buffering respectively
In raster graphics systems, whatever is written to the frame
buffer is immediately transferred to the display
- repeated frequently (30 – 60 times a second)
To do this a typical approach is to first erase the old contents by
setting all the pixels to some background color, i.e. black
- after, the new contents are drawn
Double buffering:
two separate: front buffer and back buffer
front buffer for displaying & back buffer for drawing
swapping to update the image
Sample Program
Depth buffer
Is needed in 3-dimensional graphics for
hidden surface removal
Use a special array called depth buffer.
It is a 2-dimensional array that stores the
distance (or depth) of each pixel from the
viewer
- This makes it possible to determine which surfaces
are closest, thus visible, which are farther and thus
hidden.
In OpenGL, we use GLUT_DEPTH for this
purpose
Events in OpenGL
Event Example OpenGL Callback Function
Keypress KeyDown KeyUp glutKeyboardFunc
Rendering Callback
Callback function where all our drawing is done
Every GLUT program must have a display callback
glutDisplayFunc( display ); /* this part is in main */
void display( void )
{
glClear( GL_COLOR_BUFFER_BIT );
glBegin( GL_TRIANGLE );
glVertex3fv( v[0] );
glVertex3fv( v[1] );
glVertex3fv( v[2] );
glEnd();
glFlush();
}
Idle Callback
Use for animation and continuous update
- Can use glutTimerFunc or timed callbacks
for animations
glutIdleFunc( idle );
void idle( void )
{
/* change something */
t +=dt;
glutPostRedisplay();
}
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 28
Mouse Callback
Position in the screen window is usually measured
in pixels with the origin at the top-left corner
OpenGL uses a world coordinate system with
origin at the bottom-left
- Must invert y coordinate returned by callback by
height of window
- y’ = h - y
Mouse Callback
glutMouseFunc(myMouse);
void myMouse(GLint button, GLint state, GLint x, GLint y)
- button specifies which mouse button was pressed :
GLUT_LEFT_BUTTON,
GLUT_RIGHT_BUTTON, or
GLUT_MIDDLE_BUTTON
- state of that button
GLUT_UP, GLUT_DOWN
- position in window
x and y: screen coordinates of mouse position
(origin at top-left corner) when the event occurred
Mouse Callback
Captures mouse press and release events
glutMouseFunc( my_mouse);
void my_mouse( int button, int state, int x, int
y)
{
If (button == GLUT_LEFT_BUTTON &&
state == GLUT_DOWN)
{
…
}
}
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 31
Menu
GLUT provides pop-up menu features
- that we can use with the mouse to create
sophisticated interactive applications
We must link the menu to a particular
mouse button (left, right or middle)
Finally, we must define a callback function
corresponding to each menu entry
function calls to set up the menu and to link
it to the mouse button should be placed in
main func
Menu
int main(){
glutCreateMenu(menu);
glutAddMenuEntry(“Square", 1);
glutAddMenuEntry(“Triangle", 2);
glutAttachMenu(GLUT_RIGHT_BUTTON);
…..
}
void menu(GLint option)
{
if (option == 1)
//statement
else
//statements
}
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 33
Menu
GLUT also supports hierarchical menus
- Submenu to pop up
sub_menu = glutCreateMenu(polygon);
glutAddMenuEntry(“Square", 2);
glutAddMenuEntry(“Triangle", 3);
glutCreateMenu(menu);
glutAddMenuEntry("Quit",1);
glutAddSubMenu(“Polygon", sub_menu);
glutAttachMenu(GLUT_RIGHT_BUTTON);
Keyboard Event
Link a keyboard key with a routine that’s invoked when
key is pressed
key is the ASCII value of the key that was pressed
GLUT_KEY_LEFT, GLUT_KEY_RIGHT … (Arrow keys)
x and y: screen coordinates of cursor position (origin at
top-left corner) when a key is pressed
glutKeyboardFunc( keyboard );
void keyboard( unsigned GLchar key, GLint x, GLint y )
{
switch( key ) {
case ‘q’ : case ‘Q’ :
exit( EXIT_SUCCESS );
break;
}
}
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 35
Reshape Functions
Indicates what action should be taken when the
window is resized
glutReshapeFunc(myReshape);
myReshape(int, int) “reshape” event
- automatically passed arguments that report
the new width and height of the reshape
window
- This function manages any changes needed in
the view setup to accommodate the reshape
window
- Parameter: width & height of the window
after it has been changed
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 36
Output
Primitives and
Attributes
Output Primitives
Graphics primitives: All graphics packages construct
pictures from basic building blocks
Output Primitives: Basic geometric structures (points,
straight line segment, circles and other conic sections,
quadric surfaces, spline curve and surfaces, polygon
color areas, and character strings)
Geometric primitives: primitives or routines to describe
the geometry (i.e. shape) of objects (components of the
scene), e.g. Point drawing, Line drawing, Polygon
drawing,…
- can be 2-D (points, lines, quadrilaterals, & general polygons)
and more complex 3-D primitives (spheres and polyhedral
(made from mesh of 2-D polygons))
All of these primitives are specified using sequence of vertices
Attributes
Attribute – any parameter that affects the way
a primitive will be displayed
e.g.: Colour, type, line thickness, fill style, etc.
OpenGL maintain a list of current state variables
that are used to modify the appearance of each
primitive as it is displayed
state variables represent attributes of the
primitives
All OpenGL state variables have default values
Remain in effect until new values specified
Some state variables can be changed within
glBegin() … glEnd() pairs
Attributes
Output Primitive Attributes
Point Size Color
GL_LINE_STRIP
Connected line segments
(a polyline)
GL_LINE_LOOP
Connected line segments, and last
point connected to first point
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 45
Line Attributes
Line Style
Line Width
Line Color
Pen & Brush options
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 47
Fill-Area Primitives
Refers to any enclosed boundary that can
be filled with a solid color or pattern
How do we fill shapes?
Fill-Area Primitives
Fill-area primitives are normally polygons, as they can
be filled more efficiently by graphics packages
Fill-Area algorithms are used to fill the interior of a
polygonal shape
If the polygon is to be filled we can specify a fill style
Options for filling a defined region include
- choice between a solid color or a pattern fill and
- choices for particular colors and patterns
Polygons are 2-D shapes whose boundary is formed by
any number of connected straight-line segments
- defined by 3 or more coplanar vertices (points positioned on the
same plane)
- Each pair of adjacent vertices is connected in sequence by
edges
Fill-Area Primitives
polygons should have no edge crossings: known
as simple polygons or standard polygons
Edge crossings, e.g.
Polygons are the most common form of graphics
primitive because they form the basis of
polygonal meshes, which is the most common
representation for 3-D graphics objects.
Polygonal meshes approximate curved surfaces
by forming a mesh of simple polygons.
Functions
To fill polygons with a fill-area pattern:
- Define the pattern
- Enable polygon-fill feature of OpenGL
- Draw polygons
A number of different ways:
glRect*
6 different symbolic constants
For all:
Polygons must be convex (all interior angles ≤
180o)
Must specify vertices in anti-clockwise order
when viewing the polygon from “outside”
Default fill-style is solid color, determined by
current color settings
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 57
Functions
glRect*
OpenGL provides special routine that takes 2-D
points only
glRect* (x1, y1, x2, y2)
(x1,y1) & (x2,y2) define opposite corners of the rectangle
when we call the glRect* routine, OpenGL will construct a
polygon with vertices defined in the following order:
(x1,y1), (x2,y1), (x2,y2), (x1,y2).
e.g: glRecti(200,100,50,250);
We can draw rectangles with
other functions, but glRect*can
be more efficient
Functions
All other fill-area functions use the
functions
glBegin… glEnd:
GL_POLYGON
GL_TRIANGLES
GL_TRIANGLE_STRIP
GL_TRAINGLE_FAN
GL_QUADS
GL_QUAD_STRIP
Functions
GL_POLYGON:
Displays a single convex polygon
Vertices of the polygon are specified in anti-
clockwise direction
E.g.
glBegin(GL_POLYGON);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glVertex2iv(p6);
glEnd();
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 60
Functions
GL_TRIANGLES:
Vertex list treated as groups of 3 triangle vertices
Vertices must be specified in anti-clockwise order
E.g.
glBegin(GL_TRIANGLES);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p6);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glEnd();
Functions
GL_TRIANGLE_STRIP:
Displays set of connected triangles
First triangle vertices must be anti-clockwise
E.g.
glBegin(GL_TRIANGLE_STRIP);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p6);
glVertex2iv(p3);
glVertex2iv(p5);
glVertex2iv(p4);
glEnd();
Functions
GL_QUAD_STRIP:
One quadrilateral drawn for each pair of
vertices after first two
glBegin(GL_QUAD_STRIP);
glVertex2iv(p1);
glVertex2iv(p2);
glVertex2iv(p3);
glVertex2iv(p4);
glVertex2iv(p5);
glVertex2iv(p6);
glVertex2iv(p7);
glVertex2iv(p8);
glEnd();
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 65
Character Primitives
Many pictures require text
attributes: Font size, Color and Orientation
Attributes can be set both for entire character
strings (text) and for individual characters
Most graphics packages have some support for
displaying character primitives
Type Faces (fonts) can be divided into two:
Serif – has small lines or accents at the ends of the
main character stroke. And so makes readable.
Sans-Serif – does not have accents.
Arial is a sans-serif font
Verdana is a sans-serif
font
Times Roman is a serif font
Garamond is a serif font
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 66
Character Primitives
Another category of fonts
Monospace font: always take up the same width on the display,
regardless of which character is being drawn
Proportional fonts: width used on the display will be
proportional to the actual width of the character
Two ways of representing characters:
Bitmap (Raster)
Binary pattern defined on rectangular grid
bitmap is a mapping from some domain
(e.g., a range of integers) to bits
Each character represented (stored) as a 2-D array
- Each element corresponds to a pixel in a rectangular
“character cell”
- Simplest: each element is a bit (1=pixel on, 0=pixel
off)
Character Primitives
Two ways of representing characters:
Bitmap (Raster)
00111000
01101100
11000110
11000110
11111110
11000110
11000110
00000000
9-Nov-23 Computer Graphics Mulugeta G. (BSc) STBC– CS 68
Character Primitives
Stroke(outline)
Defined using line/curve primitives
Each character represented (stored) as a series
of line segments
Takes longer time draw than bitmap fonts
change the font, colour, and also line width and
line style
width of these lines can be changed using
glLineWidth
style using
glLineStipple
Color Attributes
Colors are represented by colors code which are positive
integers
Color information is stored in frame buffer or in separate
table and use pixel values as index to the color table.
Two ways to store colour values in a frame buffer:
- Direct storage
colour (RGB) values of each pixel are stored directly in the
frame buffer
Each pixel in the frame buffer must have 3 (RGB) or 4
(RGBA) values stored.
Frame buffer take up a lot of memory.
E.g., for a screen resolution of 1366x768, total storage
required will be 1366x768x24 bits = 2.4MB(8 bits for each
of red, green & blue components of colours stored are used)
Color Attributes
Two ways to store colour values in a frame
buffer:
- Look-up/indirect table
Store an index for each pixel in the frame buffer.
actual colours are stored in a separate look-up
table, and the index looks up a colour in this table
Reduce the amount of storage
Have a limited # of different colours in scene (# of
rows in the look-up table)
For example, if each colour uses 8 bits (=24
bits in all), and the look-up table has 256 rows
the total range of colours
Color Attributes
Two ways to store colour values in a frame
buffer:
- Look-up/indirect table
glColor*, e.g.
- glColor3f(1.0,1.0,1.0); white foreground
glClearColor, e.g.
- glClearColor(0,0,0,0) black background
WHITE