CG Module-5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 78

Module 5 Input and

Interaction

5.1 INPUT AND INTERACTION


5.1.1 Interaction;
5.1.2 Input devices;

5.1.3 Clients and servers;


5.1.4 Display lists;
5.1.5 Display lists and modeling;
5.1.6 Programming event-driven input;
5.1.7 Menus;
5.1.8Picking;
5.1.9 A simple CAD program;
5.1.10 Building interactive models;
5.1.11 Animating interactive programs;
5.1.12Design of interactive programs;
5.1.13 Logic operations.

5.1.1 INTERACTION
In the field of computer graphics, interaction refers to the manner in
which the application program communicates with input and output
devices of the system.
For e.g. Image varying in response to the input from the user.
OpenGL doesn‟t directly support interaction in order to maintain
portability. However, OpenGL provides the GLUT library. This library
supports interaction with the keyboard, mouse etc and hence enables
interaction. The GLUT library is compatible with many operating systems
such as X windows, Current Windows, Mac OS etc and hence indirectly
ensures the portability of OpenGL.

5.1.2 INPUT DEVICES


 Input devices are the devices which provide input to the computer graphics
application program. Input devices can be categorized in two ways:

1
Module 5 Input and Interaction

h. Physical input devices


i. Logical input devices

PHYSICAL INPUT DEVICES


 Physical input devices are the input devices which has the particular
hardware architecture.
 The two major categories in physical input devices are:
Key board devices like standard keyboard, flexible keyboard, handheld

keyboard etc. These are used to provide character input like letters,
numbers, symbols etc.
Pointing devices like mouse, track ball, light pen etc. These are used to
specify the position on the computer screen.

✓ KEYBOARD: It is a general keyboard which has set of characters. We


make use of ASCII value to represent the character i.e. it interacts with the
programmer by passing the ASCII value of key pressed by programmer. Input
can be given either single character of array of characters to the program.
k. MOUSE AND TRACKBALL: These are pointing devices used to specify the
position. Mouse and trackball interacts with the application program by
passing the position of the clicked button. Both these devices are similar in use
and construction. In these devices, the motion of the ball is converted to signal
sent back to the computer by pair of encoders inside the device. These
encoders measure motion in 2-orthogonal directions.

2
Module 5 Input and Interaction

The values passed by the pointing devices can be considered as positions and
converted to a 2-D location in either screen or world co-ordinates. Thus, as a
mouse moves across a surface, the integrals of the velocities yield x,y values
that can be converted to indicate the position for a cursor on the screen as
shown below:

These devices are relative positioning devices because changes in the position of
the ball yield a position in the user program.

✓ DATA TABLETS: It provides absolute positioning. It has rows and


columns of wires embedded under its surface. The position of the stylus is
determined through electromagnetic interactions between signals travelling
through the wires and sensors in the stylus.

3
Module 5 Input and Interaction

n. LIGHT PEN: It consists of light-sensing device such as “photocell”. The light


pen is held at the front of the CRT. When the electron beam strikes the
phosphor, the light is emitted from the CRT. If it exceeds the threshold then
light sensing device of the light pen sends a signal to the computer specifying
the position.

The major disadvantage is that it has the difficulty in obtaining a position that
corresponds to a dark area of the screen

✓ JOYSTICK: The motion of the stick in two orthogonal directions is


encoded, interpreted as two velocities and integrated to indentify a screen
location. The integration implies that if the stick is left in its resting position,
there is no change in cursor position. The faster the stick is moved from the
resting position; the faster the screen location changes. Thus, joystick is variable
sensitivity device.

The advantage is that it is designed using mechanical elements such as springs


and dampers which offer resistance to the user while pushing it. Such
mechanical feel is suitable for application such as the flight simulators, game
controllers etc.

4
Module 5 Input and Interaction

o. SPACE BALL: It is a 3-Dimensional input device which looks like a


joystick with a ball on the end of the stick.

Stick doesn‟t move rather pressure sensors in the ball measure the forces applied by the
user. The space ball can measure not only three direct forces (up-down, front-back,
left-right) but also three independent twists. So totally device measures six
independent values and thus has six degree of freedom.

Other 3-Dimensional devices such as laser scanners, measure 3-D positions


directly. Numerous tracking systems used in virtual reality applications sense
the position of the user and so on.

LOGICAL INPUT DEVICES


 These are characterized by its high-level interface
with the application program rather than by its physical
characteristics.
 Consider the following fragment of C code:
int x;
scanf(“%d”,&x);
printf(“%d”,x);
 The above code reads and then writes an integer. Although we run this
program on workstation providing input from keyboard and seeing
output on the display screen, the use of scanf() and printf() requires no
knowledge of the properties of physical devices such as keyboard codes
or resolution of the display.

5
Module 5 Input and Interaction

 These are logical functions that are defined by how they handle input oroutput
character strings from the perspective of C program.

 From logical devices perspective inputs are from inside the application
program. The two major characteristics describe the logical behavior of input devices
are as follows:
The measurements that the device returns to the user program
The time when the device returns those measurements

API defines six classes of logical input devices which are given below:

✓ STRING: A string device is a logical device that provides the ASCII values
of input characters to the user program. This logical device is usually
implemented by means of physical keyboard.
✓ LOCATOR: A locator device provides a position in world coordinates to
the user program. It is usually implemented by means of pointing devices such
as mouse or track ball.
✓ PICK: A pick device returns the identifier of an object on the display to
the user program. It is usually implemented with the same physical device as
the locator but has a separate software interface to the user program. In
OpenGL, we can use a process of selection to accomplish picking.
✓ CHOICE: A choice device allows the user to select one of a discrete
number of options. In OpenGL, we can use various widgets provided by the
window system. A widget is a graphical interactive component provided by the
window system or a toolkit. The Widgets include menus, scrollbars and

graphical buttons. For example, a menu with n selections acts as a choice


device, allowing user to select one of „n‟ alternatives.
✓ VALUATORS: They provide analog input to the user program on some
graphical systems; there are boxes or dials to provide value.
✓ STROKE: A stroke device returns array of locations. Example, pushing
down a mouse button starts the transfer of data into specified array and
releasing of button ends this transfer.

6
Module 5 Input and Interaction

INPUT MODES
Input devices can provide input to an application program in terms of two
entities:
✓ Measure of a device is what the device returns to the application
program.
✓ Trigger of a device is a physical input on the device with which the user
can send signal to the computer
Example 1: The measure of a keyboard is a single character or array of
characters where as the trigger is the enter key.
Example 2: The measure of a mouse is the position of the cursor whereas the
trigger is when the mouse button is pressed.

The application program can obtain the measure and trigger in three distinct
modes:
✓ REQUEST MODE: In this mode, measure of the device is not returned to
the program until the device is triggered.
For example, consider a typical C program which reads a character input
using scanf(). When the program needs the input, it halts when it
encounters the scanf() statement and waits while user type characters at
the terminal. The data is placed in a keyboard buffer (measure) whose

contents are returned to the program only after enter key (trigger) is
pressed.
Another example, consider a logical device such as locator, we can move
out pointing device to the desired location and then trigger the device

with its button, the trigger will cause the location to be returned to the
application program.

7
Module 5 Input and Interaction

✓ SAMPLE MODE: In this mode, input is immediate. As soon as the


function call in the user program is executed, the measure is returned. Hence
no trigger is needed.

Both request and sample modes are useful for the situation if and only if there
is a single input device from which the input is to be taken. However, in case of
flight simulators or computer games variety of input devices are used and these
mode cannot be used. Thus, event mode is used.

❖ EVENT MODE: This mode can handle the multiple interactions. Suppose
that we are in an environment with multiple input devices, each with its
own trigger and each running a measure process.

Whenever a device is triggered, an event is generated.The device measure


including the identifier for the device is placed in an event queue.
If the queue is empty, then the application program will wait until an

event occurs. If there is an event in a queue, the program can look at the
first event type and then decide what to do.

Another approach is to associate a function when an event occurs, which is


called as “call back.”

8
Module 5 Input and Interaction

5.1.3 CLIENT AND SERVER


The computer graphics architecture is based on the client-server model.

I.e., if computer graphics is to be useful for variety of real applications, it must


function well in a world of distributed computing and network.
In this architecture the building blocks are entities called as “servers”
perform the tasks requested by the “client”
Servers and clients can be distributed over a network or can be present

within a single system. Today most of the computing is done in the form
of distributed based and network based as shown below:

Most popular examples of servers are print servers – which allow using
high speed printer devices among multiple users. File servers – allow
users to share files and programs.
Users or clients will make use of these services with the help of user

programs or client programs. The OpenGL application programs are the client
programs that use the services provided by the graphics server.
Even if we have single user isolated system, the interaction would be
configured as client-server model.

9
Module 5 Input and Interaction

5.1.4 DISPLAY LISTS


The original architecture of a graphical system was based on a general-purpose
computer connected to a display. The architecture is shown in the next page.

At that time, the disadvantage is that system was slow and expensive.
Therefore, a special purpose computer is build which is known as “display
processor”.

The user program is processed by the host computer which results a compiled
list of instruction that was then sent to the display processor, where the
instruction are stored in a display memory called as “display file” or “display list”.
Display processor executes its display list contents repeatedly at a sufficient high
rate to produce flicker-free image.

There are two modes in which objects can be drawn on the screen:

✓ IMMEDIATE MODE: This mode sends the complete description of the


object which needs to be drawn to the graphics server and no data can be
retained. i.e., to redisplay the same object, the program must re-send the
information. The information includes vertices, attributes, primitive types,
viewing details.

10
Module 5 Input and Interaction

✓ RETAINED MODE: This mode is offered by the display lists. The object is
defined once and its description is stored in a display list which is at the server
side and redisplay of the object can be done by a simple function call issued by
the client to the server.

NOTE: The main disadvantage of using display list is it requires memory at the
server architecture and server efficiency decreases if the data is changing
regularly.

DEFINITION AND EXECUTION OF DISPLAY LISTS

 Display lists are defined similarly to the geometric primitives. i.e.,


glNewList() at the beginning and glEndList() at the end is used to define a
display list.
 Each display list must have a unique identifier – an integer that is
usually a macro defined in the C program by means of #define directive
to an appropriate name for the object in the list. For example, the following
code defines red box:

 The flag GL_COMPILE indicates the system to send the list


to the server but not to display its contents. If we want an immediate
display of the contents while the list is being
constructed then GL_COMPILE_AND_EXECUTE flag is set.

11
Module 5 Input and Interaction

 Each time if the client wishes to redraw the box on the
display, it need not resend the entire description. Rather, it can call the
following
function:
glCallList(Box)

 The Box can be made to appear at different places on the monitor by


changing the projection matrix as shown below:

 OpenGL provides an API to retain the information by using stack – It is a


data structure in which the item placed most recently is removed first
[LIFO].
 We can save the present values of the attributes and the matrices by pushing them into
the stack, usually the below function calls are placed at the beginning of the display list,

glPushAttrib(GL_ALL_ATTRIB_BITS); glPushMatrix();

 We can retrieve these values by popping them from the stack, usually the below
function calls are placed at the end of the display list,
glPopAttrib();
glPopMatrix();
 We can create multiple lists with consecutive identifiers more easily
using:
glGenLists (number)
 We can display multiple display lists by using single funciton
call: glCallLists()

12
Module 5 Input and Interaction

TEXT AND DISPLAY LISTS


 There are two types of text i.e., raster text and stroke text which can be
generated.
 For example, let us consider a raster text character is to be drawn of size
8x13 pattern of bits. It takes 13 bytes to store each character.
 If we define a stroke font using only line segments, each
characterrequires a different number of lines.

 From the above figure we can observe to draw letter „I‟ is fairly simple,whereas
drawing „O‟ requires many line segments to get sufficiently smooth.

 So, on the average we need more than 13 bytes per character to


represent stroke font. The performance of the graphics system will be
degraded for the applications that require large quantity of text.
 A more efficient strategy is to define the font once, using a display list
foreach char and then store in the server. We define a function OurFont()
which will draw any ASCII character stored in variable „c‟.
 The function may have the form

 For the character „O‟ the code sequence is of the form as shown below:

13
Module 5 Input and Interaction

 The above code approximates the circle with 12 quadrilaterals.

 When we want to generate a 256-character set, the required code


using OurFont() is as follows
base = glGenLists(256);
for(i=0;i<256;i++) {
glNewList(base+i, GL_COMPILE);
OurFont(i);
glEndList();
}
 To display char from the list, offset is set by using glListBase(base)
function. The drawing of a string is accomplished in the server by the
following function, char *text_string;
glCallLists((GLint) strlen (text_string), GL_BYTE, text_string);

 The glCallLists has three arguments: (1) indicates number of lists tobe
executed (2) indicates the type (3) is a pointer to an array of a type given
by second argument.

FONTS IN GLUT
GLUT provides raster and stroke fonts; they do not make use of display
lists.

14
Module 5 Input and Interaction

glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, int character);

provides proportionally space characters. Position of a character is done


by using a translation before the character function is called.
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, int character); produces the
bitmap characters of size 8x13.

5.1.5 DISPLAY LIST AND MODELING


 Display list can call other display list. Therefore, they are powerful tools
for building hierarchical models that can incorporate relationships
among parts of a model.

 Consider a simple face modeling system that can produce images


a
sfollows:

 Each face has two identical eyes, two identical ears, one nose, one mouth
& an outline. We can specify these parts through display lists which is
given below:

15
Module 5 Input and Interaction

5.1.6 PROGRAMMING EVENT DRIVEN INPUT


 The various events can be recognized by the window system and
calback function can be called for each of these events.

USING POINTING DEVICES


 Pointing devices like mouse, trackball, data tablet allow programmer
toindicate a position on the display.
 There are two types of event associated with pointing device, which is

conventionally assumed to be mouse but could be trackball or data


tablet also.
MOVE EVENT – is generated when the mouse is move with one of the button
being pressed. If the mouse is moved without a button being pressed, this
event is called as “passive move event”.
MOUSE EVENT – is generated when one of the mouse buttons is either
pressed or released.

The information returned to the application program includes button


that generated the event, state of the button after event (up or down),
position (x,y) of the cursor. Programming a mouse event involves two
steps:
➔ The mouse callback function must be defined in the form: void myMouse(int
button, int state, int x, int y) is written by the programmer.
For example,
void myMouse(int button, int state, int x, int y)
{
if(button==GLUT_LEFT_BUTTON && state == GLUT_DOWN)
exit(0);
}

16
Module 5 Input and Interaction

The above code ensures whenever the left mouse button is pressed down,
execution of the program gets terminated.

➔ Register the defined mouse callback function in the main function, by


means of GLUT function:
glutMouseFunc(myMouse);

Write an OpenGL program to display square when a left button is pressed and to
exit the program if right button is pressed.

#include<stdio.h>
#include<stdlib.h>
#include<GL/glut.h>
int wh=500, ww=500;
float siz=3;
void myinit()
{
glClearColor(1.0,1.0,1.0,1.0);
glViewPort(0,0,w,h)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,(GLdouble) ww, 0, (GLdouble) wh);
glMatrixMode(GL_MODELVIEW);
glColor3f(1,0,0);
}

void drawsq (int x, int y)


{
y=wh-y;
glBegin(GL_POLYGON);
glVertex2f(x+siz, y+siz);

17
Module 5 Input and Interaction

glVertex2f(x-siz, y+siz);
glVertex2f(x-siz, y-siz);
glVertex2f(x+siz, y-siz);
glEnd();
glFlush();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
}

void myMouse(int button, int state, int x, int y)


{
if(button==GLUT_LEFT_BUTTON && state == GLUT_DOWN)
drawsq(x,y);
if(button==GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
exit(0);
}
void main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB|GLUT_SINGLE);
glutInitWindowSize(wh,ww);
glutCreateWindow(“square”);
glutDisplayFunc(display);
glutMouseFunc(myMouse);
myinit();
glutMainLoop();
}

18
Module 5 Input and Interaction

KEYBOARD EVENTS
 Keyboard devices are input devices which return the ASCII value to
theuser program. Keyboard events are generated when the mouse is in the window and one
of the keys is pressed or released.
 GLUT supports following two functions:
glutKeyboardFunc() is the callback for events generated by pressing a key
glutKeyboardUpFunc() is the callback for events generated by releasing a

key.

 The information returned to the program includes ASCII value of the key
pressed and the position (x,y) of the cursor when the key was pressed.
Programming keyboard event involves two steps:

✓ The keyboard callback function must be defined in the


form: void mykey (unsigned char key, int x, int y)
is written by the application programmer.
For example,
void mykey(unsigned char key, int x, int y)
{
if(key== „q‟ || key== „Q‟)
exit(0);
}

The above code ensures when „Q‟ or „q‟ key is pressed, the execution of
the program gets terminated.

✓ The keyboard callback function must be registered in the main


functionby means of GLUT function:
glutKeyboardFunc(mykey);

19
Module 5 Input and Interaction

WINDOW EVENTS
A window event is occurred when the corner of the window is dragged to new position or
size of window is minimized or maximized by using mouse.

