CG Unit - Iii
CG Unit - Iii
Color Models – RGB, YIQ, CMY, HSV – Animations – General Computer Animation,
Raster, Keyframe - Graphics programming using OPENGL – Basic graphics primitives –
Drawing three dimensional objects - Drawing three dimensional scenes
1. COLOR MODELS
Color Model is a method for explaining the properties or behavior of color within some
particular context. No single color model can explain all aspects of color, so we make use of
different models to help describe the different perceived characteristics of color.
Properties of Light
Light is a narrow frequency band within the electromagnetic system.
Other frequency bands within this spectrum are called radio waves, micro waves, infrared waves
and x-rays. The below fig shows the frequency ranges for some of the electromagnetic bands.
Each frequency value within the visible band corresponds to a distinct color.
At the low frequency end is a red color (4.3*10 14 Hz) and the highest frequency is a violet color
(7.5 *1014Hz)
Spectral colors range from the reds through orange and yellow at the low frequency end to
greens, blues and violet at the high end.
Since light is an electro magnetic wave, the various colors are described in terms of either the
frequency for the wave length λ of the wave.
The wave length ad frequency of the monochromatic wave are inversely proportional to each
other, with the proportionality constants as the speed of light C where C = λ f
A light source such as the sun or a light bulb emits all frequencies within the visible range to
produce white light. When white light is incident upon an object, some frequencies are reflected
and some are absorbed by the object. The combination of frequencies present in the reflected
light determines what we perceive as the color of the object.
If low frequencies are predominant in the reflected light, the object is described as red. In this
case, the perceived light has the dominant frequency at the red end of the spectrum. The
dominant frequency is also called the hue, or simply the color of the light.
Intensity in the radiant energy emitted per limit time, per unit solid angle, and per unit projected
area of the source.
Two different color light sources with suitably chosen intensities can be used to produce a range
of other colors.
If the 2 color sources combine to produce white light, they are called complementary colors.
E.g., Red and Cyan, green and magenta, and blue and yellow.
Color models that are used to describe combinations of light in terms of dominant frequency use
3 colors to obtain a wide range of colors, called the color gamut.
The 2 or 3 colors used to produce other colors in a color model are called primary colors.
2. STANDARD PRIMARIES
Cλ = XX + YY + ZZ-------------(1)
Where X,Y and Z designates the amounts of the standard primaries needed to match Cλ.
Any color can be represented with just the x and y amounts. The parameters x and y are called
the chromaticity values because they depend only on hue and purity.
If we specify colors only with x and y, we cannot obtain the amounts X, Y and Z. so, a complete
description of a color in given with the 3 values x, y and Y.
X = (x/y)Y, Z = (z/y)Y Where z = 1-x-y.
Starting with the pigment for a „pure color‟ the color is added to black pigment to produce
different shades. The more black pigment produces darker shades.
Different tints of the color are obtained by adding a white pigment to the original color, making
it lighter as more white is added.
Tones of the color are produced by adding both black and white pigments.
These visual pigments have a peak sensitivity at wavelengths of about 630 nm (red), 530 nm
(green) and 450 nm (blue).
This is the basis for displaying color output on a video monitor using the 3 color primaries, red,
green, and blue referred to as the RGB color model. It is represented in the below figure.
The sign represents black, and the vertex with coordinates (1,1,1) in white.
Vertices of the cube on the axes represent the primary colors, the remaining vertices represents
the complementary color for each of the primary colors.
The RGB color scheme is an additive model. (i.e.,) Intensities of the primary colors are added to
produce other colors.
Each color point within the bounds of the cube can be represented as the triple (R,G,B) where
values for R, G and B are assigned in the range from 0 to1.
Shades of gray are represented along the main diagonal of the cube from the origin (black) to the
white vertex.
The National Television System Committee (NTSC) color model for forming the composite
video signal in the YIQ model.
In the YIQ color model, luminance (brightness) information in contained in the Y parameter,
chromaticity information (hue and purity) is contained into the I and Q parameters.
A combination of red, green and blue intensities are chosen for the Y parameter to yield the
standard luminosity curve.
Since Y contains the luminance information, black and white TV monitors use only the Y signal.
Parameter I contain orange-cyan hue information that provides the flash-tone shading and
occupies a bandwidth of 1.5 MHz.
An RGB signal can be converted to a TV signal using an NTSC encoder which converts RGB
values to YIQ values, as follows
An NTSC video signal can be converted to an RGB signal using an NTSC encoder which
separates the video signal into YIQ components, the converts to RCB values, as follows:
It is a subtractive color model (i.e.,) cyan can be formed by adding green and blue light. When
white light is reflected from cyan-colored ink, the reflected light must have no red component.
i.e., red light is absorbed or subtracted by the link.
Magenta ink subtracts the green component from incident light and yellow subtracts the blue
component.
In CMY model, point (1,1,1) represents black because all components of the incident light are
subtracted.
Equal amounts of each of the primary colors produce grays along the main diagonal of the cube.
A combination of cyan and magenta ink produces blue light because the red and green
components of the incident light are absorbed.
The printing process often used with the CMY model generates a color point with a collection of
4 ink dots; one dot is used for each of the primary colors (cyan, magenta and yellow) and one dot
in black.
= -
Where the white is represented in the RGB system as the unit column vector.
Where black is represented in the CMY system as the unit column vector.
Color parameters in this model are hue (H), saturation (S), and value (V).
The 3D representation of the HSV model is derived from the RGB cube. The outline of the cube
has the hexagon shape.
The boundary of the hexagon represents the various hues, and it is used as the top of the HSV
hexcone.
In the hexcone, saturation is measured along a horizontal axis, and value is along a vertical axis
through the center of the hexcone.
Hue is represented as an angle about the vertical axis, ranging from 00 at red through 3600.
Vertices of the hexagon are separated by 600 intervals.
Yellow is at 600, green at 1200 and cyan opposite red at H = 1800. Complementary colors are
1800 apart.
Saturation S varies from 0 to 1. the maximum purity at S = 1, at S = 0.25, the hue is said to be
one quarter pure, at S = 0, we have the gray scale.
Another model based on intuitive color parameters is the HLS system used by Tektronix. This
model has the double-cone representation. The three color parameters in this model are called
hue (H), lightness (L), and saturation 6).
Hue has the same meaning as in the HSV model. It specifies an angle about the vertical
axis that locates a chosen hue. In this model, H = 0' corresponds to blue. The remaining colors
are specified around the perimeter of the cone in the same order as in the HSV model. Magenta
is at 60•‹. red is at 120•‹, and cyan is located at H = 180". Again, complementary colors are 180"
apart on the double cone.
3. ANIMATION
Computer animation refers to any time sequence of visual changes in a scene. Computer
animations can also be generated by changing camera parameters such as position, orientation
and focal length. Applications of computer-generated animation are entertainment, advertising,
training and education.
Example : Advertising animations often transition one object shape into another.
Frame-by-Frame animation Each frame of the scene is separately generated and stored. Later,
the frames can be recoded on film or they can be consecutively displayed in "real-time playback"
mode.
Design of Animation Sequences An animation sequence in designed with the following steps:
Story board
The story board is an outline of the action.
It defines the motion sequences as a set of basic events that are to take place.
Depending on the type of animation to be produced, the story board could consist of a set of
rough sketches or a list of the basic ideas for the motion.
Object Definition
An object definition is given for each participant in the action.
Objects can be defined in terms of basic shapes such as polygons or splines.
The associated movements of each object are specified along with the shape.
Key frame
A key frame is detailed drawing of the scene at a certain time in the animation sequence.
Within each key frame, each object is positioned according to the time for that frame.
Some key frames are chosen at extreme positions in the action; others are spaced so that the time
interval between key frames is not too much.
In-betweens
In betweens are the intermediate frames between the key frames.
The number of in between needed is determined by the media to be used to display the
animation.
Film requires 24 frames per second and graphics terminals are refreshed at the rate of 30 to 60
frames per seconds.
Time intervals for the motion are setup so there are from 3 to 5 in-between for each pair of key
frames.
Depending on the speed of the motion, some key frames can be duplicated.
For a 1 min film sequence with no duplication, 1440 frames are needed.
Other required tasks are
- Motion verification
- Editing
- Production and synchronization of a sound track.
Animation packages such as wave front provide special functions for designing the animation
and processing individuals objects.
Animation packages facilitate to store and manage the object database.
Object shapes and associated parameter are stored and updated in the database.
Motion can be generated according to specified constraints using 2D and 3D transformations.
Standard functions can be applied to identify visible surfaces and apply the rendering algorithms.
Camera movement functions such as zooming, panning and tilting are used for motion
simulation.
Given the specification for the key frames, the in-betweens can be automatically generated.
3.2. Raster Animations
On raster systems, real-time animation in limited applications can be generated using raster
operations.
Sequence of raster operations can be executed to produce real time animation of either 2D or 3D
objects.
We can animate objects along 2D motion paths using the color-table transformations.
- Predefine the object as successive positions along the motion path, set the successive
blocks of pixel values to color table entries.
- Set the pixels at the first position of the object to „on‟ values, and set the pixels at the
other object positions to the background color.
- The animation is accomplished by changing the color table values so that the object is
„on‟ at successive positions along the animation path as the preceding position is set to the
background intensity.
The graphics editor allows designing and modifying object shapes, using spline surfaces,
constructive solid geometry methods or other representation schemes.
Scene description includes the positioning of objects and light sources defining the photometric
parameters and setting the camera parameters.
Action specification involves the layout of motion paths for the objects and camera.
Keyframe systems are specialized animation languages designed dimply to generate the in-
betweens from the user specified keyframes.
Parameterized systems allow object motion characteristics to be specified as part of the object
definitions. The adjustable parameters control such object characteristics as degrees of freedom
motion limitations and allowable shape changes.
Scripting systems allow object specifications and animation sequences to be defined with a user
input script. From the script, a library of various objects and motions can be constructed.
3.4.1. Morphing
Transformation of object shapes from one form to another is called Morphing.
Morphing methods can be applied to any motion or transition involving a change in shape. The
example is shown in the below figure.
An edge with vertex positions 1 and 2 in key frame k evolves into two connected edges in key frame k + 1
Linear interpolation for transforming a line segment in key frame k into two connected line segments in key
frame k + 1.
The general preprocessing rules for equalizing keyframes in terms of either the number of
vertices to be added to a keyframe.
Suppose we equalize the edge count and parameters Lk and Lk+1 denote the number of line
segments in two consecutive frames. We define,
Lmax = max (Lk, Lk+1)
Lmin = min(Lk , Lk+1)
Ne = Lmax mod Lmin
Ns = int (Lmax/Lmin)
For example, if Lk = 15 and Lk+1 = 11, we divide 4 lines of keyframek+1 into 2 sections each.
The remaining lines of keyframek+1 are left infact.
If the vector counts in equalized parameters V k and Vk+1 are used to denote the number of
vertices in the two consecutive frames. In this case we define
Vmax = max(Vk,Vk+1), Vmin = min( Vk,Vk+1)
Nls = (Vmax -1) mod (Vmin – 1)
Np = int ((Vmax – 1)/(Vmin – 1 ))
OpenGL is a software interface that allows you to access the graphics hardware without
taking care of the hardware details or which graphics adapter is in the system. OpenGL is a low-
level graphics library specification. It makes available to the programmer a small set of
geometric primitives - points, lines, polygons, images, and bitmaps. OpenGL provides a set of
commands that allow the specification of geometric objects in two or three dimensions, using the
provided primitives, together with commands that control how these objects are rendered
(drawn).
Every graphics program begins with some initializations that establish the desired display
mode and set up a coordinate system for specifying points, lines etc.
Graphics commands use a coordinate system that is attached to the window,
Some elementary drawing tools used are setPixel (x,y,col) ,which sets the individual pixel at
location (x, y) to the color specified by col.
To draw a straight line the command used is line (x1, y1, x2, y2) which draws a line between
(x1, y1) and (x2, y2)
GLU provides functions for drawing more complex primitives than those of OpenGL such as
curves and surfaces and also functions to help specify 3D views of scenes. All GLU function
names start with “glu”
GLUT provides the facilities for interaction that the OpenGL lacks. It provides functions for
managing windows on the display screen and handling input events from the mouse and
keyboard. All GLUT function names start with “glut”
Include Files
For all OpenGL applications, you want to include the gl.h header file in every file. Almost all
OpenGL applications use GLU, the aforementioned OpenGL Utility Library, which also requires
inclusion of the glu.h header file. So almost every OpenGL source file begins with:
#include <GL/gl.h>
#include <GL/glu.h>
If you are using the OpenGL Utility Toolkit (GLUT) for managing your window manager
tasks, you should include:
#include <GL/glut.h>
The following files must be placed in the proper folder to run a OpenGL Program
1. glutInit(&argc, argv)
The first thing we need to do is call the glutInit() procedure. It should be called before
any other GLUT routine because it initializes the GLUT library. The parameters to glutInit()
should be the same as those to main(), specifically main(int argc, char** argv) and
glutInit(&argc, argv).
2. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
The next thing we need to do is call the glutInitDisplayMode() procedure to specify the
display mode for a window. We must first decide whether we want to use an RGBA
(GLUT_RGB) or color-index (GLUT_INDEX) color model. The RGBA mode stores its color
buffers as red, green, blue, and alpha color components. Color-index mode, in contrast, stores
color buffers in indicates. And for special effects, such as shading, lighting, and fog, RGBA
mode provides more flexibility. In general, use RGBA mode whenever possible. RGBA mode is
the default.
3. glutInitWindowSize(640,480)
A call to glutInitWindowSize() will be used to specify the size, in pixels, of our inital
window. The arguments indicate the height and width (in pixels) of the requested window.
4. glutInitWindowPosition(100,15)
A glutInitWindowPosition() is used to specify the screen location for the upper-left
corner of our initial window. The arguments, x and y, indicate the location of the window
relative to the entire display. This function positioned the screen 100 pixels over from the left
edge and 150 pixels down from the top.
5. glutCreateWindow(“Example”)
The command takes a string as a parameter which may appear in the title bar.
6. glutMainLoop()
The window is not actually displayed until the glutMainLoop() is entered. The very last
thing is we have to call this function
The method of associating a call back function with a particular type of event is called as
event driven programming. OpenGL provides tools to assist with the event management. There
are four Glut functions available
[Link](mydisplay)
The glutDisplayFunc() procedure is the first and most important event callback function.
the function that is called whenever GLUT determines that the contents of the window needs to
be redisplayed. Therefore, we should put all the routines that you need to draw a scene in this
display callback function.
2. glutReshapeFunc(myreshape)
The glutReshapeFunc() is a callback function that specifies the function that is called
whenever the window is resized or moved.
3. glutKeyboardFunc(mykeyboard)
GLUT interaction using keyboard inputs is handled. The command glutKeyboardFunc()
is used to run the callback function specified and pass as parameters, the ASCII code of the
pressed key, and the x and y coordinates of the mouse cursor at the time of the event.
GLUT_KEY_UP Up Arrow
GLUT_KEY_RIGHT Right Arrow
GLUT_KEY_DOWN Down Arrow
GLUT_KEY_PAGE_UP Page Up
GLUT_KEY_PAGE_DOWN Page Down
GLUT_KEY_HOME Home
GLUT_KEY_END End
GLUT_KEY_INSERT Insert
4. glutMouseFunc(mymouse)
GLUT supports interaction with the computer mouse that is triggered when one of the
three typical buttons is presses. This buttons are defined as either GL_LEFT_BUTTON,
GL_RIGHT_BUTTON, or GL_MIDDLE_BUTTON and the states for that button are either
GLUT_DOWN (when pressed) or GLUT_UP (when released). Finally, x and y callback
parameters indicate the location (in window-relative coordinates) of the mouse at the time of the
event.
OPENGL provides tools for drawing all the output primitives such as points, lines,
polylines, and polygons. To draw such objects using OPENGL must pass a list of vertices. The
list occurs between the two OPENGL function calls glBegin() and glEnd().
Every time to draw a primitive on the screen first call glBegin specifying what kind of primitive
to draw in the mode parameter of glBegin and then list all the vertices one by one and finally
call glEnd to tell that drawing picture is over.
My First Attempt
The above figure shows 3 points drawn in a window 640 pixels wide and 480 pixels high
glBegin(GL_POINTS);
glVertex2i(100, 50);
glVertex2i(100, 130);
glVertex2i(150, 130);
glEnd( );
glvertex2f(100.0f, 150.0f)-defines a point at x=100 y=150 z=0. This function takes only two
parameters z is always 0. Glvertex2f can be used in special cases and won’t be used a lot unless
you’re working pseudo 2D sprites or triangles and points that always have to be constrained by
the depth coordinate.
OpenGl keeps track of many state variables, such as current size of a point, the current
color of a drawing, the current background color, etc.
The value of a state variable remains active until new value is given.
glPointSize() : The size of a point can be set with glPointSize(), which takes one floating point
argument
Example : glPointSize(4.0);
glColor3f() : establishes to use for drawing objects. All objects drawn after this point use this
color, until it‟s changed with another call to set the color.
Example:
glColor3f(0.0, 0.0, 0.0); //black
glColor3f(1.0, 0.0, 0.0); //red
glColor3f(0.0, 1.0, 0.0); //green
glColor3f(1.0, 1.0, 0.0); //yellow
glFlush() : ensures that the drawing commands are actually executed rather than stored in a
buffer awaiting (ie) Force all issued OpenGL commands to be executed
myInit() function is used to set up the coordinate system. OPENGL routinely perfoms large
number of transformation which uses matrices.
OpenGL supports three types of geometric primitives: points, line segments, and closed
polygons.
POINTS
GL_POINTS: Each vertex defines a point
glpointsize can be used to set the size
void glPointSize (GLfloat sizeInPixels)// where size is measured in pixels with default of 1.0
LINE SEGMENTS
Three types
GL_LINES: Each successive pair of vertices specifies a line segment.
GL_LINE_STRIP: First pair of vertices specifies the first line segment. The end point of the
previous line segment and the next vertex from the next segment and so on.
GL_LINE_LOOP: Similar to GL_LINE_STRIP except that the last vertex is joined to the first
vertex to form a closed loop.
CLOSED POLYGONS
There are 6 filled polygonal primitives
GL_POLYGON: The vertices form one closed polygon.
In OpenGL a polyline is called a “line strip”, and is drawn by specifying the vertices in turn
between glBegin(GL_LINE_STRIP) and glEnd().
For example, the code:
// draw a rectangle with opposite corners (x1, y1) and (x2, y2);
// fill it with the current color;
glClearColor(1.0,1.0,1.0,0.0); // white background
glClear(GL_COLOR_BUFFER_BIT); // clear the window
glColor3f(0.6,0.6,0.6); // bright gray
glRecti(20,20,100,70);
glColor3f(0.2,0.2,0.2); // dark gray
glRecti(70, 50, 150, 130);
aspect ratio = width/height;
5.7. Polygons
Polygons are the areas enclosed by single closed loops of line segments, where the line
segments are specified by the vertices at their endpoints. Polygons are typically drawn by filling
in all the pixels enclosed within the boundary, but you can also draw them as outlined polygons
or simply as points at the vertices. A filled polygon might be solidly filled, or stippled with a
certain pattern.
OpenGL also supports filling more general polygons with a pattern or color. To draw a
convex polygon based on vertices (x0, y0), (x1, y1), …, (xn, yn) use the usual list of vertices,
But place them between a glBegin(GL_POLYGON) and an glEnd():
glBegin(GL_POLYGON);
glVertex2f(x0, y0);
glVertex2f(x1, y1);
. . . . ..
glVertex2f(xn, yn);
glEnd();
The following list explains the function of each of the five constants:
GL_TRIANGLES: takes the listed vertices three at a time, and draws a separate triangle for
each;
GL_QUADS: takes the vertices four at a time and draws a separate quadrilateral for each
GL_TRIANGLE_STRIP: draws a series of triangles based on triplets of vertices: v0, v1, v2,
then v2, v1, v3, then v2, v3, v4, etc. (in an order so that all triangles are “traversed” in the same
way;e.g. counterclockwise).
glutMouseFunc(myMouse) which registers myMouse() with the event that occurs when the
mouse button is pressed or released;
glutMotionFunc(myMovedMouse) which registers myMovedMouse() with the event that
occurs when the mouse is moved while one of the buttons is pressed;
glutKeyboardFunc(myKeyboard) which registers myKeyBoard() with the event that occurs
when a keyboard key is pressed.
Mouse interaction
with the obvious interpretation, and the value of state will be one of: GLUT_UP or
GLUT_DOWN. The values x and y report the position of the mouse at the time of the event.
Keyboard interaction
As mentioned earlier, pressing a key on the keyboard queues a keyboard event. The
callback function myKeyboard() is registered with this type of event through
glutKeyboardFunc(myKeyboard).
It must have prototype: void myKeyboard(unsigned int key, int x, int y);
The value of key is the ASCII value12 of the key pressed. The values x and y report the
position of the mouse at the time that the event occurred. (As before y measures the number of
pixels down from the top of the window.)
GLUT provides several 3D objects: a sphere, a cone, a torus, the five platonic solids and the
teapot.
Each is available as a wireframe model and as a solid model with faces that can be shaded.
All are drawn by default centered at the origin.
To use the solid version replace wire by solid in the functions.
Torus: glutWireTorus (GLdouble inRad, GLdouble outRad, Glint nslices, Glint nstacks);
Tetrahedron: glutWireTetrahedron();
Octahedron: glutWireOctahedron();
Dodecahedron: glutWireDodecahedron();
Icosahedron: glutWireIsosahedron();
7. 3D TRANSFORMATION IN OPENGL
The main purpose of transforming objects using 3D is to orient and position them as
desired in 3D scenes.
The matrix structure maintained by openGL makes it easy to set up a transformation for
one object and then “back up” to a previous transformation.
Three Matrices