Computer GraphicsLab Manual
Computer GraphicsLab Manual
Computer Graphics
CS-233
Air University
Islamabad
1
Lab Assessment Rubrics
PSYCHOMOTOR DOMAIN
Performance Excellent Good Satisfactory Unsatisfactory
Indicator 4.1-5 3.1-4 2.1-3 1.1-2
Ability to Ability to Ability to Ability to Unable to
perform perform the perform perform perform
experiment entire experiment with experiment with experiment, lab
without experiment with some help from a lot of help instructor
supervision negligible help the lab from the lab provides help in
from the lab instructor. instructor. every steps of
instructor. the experiment.
Ability to Follow safety Sometimes Never follows
conduct rules but with neglects safety the safety rules
experiment minor deviation rules and and procedure.
Lab Safety respectfully and requires some
Rules carefully reminders.
observes the
safety rules and
procedure
Ability to Always Good Acceptable No
demonstrate demonstrates demonstration of demonstration of demonstration of
care and respect and care respect and care respect and care respect and care
respect in for equipment. for equipment. for equipment. for equipment.
equipment set-
up
2
Lab01: Introduction and Installation of OpenGL
and GLUT
Introduction:
Introduce you with the graphics utility toolkit named as GLUT and OpenGL.
Installing OpenGL libraries.
Run simple program.
OpenGL
OpenGL (Open Graphics Library) is a standard specification defining a cross-language, cross-
platform API for writing applications that produce 2D and 3D computer graphics. The interface consists
of over 250 different function calls which can be used to draw complex three-dimensional scenes from
simple primitives.
OpenGL is an application program interface that is used to define 2D and 3D computer graphics. This
cross-platform API is generally considered to set the standard in the computer industry when it comes
to this type of interaction with 2D computer graphics and has also become the usual tool for use with 3D
graphics as well. Short for Open Graphics Library, OpenGL eliminated the need for programmers to
rewrite the graphics section of an operating system each time a business would upgrade to a new
version of the system.
The basic function of OpenGL is to issue a specific collection of executables or commands to the
operating system. In doing so, the program works with the existing graphics hardware that resides on
the hard drive or other specified source. Each command in the set is designed to engage a certain
drawing action, or launch a specific special effect associated with the graphics.
OpenGL performs the following major graphics operations to render an image on the screen:
During these stages, OpenGL might perform other operations, such as eliminating parts of objects that
are hidden by other objects (the hidden parts won't be drawn, which might increase performance). In
3
addition, after the scene is rasterized but just before it's drawn on the screen, you can manipulate the
pixel data if you want.
GLUT is designed for constructing small to medium sized OpenGL programs. While GLUT is well-suited to
learning OpenGL and developing simple OpenGL applications, GLUT is not a full-featured toolkit so large
applications requiring sophisticated user interfaces are better off using native window system toolkits.
GLUT is simple, easy, and small. It provides the following operations:
Initializing and creating window.
Handling window and input events.
Drawing basic three-dimensional objects.
Running the program.
Windows comes with OpenGL, and Visual Studio comes with the OpenGL libraries, but neither of them
comes with GLUT. Get the newest version of GLUT such as GLUT 3.7.6 for Windows.
For installing GLUT, put the following files in the following locations or directories:
Note:
If you plan on giving your program to friends to run using Windows, you must also include the glut32.dll
file. If they don't have this file in the same directory as your application or in their C:\WINDOWS\system
folder, the program will not run.
4
2. In the Project Types: pane, select Visual C++, Win32. Then select Win 32 Console Application in the
Templates: pane. Name your project, select the location for the project and click OK.
3. Click the Application Settings tab on the left, and check the Empty Project box. Then click Finish
button
5
Step 2: Add Source Code
6
2. In the Categories pane, select Visual C++, Code. Then select C++ File( ,cpp) in the Templates: pane.
Name your file, and then click Add.
Copy and paste the code below into the file. Save your time of typing.
/* Drawing Line */
#include <windows.h>
#include <GL/gl.h>
#include <GL/glut.h>
void init (void)
{
glClearColor (1.0, 1.0, 1.0, 0.0);
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 200.0);
glLineWidth(10.0);
}
void lineSegment (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 0.0, 0.0);
glBegin (GL_LINES);
glVertex2i (160, 120);
glVertex2i (40, 120);
glEnd ( );
glFlush ( );
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (50, 100);
glutInitWindowSize (400, 300);
glutCreateWindow ("LINE");
init ( );
glutDisplayFunc (lineSegment);
7
glutMainLoop ( );
}
1. Use Visual Studio's menu Project options ( Project --> Draw Properties)
The Draw Property Page dialog will open. Once it appears, do the following:
8
b. In the left pane, select the linker subtree and then click the Input option. Add the following code to
the "Additional Dependencies" text in the right pane.
9
Now Visual Studio knows where to find GLUT. Click OK button
1. Compile
From the Visual Studio's menu Build option (Build ---> Build Solution)
From the Visual Studio's menu Debug option (Debug ---> Start Without Debugging)
10
Lab Task:
1. Run “Draw Line” code and paste output of this code.
2. Modify the above code to draw number of dots.
11
Lab 02: Getting Started with Drawings
Introduction:
Although you can draw complex and interesting pictures using OpenGL, they’re all constructed from a
small number of primitive graphical items. In this lab, you will learn how to draw objects using straight
lines, polylines and polygons.
1. Tic-tac-toe Board:
Code:
#include <windows.h>
#include <GL/gl.h>
#include <GL/glut.h>
void init (void)
{
glClearColor (1.0, 1.0, 1.0, 0.0);
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 200.0);
}
void lineSegment (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 0.0, 0.0);
glBegin (GL_LINES);
glVertex2i (160, 120);
glVertex2i (40, 120);
glVertex2i (160, 80);
glVertex2i (40, 80);
glVertex2i (85, 160);
glVertex2i (85, 40);
glVertex2i (115, 160);
glVertex2i (115, 40);
glEnd ( );
glFlush ( );
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (50, 100);
glutInitWindowSize (400, 300);
glutCreateWindow ("Tic Tac Toe Board");
12
init ( );
glutDisplayFunc (lineSegment);
glutMainLoop ( );
}
Output:
#include <windows.h>
#include <GL/gl.h>
#include <GL/glut.h>
void init (void)
{
glBegin (GL_LINE_STRIP);
glVertex2i (160, 120);
glVertex2i (40, 120);
glVertex2i (160, 80);
glVertex2i (40, 80);
glVertex2i (180, 140);
glEnd ( );
13
glFlush ( );
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (50, 100);
glutInitWindowSize (400, 300);
glutCreateWindow ("Line Strip");
init ( );
glutDisplayFunc (lineSegment);
glutMainLoop ( );
}
Output:
3. Polygon
Code:
#include <windows.h>
#include <GL/gl.h>
#include <GL/glut.h>
void init (void)
{
14
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 0.0, 0.0);
glBegin (GL_POLYGON);
glVertex2i (60, 160);
glVertex2i (140, 160);
glVertex2i (180, 120);
glVertex2i (180, 80);
glVertex2i (140, 40);
glVertex2i (60, 40);
glVertex2i (20, 80);
glVertex2i (20, 120);
glEnd ( );
glFlush ( );
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (50, 100);
glutInitWindowSize (400, 300);
glutCreateWindow ("Polygon");
init ( );
glutDisplayFunc (lineSegment);
glutMainLoop ( );
}
Output:
15
Lab Tasks:
1. Modify the tic-tac-toe board code to make the lines of tic-tac-toe board thicker and paste the
output.
2. Modify the polyline code using line loop and line stipple commands and paste the outputs.
3. Modify the polygon code to draw triangle of any other color and paste the output.
16
Lab 03: Plotting Functions and Drawing Ploylines
Stored in a File
Suppose you wish to learn the behavior of some mathematical function f(x) as x varies. For example,
how does f(x) = e-x cos(2πx) vary for values of x between 0 and 4? A quick plot of f(x) versus x, such as
that shown in Figure 1, can reveal a lot.
To plot this function, simply “sample” it at a collection of equispaced x-values, and plot a dot at each
17
coordinate pair (xi, f(xi)). Choosing some suitable increment, say 0.005, between consecutive x-
values the process is basically:
glBegin(GL_POINTS);
for(GLdouble x = 0; x < 4.0 ; x += 0.005)
glVertex2d(x, f(x));
glEnd();
glFlush();
But there is a problem here: the picture produced will be impossibly tiny because values of x
between 0 and 4 map to the first four pixels at the bottom left of the screen window. Further, the
negative values of f(x) will lie below the window and will not be seen at all. We therefore need to
scale and position the values to be plotted so they cover the screen window area appropriately.
Here we do it by brute force, in essence picking some values to make the picture show up
adequately on the screen. Later we develop a general procedure that copes with these adjustments,
the so-called procedure of mapping from world coordinates to window coordinates.
• Scaling x: Suppose we want the range from 0 to 4 to be scaled so that it covers the entire width of
the screen window, given in pixels by screenWidth. Then we need only scale all x-values by
screenWidth/4 , using sx = x * screenWidth /4.0; which yields 0 when x is 0 , and screenWidth when
x is 4.0, as desired.
• Scaling, and shifting y: The values of f(x) lie between –1.0 and 1.0, so we must scale and shift them
as well. Suppose we set the screen window to have height screenHeight pixels. Then to place the
plot in the center of the window scale by screenHeight / 2 and shift up by screenHeight / 2:
sy = (y + 1.0) * screenHeight / 2.0;
As desired, this yields 0 when y is –1.0, and screenHeight when y is 1.0.
Note that the conversions from x to sx, and from y to sy, are of the form:
sx = A * x + B (2.1)
sy = C * y + D
for properly chosen values of the constants A, B, C, and D. A and C perform scaling; B and D perform
shifting. We need only set the values of A, B, C, and D appropriately, and draw the dot -plot using:
GLdouble A, B, C, D, x;
A = screenWidth / 4.0;
B = 0.0;
C = screenHeight / 2.0;
D = C;
glBegin(GL_POINTS);
for(x = 0; x < 4.0 ; x += 0.005)
glVertex2d(A * x + B, C * f(x) + D);
glEnd();
glFlush();
18
Figure 2 shows the entire program to draw the dot plot, to illustrate how the various ingredients fit
together. Notice that the width and height of the screen window are defined as constants, and used
where needed in the code.
19
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Dot Plot of a Function"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}
Most interesting pictures made up of polylines contain a rather large number of line segments. It is
convenient to store a description of the polylines in a file, so that the picture can be redrawn at will. This
lab will introduce you how to write routine that draws the polylines stored in a file.
Code:
#include<windows.h>
#include<gl/Gl.h>
#include<gl/glut.h>
#include<conio.h>
#include<fstream>
#include<iostream>
using namespace std;
inStream.close();
}
void myInit(void)
20
{
glClearColor(1.0,1.0,1.0,1.0);
glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(6.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (640.0, -200.0, 480.0, -100.0);
}
void myDisplay(void)
{
glViewport(0.0, 0.0, 640.0, 480.0);
drawPolyLineFile("D://dino.dat");
glFlush();
}
Lab Task:
1. Write a program to plot a function= sin(2*3.142*x) where x varies from 0 to 10. Adjust A,B,C,D
appropriately to perform proper scaling and shifting. Use lines instead of points to draw this
function. Your result must look like the following figure.
21
1. Using above code search dino.dat and paste output.
2. Write a routine that draws the dinosaur in up-right position.
3. Write a code to search house.dat file and paste output.
22
Lab 04: Parameterized Figures , Line Drawing and
Drawing Aligned Rectangles
Parameterized Figures
Introduction:
Objective of this lab is to introduce the benefits of Parameterizing the figure other than using hardwired
position of each endpoint in the code.
23
glVertex2i(50,100);
glVertex2i(50,120);
glVertex2i(60,120);
glVertex2i(60,110);
glEnd();
glBegin(GL_LINE_LOOP);
glVertex2i(50,40);//draw the door
glVertex2i(60,40);
glVertex2i(60,70);
glVertex2i(50,70);
glEnd();
glFlush();
}
//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Hardwired House"); // open the screen window
Output:
The above output shows a simple house consisting of a few polylines. It can be drawn using code
mentioned above. This is not a very flexible approach. The position of each endpoint is hard-wired into
this code, so it can draw only one house in one size and one location. More flexibility is achieved if we
parameterize the figure, and pass the parameter values to the routine. In this way we can draw families
of objects, which are distinguished by different parameter values. The parameters specify the location of
the peak of the roof, the width of the house, and its height.
24
#include<gl/Gl.h>
#include<gl/glut.h>
#include<math.h>
struct GLintPoint
{
GLint x,y;
};
GLintPoint cp;
//door
glBegin(GL_LINE_LOOP);
glVertex2i(peak.x-width/4.5,peak.y-height);
glVertex2i(peak.x-width/4.5,peak.y-height/1.8);
glVertex2i(peak.x-width/2.5,peak.y-height/1.8);
glVertex2i(peak.x-width/2.5,peak.y-height);
glEnd();
//chimney
glBegin(GL_LINE_STRIP);
glVertex2i(peak.x-width/3,peak.y-height/4);
glVertex2i(peak.x-width/3,peak.y+height/30);
glVertex2i(peak.x-width/5,peak.y+height/30);
glVertex2i(peak.x-width/5,peak.y-height/6.5);
glEnd();
}
void ini(void)
{
glClearColor(1,1,1,0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0,640,0,480);
}
void dis()
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 0.0, 0.0);
GLintPoint peak;
peak.x=200;
25
peak.y=400;
parameterizeHouse(peak,100,150);
glFlush();
}
void main(int argc,char**argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
glutInitWindowPosition(50,100);
glutInitWindowSize(640,480);
glutCreateWindow("Parameterized House");
ini();
glutDisplayFunc(dis);
glutMainLoop();
Output:
Introduction:
A number of graphics systems provide line drawing tools based on the functions moveto() and lineto().
These functions are so common it is important to be familiar with their use. We shall fashion our own
moveto() and lineto() that operate by calling OpenGL tools. Recall that moveto() and lineto() manipulate
the position of a hypothetical pen, whose position is called the current position, or CP. We can
summarize the effects of the two functions as: moveto(x, y): set CP to (x, y) lineto(x, y): draw a line from
CP to (x, y), and then update CP to (x, y) A line from (x1, y1) to (x2, y2) is therefore drawn using the two
calls moveto(x1, y1);lineto(x2, y2). A polyline based on the list of points (x0, y0), (x1, y1), ... , (xn-1, yn-1)
is easily drawn using:
26
moveto(x[0], y[0]);
For (int i = 1; i < n; i++)
lineto(x[i], y[i]);
It is straightforward to build moveto() and lineto() on top of OpenGL. To do this we must define and
maintain our own CP. The objective of this lab is to introduce how moveto() and lineto() functions canbe
used to draw line.
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 200.0, 0.0, 200.0);
glLineWidth(5.0);
glPointSize(10);
}
void myDisplay(void)
{
27
int x[10]={0,13,43,73,94,54,127,190,54,0};
int y[10]={0,23,64,34,190,123,54,23,94,0};
glClear(GL_COLOR_BUFFER_BIT); // clear the window
moveto(x[0], y[0]);
for (int i = 1; i <= 10; i++)
{
glColor3f(0,0,1);
lineto(x[i], y[i]);
}
}
void main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(400,300);
glutInitWindowPosition(100, 150);
glutCreateWindow("Task");
myInit();
glutDisplayFunc(myDisplay);
glutMainLoop();
}
Output:
28
// draw a rectangle with opposite corners (x1, y1) and (x2, y2);
// fill it with the current color;
This command draws the aligned rectangle based on two given points. In addition the rectangle is filled
with the current color. This lab will introduce you how to use "recti funtion" to draw different figures.
29
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(screenWidth, screenHeight); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Aligned Rectangles"); // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
myInit();
glutMainLoop(); // go into a perpetual loop
}
Output:
LAB TASKS:
glColor3f(1,0,0);
drawDot(x[i], y[i]);
30
Lab 05: Applying OpenGL Colors and Patterns
Introduction:
Objective of this lab is to get understanding of some other OpenGL drawing primitives such as working
with the faces of polygons. In this lab you will learn how to apply OpenGL colors and patterns to
polygons.
31
}
Output:
Lab Task:
1. Write a program for the "Back Face" that use different colors and paste the output.
32
Lab 06: Creating a Scenery
Introduction:
Objective of this lab is to introduce you to some other OpenGL drawing primitives. In this lab you will
learn how colorful sceneries can be created using OpenGL.
//Sky
glBegin (GL_TRIANGLE_FAN);
glColor3f (1.0, 0.8, 1.0); glVertex2i (0,250);
glColor3f (1.0, 0.8, 1.0); glVertex2i (540,250);
glColor3f (1.0, 0.8, 1.0); glVertex2i (540,260);
glColor3f (0.6, 0.8, 1.0); glVertex2i (540,350);
glColor3f (0.6, 0.8, 1.0); glVertex2i (540,380);
glColor3f (0.6, 0.8, 1.0); glVertex2i (0,380);
glEnd ();
//Sky
//Sun
glColor3f (1.0, 1.0, 0.0);
glBegin (GL_POLYGON);
glVertex2i (0,240);
glVertex2i (15,240);
glVertex2i (27,250);
glVertex2i (25,260);
glVertex2i (15,270);
33
glVertex2i (0,270);
glEnd ( );
//Sun
// Boundary of House
glLineWidth(5.0);
glColor3f (0.5, 0.3, 0.0);
glBegin (GL_LINE_STRIP);
glVertex2i (270,0);
glVertex2i (220,125);
glVertex2i (490,125);
glVertex2i (540,0);
glEnd ( );
// Boundary of house
// Roof of House
glColor3f (0.5, 0.2, 0.0);
glBegin (GL_QUADS);
glVertex2i (290,105);
glVertex2i (400,105);
glVertex2i (410,90);
glVertex2i (300,90);
glEnd ( );
//Roof of House
//Front of House
glColor3f (0.6, 0.4, 0.0);
glBegin (GL_POLYGON);
glVertex2i (290,105);
glVertex2i (285,90);
34
glVertex2i (285,40);
glVertex2i (300,20);
glVertex2i (300,90);
glEnd ( );
//Front of House
//House
glColor3f (0.5, 0.5, 0.0);
glBegin (GL_QUADS);
glVertex2i (300,76);
glVertex2i (410,76);
glVertex2i (410,90);
glVertex2i (300,90);
glEnd ( );
glColor3f (0.6, 0.5, 0.0);
glBegin (GL_QUADS);
glVertex2i (300,76);
glVertex2i (410,76);
glVertex2i (410,61);
glVertex2i (300,61);
glEnd ( );
glColor3f (0.5, 0.4, 0.0);
glBegin (GL_QUADS);
glVertex2i (300,41);
glVertex2i (410,41);
glVertex2i (410,61);
glVertex2i (300,61);
glEnd ( );
glColor3f (0.5, 0.3, 0.0);
glBegin (GL_QUADS);
glVertex2i (300,41);
glVertex2i (410,41);
glVertex2i (410,20);
glVertex2i (300,20);
glEnd ( );
glColor3f (0.5, 0.7, 0.0);
glBegin (GL_QUADS);
glVertex2i (290,33);
glVertex2i (290,54);
glVertex2i (295,48);
glVertex2i (295,27);
glEnd ( );
//House
35
glVertex2i (300,20);
glVertex2i (140,20);
glVertex2i (160,40);
glEnd ( );
glBegin (GL_QUADS);
glVertex2i (0,200);
glVertex2i (160,40);
glVertex2i (140,20);
glVertex2i (0,160);
glEnd ( );
//Road in front of House
glBegin (GL_QUADS);
glVertex2i (410,250);
glVertex2i (410,280);
glVertex2i (423,280);
glVertex2i (423,250);
glEnd ( );
glBegin (GL_QUADS);
glVertex2i (350,250);
glVertex2i (350,280);
glVertex2i (363,280);
glVertex2i (363,250);
glEnd ( );
glBegin (GL_QUADS);
glVertex2i (320,250);
glVertex2i (320,280);
glVertex2i (333,280);
glVertex2i (333,250);
glEnd ( );
36
glBegin (GL_TRIANGLES);
glVertex2i (326.5,315);
glVertex2i (306,295);
glVertex2i (347,295);
glEnd();
glBegin (GL_TRIANGLES);
glVertex2i (326.5,335);
glVertex2i (312,308);
glVertex2i (341,308);
glEnd();
glBegin (GL_TRIANGLES);
glVertex2i (356.5,315);
glVertex2i (336,295);
glVertex2i (377,295);
glEnd();
glBegin (GL_TRIANGLES);
glVertex2i (356.5,335);
glVertex2i (342,308);
glVertex2i (371,308);
glEnd();
glBegin (GL_TRIANGLES);
glVertex2i (416.5,315);
glVertex2i (396,295);
glVertex2i (437,295);
glEnd();
glBegin (GL_TRIANGLES);
glVertex2i (416.5,335);
glVertex2i (402,308);
glVertex2i (431,308);
37
glEnd();
glBegin (GL_TRIANGLES);
glColor3f (0.1, 0.6, 0.0); glVertex2i (506.5,305);
glColor3f (0.1, 0.6, 0.0); glVertex2i (480,280);
glColor3f (0.1, 0.8, 0.0); glVertex2i (533,280);
glEnd ();
glBegin (GL_TRIANGLES);
glVertex2i (506.5,335);
glVertex2i (492,308);
glVertex2i (521,308);
glEnd();
//End of Trees in upper half
38
//End of Trees near Sun
glFlush ( );
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition (200, 100);
glutInitWindowSize (540,380);
glutCreateWindow ("Scenery");
init ( );
glutDisplayFunc (Scenery);
glutMainLoop ( );
}
Output:
Lab Task:
1. Add some more objects to the scenery.
39
Lab 07: Mouse Interaction and Keyboard
Interaction
Mouse Interaction
Introduction:
Interactive graphics applications let the user control the flow of a program by natural human motions:
pointing and clicking the mouse and pressing various keys on the keyboard. The position of the mouse at
the time of the click or the identity of the key that is pressed is made available to the application
program and is processed appropriate.
When the user presses or releases a mouse button, moves the mouse an event occurs. Using the
OpenGL Utility Toolkit (GLUT) the programmer can register a callback function with each of these
events. The purpose of this lab is to introduce how data pertaining to the mouse is sent to the
application.
40
{
y = screenHeight - y;
glColor3f(0.0f, 0.0f, 0.0f);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
else if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
y = screenHeight - y;
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_POINTS);
glVertex2i(x,y);
glEnd();
}
glFlush();
}
Keyboard Interaction
Introduction:
As mentioned in the previous lab, pressing a key on the keyboard queues a keyboard event. The callback
function myKeyboard() is registered with the type of the event through
glutKeyboardFunc(myKeyboard). The purpose of this lab is to introduce how keyboard interaction can
be used to draw different figures in OpenGl.
41
#include <GL/glut.h>
//<<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>>>>>>
GLint screenHeight = 480;
//<<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>
void myDisplay(void){
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glFlush();
}
//<<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(8.0); // a ‘dot’ is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
//<<<<<<<<<<<<<<<<<<<<<<<< myKeyboard >>>>>>>>>>>>>>>>
void myKeyboard(unsigned char theKey, int mouseX, int mouseY)
{
mouseY = screenHeight - mouseY; // flip the y value as always
switch(theKey)
{
case 'p': // draw point
glBegin(GL_POINTS);
glVertex2i(mouseX,mouseY);
glEnd();
glFlush();
break;
case 'd' :
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glFlush();
break;
case 'q':
exit(-1); //terminate the program
default:
break; // do nothing
}
}
//<<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
void main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Task"); // open the screen window
glutDisplayFunc(myDisplay);
glutKeyboardFunc(myKeyboard); // keyboard callback function
myInit();
glutMainLoop(); // go into a perpetual loop
}
42
LAB TASKS:
1. Use the above code of mouse interaction and draw hut using mouse interaction.
2. Modify the above mouse interaction code in a way, that if right button of mouse is pressed then
red dot appears on the screen and if left button is pressed then blue dot appears on the screen.
3. Modify the above code for keyboard interaction in a way so that polyline can be created using
the mouse and key 'a'.
43
Lab 08: Animation, 3D Animated Objects
Introduction:
The main purpose of this lab is to present the basic elements used in an animation loop in OpenGL with
GLUT. We start with a simple code from OpenGL and make changes to that code for this.
#include <GL\glut.h>
void Draw() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINES);
glVertex3f(0.25, 0.25, 0.0);
glVertex3f(0.75, 0.75, 0.0);
glEnd();
glFlush();
}
void Initialize() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}
44
Below, we have all of the lines that have been changed for this lab from the given code highlighted
in white. The rest of the code is the same as given above.
With these changes made to our code, our previous diagonal line is now animated so that the x-
coordinates of the endpoints alternate between the 0 and 1 in opposite directions. The variable
gfPosX is used as the x-position of the lower endpoint, and (1 - gfPosX) as the x-position of the upper
endpoint. The value of gfPosX is changed by the value of gfDeltaX at each frame. The value of
gfDeltaX changes sign whenever gfPosx reaches 0 or 1 by the "if" statement that we added. This
keeps gfPosX and, by extension, the x-coordinates of the endpoints from leaving the range [0, 1].
The animation is created via an implied loop. In this case, the loop is created by redisplay event. By
calling glutDisplayFunc() with our Draw() function as the argument, we set Draw() to be called every
time the window needs to be redisplayed. For example, Draw() is originally called when the window
is drawn first time. Since this sends a redisplay message to the message queue. When this message
is handled, Draw() is called, which, in turn, posts a redisplay message at the end of the function
when glutPostRedisplay() is called. This completes the loop.
45
This simple animation is primarily for illustration and lacks some finishing touches: double buffering,
timing, etc. Depending on the speed of computer that the code runs, the animation may look much
faster or slower. For the present purposes, the value of gfDeltaX may be changed to alter the speed
of the animation to get a reasonable looking result.
3D Animated Objects
Introduction:
The main purpose of this lab is to illustrate how 3D animated objects can be created using OpenGL with
GLUT. Here is a simple code for creating 3D animated tetrahedron.
glMatrixMode(GL_MODELVIEW);
// clear the drawing buffer.
glClear(GL_COLOR_BUFFER_BIT);
// clear the identity matrix.
glLoadIdentity();
// traslate the draw by z = -4.0
// Note this when you decrease z like -8.0 the drawing will looks far , or smaller.
glTranslatef(0.0,0.0,-4.5);
// Red color used to draw.
glColor3f(0.8, 0.2, 0.1);
46
// changing in transformation matrix.
// rotation about X axis
glRotatef(xRotated,1.0,0.0,0.0);
// rotation about Y axis
glRotatef(yRotated,0.0,1.0,0.0);
// rotation about Z axis
glRotatef(zRotated,0.0,0.0,1.0);
// scaling transfomation
glScalef(1.0,1.0,1.0);
// built-in (glut library) function , draw you a Tetrahedron.
glutWireTetrahedron();
// Flush buffers to screen
glFlush();
// sawp buffers called because we are using double buffering
glutSwapBuffers();
}
gluPerspective(40.0,(GLdouble)x/(GLdouble)y,0.5,20.0);
void idleTetrahedron(void)
{
yRotated += 0.01;
displayTetrahedron();
}
47
glutIdleFunc(idleTetrahedron);
//Let start glut loop
glutMainLoop();
return 0;
}
LAB TASKS:
1. Understand and run the code provided below. Paste the output.
2. Using the provided "Line Animation" code, develop a code for animating a multicolor
triangle and its animation speed should be slower than the animated line.
Complete code for the animated line:
#include <GL\glut.h>
GLfloat gfPosX=0.0;
GLfloat gfDeltaX=.0001;
void Draw() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINES);
glVertex2f(gfPosX, 0.25);
glVertex2f(1-gfPosX, 0.75);
glEnd();
glFlush();
gfPosX += gfDeltaX;
if(gfPosX>=1.0 || gfPosX<= 0.0)
{
gfDeltaX=-gfDeltaX;
}
glutPostRedisplay();
}
void Initialize() {
glClearColor(0.0, 0.0, 0.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 1.0, 0.0, 1.0);
}
48
3. Understand and run the code provided above for 3D Animated Objects. Paste the output.
4. Using the provided code of 3D animated objects; develop codes for different 3D
animated objects.
49