CGG Technical Publication
CGG Technical Publication
Computer Graphics
(For IN SEM Exam)
Atul P. Godse
M.S. Software Systems (BITS Pilani)
B.E. Industrial Electronics
Formerly Lecturer in Department of Electronics Engg.
Vishwakarma Institute of Technology
Pune
® ®
TECHNICAL
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge
(i)
Computer Graphics
(For IN SEM Exam)
Published by :
® ®
Amit Residency, Office No.1, 412, Shaniwar Peth,
TECHNICAL Pune - 411030, M.S. INDIA, Ph.: +91-020-24495496/97
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge Email : sales@technicalpublications.org Website : www.technicalpublications.org
Printer :
Yogiraj Printers & Binders
Sr.No. 10/1A,
Ghule Industrial Estate, Nanded Village Road,
Tal. - Haveli, Dist. - Pune - 411041.
ISBN 978-81-946628-8-4
Preface
The importance of Computer Graphics is well known in various engineering fields.
Overwhelming response to our books on various subjects inspired us to write this book.
The book is structured to cover the key aspects of the subject Computer Graphics.
The book uses plain, lucid language to explain fundamentals of this subject. The
book provides logical method of explaining various complicated concepts and stepwise
methods to explain the important topics. Each chapter is well supported with necessary
illustrations, practical examples and solved problems. All the chapters in the book are
arranged in a proper sequence that permits each topic to build upon earlier studies. All
care has been taken to make students comfortable in understanding the basic concepts
of the subject.
Representative questions have been added at the end of each section to help the
students in picking important points from that section.
The book not only covers the entire scope of the subject but explains the philosophy
of the subject. This makes the understanding of this subject more clear and makes it
more interesting. The book will be very useful not only to the students but also to the
subject teachers. The students have to omit nothing and possibly have to cover nothing
more.
We wish to express our profound thanks to all those who helped in making this
book a reality. Much needed moral support and encouragement is provided on
numerous occasions by our whole family. We wish to thank the Publisher and the
entire team of Technical Publications who have taken immense pain to get this book
in time with quality printing.
Any suggestion for the improvement of the book will be acknowledged and well
appreciated.
Authors
A.P. Godse
Dr. D. A. Godse
Dr. Rajesh Prasad
Dedicated to God
(iii)
Syllabus
Computer Graphics - 210244
Credit Scheme Examination Scheme and Marks :
03 Mid-Semester (TH) : 30 Marks
(iv)
Table of Contents
Unit - I
2.2.1.2 GL_LINES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 16
2.2.1.3 GL_LINE_STRIP . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 17
2.2.1.4 GL_LINE_LOOP . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 17
2.2.1.5 GL_TRIANGLES . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 18
2.2.1.6 GL_TRIANGLE_STRIP . . . . . . . . . . . . . . . . . . . . . . . . 2 - 18
2.2.1.7 GL_TRIANGLE_FAN . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 19
2.2.1.8 GL_QUADS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 19
2.2.1.9 GL_QUAD_STRIP . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 20
2.2.1.10 GL_POLYGON . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 20
2.2.2 Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 21
2.2.2.1 Color Attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 21
2.5 Picking............................................................................................................. 2 - 42
2.5.1 Picking and Selection Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 - 43
(vii)
Unit - II
(viii)
5.3 2 D Clipping.....................................................................................................5 - 14
5.3.1 Point Clipping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 14
5.3.2 Line Clipping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 - 15
(ix)
(x)
UNIT - I
Introduction
1 to Computer Graphics
Syllabus
Introduction, graphics primitives - pixel, resolution, aspect ratio, frame buffer. Display devices,
applications of computer graphics.
Contents
1.1 Basic Concepts . . . . . . . . . . . . . . . . . . Dec.-09,11, May-13, · · · · · · Marks 2
· The computer graphics is one of the most effective and commonly used way to
communicate the processed information to the user.
· It displays the information in the form of graphics objects such as pictures, charts,
graphs and diagrams instead of simple text. Thus we can say that computer
graphics makes it possible to express data in pictorial form.
· The picture or graphics object may be an engineering drawing, business graphs,
architectural structures, a single frame from an animated movie or a machine parts
illustrated for a service manual.
1.1.1 Pixel
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
· The special procedures determine which pixel will provide the best approximation
to the desired picture or graphics object.
· The process of determining the appropriate pixels for representing picture or
graphics object is known as rasterization, and the process of representing
continuous picture or graphics object as a collection of discrete pixels is called
scan conversion.
· The computer graphics allows rotation, translation, scaling and performing various
projections on the picture before displaying it.
· It also allows to add effects such as hidden surface removal, shading or
transparency to the picture before final representation.
· It provides user the control to modify contents, structure, and appearance of
pictures or graphics objects using input devices such as a keyboard, mouse, or
touch-sensitive panel on the screen. There is a close relationship between the input
devices and display devices. Therefore, graphics devices includes both input
devices and display devices.
Review Questions
2. Define rasterization.
3. Define scan conversion.
1.2 Display Devices SPPU : Dec.-06, 10, 11, 12, 15, May-05, 09, 13, 14, 15
The display devices are also known as output devices. The most commonly used
output device in a graphics system is a video monitor. The operation of most video
monitors is based on the standard Cathode-Ray-Tube (CRT) design. Let us see the
basics of the CRT.
1.2.1 Cathode-Ray-Tubes
A CRT is an evacuated glass tube. An electron gun at the rear of the tube produces a
beam of electrons which is directed towards the front of the tube (screen) by a high
voltage typically 15000 to 20,000 volts. The negatively charged electrons are then
accelerated toward the phosphor coating at the inner side of the screen by a high
positive voltage or by using accelerating anode. The phosphor substance gives off light
when it is stroked by electrons.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
One way to keep the phosphor glowing is to redraw the picture repeatedly by
quickly directing the electron beam back over the same points. This type of display is
called a refresh CRT.
The control grid voltage determines the velocity achieved by the electrons before they
hit the phosphor. The control grid voltage determines how many electrons are actually
in the electron beam.
A more negative voltage applied to the control grid will shut off the beam. A smaller
negative voltage on the control grid simply decreases the number of electrons passing
through. Since the amount of light emitted by the phosphor coating depends on the
number of electrons striking the screen, we control the brightness of a display by
varying the voltage on the control grid.
The focusing system concentrates the electron beam so that the beam converges to a
small point when it hits the phosphor coating. It is possible to control the point at which
the electron beam strikes the screen, and therefore the position of the dot upon the
screen, by deflecting the electron beam. Fig. 1.2.1 shows the electrostatic deflection of the
electron beam in a CRT.
Electron gun
Aquadag
coating
Vertical deflection
Pre-accelerating plates
anode Focusing
Pins Heater anode
Electron beam
Base
Cathod Grid Accelerating Phosphor screen
anode Horizontal deflection
plates
The deflection system of the cathode-ray-tube consists of two pairs of parallel plates,
referred to as the vertical and horizontal deflection plates. The voltage applied to
vertical plates controls the vertical deflection of the electron beam and voltage applied to
the horizontal deflection plates controls the horizontal deflection of the electron beam.
The electrons that strike the screen, release secondary emission electrons. Aqueous
graphite solution known as Aquadag collects these secondary electrons. To maintain the
CRT in electrical equilibrium, it is necessary to collect the secondary electrons.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
The Fig. 1.2.4 shows the architecture of a raster display. It consists of display
controller, central processing unit (CPU), video controller, refresh buffer, keyboard,
mouse and the CRT.
As shown in the Fig. 1.2.4, the display image is stored in the form of 1s and 0s in the
refresh buffer. The video controller reads this refresh buffer and produces the actual
image on the screen. It does this by scanning one scan line at a time, from top to bottom
and then back to the top, as shown in the Fig. 1.2.4.
CPU
I/O port
Keyboard
Display controller
Mouse
000000000000000000000
000000000000000000000
000000000000000000000
000001
0101
0010
1010
1010
1010
10 0 0 0 0
000001
0101
0010
1010
1010
1010
10 0 0 0 0
000001
0101
0010
1010
1010
1010
10 0 0 0 0 Video controller
0000000000 1010
1000000000
0000000000 1010
1000000000
0000000000 1010
1000000000
0000000000 1010
1000000000
000000000000000000000
000000000000000000000
000000000000000000000
Refresh buffer
Fig. 1.2.4 Architecture of a raster display
When the beam reaches the bottom of the screen, it is made OFF and rapidly retraced
back to the top left to start again. A display produced in this way is called raster scan
display. Raster scanning process is similar to reading different lines on the page of a
book. After completion of scanning of one line, the electron beam flies back to the start
of next line and process repeats. In the raster scan display, the screen image is
maintained by repeatedly scanning the same image. This process is known as refreshing
of screen.
Frame Buffer
In raster scan displays a special area of memory is dedicated to graphics only. This
memory area is called frame buffer. It holds the set of intensity values for all the screen
points. The stored intensity values are retrieved from frame buffer and displayed on the
screen one row (scan line) at a time. Each screen point is referred to as a pixel or pel
(shortened forms of picture element). Each pixel on the screen can be specified by its
row and column number. Thus by specifying row and column number we can specify
the pixel position on the screen.
Intensity range for pixel positions depends on the capability of the raster system. It
can be a simple black and white system or colour system. In a simple black and white
system, each pixel position is either on or off, so only one bit per pixel is needed to
control the intensity of the pixel positions. Additional bits are required when colour and
intensity variations can be displayed. Upto 24 bits per pixel are included in high quality
display systems, which can require several megabytes of storage space for the frame
buffer. On a black and white system with one bit per pixel, the frame buffer is
commonly called a bitmap. For systems with multiple bits per pixel, the frame buffer is
often referred to as a pixmap.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
5. Vector display draws a continuous and Raster display can display mathematically
smooth lines. smooth lines, polygons, and boundaries of
curved primitives only by approximating them
with pixels on the raster grid.
6. Cost is more. Cost is low.
7. Vector display only draws lines and Raster display has ability to display areas filled
characters. with solid colours or patterns.
Table 1.2.1
Example 1.2.1 How much memory is needed for the frame butter to store a 640 ´ 400 display
16 gray levels ?
Solution : 2 4 = 16. Therefore, 4-bits are required to store 16 gray levels.
Solution :
1
Refresh rate =
Access time for each pixel ´ Number of pixels information in frame buffer
1
= = 19.0734 frames /sec.
200 ´ 10 -9 ´ 512 ´ 512
Example 1.2.3 Find the amount of memory required by an 8 plane frame buffer each of red,
green, blue having resolution of 1024 ´ 768. SPPU : Dec.-12, Marks 4
Solution : For 8 plane frame buffer each of red, green and blue requires 24-bits to
represent per pixel.
\ Amount of memory required = 24 ´ 1024 ´ 768
= 18874368 bits
= 2359296 bytes
Example 1.2.4 How long would it take to load a 1280 by 1024 frame buffer with 12 bits per
pixel if transfer rate is 1 Mbps ?
Solution :
1280 ´ 1024 ´ 12
Time required to load frame buffer = = 15.72 64 sec
10 6
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
electron guns, one for each colour dot, and a shadow mask grid just behind the
phosphor coated screen.
The shadow mask grid consists of series of holes aligned with the phosphor dot
pattern. As shown in the Fig. 1.2.6, three electron beams are deflected and focused as a
group onto the shadow mask and when they pass through a hole in the shadow mask,
they excite a dot triangle. A dot triangle consists of three small phosphor dots of red,
green and blue colour. These phosphor dots are arranged so that each electron beam can
activate only its corresponding colour dot when it passes through the shadow mask. A
dot triangle when activated appears as a small dot on the screen which has colour of
combination of three small dots in the dot triangle. By varying the intensity of the three
electron beams we can obtain different colours in the shadow mask CRT.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Advantages of DVST
1. Refreshing of CRT is not required.
2. Because no refreshing is required, very complex pictures can be displayed at very
high resolution without flicker.
3. It has flat screen.
Disadvantages of DVST
1. They do not display colours and are available with single level of line intensity.
2. Erasing requires removal of charge on the storage grid. Thus erasing and
redrawing process takes several seconds.
3. Selective or part erasing of screen is not possible.
4. Erasing of screen produces unpleasant flash over the entire screen surface which
prevents its use of dynamic graphics applications.
5. It has poor contrast as a result of the comparatively low accelerating potential
applied to the flood electrons.
6. The performance of DVST is some what inferior to the refresh CRT.
The term flat-panel display refers to a class of video devices that have reduced
volume, weight, and power requirements compared to a CRT. The important feature of
flat-panel display is that they are thinner than CRTs. There are two types of flat panel
displays : emissive displays and nonemissive displays.
Emissive displays : They convert electrical energy into light energy. Plasma panels,
thin-film electro luminescent displays, and light emitting diodes are examples of
emissive displays.
Nonemissive displays : They use optical effects to convert sunlight or light from
some other source into graphics patterns. Liquid crystal display is an example of
nonemissive flat panel display.
sealed. By applying voltages between the electrodes the gas within the panel is made to
behave as if it were divided into tiny cells, each one independent of its neighbours.
These independent cells are made to glow by placing a firing voltage of about 120 volts
across it by means of the electrodes. The glow can be sustained by maintaining a high
frequency alternating voltage of about 90 volts across the cell. Due to this refreshing is
not required.
Horizontal
conductors/electrodes
Gas panel
Glass plate
Glass plate
Vertical
conductors/electrodes
Cell
Glass plate
Fig. 1.2.8 Construction of plasma panel display
Advantages
1. Refreshing is not required.
2. Produces a very steady image, totally free of flicker.
3. Less bulky than a CRT.
4. Allows selective writing and selective erasing, at speed of about 20 msec per cell.
5. It has the flat screen and is transparent, so the displayed image can be
superimposed with pictures from slides or other media projected through the rear
panel.
Disadvantages
1. Relatively poor resolution of about 60 dots per inch.
2. It requires complex addressing and wiring.
3. Costlier than the CRTs.
The term liquid crystal refers to the fact that these compounds have a crystalline
arrangement of molecules, yet they flow like a liquid. Flat panel displays commonly use
nematic (thread like) liquid-crystal compounds that tend to keep the long axes of the
rod- shaped molecules aligned.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Two glass plates, each containing a light polarizer at right angles to the other plate
sandwich the liquid-crystal material. Rows of horizontal transparent conductors are built
into one glass plate, and columns of vertical conductors are put into the other plate. The
intersection of two conductors defines a pixel position. In the ON state, polarized light
passing through material is twisted so that it will pass through the opposite polarizer. It
is then reflected back to the viewer. To turn OFF the pixel, we apply a voltage to the
two intersecting conductors to align the molecules so that the light is not twisted as
shown in the Fig. 1.2.9. This type of flat panel device is referred to as a passive matrix LCD.
In active matrix LCD, transistors are used at each (x, y) grid point. Use of transistors
cause the crystal to change their state quickly and also to control the degree to which
the state has been changed. These two properties allow LCDs to be used in miniature
television sets with continuous-tone images.
Nematic
Transparent liquid crystal
conductor
Polarizer
Polarizer Transparent
ON State conductor
Polarizer Transparent
OFF State conductor
(b) Field effect display 'OFF State'
Fig. 1.2.9
The transistor can also serve as a memory for the state of a cell and can hold the cell
in that state until it is changed. Thus use of transistor make cell on for all the time
giving brighter display than it would be if it had to be refreshed periodically.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
simultaneously at the left view with the left eye and the right view with right eye, two
views are merged into a single image providing necessary depth to appear as an 3D
image. Two views of a scene can be obtained using computer or we can use a stereo
camera pair to photograph scene.
We can produce stereoscopic effect in raster system by :
· Displaying each of the two views on alternate refresh cycles
· And then viewing screen through glasses with each lens designed to act as a
rapidly alternating shutter that is synchronized to block out one of the views.
The stereoscopic viewing plays important role in the virtual reality systems. In such
systems, the viewer can step into stereoscopic scenes and interact with the environment.
Usually, a headset containing an optical system is used to generate the stereoscopic
views.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Review Questions
18. Define the following terms : 1) Persistence 2) Frame buffer 3) Resolution 4) Aspect ratio.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
The use of computer graphics is wide spread. It is used in various areas such as
industry, business, government organizations, education, entertainment and most
recently the home. Let us discuss the representative uses of computer graphics in brief.
· User Interfaces : User friendliness is one of the main factors underlying the
success and popularity of any system. It is now a well established fact that
graphical interfaces provide an attractive and easy interaction between users and
computers. The built-in graphics provided with user interfaces use visual control
items such as buttons, menus, icons, scroll bar etc, which allows user to interact
with computer only by mouse-click. Typing is necessary only to input text to be
stored and manipulated.
· Plotting of Graphics and Chart : In industry, business, government and
educational organizations, computer graphics is most commonly used to create 2D
and 3D graphs of mathematical, physical and economic functions in form of
histograms, bars and pie-charts. These graphs and charts are very useful for
decision making.
· Office Automation and Desktop Publishing : The desktop publishing on
personal computers allow the use of graphics for the creation and dissemination of
information. Many organizations do the in-house creation and printing of
documents. The desktop publishing allows user to create documents which contain
text, tables, graphs and other forms of drawn or scanned images or pictures. This
is one approach towards the office automation.
· Computer-aided Drafting and Design : The computer-aided drafting uses graphics
to design components and systems electrical, mechanical, electro-mechanical and
electronic devices such as automobile bodies, structures of building, airplane,
ships, very large-scale integrated (VLSI) chips, optical systems and computer
networks.
· Simulation and Animation : Use of graphics in simulation makes mathematic
models and mechanical systems more realistic and easy to study. The interactive
graphics supported by animation software proved their use in production of
animated movies and cartoons films.
· Art and Commerce : There is a lot of development in the tools provided by
computer graphics. This allows user to create artistic pictures which express
messages and attract attentions. Such pictures are very useful in advertising.
· Process Control : By the use of computer now it is possible to control various
processes in the industry from a remote control room. In such cases, process
systems and processing parameters are shown on the computer with graphic
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
symbols and identifications. This makes it easy for operator to monitor and control
various processing parameters at a time.
· Cartography : Computer graphics is also used to represent geographic maps,
weather maps, oceanographic charts, contour maps, population density maps and
so on.
· Education and Training : Computer graphics can be used to generate models of
physical, financial and economic systems. These models can be used as educational
aids. Models of physical systems, physiological systems, population trends, or
equipment, such as colour-coded diagram can help trainees to understand the
operation of the system.
· Image Processing : In computer graphics, a computer is used to create pictures.
Image processing, on the other hands, applies techniques to modify or interpret
existing pictures such as photographs and scanned images. Image processing and
computer graphics are typically combined in many applications such as to model
and study physical functions, to design artificial limbs, and to plan and practice
surgery. Image processing techniques are most commonly used for picture
enhancements to analyze satellite photos, X-ray photography and so on.
Review Questions
2. Write and explain any four state of the applications of computer graphics.
SPPU : May-16, Marks 4
qqq
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
UNIT - I
2 Introduction to OpenGL
Syllabus
OpenGL architecture, primitives and attributes, simple modelling and rendering of two- and
three-dimensional geometric objects, GLUT, interaction, events and call-backs picking. (Simple
Interaction with the Mouse and Keyboard)
Contents
2.1 OpenGL Architecture
2.4 Interaction
2.5 Picking
· Function names in the OpenGL basic library (also called the OpenGL core
library) are prefixed with gl and each component word within a function name
has its first letter capitalized. The following examples illustrate this naming
convention.
glBegin, glClear, glCopyPixels, glPolygonMode
· Some functions in OpenGl require that one (or more) of their arguments be
assigned a symbolic constant specifying, for instance, a parameter name, a value
for a parameter or a particular mode. All such constants begin with the uppercase
letters GL. In addition, component words within a constant name are written in
capital letters and the underscore ( ) is used as a separator between all component
words in the name. Following are a few examples of the several hundred symbolic
constants available for use with OpenGL functions.
GL_2D, GL_RGB, GL_CCW, GL_POLYGON, GL_AMBIENT_AND_DIFFUSE
· The OpenGL functions uses specific data types. For example, an OpenGL function
parameter might use a value that is specified as a 32-bit integer. But the size of an
integer specification can be different on different machines.
· Special built-in, data-type supported by OpenGL are : GLbyte, GLshort, GLint,
GLfloat, GLdouble, GLboolean. Each data-type name begins with the capital
letters GL and the remainder of the name is a standard data-type designation,
written in lower-case letters.
· It is also possible to assign values using an array that lists a set of data values for
some arguments of OpenGL functions. These values are specified as a pointer to
an array, rather than specifying each element of the list explicitly as a parameter
argument.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
· In addition to the OpenGL basic (core) library, there are a number of associated
libraries for handling special operations.
OpenGL Utility (GLU) Provides routines for setting upviewing and projection matrices,
describing complex objects with line and polygon approximations,
displaying quadrics and B-splines using linear approximations,
processing the surface-rendering operations and other complex tasks.
Object Oriented Toolkit Provides routines and predefined object shapes for interactive
(Open Inventor) three-dimensional applications.
This toolkit is written in C++.
Apple GL (AGL) Apple systems can use the Apple GL (AGL) interface for
window-management operations.
Function names for this library are prefixed with agl.
Presentation Manager Provides interface for the IBM OS/2, which uses the prefix pgl for the
to OpenGL (PGL) library routines.
OpenGL Utility Provides a library of functions for interacting with any screen-windowing
Toolkit (GLUT) system. The GLUT library functions are prefixed with glut, and this library
also contains methods for describing and rendering quadric curves and
surfaces.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
· For graphics programs we need to include the header file for the OpenGL core
library.
· For most applications we will also need GLU. For instance, with Microsoft
Windows, we need to include the header file (windows.h) for the window system.
· This header file must be listed before the OpenGL and GLU header files because it
contains macros needed by the Microsoft Windows version of the OpenGL
libraries. So the source file in this case would begin with
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
· However, if we use GLUT to handle the window-managing operations, we do not
need to include gl.h and glu.h because GLUT ensures that these will be included
correctly. Thus, we can replace the header files for OpenGL and GLU with
#include <GL/glut.h>
· We could include gl.h and glu.h as well, but doing so would be redundant and
could affect program portability.
· In addition, we will often need to include header files that are required by the
C++ code. For example,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
· But the display window is not yet on the screen. We need one more GLUT
function to complete the window-processing operations. After execution of the
following statement, all display windows that we have created, including their
graphic content, are now activated.
glutMainLoop ( ); Video screen
Display
· This function must be the last one 80 window
in our program. It displays the 50
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
gl Vertex 2 i (.....)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Fig. 2.1.3 shows a simple OpenGL program. Although this program does nothing
useful, it defines a pattern that is used by most OpenGL programs. The line numbers
are not part of the program, but are used in the explanation below.
1 #include <GL/glut.h>
2
3 void display (void)
4 {
5 glClear(GL_COLOR_BUFFER_BIT);
6 }
7
8 void init (void)
9 {
10 }
11
12 int main (int argc, char *argv[])
13 {
14 glutInit(&argc, argv);
15 glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA);
16 glutInitWindowSize(800, 600);
17 glutInitWindowPosition(100, 50);
18 glutCreateWindow("My first openGL program");
19 init();
20 glutDisplayFunc(display);
21 glutMainLoop();
22 return 0;
23 }
Fig. 2.1.3 The basic OpenGL program
Line 1. Every OpenGL program should include GL/glut.h. The file glut.h includes
glu.h, gl.h and other header files required by GLUT.
Line 3. You must write a function that displays the graphical objects in your model.
The function shown here clears the screen but does not display anything. Your
program does not call this function explicitly, but it will be called at
appropriate times by OpenGL.
Line 5. It is usually a good idea to clear various buffers before starting to draw new
objects. The colour buffer, cleared by this call, is where the image of your
model is actually stored.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Line 8. It is a good idea to put "standard initialization" (the glut... calls) in the main
program and application dependent initialization in a function with a name
like init() or myInit(). We follow this convention in these text because it is
convenient to give different bodies for init without having to explain where to
put the initialization statements. In this program, the function init() is defined
in lines 8 through 10, does nothing, and is invoked at line 19.
Line 14. The function glutInit() initializes the OpenGL library. It is conventional to pass
the command line arguments to this function because it may use some of
them. You will probably not need this feature.
Line 15. The function glutInitDisplayMode() initializes the display. Its argument is a bit
string. Deleting this line would not affect the execution of the program,
because the arguments shown are the default values.
Line 16. This call requests a graphics window 800 pixels wide and 600 pixels high. If
this line was omitted, GLUT would use the window manager's default values
for the window's size.
Line 17. This call says that the left side of the graphics window should be 100 pixels
from the left of the screen and the top of the graphics window should be 50
pixels below the top of the screen. Note that the Y value is measured from the
top of the screen. If this line was omitted, GLUT would use the window
manager's default values for the window's position.
Line 18. This call creates the window using the settings given previously. The text in
the argument becomes the title of the window. The window does not actually
appear on the screen until glutMainLoop() has been called.
Line 19. This is a good place to perform any additional initialization that is needed (see
above). Some initialization, such as calls to glEnable(), must come after the call
to glutCreateWindow().
Line 20. This call registers the callback function display(). After executing the call,
OpenGL knows what function to call to display your model in the window.
Section 2.4 describes callback functions.
Line 21. The last statement of an OpenGL program calls glutMainLoop(). This function
processes events until the program is terminated. Well-written programs
should provide the user with an easy way of stopping the program, for
example by selecting Quit from a menu or by pressing the esc key.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Drawing Objects
All that remains is to describe additions to Fig. 2.1.3. The first one that we will
consider is an improved display() function. Fig. 2.1.4 shows a function that displays a
line. The call glColor3f(1.0, 0.0, 0.0) specifies the colour of the line as "maximum red, no
green, no blue".
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
{
float x = i / 25.0;
glVertex2f(x, -1.0);
glVertex2f(x, 1.0);
}
glEnd();
}
Fig. 2.1.5 Drawing vertical yellow lines
The call glClear(GL_COLOR_BUFFER_BIT) clears the colour buffer to the background
colour. You can set the background colour by executing
glClearColor(r, g, b, a);
with appropriate values of r, g, b and a during initialization. Each argument is a
floating point number in the range [0, 1] specifying the amount of a colour (red, green,
blue) or blending (alpha). The default values are all zero, giving a black background. To
make the background blue, you could call
· At this point we are not using Blending operations, so the value of alpha is
irrelevant. For now, we simply set alpha to 0.0.
· Although the glClearColor command assigns a color to the display window, it
does not put the display window on the screen. To get the assigned window color
displayed, we need to invoke the following OpenGL function.
glClear (GL_COLOR_BUFFER_BIT);
· The argument GL_COLOR_BUFFER_BIT is an OpenGL symbolic constant
specifying that it is the bit values in the color buffer (refresh buffer) that are to be
set to the values indicated in the glClearColor function.
· In addition to setting the background color for the display window, we can choose
a variety of color schemes for the objects we want to display in a scene.
· For example, the following function sets object color to be blue.
glColor3f (0.0, 0.0, 1.0);
· The suffix 3f on the glColor function indicates that we are specifying the three
RGB color components using floating-point (f) values. These values must be in the
range from 0.0 to 1.0 and we have set red and green = 0.0 and blue = 1.0.
· In our first program, we simply display a two-dimensional line segment. To do
this, we have to set the projection type (mode) and other viewing parameters to
tell OpenGL how we want to “project” our picture onto the display window.
· We can set the projection type (mode) and other viewing parameters with
following two functions.
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 150.0, 0.0, 120.0);
· The above functions specify that an orthogonal projection is to be used to map the
contents of a two-dimensional (2D) rectangular area of world coordinates to the
screen and that the x-coordinate values within this rectangle range from 0.0 to
150.0 with y-coordinate values ranging from 0.0 to 120.0.
· Whatever objects we define within this world-coordinate rectangle will be shown
within the display window. Anything outside this coordinate range will not be
displayed. Therefore, the GLU function gluOrtho2D defines the coordinate
reference frame with in the display window to be (0.0, 0.0) at the lower-left corner
of the display window and (150.0, 120.0) at the upper-right window corner.
· Finally, we need to call the appropriate OpenGL routines to create the line
segment. The following code defines a two-dimensional, straight-line segment with
integer, Cartesian endpoint coordinates (110, 25) and (20, 100).
glBegin (GL_LINES);
glVertex2i (110, 25);
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
· An API for interfacing with graphics system can contain hundreds of individual
functions. These functions are divided into seven major groups :
1. Primitive functions
2. Attribute functions
3. Viewing functions
4. Transformation functions
5. Input functions
6. Control functions
7. Query functions
· Primitive functions : These functions 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 types of curves and
surfaces.
· Attribute functions : These functions allow us to perform operations ranging from
choosing the color with which we display a line segment, to picking a pattern
with which to fill the inside of a polygon, to selecting a typeface for the titles on a
graph.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Review Questions
1. What is openGL ?
2. List the datatypes supported by openGL.
3. List the libraries supported by openGL and their supported operations.
4. Explain the display window management using GLUT.
5. Draw the format of OpenGL command.
6. Explain the vertex function with examples.
7. Explain the various types of function supported by OpenGL.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Geometric pipeline
OpenGL
application Frame
program Pixel operations buffer
Pixel pipeline
· OpenGL supports several basic primitive types: points, lines, quadrilaterals, and
general polygons. All of these primitives are specified using a sequence of vertices.
· Fig. 2.2.2 shows the basic primitive types, where the numbers indicate the order in
which the vertices have been specified. Note that for the GL_LINES primitive only
every second vertex causes a line segment to be drawn. Similarly, for the
GL_TRIANGLES primitive, every third vertex causes a triangle to be drawn. Note
that for the GL_TRIANGLE_STRIP and GL_TRIANGLE_FAN primitives, a new
triangle is produced for every additional vertex. All of the closed primitives shown
below are solid-filled, with the exception of GL_LINE_LOOP, which only draws
lines connecting the vertices.
· OpenGL provides ten different primitive types for drawing points, lines, and
polygons, as shown in Fig. 2.2.2.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
4 0 3 1 5 3
1
4
0
3 2 5 0 4
2 2 6
1
GL_POINTS GL_LINES GL_LINE_STRIP
2 3
1 1 2 0 5 6
5 3
0 2
0 4 3 4
4 1 7
GL_LINE_LOOP GL_POLYGON GL_QUADS
3 5 4 8
0 2
1
7
5
0 2 6 3
1 7
4 6
GL_QUAD_STRIP GL_TRIANGLES
1
3 5 3 4
2
1
0 5
2 0
4
GL_TRIANGLE_STRIP GL_TRIANGLE_FAN
Fig. 2.2.2 OpenGL primitive types
2.2.1.1 GL_POINTS
· We use this primitive type to render mathematical points. OpenGL renders a point
for each vertex specified.
n Treats each vertex as a single point.
n Vertex n defines a point n.
· Example :
glBegin(GL_POINTS);
glVertex2f(x1, y1);
glEnd();
2.2.1.2 GL_LINES
· We use this primitive to draw unconnected line segments. OpenGL draws a line
segment for each group of two vertices. If the application specifies n vertices,
OpenGL renders n/2 line segments. If n is odd, OpenGL ignores the final vertex.
n Treats each pair of vertices as an independent line segment.
n Vertices 2n–1 and 2n define a line n.
n n/2 lines are drawn.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
· Example :
glBegin(GL_LINES);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glEnd();
2.2.1.3 GL_LINE_STRIP
· We use this primitive to draw a sequence of connected line segments. OpenGL
renders a line segment between the first and second vertices, between the second
and third, between the third and fourth, and so on. If the application specifies n
vertices, OpenGL renders n–1 line segments.
n Draws a connected group of line segments from the first vertex to the last.
n Vertices n and n+1 define line n.
n N–1 lines are drawn.
· Example :
glBegin(GL_LINE_STRIP);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glVertex2f(x3, y3);
glEnd();
2.2.1.4 GL_LINE_LOOP
· We use this primitive to close a line strip. OpenGL renders this primitive like a
GL_LINE_STRIP with the addition of a closing line segment between the final and
first vertices.
n Draws a connected group of line segments from the first vertex to the last,
then back to the first.
n Vertices n and n+1 define line n.
n n lines are drawn.
· Example :
glBegin(GL_LINE_LOOP);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glVertex2f(x3,y3);
glEnd();
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
2.2.1.5 GL_TRIANGLES
· We use this primitive to draw individual triangles. OpenGL renders a triangle for
each group of three vertices. If your application specifies n vertices, OpenGL
renders n/3 triangles. If n isn't a multiple of 3, OpenGL ignores the excess
vertices.
n Treats each triplet of vertices as an independent triangle.
n Vertices 3n–2, 3n–1, and 3n define triangle n.
n n/3 triangles are drawn.
· Example :
glBegin(GL_TRIANGLES);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glVertex2f(x3, y3);
glEnd();
2.2.1.6 GL_TRIANGLE_STRIP
· We use this primitive to draw a sequence of triangles that share edges. OpenGL
renders a triangle using the first, second, and third vertices, and then another
using the second, third, and fourth vertices, and so on. If the application specifies
n vertices, OpenGL renders n–2 connected triangles. If n is less than 3, OpenGL
renders nothing.
n Draws a connected group of triangles.
n One triangle is defined for each vertex presented after the first two
vertices.
n For odd n, vertices n, n+1, and n+2 define triangle n.
n For even n, vertices n+1, n, and n+2 define triangle n.
n n–2 triangles are drawn.
· Example :
glBegin(GL_TRIANGLE_STRIP);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glVertex2f(x3, y3);
glVertex2f(x4, y4);
glEnd();
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
2.2.1.7 GL_TRIANGLE_FAN
· We use this primitive to draw a fan of triangles that share edges and also share a
vertex. Each triangle shares the first vertex specified. If the application specifies a
sequence of vertices v, OpenGL renders a triangle using v0 , v1 and v2 ; another
triangle using v0 , v2 and v3 ; another triangle using v0 , v3 and v4 and so on. If
the application specifies n vertices, OpenGL renders n–2 connected triangles. If n
is less than 3, OpenGL renders nothing.
n Draws a connected group of triangles that fan around a central point.
n One triangle is defined for each vertex presented after the first two
vertices.
n Vertices 1, n+1, and n+2 define triangle n.
n n–2 triangles are drawn.
· Example :
glBegin(GL_TRIANGLE_FAN);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glVertex2f(x3, y3);
glVertex2f(x4, y4);
glEnd();
2.2.1.8 GL_QUADS
· We use this primitive to draw individual convex quadrilaterals. OpenGL renders a
quadrilateral for each group of four vertices. If the application specifies n vertices,
OpenGL renders n/4 quadrilaterals. If n isn't a multiple of 4, OpenGL ignores the
excess vertices.
n Treats each group of four vertices as an independent quadrilateral.
· Example :
glBegin(GL_QUADS);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glVertex2f(x3, y3);
glVertex2f(x4, y4);
glEnd();
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
2.2.1.9 GL_QUAD_STRIP
· We use this primitive to draw a sequence of quadrilaterals that share edges. If the
application specifies a sequence of vertices v, OpenGL renders a quadrilateral
using v0, v1, v3 and v2 ; another quadrilateral using v2 ,v3 ,v5 and v4 ; and so
on. If the application specifies n vertices, OpenGL renders (n–2)/2 quadrilaterals. If
n is less than 4, OpenGL renders nothing.
n Draws a connected group of quadrilaterals.
n Treats each group of four vertices as an independent quadrilateral.
n Vertices 4n–3, 4n–2, 4n–1, and 4n define quadrilateral n.
n n/4 quadrilaterals are drawn.
· Example :
glBegin(GL_QUADS);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glVertex2f(x3,y3);
glVertex2f(x4,y4);
glEnd();
2.2.1.10 GL_POLYGON
· We use GL_POLYGON to draw a single filled convex n-gon primitive. OpenGL
renders an n-sided polygon, where n is the number of vertices specified by the
application. If n is less than 3, OpenGL renders nothing.
n Draws a single, convex polygon.
n Vertices 1 through N define this polygon.
n A polygon is convex if all points on the line segment between any two
points in the polygon or at the boundary of the polygon lie inside the
polygon.
· Example :
glBegin(GL_POLYGON);
glVertex2f(x1, y1);
glVertex2f(x2, y2);
glVertex2f(x3, y3);
glVertex2f(x4, y4);
glVertex2f(x5, y5);
glEnd();
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
2.2.2 Attributes
· Properties that describe how an object should be rendered are called attributes.
· Available attributes depend on the type of object. For example, a line could be
black or green. It could be solid or dashed. A polygon could be filled with a
single color or with a pattern. We could display it as filled or only by its edges.
· Fig. 2.2.3 shows various attributes for lines and polygons.
· Some of the text
attributes include the
direction of the text
string, the path followed
by successive characters
in the string, the height
and width of the
characters, the font, and
the style (bold, italic,
underlined). (a) (b)
Fig. 2.2.3 Attributes for (a) Lines and (b) Polygons
2.2.2.1 Color Attribute
Colour can be viewed as a point in a
G
colour solid, as shown in Fig. 2.2.4. As
shown in Fig. 2.2.4, the solid is drawn
using a coordinate system
corresponding to the three primaries.
Green
The distance along a coordinate axis (0,1,0) Yellow
represents the amount of the Cyan (1,1,0)
(0,1,1)
corresponding primary in the colour.
White
The maximum value of each primary (1,1,1)
Black
is normalized to 1. Any colour can be (0,0,0) R
represented with this set of primaries as Red
(1,0,0)
a point in a unit cube. The vertices of Blue Magenta
the cube correspond to black (no (0,0,1) (1,0,1)
primaries on); red, green, and blue (one Gray
B scale
primary fully on); the pairs of Fig. 2.2.4 Colour solid
primaries, cyan (green and blue fully
on), magenta (red and blue fully on), and yellow (red and green fully on); and white (all
primaries fully on). The principal diagonal of the cube connects the origin (black) with
white. All colours along this line have equal tristimulus values and appear as shades of
gray.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
RGB Colour
· The red, green and blue (RGB) colour model used in colour CRT monitors and
colour raster graphics employs a Cartesian co-ordinate system. In this model, the
individual contribution of red, green and blue are added together to get the
resultant colour.
· We can represent this colour model with the unit cube defined on R, G and B
axes, as shown in the Fig. 2.2.4.
· The vertex of the cube on the axes represent the primary colours and the
remaining vertices represent the complementary colour for each of the primary
colours. The main diagonal of the cube, with equal amounts of each primary
represents the gray levels. The end at the origin of the diagonal represents black
(0, 0, 0) and other end represents white (1, 1, 1).
· Each colour point within the bounds of the cube is represented as the triple
(R, G, B), where value for R, G, B are assigned in the range from 0 to 1. As
mentioned earlier, it is an additive model. Intensities of the primary colours are
added to get the resultant colour. Thus, the resultant colour C l is expressed in
RGB component as,
C l = RR + GG + BB
· The RGB colour model is used in image capture devices, televisions and colour
monitors. This model is additive in which different intensities of red, green and
blue are added to generate various colours. However, this model is not suitable
for image processing.
· In OpenGL, we use the colour cube as follows. To set a colour for drawing in
blue, we have to issue following function call.
glColor3f(0.0, 0.0, 1.0);
· In four-dimensional colour scheme to clear an area of the screen (a drawing
window) we use following function call.
glClearColor(1.0, 1.0, 1.0, 1.0);
· Since RGB options are 1.0, 1.0, 1.0 clear colour is white.
· The fourth component in the function call is alpha. It specifies the opacity value.
When alpha = 1.0, it is opaque and alpha = 0.0 it is transparent.
Indexed Colour
· It is a fact that any picture has finite number of colours. Thus by storing limited
number colour information in the colour look-up table it is possible to manage
digital images. This techniques is known as indexed colouring.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
· This technique is used in order to save computer memory and file storage, while
speeding up display refresh and file transfers. It is a form of vector quantization
compression.
· When an image is encoded in this way, colour information is not directly carried
by the image pixel data, but is stored in a separate piece of data called a palette:
an array of colour elements, in which every element, a colour, is indexed by its
position within the array. The image pixels do not contain the full specification of
its colour, but only its index in the palette. Thus this technique is also referred as
pseudocolour or indirect colour, as colours are addressed indirectly.
· Suppose that our frame buffer has k bits per pixel. Each pixel value or index is an
integer between 0 and 2 k - 1. Suppose that we can display each color component
with a precision of n bits; that is, we can choose from 2 n reds, 2 n greens and 2 n
blues. Hence, we can produce any of 2 3n colours on the display, but the frame
buffer can specify only 2 k of them.
· In OpenGL, GLUT allows us to set the entries in a colour table for each window
through the following function call.
glutsetColor (int color, GLfloat red, GLfloat green, GLfloat blue);
· If we are in colour-index mode, the present colour is selected by following
function call.
glIndexi (element) ;
Red
n
k - bit Colour Green
Frame Monitor
look-up n
buffer (index) table
Blue
n
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
glEnable (GL_LINE_STIPPLE);
· Without enabling this feature, lines would still appear as solid lines, even though
a pattern was provided.
· To disable the use of a pattern we can issue the following function call:
glDisable (GL_LINE_STIPPLE);
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Review Questions
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
#include <GL/glut.h>
void drawChessBoard(int left, int top, int size)
{
int length;
GLfloat col = 0.0;
length = size/8.0;
for(int i=0; i < 8; i++)
{
for(int j=0; j < 8; j++)
{
glColor3f(1.0, col, 0.0);
glRecti(left + length * j, top - length *i, left + length * j+length,
top - length *i-length);
if(col == 0.0)
{
col = 1.0;
}
else
{
col = 0.0;
}
}
if(col == 0.0)
{
col = 1.0;
}
else
{
col = 0.0;
}
}
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Output
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
#include <GL/glut.h>
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINE_LOOP); // Draw Polygon
glVertex2i(100, 50); // Point A
glVertex2i(310, 50); // Point B
glVertex2i(310, 250); // Point C
glVertex2i(240, 250); // Point D
glVertex2i(205, 350); // Point E
glVertex2i(170, 250); // Point F
glVertex2i(100, 250); // Point G
glEnd();
glFlush(); // send all output to display
}
void myinit()
{
// Set a deep black background and draw in a White.
glClearColor(0.0, 0.0, 0.0, 1.0); // Set background as black
glColor3f(1.0, 1.0, 1.0); // Draw in White
glMatrixMode(GL_PROJECTION); // Establish the coordinate system
glLoadIdentity();
gluOrtho2D(0.0, 400.0, 0.0, 400.0);
}
int main(int argc, char **argv)
{
glutInit(&argc, argv); // Initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); // Set display mode
glutInitWindowSize(500, 500); // Set window size
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
· Now we can specify the faces of the cube. An example, code to specify one face is
as given below :
glBegin (GL_POLYGON) ;
glVertex3fv (vertices [0]) ;
glVertex3fv (vertices [3]) ;
glVertex3fv (vertices [2]) ;
glVertex3fv (vertices [1]) ;
glEnd ( ) ;
· Similarly the other five faces can be defined.
The other five faces are - (2, 3, 7, 6), (0, 4, 7, 3),
1 2
(1, 2, 6, 5), (4, 5, 6, 7) and (0, 1, 5, 4). Here, the
order of traversal of the edges of cube faces is
determined by right hand rule. This is
illustrated in Fig. 2.3.3. 0 3
1. What is modeling ?
2. What is rendering ?
3. Write a short note on modeling and rendering.
2.4 Interaction
· Definition : Interaction in the field of computer graphics refers to the process of
enabling the users to interact with computer displays. The user can observe the
image change in response to the input from the user and act accordingly.
· Support by OpenGL for Interaction OpenGL does not support interaction directly.
The main reason for this is to make OpenGL portable (i.e., work on all types of
systems irrespective of the hardware).
· However, OpenGL provides the GLUT tool kit which supports minimum
functionality such as opening of windows, use of keyboard, mouse and creation of
pop-up menus, etc.
2.4.1 Events
· The OpenGL supports basic window events : the window has been resized, the
window needs to draw its contents, a key on the keyboard has been pressed or
released, a mouse has moved or mouse button was pressed or released. All such
event processing is based on callbacks. It is necessary to write functions to process
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
specific events and set them as callbacks for a specific window. When event
occurs, a corresponding callback function is called.
· GLUT handles events with callback functions. If you want to handle an event,
such as a keystroke or mouse movement, you write a function that performs the
desired action. Then you register your function by passing its name as an
argument to a function with a name of the form glut...Func(), in which "..."
indicates which callback you are registering.
· If the program has registered a keyboard callback function, the keyboard callback
function is called whenever the user presses a key.
1. Register a keyboard callback function.
glutKeyboardFunc(keyboard);
2. A keyboard callback function. It receives three arguments : The key that was
pressed, and the current X and Y coordinates of the mouse.
· The callback function registered by glutKeyboardFunc() recognizes only keys
corresponding to ASCII graphic characters and esc, backspace and delete. The
keyboard callback function in Fig. 2.4.1 is a useful default keyboard function : It
allows the user to quit the program by pressing the escape key.
#define ESCAPE 27
void keyboard (unsigned char key, int x, int y)
{
if (key == ESCAPE)
exit(0);
}
Fig. 2.4.1 Quitting with the escape key
· To make your program respond to other keys, such as the arrow keys and the
function ("F") keys :
1. Register a special key callback function.
glutSpecialFunc(special);
2. Declare the special key function as follows :
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Program 2.4.1 : This program uses keyboard callback function. The keyboard
graphics primitive.
#include <GL/glut.h>
int Height=650, Width= 650;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush(); // Send all output to display
}
void myinit()
{
// Set a deep black background and draw in a red.
glClearColor(0.0, 0.0, 0.0, 1.0); // Set background as black
glColor3f(1.0, 0.0, 0.0); // Draw in Red
glMatrixMode(GL_PROJECTION); // Establish the coordinate system
glLoadIdentity();
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
case 'f':
glBegin(GL_POLYGON); // Draw Polygon with fill
glColor3f(1, 0, 0); glVertex3i(100, 500, 0.5);
glColor3f(0, 1, 0); glVertex3i(300, 500, 0);
glColor3f(0, 0, 1); glVertex3i(200, 625, 0);
glEnd();
break;
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
case 27:
exit(0); // Terminate the program
}
glFlush();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv); // Initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); // Set display mode
glutInitWindowSize(500, 500); // Set window size
glutInitWindowPosition(100,100); // Set window position on the screen
// Open the screen window
glutCreateWindow("Draw Graphics Primitives on Keypress");
glutDisplayFunc(display); // Register redraw function
glutKeyboardFunc(myKeyboard); // Register keyboard function
myinit();
glutMainLoop(); // go into a perpetual loop
return 0;
}
Output
Keypressed
l
r
t
p
f
· There are several ways of using the mouse and two ways of responding to mouse
activity. The first callback function responds to pressing or releasing one of the
mouse buttons.
1. Register a mouse callback function.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
glutMouseFunc(mouse_button);
2. The mouse callback function is passed four arguments.
· The first argument specifies the button. Its value is one of
n GLUT_LEFT_BUTTON,
n GLUT_MIDDLE_BUTTON, or
n GLUT_RIGHT_BUTTON
· The second argument specifies the button state. Its value is one of
n GLUT_DOWN (the button has been pressed) or
n GLUT_UP (the button has been released).
· The remaining two arguments are the X and Y co-ordinates of the mouse.
Program 2.4.2 : This program displays rectangle on left mouse click and
#include <GL/glut.h>
int Height=650, Width= 650;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush(); // Send all output to display
}
void myinit()
{
// Set a deep black background and draw in a red.
glClearColor(0.0, 0.0, 0.0, 1.0); // Set background as black
glColor3f(1.0, 0.0, 0.0); // Draw in Red
glMatrixMode(GL_PROJECTION); // Establish the coordinate system
glLoadIdentity();
gluOrtho2D(0.0, 650.0, 0.0, 650.0);
}
void myMouse(int button, int state, int x, int y )
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
glRecti(100, 100, 300, 300); // Draw rectangle
}
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge