CGV M5
CGV M5
5.1.1INTERACTION
In the field of computer graphics, interaction refers to the manner in
VTUPulse.com
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.
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
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.
VTUPulse.com
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.
2. 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.
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:
VTUPulse.com
These devices are relative positioning devices because changes in the
position of the ball yield a position in the user program.
3
Module 5 Input and Interaction
The major disadvantage is that it has the difficulty in obtaining a position that
corresponds to a dark area of the screen
VTUPulse.com
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.
4
Module 5 Input and Interaction
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.
VTUPulse.com
the position of the user and so on.
5
Module 5 Input and Interaction
These are logical functions that are defined by how they handle input or
output 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:
1. 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.
2. 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.
3.
VTUPulse.com
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.
4. 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
6
Module 5 Input and Interaction
INPUT MODES
The application program can obtain the measure and trigger in three distinct
modes:
VTUPulse.com
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
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.
VTUPulse.com
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.
8
Module 5 Input and Interaction
within a single system. Today most of the computing is done in the form
of distributed based and network based as shown below:
VTUPulse.com
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
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”.
VTUPulse.com
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:
10
Module 5 Input and Interaction
2. 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.
VTUPulse.com
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)
VTUPulse.com
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
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
VTUPulse.com
degraded for the applications that require large quantity of text.
A more efficient strategy is to define the font once, using a display list for
each 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
VTUPulse.com
}
FONTS IN GLUT
GLUT provides raster and stroke fonts; they do not make use of display
lists.
14
Module 5 Input and Interaction
VTUPulse.com
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
VTUPulse.com
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:
1. 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.
#include<stdio.h>
#include<stdlib.h>
#include<GL/glut.h>
int wh=500, ww=500;
float siz=3;
void myinit()
{
VTUPulse.com
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);
}
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);
}
} VTUPulse.com exit(0);
18
Module 5 Input and Interaction
KEYBOARD EVENTS
Keyboard devices are input devices which return the ASCII value to the
user 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:
{ VTUPulse.com
void mykey(unsigned char key, int x, int y)
The above code ensures when ‘Q’ or ‘q’ key is pressed, the execution of
the program gets terminated.
19
Module 5 Input and Interaction
WINDOW EVENTS
VTUPulse.com
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;
}
20
Module 5 Input and Interaction
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);
VTUPulse.com
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:
1. Define the actions corresponding to each entry in the menu.
2. Link the menu to a corresponding mouse button.
3. Register a callback function for each entry in the menu.
21
Module 5 Input and Interaction
VTUPulse.com
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
O Selection:
VTUPulse.com
O Usage of back buffer and extra rendering:
23
Module 5 Input and Interaction
O We draw the objects into back buffer with the pick colors.
O We get the position of the mouse using the mouse callback.
O Use glReadPixels() to find the color at the position in the frame
buffer corresponding to the mouse position.
O We search table of colors to find the object corresponds to the color
read.
VTUPulse.com
O
O
void glSelectBuffer(GLsizei n, GLuint *buff) : specifies array
buffer of size ‘n’ in which to place selection data.
void glInitNames() : initializes the name stack.
O void glPushName(GLuint name) : pushes name on the name
stack.
O void glPopName() : pops the top name from the name stack.
O void glLoadName(GLuint name) : replaces the top of the name
stack with name.
24
Module 5 Input and Interaction
(a) 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.
(b) It shows window and display after the window has been changed by
gluPickMatrix.
#include<glut.h>
VTUPulse.com
25
Module 5 Input and Interaction
VTUPulse.com
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);
}
VTUPulse.com
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();
}
VTUPulse.com
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.
Refer appendix A.5 polygon modeling program for the entire code from the
28
Module 5 Input and Interaction
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
VTUPulse.com
O
object as specified in the bounding box and then set its type to 0.
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.
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:
VTUPulse.com
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:
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.
VTUPulse.com
DOUBLE BUFFERING:
31
Module 5 Input and Interaction
USING TIMER:
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.
VTUPulse.com
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.
32
Module 5 Input and Interaction
VTUPulse.com
When program specifies about visible primitive then OpenGL renders it
into set of color pixels and stores it in the present drawing buffer.
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
VTUPulse.com
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:
VTUPulse.com
In this example, we draw rectangle using same concept and the code for
callback function are given below:
35
Module 5 Input and Interaction
VTUPulse.com
36
Module 5 Input and Interaction
After that each time that we get vertex, we first erase the existing
rectangle by redrawing new rectangle using new vertex.
VTUPulse.com
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
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.
VTUPulse.com
38
Module 5 Input and Interaction
VTUPulse.com
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
VTUPulse.com
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
1. 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
x = r cos φ cos θ, − π/2 ≤ φ ≤ π/2
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 φ
VTUPulse.com
3. Torus
A torus is a doughnut-shaped object, as shown in fig. below.
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
x = (raxial + r cos φ) cos θ, − π ≤ φ ≤ π
y = (raxial + r cos φ) sin θ, − π ≤ θ ≤ π
z = r sin φ
We could also generate a torus by rotating an ellipse, instead of a circle, about the z axis.
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
VTUPulse.com
is
The corresponding parametric representation for the torus with an elliptical crosssection
4
Module 5 Curves
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 approximate
the sphere.
Cone
Function:
glutWireCone (rBase, height, nLongitudes, nLatitudes);
VTUPulse.com
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 of
orthogonal 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
VTUPulse.com
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 display
mode 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
VTUPulse.com
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 the
world-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);
VTUPulse.com
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
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);
VTUPulse.com
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
}
VTUPulse.com
glClear (GL_COLOR_BUFFER_BIT);
10
Module 5 Curves
VTUPulse.com
The Bézier blending functions BEZk,n(u) are the Bernstein polynomials
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).
VTUPulse.com
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
}
VTUPulse.com
glEnd ( );
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;
VTUPulse.com
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
}
VTUPulse.com
gluOrtho2D (xwcMin, xwcMax, ywcMin,
ywcMax); glClear (GL_COLOR_BUFFER_BIT);
glutDisplayFunc (displayFcn);
glutReshapeFunc (winReshapeFcn);
glutMainLoop ( );
}
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
VTUPulse.com
(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
VTUPulse.com
the preceding section
If the first curve section has n control points and the next curve section has n’ control
points, then we match curve tangents by placing control point p1’ at the position
17
Module 5 Curves
Plots of the four cubic Bézier blending functions are given in Figure
VTUPulse.com
At the end positions of the cubic Bézier curve, the parametric first derivatives (slopes) are
A matrix formulation for the cubic-Bézier curve function is obtained by expanding the
polynomial expressions for the blending functions and restructuring the equations as
18
Module 5 Curves
VTUPulse.com
dashed 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 fixed
at 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 convenient
method for interactive design applications.
To specify the threedimensional coordinate positions for the control points, we could first
construct 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 the z-
coordinate values for the control points.
VTUPulse.com
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 algorithms
with respect to line drawing and circle drawing.
20
Module 5 Curves
VTUPulse.com
beginning of one coordinate position in array ctrlPts and the beginning of the next
coordinate position
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);
glEnd ( );
glEvalCoord1f (u1 + k * (u2 - u1) / n);
22
Module 5 Curves
which maps each of uValue and vValue to the interval from 0 to 1.0
VTUPulse.com
GLU B-Spline Curve Functions
Although the GLU B-spline routines are referred to as NURBs functions, they can be used
to 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 calls
to the following GLU function:
gluNurbsProperty (splineName, property, value);
VTUPulse.com
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 query
function:
gluGetNurbsProperty (splineName, property, value);
When the property GLU_AUTO_LOAD_MATRIX is set to the value GL_FALSE, we
invoke
gluLoadSamplingMatrices (splineName, modelviewMat, projMat, viewport);
Various events associated with spline objects are processed using
gluNurbsCallback (splineName, event, fcn);
24
Module 5 Curves
VTUPulse.com
25
Module 5 ***SAI RAM*** Curves
VTUPulse.com
26
Module 5 Curves
VTUPulse.com
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
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.
VTUPulse.com
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
1. 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.
2. 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
Double Buffering
One method for producing a real-time animation with a raster system is to employ two
refresh buffers.
We create a frame for the animation in one of the buffers.
VTUPulse.com
Then, while the screen is being refreshed from that buffer, we construct the next frame in
the other buffer.
When that frame is complete, we switch the roles of the two buffers so that the 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 buffers at 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 current frame 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 animation frame rate is
reduced to 20 frames per second because each frame is displayed three times.
Irregular animation frame rates can occur with double buffering when the frame
construction 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 shorten the frame
construction time.
VTUPulse.com
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 table
transformations.
Here we predefine the object at successive positions along the motion path and set the
successive 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 at
the 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
3
Module 5 Computer Animation
1. Storyboard layout
2. Object definitions.
3. Key-frame specifications
4. Generation of in-between frames.
This approach of carrying out animations is applied to any other applications as well,
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 in
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
VTUPulse.com
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 the
time 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 that
we 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. For a
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 requirement
for example synchronization of a sound track.
4
Module 5 Computer Animation
VTUPulse.com
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 indicate
an anticipation of a coming motion
5
Module 5 Computer Animation
Some animation packages, such as Wavefront for example, provide special functions for
both the overall animation design and the processing of individual objects.
Others are special-purpose packages for particular features of an animation, such as a
system 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 are
zooming, panning, and tilting. Finally, given the specification for the key frames, the in-
betweens can be generated automatically.
VTUPulse.com
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>
class scrPt {
public:
GLint x, y;
};
static void init (void)
{
VTUPulse.com
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.
* Vertices for the hexagon are six equally spaced
* 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
VTUPulse.com
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;
}
VTUPulse.com
}
glutDisplayFunc (displayHex);
glutReshapeFunc (winReshapeFcn);
glutMouseFunc (mouseFcn);
glutMainLoop ( );
}