0% found this document useful (0 votes)
94 views23 pages

Module 3 Notes CG

Module 3 of the Computer Graphics and Fundamentals of Image Processing course covers interactive input methods and graphical user interfaces, detailing various logical classifications of input devices such as locators, stroke devices, and valuators. It explains the input functions for graphical data, including input modes and echo feedback, and introduces OpenGL interactive input-device functions for mouse and keyboard inputs. The document provides examples of how to implement these functions using GLUT in OpenGL for handling mouse and keyboard events.

Uploaded by

ranjitha1065r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views23 pages

Module 3 Notes CG

Module 3 of the Computer Graphics and Fundamentals of Image Processing course covers interactive input methods and graphical user interfaces, detailing various logical classifications of input devices such as locators, stroke devices, and valuators. It explains the input functions for graphical data, including input modes and echo feedback, and introduces OpenGL interactive input-device functions for mouse and keyboard inputs. The document provides examples of how to implement these functions using GLUT in OpenGL for handling mouse and keyboard events.

Uploaded by

ranjitha1065r
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

Module 3
Session 1
Interactive Input Methods and Graphical User Interfaces
Graphical Input Data:
Graphics programs use several kinds of input data, such as coordinate positions, attribute
values, character-string specifications, geometric-transformation values, viewing conditions,
and illumination parameters.
Many graphics packages, including the International Standards Organization (ISO) and
American National Standards Institute (ANSI) standards, provide an extensive set of input
functions for processing such data. But input procedures require interaction with display-
window managers and specific hardware devices. Therefore, some graphics systems,
particularly those that provide mainly device-independent functions, often include relatively
few interactive procedures for dealing with input data.
A standard organization for input procedures in a graphics package is to classify the functions
according to the type of data that is to be processed by each function. This scheme allows
any physical device, such as a keyboard or a mouse, to input any data class, although most
input devices can handle some data types better than others.

Logical Classification of Input Devices:


When input functions are classified according to data type, any device that is used to provide
the specified data is referred to as a logical input device for that data type.
The standard logical input-data classifications are

 LOCATOR - A device for specifying one coordinate position.


 STROKE - A device for specifying a set of coordinate positions.
 STRING - A device for specifying text input.
 VALUATOR - A device for specifying a scalar value.
 CHOICE - A device for selecting a menu option.
 PICK - A device for selecting a component of a picture.
Locator Devices:
 Interactive selection of a coordinate point is usually accomplished by positioning the
screen cursor at some location in a displayed scene, although other methods, such as
menu options, could be used in certain applications.
 We can use a mouse, touchpad, joystick, trackball, spaceball, thumbwheel, dial, hand
cursor, or digitizer stylus for screen-cursor positioning.
 In addition, various buttons, keys, or switches can be used to indicate processing
options for the selected location.
 Keyboards are used for locator input in several ways.
 Sometimes a keyboard includes a touchpad, joystick, trackball, or other device for
positioning the screen cursor.
 For some applications, it may also be convenient to use a keyboard to type in
numerical values or other codes to indicate coordinate positions.
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

 Other devices, such as a light pen, have also been used for interactive input of
coordinate positions.

Stroke Devices:
 This class of logical devices is used to input a sequence of coordinate positions, and
the physical devices used for generating locator input are also used as stroke devices.
 Continuous movement of a mouse, trackball, joystick, or hand cursor is translated into
a series of input coordinate values.
 The graphics tablet is one of the more common stroke devices. Button activation can
be used to place the tablet into “continuous” mode.
 As the cursor is moved across the tablet surface, a stream of coordinate values is
generated. This procedure is used in paintbrush systems to generate drawings using
various brush strokes.
 Engineering systems also use this process to trace and digitize layouts.

String Devices:
 The primary physical device used for string input is the keyboard.
 Character strings in computer-graphics applications are typically used for picture or
graph labeling.
 Other physical devices can be used for generating character patterns for special
applications.
 Individual characters can be sketched on the screen using a stroke or locator-type
device.
 A pattern recognition program then interprets the characters using a stored dictionary
of predefined patterns.

Valuator Devices:
 A typical physical device used to provide valuator input is a panel of control dials.
 Dial settings are calibrated to produce numerical values within some predefined range.
 Rotary potentiometers convert dial rotation into a corresponding voltage, which is then
translated into a number within a defined scalar range, such as −10.5 to 25.5. Instead
of dials, slide potentiometers are sometimes used to convert linear movements into
scalar values.
 Any keyboard with a set of numeric keys can be used as a valuator device.
 Joysticks, trackballs, tablets, and other interactive devices can be adapted for valuator
input by interpreting pressure or movement of the device relative to a scalar range.
 Another technique for providing valuator input is to display graphical representations
of sliders, buttons, rotating scales, and menus on the video monitor.
 Cursor positioning, using a mouse, joystick, spaceball, or other device, can be used to
select a value on one of these valuators.
 As a feedback mechanism for the user, selected values are usually displayed in text
or color fields elsewhere within the graphical display belonging to the application.

Choice Devices:
 Menus are typically used in graphics programs to select processing options, parameter
values, and object shapes that are to be used in constructing a picture.
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

 Commonly used choice devices for selecting a menu option are cursor-positioning
devices such as a mouse, trackball, keyboard, touch panel, or button box.
 Keyboard function keys or separate button boxes are often used to enter menu
selections.
 Each button or function key is programmed to select a particular operation or value,
although pre-set buttons or keys are sometimes included on an input device.
 For screen selection of listed menu options, we use a cursor-positioning device.
 Alternate methods for choice input include keyboard and voice entry.
 A standard keyboard can be used to type in commands or menu options

Pick Devices:
 We use a pick device to select a part of a scene that is to be transformed or edited in
some way.
 Several different methods can be used to select a component of a displayed scene,
and any input mechanism used for this purpose is classified as a pick device.
 Most often, pick operations are performed by positioning the screen cursor. Using a
mouse, joystick, or keyboard, for example, we can perform picking by positioning the
screen cursor and pressing a button or key to record the pixel coordinates. This screen
position can then be used to select an entire object, a facet of a tessellated surface, a
polygon edge, or a vertex.
 Other pick methods include highlighting schemes, selecting objects by name, or a
combination of methods.

Session 2
Input Functions for Graphical Data:
Graphics packages that use the logical classification for input devices provide several
functions for selecting devices and data classes. These functions allow a user to specify the
following options:

 The input interaction mode for the graphics program and the input devices. Either the
program or the devices can initiate data entry, or both can operate simultaneously.
 Selection of a physical device that is to provide input within a particular logical
classification (for example, a tablet used as a stroke device).
 Selection of the input time and device for a particular set of data values.

Input Modes:
Some input functions in an interactive graphics system are used to specify how the program
and input devices should interact.

 A program could request input at a particular time in the processing (request mode),
 or an input device could independently provide updated input (sample mode),
 or the device could independently store all collected data (event mode).
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

In request mode, the application program initiates data entry. When input values are
requested, processing is suspended until the required values are received. This input mode
corresponds to the typical input operation in a general programming language. The program
and the input devices operate alternately. Devices are put into a wait state until an input
request is made; then the program waits until the data are delivered.
In sample mode, the application program and input devices operate independently.
Input devices may be operating at the same time that the program is processing other data.
New values obtained from the input devices replace previously input data values. When the
program requires new data, it samples the current values that have been stored from the
device input.
In event mode, the input devices initiate data input to the application program. The
program and the input devices again operate concurrently, but now the input devices deliver
data to an input queue, also called an event queue. All input data is saved. When the program
requires new data, it goes to the data queue.

Echo Feedback:
Requests can usually be made in an interactive input program for an echo of input data and
associated parameters. When an echo of the input data is requested, it is displayed within a
specified screen area.

Echo feedback can include, for example, the size of the pick window, the minimum pick
distance, the type and size of a cursor, the type of highlighting to be employed during pick
operations, the range (mininum and maximum) for valuator input, and the resolution (scale)
for valuator input.
Callback Functions:
For device-independent graphics packages, a limited set of input functions can be provided in
an auxiliary library. Input procedures can then be handled as callback functions that interact
with the system software. These functions specify what actions are to be taken by a program
when an input event occurs. Typical input events are moving a mouse, pressing a mouse
button, or pressing a key on the keyboard.
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3
Session 3

OpenGL Interactive Input-Device Functions


GLUT Mouse Functions:
We use the following function to specify (“register”) a procedure that is to be called when the
mouse pointer is in a display window and a mouse button is pressed or released:
glutMouseFunc (mouseFcn);

This mouse callback procedure, which we named mouseFcn, has four arguments:
void mouseFcn (GLint button, GLint action, GLint xMouse, GLint yMouse)

 Parameter button is assigned a GLUT symbolic constant that denotes one of the three
mouse buttons, and parameter action is assigned a symbolic constant that specifies
which button action we want to use to trigger the mouse activation event.
 Allowable values for button are GLUT_LEFT_BUTTON, GLUT_MIDDLE_BUTTON,
and GLUT_RIGHT_BUTTON.
 Parameter action can be assigned either GLUT_DOWN or GLUT_UP, depending on
whether we want to initiate an action when we press a mouse button or when we
release it.
When procedure mouseFcn is invoked, the display-window location of the mouse cursor is
returned as the coordinate position (xMouse, yMouse). This location is relative to the top-left
corner of the display window, so that xMouse is the pixel distance from the left edge of the
display window and yMouse is the pixel distance down from the top of the display window.
As a simple example of the use of the glutMouseFunc routine, the following program plots a
red point, with a point size equal to 3, at the position of the mouse cursor in the display window,
each time that we press the left mouse button.
Because the coordinate origin for the OpenGL primitive functions is the lowerleft corner of the
display window, we need to flip the returned yMouse value in the procedure mousePtPlot.
#include <GL/glut.h>
GLsizei winWidth = 400, winHeight = 300; // Initial display-window size.
void init (void)
{
glClearColor (0.0, 0.0, 1.0, 1.0) // Set display-window color to blue.
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 150.0);
}
void displayFcn (void)
{
glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f (1.0, 0.0, 0.0); // Set point color to red.
glPointSize (3.0); // Set point size to 3.0.
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
/* Reset viewport and projection parameters */
glViewport (0, 0, newWidth, newHeight);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (0.0, GLdouble (newWidth), 0.0, GLdouble (newHeight));
/* Reset display-window size parameters. */
winWidth = newWidth;
winHeight = newHeight;
}
void plotPoint (GLint x, GLint y)
{
glBegin (GL_POINTS);
glVertex2i (x, y);
glEnd ( );
}
void mousePtPlot (GLint button, GLint action, GLint xMouse, GLint yMouse)
{
if (button == GLUT_LEFT_BUTTON && action == GLUT_DOWN)
plotPoint (xMouse, winHeight - yMouse);
glFlush ( );
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (100, 100);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Mouse Plot Points");
init ( );
glutDisplayFunc (displayFcn);
glutReshapeFunc (winReshapeFcn);
glutMouseFunc (mousePtPlot);
glutMainLoop ( );
}

Another GLUT mouse routine that we can use is


glutMotionFunc (fcnDoSomething);
This routine invokes fcnDoSomething when the mouse is moved within the display window
with one or more buttons activated. The function that is invoked in this case has two
arguments:
void fcnDoSomething (GLint xMouse, GLint yMouse)
whereAND
COMPUTER GRAPHICS (xMouse, yMouse)
FUNDAMENTALS is the
OF IMAGE mouse location
PROCESSING in the display window relative to the top-left
(21CS63) MODULE 3
corner, when the mouse is moved with a button pressed.

Similarly, we can perform some action when we move the mouse within the display window
without pressing a button:
glutPassiveMotionFunc (fcnDoSomethingElse);

Again, the mouse location is returned to fcnDoSomethingElse as coordinate position (xMouse,


yMouse), relative to the top-left corner of the display window.

GLUT Keyboard Functions


With keyboard input, we use the following function to specify a procedure that is to be
invoked when a key is pressed:
glutKeyboardFunc (keyFcn);
The specified procedure has three arguments:
void keyFcn (GLubyte key, GLint xMouse, GLint yMouse)

Parameter key is assigned a character value or the corresponding ASCII code. The display-
window mouse location is returned as position (xMouse, yMouse) relative to the top-left corner
of the display window. When a designated key is pressed, we can use the mouse location to
initiate some action, independently of whether any mouse buttons are pressed.
In the following code, we present a simple curve-drawing procedure using keyboard input. A
freehand curve is generated by moving the mouse within the display window while holding
down the “c” key. This displays a sequence of red dots at each recorded mouse position. By
slowly moving the mouse, we can obtain a solid curved line. Mouse buttons have no effect in
this example.
#include <GL/glut.h>
GLsizei winWidth = 400, winHeight = 300; // Initial display-window size.
void init (void)
{
glClearColor (0.0, 0.0, 1.0, 1.0); // Set display-window color to blue.
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 150.0);
}
void displayFcn (void)
{
glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f (1.0, 0.0, 0.0); // Set point color to red.
glPointSize (3.0); // Set point size to 3.0.
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
/* Reset viewport and projection parameters */
glViewport (0, 0, newWidth, newHeight);
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (0.0, GLdouble (newWidth), 0.0, GLdouble (newHeight));
/* Reset display-window size parameters. */
winWidth = newWidth;
winHeight = newHeight;
}
void plotPoint (GLint x, GLint y)
{
glBegin (GL_POINTS);
glVertex2i (x, y);
glEnd ( );
}
/* Move cursor while pressing c key enables freehand curve drawing. */
void curveDrawing (GLubyte curvePlotKey, GLint xMouse, GLint yMouse)
{
GLint x = xMouse;
GLint y = winHeight - yMouse;
switch (curvePlotKey)
{
case 'c':
plotPoint (x, y);
break;
default:
break;
}
glFlush ( );
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (100, 100);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Keyboard Curve-Drawing Example");
init ( );
glutDisplayFunc (displayFcn);
glutReshapeFunc (winReshapeFcn);
glutKeyboardFunc (curveDrawing);
glutMainLoop ( );
}

For function keys, arrow keys, and other special-purpose keys, we can use the command
glutSpecialFunc (specialKeyFcn);

The specified procedure has the same three arguments:


COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

void specialKeyFcn (GLint specialKey, GLint xMouse, GLint yMouse)


but now parameter specialKey is assigned an integer-valued GLUT symbolic constant.

 To select a function key, we use one of the constants GLUT_KEY_F1 through


GLUT_KEY_F12.
 For the arrow keys, we use constants such as GLUT_KEY_UP and
GLUT_KEY_RIGHT.
 Other keys can be designated using GLUT_KEY_PAGE_DOWN, GLUT_KEY_HOME,
and similar constants for the page up, end, and insert keys.
 The backspace, delete, and escape keys can be designated with the
glutKeyboardFunc routine using their ASCII codes, which are 8, 127, and 27,
respectively.
An interactive program using the mouse, keyboard, and function keys is demonstrated in the
following code.

#include <GL/glut.h>
#inclue <stdlib.h>
GLsizei winWidth = 400, winHeight = 300; // Initial display-window size.
GLint edgeLength = 10; // Initial edge length for square.
void init (void)
{
glClearColor (0.0, 0.0, 1.0, 1.0) // Set display-window color to blue.
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 150.0);
}
void displayFcn (void)
{
glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f (1.0, 0.0, 0.0); // Set fill color to red.
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
/* Reset viewport and projection parameters */
glViewport (0, 0, newWidth, newHeight);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (0.0, GLdouble (newWidth), 0.0, GLdouble (newHeight));
/* Reset display-window size parameters. */
winWidth = newWidth;
winHeight = newHeight;
}
/* Display a red square with a selected edge-length size. */
void fillSquare (GLint button, GLint action, GLint xMouse, GLint yMouse)
{
GLint x1, y1, x2, y2;
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

/* Use left mouse button to select a position for the


* lower-left corner of the square.
*/
if (button == GLUT_LEFT_BUTTON && action == GLUT_DOWN)
{
x1 = xMouse;
y1 = winHeight - yMouse;
x2 = x1 + edgeLength;
y2 = y1 + edgeLength;
glRecti (x1, y1, x2, y2);
}
else
if (button == GLUT_RIGHT_BUTTON) // Use right mouse button to quit.
exit (0);
glFlush ( );
}

/* Use keys 2, 3, and 4 to enlarge the square. */


void enlargeSquare (GLubyte sizeFactor, GLint xMouse, GLint yMouse)
{
switch (sizeFactor)
{
case '2':edgeLength *= 2;
break;
case '3':edgeLength *= 3;
break;
case '4':edgeLength *= 4;
break;
default: break;
}
}
/* Use function keys F2 and F4 for reduction factors 1/2 and 1/4. */
void reduceSquare (GLint reductionKey, GLint xMouse, GLint yMouse)
{
switch (reductionKey)
{
case GLUT_KEY_F2: edgeLength /= 2;
break;
case GLUT_KEY_F3: edgeLength /= 4;
break;
default: break;
}
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

glutInitWindowPosition (100, 100);


glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Display Squares of Various Sizes");
init ( );
glutDisplayFunc (displayFcn);
glutReshapeFunc (winReshapeFcn);
glutMouseFunc (fillSquare);
glutKeyboardFunc (enlargeSquare);
glutSpecialFunc (reduceSquare);
glutMainLoop ( );
}
Mouse input is used to select a location for the lower-left corner of a red square. Keyboard
input is used to scale the size of the square, and a new square is obtained with each click of
the left mouse button.

GLUT Tablet Functions:


Usually, tablet activation occurs only when the mouse cursor is in the display window. A button
event for tablet input is then recorded with
glutTabletButtonFunc (tabletFcn);
and the arguments for the invoked function are similar to those for a mouse:
void tabletFcn (GLint tabletButton, GLint action,GLint xTablet, GLint yTablet)

We designate a tablet button with an integer identifier such as 1, 2, 3, and so on, and the
button action is again specified with either GLUT_UP or GLUT_DOWN.
The returned values xTablet and yTablet are the tablet coordinates.
We can determine the number of available tablet buttons with the command
glutDeviceGet (GLUT_NUM_TABLET_BUTTONS);
Motion of a tablet stylus or cursor is processed with the following function:
glutTabletMotionFunc (tabletMotionFcn);

where the invoked function has the form


void tabletMotionFcn (GLint xTablet, GLint yTablet)
The returned values xTablet and yTablet give the coordinates on the tablet surface.

GLUT Spaceball Functions:


We use the following function to specify an operation when a spaceball button is activated for
a selected display window:
glutSpaceballButtonFunc (spaceballFcn);
The callback function has two parameters:
void spaceballFcn (GLint spaceballButton, GLint action)
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

Spaceball buttons are identified with the same integer values as a tablet, and parameter action
is assigned either the value GLUT_UP or the value GLUT_DOWN.
We can determine the number of available spaceball buttons with a call to glutDeviceGet
using the argument GLUT_NUM_SPACEBALL_BUTTONS.
Translational motion of a spaceball, when the mouse is in the display window, is recorded with
the function call
glutSpaceballMotionFunc (spaceballTranlFcn);