The information returned to the program includes the height and width
of newly resized window. Programming the window event involves two
steps:

✓ Window call back function must be defined in the form:


void myReshape(GLsizei w, GLsizei h) is written by the application programmer.
Let us consider drawing square as an example, the square of same size
must be drawn regardless of window size.
void myReshape(GLsizei w, GLsizei h)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,(GLdouble) w, 0, (GLdouble) h);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glViewPort(0,0,w,h)
/*save new window size in global variables*/
ww=w;
wh=h;
}

✓ The window callback function must be registered in the main function,


glutReshapeFunc(myReshape);

20
Module 5 Input and Interaction

THE DISPLAY AND IDLE CALLBACKS


Display callback is specified by GLUT using
glutDisplayFunc(myDisplay). It is invoked when GLUT determines that
window should be redisplayed. Re-execution of the display function can
be achieved by using glutPostRedisplay().
The idle callback is invoked when there are no other events. It is
specified by GLUT using glutIdleFunc(myIdle).

WINDOW MANAGEMENT
 GLUT also supports multiple windows of a given window. We can create a
second top-level window as follows:
id = glutCreateWindow(“second window”);

 The returned integer value allows us to select this window as the current
window.
i.e., glutSetWindow(id);

NOTE: The second window can have different properties from other window by
invoking the glutInitDisplayMode before glutCreateWindow.

5.1.7 MENUS
 Menus are an important feature of any application program. OpenGL
provides a feature called “Pop-up-menus” using which sophisticated
interactive applications can be created.
 Menu creation involves the following steps:
h) Define the actions corresponding to each entry in the menu.
i) Link the menu to a corresponding mouse button.
j) Register a callback function for each entry in the menu.

21
Module 5 Input and Interaction

 The glutCreateMenu() registers the callback function demo_menu. The


function glutAddMenuEntry() adds the entry in the menu whose name is
pased in first argument and the second argument is the identifier passed
to the callback when the entry is selected.

 GLUT also supports the creation of hierarchical menus which is given


below:

5.1.8 PICKING
Picking is the logical input operation that allows the user to identify an object on the
display.

The action of picking uses pointing device but the information returned
to the application program is the identifier of an object not a position.

22
Module 5 Input and Interaction

It is difficult to implement picking in modern system because of graphics

pipeline architecture. Therefore, converting from location on the display


to the corresponding primitive is not direct calculation.
There are at least three ways to deal with this difficulty:
➔ Selection:

It involves adjusting the clipping region and viewport such


that we can keep track of which primitives lies in a small
clipping region and are rendered into region near the cursor.
These primitives are sent into a hit list that can be
examined later by the user program.
➔ Bounding boxes or extents:

➔ Usage of back buffer and extra rendering:

When we use double buffering it has two color buffers: front


and back buffers. The contents present in the front buffer is
displayed, whereas contents in back buffer is not displayed so
we can use back buffer for other than rendering the scene

Picking can be performed in four steps that are initiated by user defined
pick function in the application:

23
Module 5 Input and Interaction

➔ We draw the objects into back buffer with the pick colors.
➔ We get the position of the mouse using the mouse callback.

➔ Use glReadPixels() to find the color at the position in the frame


buffer corresponding to the mouse position.
➔ We search table of colors to find the object corresponds to the color
read.

PICKING AND SELECTION MODE


The difficulty in implementing the picking is we cannot go backward
directly from the position of the mouse to the primitives.

OpenGL provides “selection mode” to do picking. The glRenderMode() is


used to choose select mode by passing GL_SELECT value.
When we enter selection mode and render a scene, each primitive within
the clipping volume generates a message called “hit” that is stored in a
buffer called “name stack”.
The following functions are used in selection mode:

void glSelectBuffer(GLsizei n, GLuint *buff) : specifies array


buffer of size „n‟ in which to place selection data.
void glInitNames() : initializes the name stack.
void glPushName(GLuint name) : pushes name on the name stack.
void glPopName() : pops the top name from the name stack. void
glLoadName(GLuint name) : replaces the top of the name stack with
name.

OpenGL allow us to set clipping volume for picking using gluPickMatrix()


which is applied before gluOrtho2D.
gluPickMatrix(x,y,w,h,*vp) :creates a projection matrix for picking that

restricts drawing to a w x h area and centered at (x,y) in window


coordinates within the viewport vp.

24
Module 5 Input and Interaction

❖ There is a normal window and image on the display. We also see the
cursor with small box around it indicating the area in which primitive is
rendered.
❖ It shows window and display after the window has been changed by
gluPickMatrix.

The following code provides the implementation of picking process:

#include<glut.h>

25
Module 5 Input and Interaction

26
Module 5 Input and Interaction

void myReshape()
{
glViewPort(0,0,w,h)
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0,(GLdouble) w, 0, (GLdouble) h);
glMatrixMode(GL_MODELVIEW);
}

void main(int argc, char** argv)


{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE |GLUT_RGB);

27
Module 5 Input and Interaction

glutInitWindowSize(500,500);
glutInitWindowPosition(100,100);
glutCreateWindow(“picking”);
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutMouseFunc(Mouse);
glClearColor(0.0,0.0,0.0,0.0);
glutMainLoop();
}

5.1.9 A SIMPLE CAD PROGRAM

Applications like interactive painting, design of mechanical parts and creating


characters for a game are all examples of computer-aided design (CAD). CAD
programs allow –
The use of multiple windows and viewports to display a variety of
information.
The ability to create, delete and save user-defined objects.
Multiple modes of operations employing menus, keyboard and mouse.

For example, consider the polygon-modeling CAD program which supports


following operations:
✓ Creation of polygons
✓ Deletion of polygons
✓ Selection and movement of polygons
Refer appendix A.5 polygon modeling program for the entire code from the

prescribed text (Interactive Computer Graphics by Edward Angel 5 th edition)

28
Module 5 Input and Interaction

5.1.10 BUILDING INTERACTIVE MODELS


Using OpenGL, we can develop a program where we can do insertion,

manipulation, deletion etc and we can also build a program which is


quite interactive by using the concept of instancing and display lists.
Consider an interior design application which has items like
chairs, tables and other house hold items. These items are called the
basic building blocks of the application. Each occurrence of these basic
items is referred to as “instance”.
Whenever the instances of building blocks are created by the user using
the application program, the object (instance) is stored into an array
called as “instance table”. We reserve the type 0 to specify that the
object no longer exists (i.e., for deletion purpose)

Now suppose that the user has indicated through a menu that he wishes to eliminate an
object and use the mouse to locate the object.

O The program can now search the instance table till it finds the
object as specified in the bounding box and then set its type to 0.
O Hence, next time when the display process goes through the
instance table, the object would not be displayed and thereby it
appears that object has been deleted.
Although the above strategy works fine, a better data structure to
implement the instance table is using linked lists instead of arrays.

5.1.11 ANIMATING INTERACTIVE PROGRAMS


 Using OpenGl, the programmer can design interactive programs.

Programs in which objects are not static rather they appear to be moving
or changing is considered as “Interactive programs”.
 Consider the following diagram:

29
Module 5 Input and Interaction

 Consider a 2D point p(x,y) such that x = cos , y= sin . This point would lie
on a unit circle regardless of the value of . Thus, if we connect the above
given four points we get a square which has its center as the
origin. The above square can be displayed as shown below:

 Suppose that we change the value of as the program is running, the


square appears to rotating about its origin. If the value of is to be
changed by a fixed amount whenever nothing else is happening then an
idle callback function must be designed as shown below:

 The above idle callback function must be registered in the main


function: glutIdleFunc(idle);
 Suppose that we want to turn off and turn on the rotation feature then
we can write a mouse callback function as shown below:

30
Module 5 Input and Interaction

 The above mouse callback function starts the rotation of the cube when
the left mouse button and when the middle button is pressed it will halt
the rotation.
 The above mouse callback function must be registered in the main
function as follow:
glutMouseFunc(mouse);

 However, when the above program is executed using single buffering


scheme then flickering effect would be noticed on the display. This
problem can be overcome using the concept of double buffering.

DOUBLE BUFFERING:
 Double buffering is a must in such animations where the primitives,
attributes and viewing conditions are changing continuously.
 Double buffer consists of two buffers: front buffers and back buffers.

Doublebuffering mode can be initialized:


glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);

 Further in the display function, we have to include: glutSwapBuffers()


to exchange the contents of front and the back buffer.
 Using this approach, the problems associated with flicker can be
eliminated.

31
Module 5 Input and Interaction

USING TIMER:
 To understand the usage of timer, consider cube rotation program and