The three-dimensional translation distances are passed to the invoked function as, for
example:
void spaceballTranslFcn (GLint tx, GLint ty, GLint tz)
These translation distances are normalized within the range from −1000 to 1000. Similarly, a
spaceball rotation is recorded with
glutSpaceballRotateFunc (spaceballRotFcn);
The three-dimensional rotation angles are then available to the callback function, as follows:
void spaceballRotFcn (GLint thetaX, GLint thetaY, GLint thetaZ)

GLUT Button-Box Function


Input from a button box is obtained with the following statement:
glutButtonBoxFunc (buttonBoxFcn);
Button activation is then passed to the invoked function:
void buttonBoxFcn (GLint button, GLint action);
The buttons are identified with integer values, and the button action is specified as GLUT_UP
or GLUT_DOWN.

GLUT Dials Function


A dial rotation can be recorded with the following routine:
glutDialsFunc (dialsFcn);

In this case, we use the callback function to identify the dial and obtain the angular amount of
rotation:
void dialsFcn (GLint dial, GLint degreeValue);

Dials are designated with integer values, and the dial rotation is returned as an integer degree
value.
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

Session 4
OpenGL Picking Operations
In an OpenGL program, we can interactively select objects by pointing to screen positions.
However, the picking operations in OpenGL are not straightforward. Basically, we perform
picking using a designated pick window to form a revised view volume.
We assign integer identifiers to objects in a scene, and the identifiers for those objects that
intersect the revised view volume are stored in a pick-buffer array. Thus, to use the OpenGL
pick features, we need to incorporate the following procedures into a program:

 Create and display a scene.


 Pick a screen position and, within the mouse callback function, do the following:
o Set up a pick buffer.
o Activate the picking operations (selection mode).
o Initialize an ID name stack for object identifiers.
o Save the current viewing and geometric-transformation matrix.
o Specify a pick window for the mouse input.
o Assign identifiers to objects and reprocess the scene using the revisedview
volume. (Pick information is then stored in the pick buffer.)
o Restore the original viewing and geometric-transformation matrix.
o Determine the number of objects that have been picked, and return to the
normal rendering mode.
o Process the pick information.
Each record in the pick buffer contains the following information:
1. The stack position of the object, which is the number of identifiers in the name stack,
up to and including the position of the picked object.
2. The minimum depth of the picked object.
3. The maximum depth of the picked object.
4. The list of the identifiers in the name stack from the first (bottom) identifier to the
identifier for the picked object.
We illustrate the OpenGL picking operations in the following program:

#include <GL/glut.h>
#include <stdio.h>
const GLint pickBuffSize = 32;
/* Set initial display-window size. */
GLsizei winWidth = 400, winHeight = 400;
void init (void)
{
/* Set display-window color to white. */
glClearColor (1.0, 1.0, 1.0, 1.0);
}
/* Define 3 rectangles and associated IDs. */
void rects (GLenum mode)
{
if (mode == GL_SELECT)
glPushName (30); // Red rectangle.
glColor3f (1.0, 0.0, 0.0);
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

glRecti (40, 130, 150, 260);


if (mode == GL_SELECT)
glPushName (10); // Blue rectangle.
glColor3f (0.0, 0.0, 1.0);
glRecti (150, 130, 260, 260);
if (mode == GL_SELECT)
glPushName (20); // Green rectangle.
glColor3f (0.0, 1.0, 0.0);
glRecti (40, 40, 260, 130);
}
/* Print the contents of the pick buffer for each mouse selection. */
void processPicks (GLint nPicks, GLuint pickBuffer [ ])
{
GLint j, k;
GLuint objID, *ptr;
printf (" Number of objects picked = %d\n", nPicks);
printf ("\n");
ptr = pickBuffer;
/* Output all items in each pick record. */
for (j = 0; j < nPicks; j++) {
objID = *ptr;
printf (" Stack position = %d\n", objID);
ptr++;
printf (" Min depth = %g,", float (*ptr/0x7fffffff));
ptr++;
printf (" Max depth = %g\n", float (*ptr/0x7fffffff));
ptr++;
printf (" Stack IDs are: \n");
for (k = 0; k < objID; k++) {
printf (" %d ",*ptr);
ptr++;
}
printf ("\n\n");
}
}
void pickRects (GLint button, GLint action, GLint xMouse, GLint yMouse)
{
GLuint pickBuffer [pickBuffSize];
GLint nPicks, vpArray [4];
if (button != GLUT_LEFT_BUTTON || action != GLUT_DOWN)
return;
glSelectBuffer (pickBuffSize, pickBuffer); // Designate pick buffer.
glRenderMode (GL_SELECT); // Activate picking operations.
glInitNames ( ); // Initialize the object-ID stack.
/* Save current viewing matrix. */
glMatrixMode (GL_PROJECTION);
glPushMatrix ( );
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

glLoadIdentity ( );
/* Obtain the parameters for the current viewport. Set up
* a 5 x 5 pick window, and invert the input yMouse value
* using the height of the viewport, which is the fourth
* element of vpArray.
*/
glGetIntegerv (GL_VIEWPORT, vpArray);
gluPickMatrix (GLdouble (xMouse), GLdouble (vpArray [3] - yMouse), 5.0, 5.0, vpArray);
gluOrtho2D (0.0, 300.0, 0.0, 300.0);
rects (GL_SELECT); // Process the rectangles in selection mode.
/* Restore original viewing matrix. */
glMatrixMode (GL_PROJECTION);
glPopMatrix ( );
glFlush ( );
/* Determine the number of picked objects and return to the
* normal rendering mode.
*/
nPicks = glRenderMode (GL_RENDER);
processPicks (nPicks, pickBuffer); // Process picked objects.
glutPostRedisplay ( );
}
void displayFcn (void)
{
glClear (GL_COLOR_BUFFER_BIT);
rects (GL_RENDER); // Display the rectangles.
glFlush ( );
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
/* Reset viewport and projection parameters. */
glViewport (0, 0, newWidth, newHeight);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (0.0, 300.0, 0.0, 300.0);
glMatrixMode (GL_MODELVIEW);
/* Reset display-window size parameters. */
winWidth = newWidth;
winHeight = newHeight;
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (100, 100);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Example Pick Program");
init ( );
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

glutDisplayFunc (displayFcn);
glutReshapeFunc (winReshapeFcn);
glutMouseFunc (pickRects);
glutMainLoop ( );
}