its execution is done by using fast GPU (modern GPUs can render tens of
millions of primitives per second) then cube will be rendered thousands
of time per second and we will see the blur on the display.
 Therefore, GLUT provides the following timer function:

glutTimerFunc(int delay, void(*timer_func (int), int value)

 Execution of this function starts timer in the event loop that delays for
delay milliseconds. When timer has counted down, timer_func is executed the
value parameter allow user to pass variable into the timer call back.

5.1.12 DESIGN OF INTERACTIVEPROGRAMS


The following are the features of most interactive program:

 A smooth display, showing neither flicker nor any artifacts of the refresh
process.
 A variety of interactive devices on the display
 A variety of methods for entering and displaying information
 An easy to use interface that does not require substantial effort to learn
 Feedback to the user
 Tolerance for user errors

 A design that incorporates consideration of both the visual and motor


properties of the human.

TOOLKITS, WIDGETS AND FRAME BUFFER:


The following two examples illustrate the limitations of geometric rendering.
➢ Pop-up menus: When menu callback is invoked, the menu appears over
whatever was on the display. After we make our selection, the menu
disappears and screen is restored to its previous state.

32
Module 5 Input and Interaction

➢ Rubberbanding: It is a technique used to define the elastic nature of


pointing device to draw primitives.

 Consider paint application, if we want to draw a line, we indicate


onlytwo end points of our desired line segment. i.e., after locating first point,
as we move the mouse, a line segment is drawn automatically [is updated
on each refresh] from first location to present position of mouse.
 Rubberbanding begin when mouse button is pressed and continue until
button is released at that time final line segment is drawn.

 We cannot implement this sequence of operations using only


what w
e
have presented so for. We will explore it in next chapters.

5.1.13 LOGIC OPERATIONS


Two types of functions that define writing modes are:
1. Replacement mode 2. Exclusive OR (XOR)

When program specifies about visible primitive then OpenGL renders it


into set of color pixels and stores it in the present drawing buffer.

In case of default mode, consider we start with a color buffer then


has been cleared to black. Later we draw a blue color rectangle of size 10

x10 pixels then 100 blue pixels are copied into the color buffer, replacing
100 black pixels. Therefore, this mode is called as “copy or replacement
mode”.
Consider the below model, where we are writing single pixel into color
buffer.

33
Module 5 Input and Interaction

The pixel that we want to write is called as “source pixel”.


The pixel in the drawing buffer which gets replaced by source pixel is
called as “destination pixel”.
In Exclusive-OR or (XOR) mode, corresponding bits in each pixel are
combing using XOR logical operation.

If s and d are corresponding bits in the source and destination pixels, we


can denote the new destination bit as d‟. d‟ = d s
One special property of XOR operation is if we apply it twice, it returns to
the original state, it returns to the original state. So, if we draw some thing in
XOR mode, we can erase it by drawing it again.
d =( d s) s

OpenGL supports all 16 logic modes, copy mode (GL_COPY) is the


default. To change mode, we must enable logic operation,

glEnable(GL_COLOR_LOGIC_OP) and then it can change to XOR mode


glLogicOp(GL_XOR)

DRAWING ERASABLE LINES


One way to draw erasable lines is given below:
Mouse is used to get first end point and store this in object coordinates.

Again mouse is used to get second point and draw a line segment in XOR
mode.

34
Module 5 Input and Interaction

Here in the above code, copy mode is used to switch back in order to
draw other objects in normal mode.
If we enter another point with mouse, we first draw line in XOR mode

from 1st point to 2nd point and draw second line using 1st point to
current point is as follows:

Final form of code can be written as shown below:

In this example, we draw rectangle using same concept and the code for
callback function are given below:

35
Module 5 Input and Interaction

36
Module 5 Input and Interaction

For the first time, we draw a single rectangle in XOR mode.

After that each time that we get vertex, we first erase the existing
rectangle by redrawing new rectangle using new vertex.

Finally, when mouse button is released the mouse callback is executed


again which performs final erase and draw and go to replacement mode.

XOR AND COLOR


 Consider we would like to draw blue color line where 24 bit RGB values
(00000000, 00000000, 11111111).
 Suppose the screen is clear to write (11111111, 11111111, 11111111)
then when we draw blue line using XOR mode, then the resultant line
would appear in yellow color (11111111, 11111111, 00000000) because
XOR operation is applied bit-wise.
 This leads to form annoying visual effects.
 Therefore, we should use copy mode while drawing final output to get it
in required color.
CURSORS AND OVERLAY PLANES
Rubberbanding and cursors can place a significant burden on graphics
system as they require the display to be updated constantly.

Although XOR mode simplifies the process, it requires the system to read
present destination pixels before computing new destination pixels.

37
Module 5 Input and Interaction

Alternative is to provide hardware support by providing extra bits in the


color buffer by adding “overlay planes”.

Therefore, typical color buffer may have 8 bits for each Red, green and blue and
one red, one green and one blue overlay plane. i.e., each color will be having its
own overlay plane then those values will be updated to color buffer.

38
Module 5 Input and Interaction

39
Module 5 Curves

5.2 Curves:
5.2.1 Curved surfaces
5.2.2 Quadric surfaces
5.2.3 OpenGL quadric surfaces and cubic surface functions
5.2.4 Bezier spline curves
5.2.5 Bezier surfaces
5.2.6 Opengl curve functions
5.2.7 Corresponding opengl functions

5.2.1 Curved surfaces


 Sometimes it is required to generate curved objects instead of polygons, for the curved
objects the equation can be expressed either in parametric form or non parametric form.
Curves and surfaces can be described by parameters
 Parametric form:
When the object description is given in terms of its dimensionality parameter, the
description is termed as parametric representation.
A curve in the plane has the form C(t) = (x(t), y(t)), and a curve in space has the
form C(t) = (x(t), y(t), z(t)).
The functions x(t), y(t) and z(t) are called the coordinates functions.
The image of C(t) is called the trace of C, and C(t) is called a parametrization of C
A parametric curve defined by polynomial coordinate function is called a
polynomial curve.
The degree of a polynomial curve is the highest power of the variable occurring in
any coordinate function.
 Non parametric form:
When the object descriptions are directly in terms of coordinates of reference
frame, then the representation is termed as non parametric.
Example: a surface can be described in non parametric form as:
f1(x,y,z)=0 or z=f2(x,y)

1
Module 5 Curves

 The coordinates (x, y) of points of a no parametric explicit planner curve satisfy y


= f(x) or x = g(y).
 Such curve have the parametric form C(t) = (t, f(t)) or C(t) = (g(t), t).

5.2.2 Quadric surfaces


 A frequently used class of objects is the quadric surfaces, which are
described withsecond - degree equations (quadratics).
 They include spheres, ellipsoids, tori, paraboloids, and hyperboloids.

9) Sphere
 A spherical surface with radius r centered on the coordinate origin
is defined as the set of points (x, y, z) that satisfy the equation
2 2 2 2
x +y +z =r
 We can also describe the spherical surface in parametric form, using latitude and
longitude angles as shown in figure
= r cos φ cos θ, − π/2 ≤ φ ≤ π/2
= r cos φ sin θ, − π ≤ θ ≤ π
= r sin φ

 Alternatively, we could write the parametric


equations using standard spherical
coordinates, where angle φ is specified as the
colatitudes as shown in figure

2. Ellipsoid
 An ellipsoidal surface can be described as an extension of a spherical surface where the
radii in three mutually perpendicular directions can have different values

2
Module 5 Curves

 The Cartesian representation for points over the surface of an ellipsoid centered on the
origin is

 And a parametric representation for the ellipsoid in terms of the latitude angle φ and the
longitude angle θ
x = rx cos φ cos θ, − π/2 ≤ φ ≤ π/2
y = ry cos φ sin θ, − π ≤ θ ≤ π
z = rz sin φ

Torus
 A torus is a doughnut-shaped object, as shown in fig. below.

 It can be generated by rotating a circle or other conic about a specified axis.


 The equation for the cross-sectional circle shown in the side view is given by
2 2 2
(y − raxial) + z = r

3
Module 5 Curves

 Rotating this circle about the z axis produces the torus whose surface
positions are described with the Cartesian equation

 The corresponding parametric equations for the torus with a circular cross-section are
= (raxial + r cos φ) cos θ, − π ≤ φ ≤ π
= (raxial + r cos φ) sin θ, − π ≤ θ ≤ π
= r sin φ

 We could also generate a torus by rotating an ellipse, instead of a circle, about the z
axsi.we can write the ellipse equation as

where raxial is the distance along the y axis from the rotation z axis to the ellipse
center. This generates a torus that can be described with the Cartesian equation

 The corresponding parametric representation for the torus with an elliptical