OpenGL Menu Functions:


Creating a GLUT Menu:
A pop-up menu is created with the statement
glutCreateMenu (menuFcn);

where parameter menuFcn is the name of a procedure that is to be invoked when a menu
entry is selected. This procedure has one argument, which is the integer value corresponding
to the position of a selected option.
void menuFcn (GLint menuItemNumber)
The integer value passed to parameter menuItemNumber is then used by menuFcn to
perform an operation. When a menu is created, it is associated with the current display
window.
Once we have designated the menu function that is to be invoked when a menu item is
selected, we must specify the options that are to be listed in the menu. We do this with a series
of statements that list the name and position for each option. These statements have the
general form
glutAddMenuEntry (charString, menuItemNumber);
Parameter charString specifies text that is to be displayed in the menu, and parameter
menuItemNumber gives the location for that entry in the menu.
For example, the following statements create a menu with two options:
glutCreateMenu (menuFcn);
glutAddMenuEntry ("First Menu Item", 1);
glutAddMenuEntry ("Second Menu Item", 2);

Next, we must specify a mouse button that is to be used to select a menu option. This is
accomplished with
glutAttachMenu (button);

where parameter button is assigned one of the three GLUT symbolic constants referencing
the left, middle, or right mouse button.
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

To illustrate the creation and use of a GLUT menu, the following program provides two options
for displaying the interior fill of a triangle

#include <GL/glut.h>
GLsizei winWidth = 400, winHeight = 400; // Initial display-window size.
GLfloat red = 1.0, green = 1.0, blue = 1.0; // Initial triangle color: white.
GLenum fillMode = GL_SMOOTH; // Initial polygon fill: color interpolation.
void init (void)
{
glClearColor (0.6, 0.6, 0.6, 1.0); // Set display-window color to gray.
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 300.0, 0.0, 300.0);
}
void fillOption (GLint selectedOption)
{
switch (selectedOption) {
case 1: fillMode = GL_FLAT; break; // Flat surface rendering.
case 2: fillMode = GL_SMOOTH; break; // Gouraud rendering.
}
glutPostRedisplay ( );
}
void displayTriangle (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glShadeModel (fillMode); // Set fill method for triangle.
glColor3f (red, green, blue); // Set color for first two vertices.
glBegin (GL_TRIANGLES);
glVertex2i (280, 20);
glVertex2i (160, 280);
glColor3f (red, 0.0, 0.0); // Set color of last vertex to red.
glVertex2i (20, 100);
glEnd ( );
glFlush ( );
}
void reshapeFcn (GLint newWidth, GLint newHeight)
{
glViewport (0, 0, newWidth, newHeight);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (0.0, GLfloat (newWidth), 0.0, GLfloat (newHeight));
displayTriangle ( );
glFlush ( );
}
void main (int argc, char **argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

glutInitWindowPosition (200, 200);


glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Menu Example");
init ( );
glutDisplayFunc (displayTriangle);
glutCreateMenu (fillOption); // Create pop-up menu.
glutAddMenuEntry ("Solid-Color Fill", 1);
glutAddMenuEntry ("Color-Interpolation Fill", 2);
/* Select a menu option using the right mouse button. */
glutAttachMenu (GLUT_RIGHT_BUTTON);
glutReshapeFunc (reshapeFcn);
glutMainLoop ( );
}