crosssection is
x = (raxial + ry cos φ) cos θ, − π ≤ φ ≤ π
y = (raxial + ry cos φ) sin θ, − π ≤ θ ≤ π
z = rz sin φ

5.2.3 OpenGL Quadric-Surface and Cubic-Surface Functions


 A number of other three-dimensional quadric-surface objects can be displayed using functions
that are included in the OpenGL Utility Toolkit (GLUT) and in the OpenGL Utility (GLU).
 With the GLUT functions, we can display a sphere, cone, torus, or the teapot
 With the GLU functions, we can display a sphere, cylinder, tapered cylinder, cone, flat
circular ring (or hollow disk), and a section of a circular ring (or disk).

4
Module 5 Curves

GLUT Quadric-Surface Functions

Sphere
Function:
glutWireSphere (r, nLongitudes, nLatitudes);
or
glutSolidSphere (r, nLongitudes, nLatitudes);
where,
 r is sphere radius which is double precision point.
 nLongitudes and nLatitudes is number of longitude and latitude lines used to
approximatethe sphere.

Cone
Function:
glutWireCone (rBase, height, nLongitudes, nLatitudes);
or
glutSolidCone (rBase, height, nLongitudes, nLatitudes);
where,
 rBase is the radius of cone base which is double precision point.
 height is the height of cone which is double precision point.
 nLongitudes and nLatitudes are assigned integer values that specify the
number oforthogonal surface lines for the quadrilateral mesh approximation.

Torus
Function:
glutWireTorus (rCrossSection, rAxial, nConcentrics, nRadialSlices);
or
glutSolidTorus (rCrossSection, rAxial, nConcentrics, nRadialSlices);
where,
 rCrossSection radius about the coplanar z axis

5
Module 5 Curves

 rAxial is the distance of the circle center from the z axis


 nConcentrics specifies the number of concentric circles (with center on the z axis)
tobeused on the torus surface,
 nRadialSlices specifies the number of radial slices through the torus surface

GLUT Cubic-Surface Teapot Function


Function:
glutWireTeapot (size);
or
glutSolidTeapot (size);
 The teapot surface is generated using OpenGL B´ezier curve functions.
 Parameter size sets the double-precision floating-point value for the maximum
radius ofthe teapot bowl.
 The teapot is centered on the world-coordinate origin coordinate origin with its
verticalaxis along the y axis.

GLU Quadric-Surface Functions


 To generate a quadric surface using GLU functions
1. assign a name to the quadric,
2.activate the GLU quadric renderer, and
3.designate values for the surface parameters
 The following statements illustrate the basic sequence of calls for displaying a wire-frame
sphere centered on the world-coordinate origin:
GLUquadricObj *sphere1; sphere1 =
gluNewQuadric ( ); gluQuadricDrawStyle
(sphere1, GLU_LINE); gluSphere (sphere1, r,
nLongitudes, nLatitudes);

where,
 sphere1 is the name of the object

6
Module 5 Curves

 the quadric renderer is activated with the gluNewQuadric function, and then the
displaymode GLU_LINE is selected for sphere1 with the gluQuadricDrawStyle
command
 Parameter r is assigned a double-precision value for the sphere radius
 nLongitudes and nLatitudes. number of longitude lines and latitude lines

Three other display modes are available for GLU quadric


surfaces GLU_POINT: quadric surface is displayed as point plot
GLU_SILHOUETTE: quadric surface displayed will not contain shared edges between two
coplanar polygon facets
GLU_FILL: quadric surface is displayed as patches of filled area.

 To produce a view of a cone, cylinder, or tapered cylinder, we replace the gluSphere


function with
gluCylinder (quadricName, rBase, rTop, height, nLongitudes, nLatitudes);
The base of this object is in the xy plane (z=0), and the axis is the z axis.
rBase is the radius at base and rTop is radius at top
If rTop=0.0,weget a cone; if rTop=rBase,weobtain a cylinder
Height is the height of the object and latitudes and longitude values will be given
as nLatitude and nLongitude.

 A flat, circular ring or solid disk is displayed in the xy plane (z=0) and centered on
h
teworld-coordinate origin with
gluDisk (ringName, rInner, rOuter, nRadii, nRings);
We set double-precision values for an inner radius and an outer radius with
parameters rInner and rOuter. If rInner = 0, the disk is solid.
Otherwise, it is displayed with a concentric hole in the center of the disk.
The disk surface is divided into a set of facets with integer parameters nRadii and
nRings

7
Module 5 Curves

 We can specify a section of a circular ring with the following GLU


function:
gluPartialDisk (ringName, rInner, rOuter, nRadii, nRings, startAngle,
sweepAngle);
startAngle designates an angular position in degrees in the xy plane measured
clockwise from the positive y axis.
parameter sweepAngle denotes an angular distance in degrees from the
startAngle position.
A section of a flat, circular disk is displayed from angular position startAngle to
startAngle + sweepAngle
For example, if startAngle = 0.0 and sweepAngle = 90.0, then the section of
the disk lying in the first quadrant of the xy plane is displayed.

 Allocated memory for any GLU quadric surface can be reclaimed and the surface
eliminated with
gluDeleteQuadric (quadricName);

 Also, we can define the front and back directions for any quadric surface with the
following orientation function:
gluQuadricOrientation (quadricName, normalVectorDirection);
Where,
Parameter normalVectorDirection is assigned either GLU_OUTSIDE or
GLU_ INSIDE

 Another option is the generation of surface-normal vectors, as follows:


gluQuadricNormals (quadricName, generationMode);
Where,
 A symbolic constant is assigned to parameter generationMode to indicate how
surface-normal vectors should be generated. The default is GLU_NONE.
 For flat surface shading (a constant color value for each surface), we use the
symbolic constant GLU_FLAT

8
Module 5 Curves

When other lighting and shading conditions are to be applied, we use the constant
GLU_SMOOTH, which generates a normal vector for each surface vertex
position.

 We can designate a function that is to be invoked if an error occurs during the generation
of a quadric surface:
gluQuadricCallback (quadricName, GLU_ERROR, function);

Example Program Using GLUT and GLU Quadric-Surface