Creating and Managing Multiple GLUT Menus:

When a menu is created, it is associated with the current display window. We can create
multiple menus for a single display window, and we can create different menus for different
windows. As each menu is created, it is assigned an integer identifier, starting with the value
1 for the first menu created. The integer identifier for a menu is returned by the glutCreateMenu
routine, and we can record this value with a statement such as
menuID = glutCreateMenu (menuFcn);

A newly created menu becomes the current menu for the current display window. To activate
a menu for the current display window, we use the statement
glutSetMenu (menuID);

This menu then becomes the current menu, which will pop up in the display window when the
mouse button that has been attached to that menu is pressed.
We eliminate a menu with the command
glutDestroyMenu (menuID);
If the designated menu is the current menu for a display window, then that window has no
menu assigned as the current menu, even though other menus may exist.

The following function is used to obtain the identifier for the current menu in the current display
window:
currentMenuID = glutGetMenu ( );

A value of 0 is returned if no menus exist for this display window or if the previous current
menu was eliminated with the glutDestroyMenu function.
Creating GLUT Submenus:

A submenu can be associated with a menu by first creating the submenu using
glutCreateMenu, along with a list of suboptions, and then listing the submenu as an additional
option in the main menu. We can add the submenu to the option list in a main menu (or other
submenu) using a sequence of statements such as
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

submenuID = glutCreateMenu (submenuFcn);


glutAddMenuEntry ("First Submenu Item", 1);
.
.
.
glutCreateMenu (menuFcn);
glutAddMenuEntry ("First Menu Item", 1);
.
.
.
glutAddSubMenu ("Submenu Option", submenuID);

The glutAddSubMenu function can also be used to add the submenu to the current menu.
In the following program, we illustrate the creation of a submenu

#include <GL/glut.h>
GLsizei winWidth = 400, winHeight = 400; // Initial display-window size.
GLfloat red = 1.0, green = 1.0, blue = 1.0; // Initial color values.
GLenum renderingMode = GL_SMOOTH; // Initial fill method.
void init (void)
{
glClearColor (0.6, 0.6, 0.6, 1.0); // Set display-window color to gray.
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 300.0, 0.0, 300.0);
}
void mainMenu (GLint renderingOption)
{
switch (renderingOption) {
case 1: renderingMode = GL_FLAT; break;
case 2: renderingMode = GL_SMOOTH; break;
}
glutPostRedisplay ( );
}
/* Set color values according to the submenu option selected. */
void colorSubMenu (GLint colorOption)
{
switch (colorOption) {
case 1:
red = 0.0; green = 0.0; blue = 1.0;
break;
case 2:
red = 0.0; green = 1.0; blue = 0.0;
break;
case 3:
red = 1.0; green = 1.0; blue = 1.0;
}
glutPostRedisplay ( );
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

}
void displayTriangle (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glShadeModel (renderingMode); // Set fill method for triangle.
glColor3f (red, green, blue); // Set color for first two vertices.
glBegin (GL_TRIANGLES);
glVertex2i (280, 20);
glVertex2i (160, 280);
glColor3f (1.0, 0.0, 0.0); // Set color of last vertex to red.
glVertex2i (20, 100);
glEnd ( );
glFlush ( );
}
void reshapeFcn (GLint newWidth, GLint newHeight)
{
glViewport (0, 0, newWidth, newHeight);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (0.0, GLfloat (newWidth), 0.0, GLfloat (newHeight));
displayTriangle ( );
glFlush ( );
}
void main (int argc, char **argv)
{
GLint subMenu; // Identifier for submenu.
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (200, 200);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Submenu Example");
init ( );
glutDisplayFunc (displayTriangle);
subMenu = glutCreateMenu (colorSubMenu);
glutAddMenuEntry ("Blue", 1);
glutAddMenuEntry ("Green", 2);
glutAddMenuEntry ("White", 3);
glutCreateMenu (mainMenu); // Create main pop-up menu.
glutAddMenuEntry ("Solid-Color Fill", 1);
glutAddMenuEntry ("Color-Interpolation Fill", 2);
glutAddSubMenu ("Color", subMenu);
/* Select menu option using right mouse button. */
glutAttachMenu (GLUT_RIGHT_BUTTON);
glutReshapeFunc (reshapeFcn);
glutMainLoop ( );
}
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

Designing a Graphical User Interface:


The User Dialogue:
 For any application, the user’s model serves as the basis for the design of the dialogue
by describing what the system is designed to accomplish and what operations are
available.
 It states the type of objects that can be displayed and how the objects can be
manipulated.
 For example, if the system is to be used as a tool for architectural design, the model
describes how the package can be used to construct and display views of buildings by
positioning walls, doors, windows, and other building components.
 All information in the user dialogue is presented in the language of the application.
 In an architectural design package, this means that all interactions are described only
in architectural terms, without reference to particular data structures, computer-
graphics terms, or other concepts that may be unfamiliar to an architect.

Windows and Icons:


 In addition to the standard display-window operations, such as opening, closing,
positioning, and resizing, other operations are needed for working with the sliders,
buttons, icons, and menus.
 Some systems are capable of supporting multiple window managers so that different
window styles can be accommodated, each with its own window manager, which could
be structured for a particular application.
 Icons representing objects such walls, doors, windows, and circuit elements are often
referred to as application icons.
 The icons representing actions, such as rotate, magnify, scale, clip, or paste, are called
control icons, or command icons.
Accommodating Multiple Skill Levels:
 A less experienced user may find an interface with a large, comprehensive set of
operations to be difficult to use, so a smaller interface with fewer but more easily
understood operations and detailed prompting may be preferable.
 Experienced users, on the other hand, typically want speed.
 This means fewer prompts and more input from the keyboard or with multiple mouse-
button clicks.
 Actions are selected with function keys or with simultaneous combinations of keyboard
keys, because experienced users will remember these shortcuts for commonly used
actions.
 An interface may be designed to provide different sets of options to users with different
experience levels.
 This may be selectable by the user through an application preference setting, or
suggested by the application itself as the user gains experience with it.
 Similarly, help facilities can be designed on several levels so that beginners can carry
on a detailed dialogue, while more experienced users can reduce or eliminate prompts
and messages.
 Help facilities can also include one or more tutorial applications, which provide users
with an introduction to the capabilities and use of the system.
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

Consistency:
 An important design consideration in an interface is consistency.
 An icon shape should always have a single meaning, rather than serving to represent
different actions or objects depending on the context.
 Some other examples of consistency are always placing menus in the same relative
positions so that a user does not have to hunt for a particular option, always using the
same combination of keyboard keys for an action, and always using the same color
encoding so that a color does not have different meanings in different situations.

Minimizing Memorization
 Operations in an interface should also be structured so that they are easy to
understand and to remember.
 Obscure, complicated, inconsistent, and abbreviated command formats lead to
confusion and reduction in the effective application of the software.
 One key or button used for all delete operations, for example, is easier to remember
than a number of different keys for different kinds of delete procedures.
 Icons and window systems can also be organized to minimize memorization.
 Different kinds of information can be separated into different windows so that a user
can identify and select items easily.
 Icons should be designed as easily recognizable shapes that are related to application
objects and actions.
 To select a particular action, a user should be able to select an icon that resembles
that action.
Backup and Error Handling:
 A mechanism for undoing a sequence of operations is another common feature of an
interface, which allows a user to explore the capabilities of a system, knowing that the
effects of a mistake can be corrected.
 Typically, systems can now undo several operations, thus allowing a user to reset the
system to some specified action.
 For those actions that cannot be reversed, such as closing an application without
saving changes, the system asks for a verification of the requested operation.
 In addition, good diagnostics and error messages help a user to determine the cause
of an error.
 Interfaces can attempt to minimize errors by anticipating certain actions that could lead
to an error; and users can be warned if they are requesting ambiguous or incorrect
actions, such as attempting to apply a procedure to multiple application objects.

Feedback:
 Responding to user actions is another important feature of an interface, particularly for
an inexperienced user.
 As each action is entered, some response should be given. Otherwise, a user might
begin to wonder what the system is doing and whether the input should be reentered.
 Feedback can be given in many forms, such as highlighting an object, displaying an
icon or message, and displaying a selected menu option in a different color.
 When the processing of a requested action is lengthy, the display of a flashing
message, clock, hourglass, or other progress indicator is important.
COMPUTER GRAPHICS AND FUNDAMENTALS OF IMAGE PROCESSING (21CS63) MODULE 3

 It may also be possible for the system to display partial results as they are completed,
so that the final display is built up a piece at a time.
 The system might also allow a user to input other commands or data while one
instruction is being processed.
 Clarity is another important feature of feedback. A response should be easily
understood, but not so overpowering that the user’s concentration is interrupted.
 With function keys, feedback can be given as an audible click or by lighting up the key
that has been pressed.
 Audio feedback has the advantage that it does not use up screen space, and it does
not divert the user’s attention from the work area.
 A fixed message area can be used so that a user always know where to look for
messages, but it may be advantageous in some cases to place feedback messages in
the work area near the cursor.
 Feedback can also be displayed in different colors to distinguish it from other displayed
objects.
 Echo feedback is often useful, particularly for keyboard input, so that errors can be
detected quickly.
 Button and dial input can be echoed in the same way.
 Scalar values that are selected with dials or from displayed scales are usually echoed
on the screen so that a user can check the input values for accuracy.
 Selection of coordinate points can be echoed with a cursor or other symbol that
appears at the selected position.
 For more precise echoing of selected positions, the coordinate values could also be
displayed on the screen.

You might also like