Functions #include <GL/glut.h>
GLsizei winWidth = 500, winHeight = 500; // Initial display-window size.
void init (void)
{
glClearColor (1.0, 1.0, 1.0, 0.0); // Set display-window color.
}
void wireQuadSurfs (void)
{
glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glColor3f (0.0, 0.0, 1.0); // Set line-color to blue.
/* Set viewing parameters with world z axis as view-up direction.
*/ gluLookAt (2.0, 2.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
/* Position and display GLUT wire-frame sphere. */
glPushMatrix ( );
glTranslatef (1.0, 1.0, 0.0);
glutWireSphere (0.75, 8, 6);
glPopMatrix ( );
/* Position and display GLUT wire-frame cone. */
glPushMatrix ( );
glTranslatef (1.0, -0.5, 0.5);
glutWireCone (0.7, 2.0, 7, 6);
glPopMatrix ( );

9
Module 5 Curves

/* Position and display GLU wire-frame cylinder. */


GLUquadricObj *cylinder; // Set name for GLU quadric object.
glPushMatrix ( );
glTranslatef (0.0, 1.2, 0.8);
cylinder = gluNewQuadric ( );
gluQuadricDrawStyle (cylinder, GLU_LINE);
gluCylinder (cylinder, 0.6, 0.6, 1.5, 6, 4);
glPopMatrix ( );
glFlush ( );
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
glViewport (0, 0, newWidth, newHeight);
glMatrixMode (GL_PROJECTION);
glOrtho (-2.0, 2.0, -2.0, 2.0, 0.0, 5.0);
glMatrixMode (GL_MODELVIEW);
glClear (GL_COLOR_BUFFER_BIT);
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitWindowPosition (100, 100);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Wire-Frame Quadric Surfaces");
init ( );
glutDisplayFunc (wireQuadSurfs);
glutReshapeFunc (winReshapeFcn);
glutMainLoop ( );
}

10
Module 5 Curves

5.2.4 Bézier Spline Curves


 It was developed by the French engineer Pierre Bézier for use in the design of Renault
automobile bodies.
 Bézier splines have a number of properties that make them highly useful and
convenient for curve and surface design. They are also easy to implement.
 In general, a Bézier curve section can be fitted to any number of control points, although
some graphic packages limit the number of control points to four.

Bézier Curve Equations


 We first consider the general case of n + 1 control-point positions, denoted as
pk = (xk , yk , zk), with k varying from 0 to n.
 These coordinate points are blended to produce the following position vector P(u), which
describes the path of an approximating Bézier polynomial function between p0 and
pn:

 The Bézier blending functions BEZk,n(u) are the Bernstein polynomials

where parameters C(n, k) are the binomial coefficients

 A set of three parametric equations for the individual curve coordinates can be
represented as

11
Module 5 Curves

 Below Figure demonstrates the appearance of some Bézier curves for various selections
of control points in the xy plane (z = 0).

 Recursive calculations can be used to obtain successive binomial-coefficient values as

for n ≥ k. Also, the Bézier blending functions satisfy the recursive relationship
BEZk,n(u) = (1 − u)BEZk,n−1(u) + u BEZk−1,n−1(u), n > k ≥ 1 (27)
with BEZk,k = uk and BEZ0,k = (1 − u)k .

Program
#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
/* Set initial size of the display window. */
GLsizei winWidth = 600, winHeight = 600;

12
Module 5 Curves

/* Set size of world-coordinate clipping window.


*/ GLfloat xwcMin = -50.0, xwcMax = 50.0;
GLfloat ywcMin = -50.0, ywcMax = 50.0; class
wcPt3D {
public:
GLfloat x, y, z;
};
void init (void)
{
/* Set color of display window to white. */
glClearColor (1.0, 1.0, 1.0, 0.0);
}
void plotPoint (wcPt3D bezCurvePt)
{
glBegin (GL_POINTS);
glVertex2f (bezCurvePt.x, bezCurvePt.y);
glEnd ( );
}
/* Compute binomial coefficients C for given value of n. */
void binomialCoeffs (GLint n, GLint * C) {

GLint k, j;
for (k = 0; k <= n; k++) {
/* Compute n!/(k!(n - k)!). */
C [k] = 1;
for (j = n; j >= k + 1; j--)
C [k] *= j;
for (j = n - k; j >= 2; j--)
C [k] /= j;
}
}

13
Module 5 Curves

void computeBezPt (GLfloat u, wcPt3D * bezPt, GLint nCtrlPts, wcPt3D * ctrlPts, GLint * C)
{
GLint k, n = nCtrlPts - 1;
GLfloat bezBlendFcn;
bezPt->x = bezPt->y = bezPt->z = 0.0;
/* Compute blending functions and blend control points. */
for (k = 0; k < nCtrlPts; k++) {
bezBlendFcn = C [k] * pow (u, k) * pow (1 - u, n - k);
bezPt->x += ctrlPts [k].x * bezBlendFcn; bezPt->y
+= ctrlPts [k].y * bezBlendFcn;
bezPt->z += ctrlPts [k].z * bezBlendFcn;
}
}
void bezier (wcPt3D * ctrlPts, GLint nCtrlPts, GLint nBezCurvePts)
{
wcPt3D bezCurvePt;
GLfloat u;
GLint *C, k;
/* Allocate space for binomial coefficients */
C = new GLint [nCtrlPts];
binomialCoeffs (nCtrlPts - 1, C);
for (k = 0; k <= nBezCurvePts; k++) {
u = GLfloat (k) / GLfloat (nBezCurvePts);
computeBezPt (u, &bezCurvePt, nCtrlPts, ctrlPts,
C); plotPoint (bezCurvePt);
}
delete [ ] C;
}
void displayFcn (void)
{
/* Set example number of control points and number of

14
Module 5 Curves

➢ curve positions to be plotted along the Bezier


curve. */ GLint nCtrlPts = 4, nBezCurvePts = 1000;
wcPt3D ctrlPts [4] = { {-40.0, -40.0, 0.0}, {-10.0, 200.0, 0.0},
{10.0, -200.0, 0.0}, {40.0, 40.0, 0.0} };
glClear (GL_COLOR_BUFFER_BIT); // Clear display window.
glPointSize (4);
glColor3f (1.0, 0.0, 0.0); // Set point color to red.
bezier (ctrlPts, nCtrlPts, nBezCurvePts); glFlush
( );
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
/* Maintain an aspect ratio of 1.0. */
glViewport (0, 0, newHeight, newHeight);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (xwcMin, xwcMax, ywcMin,
ywcMax); glClear (GL_COLOR_BUFFER_BIT);
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE |
GLUT_RGB); glutInitWindowPosition (50, 50);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Bezier Curve"); init ( );

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

Properties of Bézier Curves

15
Module 5 Curves

Property1:

 A very useful property of a Bézier curve is that the curve connects the first and last
control points.
 Thus, a basic characteristic of any Bézier curve is that
P(0) = p0
P(1) = pn

 Values for the parametric first derivatives of a Bézier curve at the endpoints can be
calculated from control-point coordinates as

 The parametric second derivatives of a Bézier curve at the endpoints are calculated as

Property 2:

 Another important property of any Bézier curve is that it lies within the convex hull
(convex polygon boundary) of the control points.

 This follows from the fact that the Bézier blending functions are all positive and their
sum is always 1:

Other Properties:
 The basic functions are real.
 The degree of the polynomial defining the curve segment is one less than the number of
defining points.
 The curve generally follows the shape of the defining polygon,
 The tangent vectors at the ends of the curve have the same direction as the first and last
polygon spans respectively.

16
Module 5 Curves

Design Techniques Using Bézier Curves


 A closed Bézier curve is generated when we set the last control-point position
to thecoordinate position of the first control point.
 Specifying multiple control points at a single coordinate position gives more weight ot
that position a single coordinate position is input as two control points, and the resulting
curve is pulled nearer to this position.
 When complicated curves are to be generated, they can be formed by piecing
togetherseveral Bézier sections of lower degree.
 Generating smaller Bézier-curve sections also gives us better local control over the
shapeof the curve.
 Because Bézier curves connect the first and last control points, it is easy to match
curvesections.
 Also,Bézier curves have the important property that the tangent to the curve at an
endpoint is along the line joining that endpoint to the adjacent control point to obtain
first-order continuity between curve sections, we can pick control points p0’ and p1’for
the next curve section to be along the same straight line as control points pn−1 and pn of
the preceding section

 If the first curve section has n control points and the next curve section has n’
controlpoints, then we match curve tangents by placing control point p1’ at the position

17
Module 5 Curves

Cubic Bézier Curves


 Cubic Bézier curves are generated with four control points. The four blending
functionsfor cubic Bézier curves, obtained by substituting n = 3 in the equations below,
they are

 Plots of the four cubic Bézier blending functions are given in Figure

 At the end positions of the cubic Bézier curve, the parametric first derivatives (slopes) are

and the parametric second derivatives are

 A matrix formulation for the cubic-Bézier curve function is obtained by


expanding thepolynomial expressions for the blending functions and restructuring the
equations as
18
Module 5 Curves

where the Bézier matrix is

5.2.5 Bézier Surfaces


 The parametric vector function for the Bézier surface is formed as the tensor
product ofBézier blending functions:

with pj,k specifying the location of the (m + 1) by (n + 1) control points


 Figure below illustrates two Bézier surface plots. The control points are
connected bydashed lines, and the solid lines show curves of constant u and constant v.
 Each curve of constant u is plotted by varying v over the interval from 0 to 1, with u
fixedat one of the values in this unit interval. Curves of constant v are plotted similarly.

 Bézier surfaces have the same properties as Bézier curves, and they provide a
convenientmethod for interactive design applications.
 To specify the threedimensional coordinate positions for the control points, we
could firstconstruct a rectangular grid in the xy “ground” plane.

19
Module 5 Curves

 We then choose elevations above the ground plane at the grid intersections as thez-
coordinate values for the control points.

5.2.6 OpenGL Curve Functions


 There are routines in the OpenGL Utility Toolkit (GLUT) that we can use to
display some three-dimensional quadrics, such as spheres and cones, and some other
shapes.
 Another method we can use to generate a display of a simple curve is to approximate it
using a polyline. We just need to locate a set of points along the curve path and connect
the points with straight-line segments.

 Figure above illustrates various polyline displays that could be used for a circle segment.
 A third alternative is to write our own curve-generation functions based on the
algorithmswith respect to line drawing and circle drawing.

20
Module 5 Curves

5.2.7 OpenGL Approximation-Spline Functions


OpenGL Bézier-Spline Curve Functions
 We specify parameters and activate the routines for Bézier-curve display
with theOpenGL functions
glMap1* (GL_MAP1_VERTEX_3, uMin, uMax, stride, nPts,
*ctrlPts); glEnable (GL_MAP1_VERTEX_3);
 We deactivate the routines with
glDisable (GL_MAP1_VERTEX_3);
where,
 A suffix code of f or d is used with glMap1 to indicate either floating-point or
doubleprecision for the data values. M
 inimum and maximum values for the curve parameter u are specified in uMin and
uMax,although these values for a Bézier curve are typically set to 0 and 1.0, respectively.
 Bézier control points are listed in array ctrlPts number of elements in this array is
givenas a positive integer using parameter nPts.
 stride is assigned an integer offset that indicates the number of data values between
the beginning of one coordinate position in array ctrlPts and the beginning of the next
coordinate position

 A coordinate position along the curve path is calculated with


glEvalCoord1* (uValue);
Where,
 parameter uValue is assigned some value in the interval from uMin to uMax.
 Function glEvalCoord1 calculates a coordinate position using equation with
the parameter value

which maps the uValue to the interval from 0 to 1.0.

21
Module 5 Curves

 A spline curve is generated with evenly spaced parameter values, and OpenGL provides
the following functions, which we can use to produce a set of uniformly spaced parameter
values:
glMapGrid1* (n, u1, u2);
glEvalMesh1 (mode, n1, n2);
Where,
 The suffix code for glMapGrid1 can be either f or d.
 Parameter n specifies the integer number of equal subdivisions over the range from u1 to
u2.
 Parameters n1 and n2 specify an integer range corresponding to u1 and u2.
 Parameter mode is assigned either GL POINT or GL LINE, depending on whether we
want to display the curve using discrete points (a dotted curve) or using straight-line
segments
 In other words, with mode = GL LINE, the preceding OpenGL commands are
equivalent to
glBegin (GL_LINE_STRIP);
for (k = n1; k <= n2; k++)
glEvalCoord1f (u1 + k * (u2 - u1) / n);
glEnd ( );

OpenGL Bézier-Spline Surface Functions


 Activation and parameter specification for the OpenGL Bézier-surface routines
areaccomplished with

glMap2* (GL_MAP2_VERTEX_3, uMin, uMax, uStride, nuPts, vMin,


vMax, vStride, nvPts, *ctrlPts);
glEnable (GL_MAP2_VERTEX_3);
Where,
 A suffix code of f or d is used with glMap2 to indicate either floating-point or double
precision for the data values.
 For a surface, we specify minimum and maximum values for both parameter u and
parameter v.

22
Module 5 Curves

 If control points are to be specified using four-dimensional homogeneous coordinates, we


use the symbolic constant GL_MAP2_VERTEX_4 instead of GL_MAP2_VERTEX_3

 We deactivate the Bézier-surface routines with


glDisable {GL_MAP2_VERTEX_3}
 Coordinate positions on the Bézier surface can be calculated with
glEvalCoord2* (uValue,
vValue); or
glEvalCoord2*v (uvArray);
Where,
 Parameter uValue is assigned some value in the interval from uMin to uMax,
 Parameter vValue is assigned some value in the interval from vMin to vMax.

which maps each of uValue and vValue to the interval from 0 to 1.0

GLU B-Spline Curve Functions


 Although the GLU B-spline routines are referred to as NURBs functions, they can be usedto
generate B-splines that are neither nonuniform nor rational.
 The following statements illustrate the basic sequence of calls for displaying a B-spline
curve:
GLUnurbsObj *curveName;
curveName = gluNewNurbsRenderer
( ); gluBeginCurve (curveName);
gluNurbsCurve (curveName, nknots, *knotVector, stride, *ctrlPts,

degParam,
GL_MAP1_VERTEX_3); gluEndCurve (curveName);
 We eliminate a defined B-spline with
gluDeleteNurbsRenderer (curveName);

 A B-spline curve is divided automatically into a number of sections and displayed as a


polyline by theGLUroutines.

23
Module 5 Curves

 However, a variety of B-spline rendering options can also be selected with repeated cals
to the following GLU function:
gluNurbsProperty (splineName, property, value);

GLU B-Spline Surface Functions


GLUnurbsObj *surfName
surfName = gluNewNurbsRenderer ( );
gluNurbsProperty (surfName, property1, value1);
gluNurbsProperty (surfName, property2, value2);
gluNurbsProperty (surfName, property3, value3);
...
gluBeginSurface (surfName);
gluNurbsSurface(surfName, nuKnots, uKnotVector, nvKnots, vKnotVector,
uStride, vStride, &ctrlPts [0][0][0], uDegParam, vDegParam,
GL_MAP2_VERTEX_3);
gluEndSurface (surfName);

 As an example of property setting, the following statements specify a wire-


frame,triangularly tessellated display for a surface:
gluNurbsProperty (surfName, GLU_NURBS_MODE, GLU_NURBS_TESSELLATOR);
gluNurbsProperty (surfName, GLU_DISPLAY_MODE, GLU_OUTLINE_POLYGON);

 To determine the current value of a B-spline property, we use the following


queryfunction:
gluGetNurbsProperty (splineName, property, value);
 When the property GLU_AUTO_LOAD_MATRIX is set to the value
GL_FALSE, weinvoke
gluLoadSamplingMatrices (splineName, modelviewMat, projMat, viewport);

 Various events associated with spline objects are processed using


gluNurbsCallback (splineName, event, fcn);

24
Module 5 Curves

 Data values for the gluNurbsCallback function are supplied by


gluNurbsCallbackData (splineName, dataValues);

GLU Surface-Trimming Functions


 A set of one or more two-dimensional trimming curves is specified for a B-spline
surfacewith the following statements:
gluBeginTrim (surfName);
gluPwlCurve (surfName, nPts, *curvePts, stride, GLU_MAP1_TRIM_2);
...
gluEndTrim (surfName);
Where,
 Parameter surfName is the name of the B-spline surface to be trimmed.
 A set of floating-point coordinates for the trimming curve is specified in array parameter
curvePts, which contains nPts coordinate positions.
 An integer offset between successive coordinate positions is given in parameter stride

25
Module 5 Curves

26
Module 5 Curves

27
Module 5 Computer Animation

5.3 Animation
5.3.1 Raster methods of computer animation
5.3.2 Design of animation sequences
5.3.3 Traditional animation techniques
5.3.4 General computer animation function
5.3.5 OpenGL animation procedures
5.3.6 Questions

Introduction:
 To 'animate' is literally 'to give life to'.
 'Animating' is moving something which can't move itself.

 Animation adds to graphics the dimension of time which vastly increases the amount of
information which can be transmitted.

 Computer animation generally refers to any time sequence of visual changes in a


picture.

 In addition to changing object positions using translations or rotations, a computer-


generated animation could display time variations in object size, color, transparency, or
surface texture.
 Two basic methods for constructing a motion sequence are
real-time animation and
In a real-time computer-animation, each stage of the sequence is viewed as it
is created.
Thus the animation must be generated at a rate that is compatible with the
constraints of the refresh rate.
frame-by-frame animation
For a frame-by-frame animation, each frame of the motion is separately
generated and stored.
Later, the frames can be recorded on film, or they can be displayed
consecutively on a video monitor in “real-time playback” mode.

1
Module 5 Computer Animation

5.3.1 Raster Methods for Computer Animation


 We can create simple animation sequences in our programs using real-time methods.
 We can produce an animation sequence on a raster-scan system one frame at a
time, sothat each completed frame could be saved in a file for later viewing.
 The animation can then be viewed by cycling through the completed frame
sequence, orthe frames could be transferred to film.
 If we want to generate an animation in real time, however, we need to produce the
motionframes quickly enough so that a continuous motion sequence is displayed.
 Because the screen display is generated from successively modified pixel values in the
refresh buffer, we can take advantage of some of the characteristics of the raster screen-
refresh process to produce motion sequences quickly.

Double Buffering
 One method for producing a real-time animation with a raster system is to
employtwo refresh buffers.
 We create a frame for the animation in one of the buffers.
 Then, while the screen is being refreshed from that buffer, we
construct thenext frame in the other buffer.
 When that frame is complete, we switch the roles of the two
buffers sothatthe refresh routines use the second buffer during the process of creating the
next frame in the first buffer.
 When a call is made to switch two refresh buffers, the
interchange could be performed at various times.
 The most straight forward implementation is to switch
the two bufersat the end of the current refresh cycle, during the vertical retrace of the
electron beam.
 If a program can complete the construction of a frame
within the time of a refresh cycle, say 1/60 of a second, each motion sequence is
displayed in synchronization with the screen refresh rate.
 If the time to construct a frame is longer than the refresh time,
the curentframe is displayed for two or more refresh cycles while the next animation
frame is being generated.

2
Module 5 Computer Animation

 Similarly, if the frame construction time is 1/25 of a second, the


animationframerate is reduced to 20 frames per second because each frame is displayed three
times.
 Irregular animation frame rates can occur with double buffering
when theframeconstruction time is very nearly equal to an integer multiple of the screen
refresh time the animation frame rate can change abruptly and erratically.
 One way to compensate for this effect is to add a small time delay to the
program.
 Another possibility is to alter the motion or scene
description to shortenthe frame construction time.

Generating Animations Using Raster Operations


 We can also generate real-time raster animations for limited applications using
blocktransfers of a rectangular array of pixel values.
 A simple method for translating an object from one location to another in the xy plane
si to transfer the group of pixel values that define the shape of the object to the new
location
 Sequences of raster operations can be executed to produce realtime animation for either
two-dimensional or three-dimensional objects, so long as we restrict the animation to
motions in the projection plane.
 Then no viewing or visible-surface algorithms need be invoked.
 We can also animate objects along two-dimensional motion paths using color
tabletransformations.
 Here we predefine the object at successive positions along the motion path and
set thesuccessive blocks of pixel values to color-table entries.
 The pixels at the first position of the object are set to a foreground color, and the
pixels atthe other object positions are set to the background color .
 Then the animation is then accomplished by changing the color-table values so that the
object color at successive positions along the animation path becomes the foreground
color as the preceding position is set to the background color

5.3.2 Design of Animation Sequences


 Animation sequence in general is designed in the following steps.
3
Module 5 Computer Animation

Storyboard layout
Object definitions.
Key-frame specifications
Generation of in-between frames.
 This approach of carrying out animations is applied to any other applications as
wel,although some applications are exceptional cases and do not follow this sequence.
 For frame-by-frame animation, every frame of the display or scene is generated
separately and stored. Later, the frame recording can be done and they might be displayed
consecutively in terms of movie.
 The outline of the action is storyboard. This explains the motion sequence. The
storyboard consists of a set of rough structures or it could be a list of the basic ideas for
the motion.
 For each participant in the action, an object definition is given. Objects are described ni
terms of basic shapes the examples of which are splines or polygons. The related
movement associated with the objects are specified along with the shapes.
 A key frame in animation can be defined as a detailed drawing of the scene at a certain
time in the animation sequence. Each object is positioned according to the time for that
frame, within each key frame.
 Some key frames are selected at extreme positions and the others are placed so that
thetime interval between two consecutive key frames is not large. Greater number of key
frames are specified for smooth motions than for slow and varying motion.
 And the intermediate frames between the key frames are In-betweens. And the
Media thatwe use determines the number of In-betweens which are required to display
the animation. A Film needs 24 frames per second, and graphics terminals are refreshed at
the rate of 30 to 60 frames per second.
 Depending on the speed specified for the motion, some key frames are duplicated. Fora
one minutes film sequence with no duplication, we would require 288 key frames. We
place the key frames a bit distant if the motion is not too complicated.
 A number of other tasks may be carried out depending upon the application
requirementfor example synchronization of a sound track.

4
Module 5 Computer Animation

5.3.3 Traditional Animation Techniques


 Film animators use a variety of methods for depicting and emphasizing
motionsequences.
 These include object deformations, spacing between animation frames,
motionanticipation and follow-through, and action focusing

 One of the most important


techniques forsimulating acceleration effects,
particularly for non rigid objects, is squash
and stretch.
 Figure shows how this technique is used
to emphasize the acceleration and deceleration
of a bouncing ball. As the ball accelerates,
it begins to stretch. When the ball hits
the floor and stops, it is first compressed
(squashed) and then stretched again as it accelerates and bounces upwards.

 Another technique used by film animators is


timing, which refers to the spacing between
motion frames. A slower moving object is
represented with more closely spaced frames, and
a faster moving object is displayed with fewer
frames over the path of the motion.

 Object movements can also be emphasized by creating preliminary actions that


indicatean anticipation of a coming motion

5.3.4 General Computer-Animation Functions


 Typical animation functions include managing object motions, generating
views ofobjects, producing camera motions, and the generation of in-between frames

5
Module 5 Computer Animation

 Some animation packages, such as Wavefront for example, provide special


functions forboth the overall animation design and the processing of individual objects.
 Others are special-purpose packages for particular features of an animation,
such asasystem for generating in-between frames or a system for figure animation.
 A set of routines is often provided in a general animation package for storing and
managing the object database. Object shapes and associated parameters are stored and
updated in the database. Other object functions include those for generating the object
motion and those for rendering the object surfaces
 Another typical function set simulates camera movements. Standard camera motions
arezooming, panning, and tilting. Finally, given the specification for the key frames, the in-
betweens can be generated automatically.

5.3.5 OpenGL Animation Procedures


 Double-buffering operations, if available, are activated using the
following G
L
UTcommand:
glutInitDisplayMode (GLUT_DOUBLE);
 This provides two buffers, called the front buffer and the back
buffer, that we can use alternately to refresh the screen display
 We specify when the roles of the two buffers are to be
interchanged using glutSwapBuffers ( );
 To determine whether double-buffer operations are available on a system,
we can issue the following query:
glGetBooleanv (GL_DOUBLEBUFFER, status);
 A value of GL_TRUE is returned to array parameter status if both
front and back buffers are available on a system. Otherwise, the returned value is GL
_FALSE.
 For a continuous animation, we can also use
glutIdleFunc (animationFcn);
 This procedure is continuously executed whenever there are no
display-window events that must be processed.
 To disable the glutIdleFunc, we set its argument to the value
NULL or the value 0.

6
Module 5 Computer Animation

Example Program
#include <GL/glut.h>
#include <math.h>
#include <stdlib.h>

const double TWO_PI = 6.2831853;


GLsizei winWidth = 500, winHeight = 500; // Initial display window size.
GLuint regHex; // Define name for display list.
static GLfloat rotTheta = 0.0;

class scrPt {
public:
GLint x, y;
};
static void init (void)
{
scrPt hexVertex;
GLdouble hexTheta;
GLint k;
glClearColor (1.0, 1.0, 1.0, 0.0);
/* Set up a display list for a red regular hexagon.
9. Vertices for the hexagon are six equally spaced
10. points around the circumference of a circle.
*/
regHex = glGenLists (1);
glNewList (regHex, GL_COMPILE);
glColor3f (1.0, 0.0, 0.0);
glBegin (GL_POLYGON);
for (k = 0; k < 6; k++) {
hexTheta = TWO_PI * k / 6;

7
Module 5 Computer Animation

hexVertex.x = 150 + 100 * cos (hexTheta);


hexVertex.y = 150 + 100 * sin (hexTheta);
glVertex2i (hexVertex.x, hexVertex.y);
}
glEnd ( );
glEndList ( );
}
void displayHex (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glPushMatrix ( );
glRotatef (rotTheta, 0.0, 0.0, 1.0);
glCallList (regHex);
glPopMatrix ( );
glutSwapBuffers ( );
glFlush ( );
}
void rotateHex (void)
{
rotTheta += 3.0;
if (rotTheta > 360.0)
rotTheta -= 360.0;
glutPostRedisplay ( );
}
void winReshapeFcn (GLint newWidth, GLint newHeight)
{
glViewport (0, 0, (GLsizei) newWidth, (GLsizei)
newHeight); glMatrixMode (GL_PROJECTION);
glLoadIdentity ( );
gluOrtho2D (-320.0, 320.0, -320.0, 320.0);
glMatrixMode (GL_MODELVIEW);

8
Module 5 Computer Animation

glLoadIdentity ( );
glClear (GL_COLOR_BUFFER_BIT);
}
void mouseFcn (GLint button, GLint action, GLint x, GLint y)
{
switch (button) {
case GLUT_MIDDLE_BUTTON: // Start the rotation.
if (action == GLUT_DOWN)
glutIdleFunc (rotateHex);
break;
case GLUT_RIGHT_BUTTON: // Stop the rotation.
if (action == GLUT_DOWN)
glutIdleFunc (NULL);
break;
default:
break;
}
}
void main(int argc, char ** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE |
GLUT_RGB); glutInitWindowPosition (150, 150);
glutInitWindowSize (winWidth, winHeight);
glutCreateWindow ("Animation Example"); init ( );

glutDisplayFunc (displayHex);
glutReshapeFunc (winReshapeFcn);
glutMouseFunc (mouseFcn);
glutMainLoop ( );
}

9
5.3.6 QUESTIONS

1. Explain the different types of physical input devices?


2. Explain the 6 classes of logical input devices?
3. Explain the different input modes?
4. What are display lists. Explain with suitable example?
5. Explain the event driven input?
6. What is picking, explain picking in selection mode?
7. Write an openGL program to animate/rotate a square?
8. Explain drawing erasable lines using XOR mode writing?
9. Explain drawing erasable lines using XOR mode writing?
10. Explain quadratic surfaces and give their equation representation?
11. Explain Traditional animation techniques?
12. What is computer animation, Explain the various stages in the development of
animation?

You might also like