Computer Graphics 1 Computer Graphics Computer Graphics Faizan Ahmed (1274) Husnain Raza(1280)
Computer Graphics 1
Index
Topics Name Page no
1 Line Algorithm 3
Computer GraphicsComputer Graphics
Faizan Ahmed (1274) Husnain Raza(1280)
Computer Graphics 2
2 Increment Line Algorithm, c++ code, output 4
3 Digital Difference Analyzer algorithm, c++ code, output 9
4 Bresenham line algorithm, c++ code, output 14
5 Circle Algorithms 19
6 Cartesian Coordinate algorithm, c++ code, output 20
7 Polar Coordinate algorithm, c++ code, output 23
8 Mid Point algorithm, c++ code, output 25
9 Filled Area Primitive algorithm, c++ code, output 26
10 Boundry Fill algorithm, c++ code, output 27
11 Flood Fill algorithm, c++ code, output 31
12 Line Clipping algorithm, c++ code, output 35
13 Two Dimensional Geometric Transformation 40
14 Translation Transformatin algorithm, c++ code, output 41
15 Rotation Transformation algorithm, c++ code, output 45
16 Scaling Transformatin algorithm, c++ code, output 49
Table Of Contents:
Computer Graphics 3
Line Algorithm:-
A line, or straight line, is, roughly speaking, an (infinitely) thin,(infinitely) long, straight
geometrical object, i.e. a curve that is long and straight. A line segment is defined by an
infinite set of points which lie between two points; these points have no area. A line
drawing algorithm is a graphical algorithm for approximating a line segment on discrete
graphical media. Line drawing is accomplished by calculating intermediate positions
along the line path between two specified endpoint positions. Digital devices display a
straight line segment by plotting discrete points between the two end points. We have
three methods for line drawing;
Increment line algorithm.
Digital differential analyzer algorithm.
Bresenham’s line drawing algorithm.
Computer Graphics 4
Increment Line Algorithm:-
This algorithm exploits simple line equation y = m x + bWhere m = dy / dxAnd b = y – m xNow check if |m| < 1 then starting at the first point, simply increment x by 1 till it reaches ending point; whereas calculate y point by the equation for each x and conversely if |m|>1 then increment y by 1 till it reaches ending point; whereas calculate x point corresponding to each y, by the equation.
Advantage:-
Incremental algorithm is quite simple and easy.
Disadvantage:-
It involves lot of mathematical calculations that is for calculating coordinate using equation each time.
It works only in incremental direction.
Algorithm:-
Incremental_Line (Point p1, Point p2)dx = p2.x – p1.xdy = p2.y – p1.ym = dy / dxx = p1.xy = p1.yb = y – m * xif |m| < 1for counter = p1.x to p2.xdrawPixel (x, y)x = x + 1y = m * x + belsefor counter = p1.y to p2.y
Computer Graphics 5
drawPixel (x, y)y = y + 1x = (y – b) / m
Computer Graphics 6
Code in C++:-
#include<graphics.h>#include<stdio.h>#include<conio.h>#include<math.h>struct point{ int x,y;};void lineincrement(point p1,point p2){
int dx = p2.x-p1.x;int dy = p2.y-p1.x;float m=dy/dx;int x = p1.x;int y = p1.y;float c = y-m*c;if(abs(m)<1)for(int counter=p1.x; counter<p2.x; counter++){putpixel(x,y,15);x++;y=m*x+c;}elsefor(int counter=p1.y; counter<p2.y; counter++){putpixel(x,y,15);y++;x=y-c/m;}
}int main(void){ int gdriver=DETECT,gmode; initgraph(&gdriver,&gmode,"../bgi"); point p1={10,12}, p2={80,90}; lineincrement(p1,p2); getch(); closegraph();
Computer Graphics 7
return 0;}
Computer Graphics 8
Out Put:-
Computer Graphics 9
Digital Differential Analyzer Algorithm:-
Digital differential analyzer has very simple technique. Find difference dx and dy between x coordinates and y coordinates respectively ending points of a line. The digital differential analyzer (DDA) samples the line at unit intervals in one coordinate corresponding integer values nearest the line path of the other coordinate. The digital differential analyzer (DDA) is a scan conversion line algorithm based on calculation either dy or dx.
Advantage:-
Faster method for calculating pixel position then the equation of a pixel position. DDA is the simplest line drawing algorithm. Faster than the direct use of the line equation and it does not do any floating point
multiplication.
Disadvantage:- Not very efficient. Round operation is expensive. Precision loss because of rounding off. It drift away from the actual line path because of rounding off float values to integer. It causes jaggies or stair-step effect.
Algorithm:-
DDA_Line (Point p1, Point p2)dx = p2.x – p1. xdy = p2.y – p1. yx1=p1.xy1=p1.yif |dx|>|dy| thenstep = |dx|elsestep = |dy|xincrement = dx/stepyincrement = dy/stepfor counter = 1 to stepdrawPixel (x1, y1)
Computer Graphics 10
x1 = x1 + xIncrementy1 = y1 + yIncrement
Computer Graphics 11
Code in C++:-
#include<iostream.h>#include<stdio.h>#include<conio.h>#include<math.h>#include<graphics.h>struct point{ int x,y;};void ddaline(point p1,point p2){ int dx = p2.x-p1.x; int dy = p2.y-p1.y; int x=p1.x; int y=p1.y; float step; if(abs(dx)>abs(dy)) { step=abs(dx); } else { step=abs(dy); } float xincrement = dx/step; float yincrement = dy/step; for (int counter=1; counter<step; counter++) { putpixel(x,y,2); x=x+xincrement; y=y+yincrement; }}int main(void){int gdriver=DETECT,gmode;initgraph (&gdriver, &gmode, "../bgi");
Computer Graphics 12
point p1={110,100},p2={270,250};ddaline(p1,p2);getch();closegraph();return 0;}
Computer Graphics 13
Output:-
Computer Graphics 14
Bresenham’s Line Drawing Algorithm:-
Bresenham's algorithm finds the closest integer coordinates to the actual line, usingonly integer math. The algorithm was developed by Jack E. Bresenham in 1962 at IBM. The Bresenham line algorithm is an algorithm which determines which points in an n-dimensional raster should be plotted in order to form a close approximation to a straight line between two given points. It is commonly used to draw lines on a computer screen, as it uses only integer addition, subtraction and bit shifting.
Advantage:-
It uses only integer calculations such as addition/subtraction and bit shifting. It is time saving and fast algorithm for drawing lines. This algorithm uses only integer arithmetic, and runs significantly faster. It gives accurate and efficient result. Uses Symmetry.
Disadvantage:-
It is meant for basic line drawing.
Algorithm:-
Line_Bresenham (x1, y1, x2, y2)dx = x2-x1dy = y2-y1p = 2dy-dxc1 = 2dyc2 = 2(dy-dx)x = x1y = y1putpixel (x,y,colour)while (x < x2 )x++;if (p < 0)p = p + c1else
Computer Graphics 15
p = p + c2y++putpixel (x, y, colour)
Computer Graphics 16
Code in C++:-
#include<iostream.h>#include<conio.h>#include<stdio.h>#include<math.h>#include<graphics.h>#include<stdlib.h>struct point{int x,y;};void breshamline(int x1,int y1,int x2,int y2){ int dx = x2-x1; int dy = y2-y1; int p = 2*(dy)-dx; int c1 = 2*(dy); int c2 = 2*(dy-dx); int x = x1; int y = y1; putpixel(x,y,4); while(x<x2) { x++; if(p<0) p=p+c1; else p=p+c2; y++; putpixel(x,y,4); }}void main(){int gdriver = DETECT, gmode;initgraph(&gdriver,&gmode,"../bgi");breshamline(120,150,250,350);getch();
Computer Graphics 17
closegraph();}
Computer Graphics 18
Output:-
Computer Graphics 19
Circle Algorithm:-
Circle algorithm is an algorithm used to determine the points needed for drawing a circle. A
circle is the set of points in a plane that are equidistant from a given point O. The distance r from
the center is called the radius, and the point O is called the center. Twice the radius is known as
the diameter. The angle a circle subtends from its
center is a full angle, equal to 360° or radians. The perimeter C of a circle is called the
circumference, and is given by
C = 2 π r
We can use three methods for drawing a circle which are as follows;
Circle drawing using Cartesian coordinates.
Circle drawing using polar coordinates.
Midpoint circle algorithm.
Computer Graphics 20
Circle Drawing Using Cartesian Coordinates:-
The equation for a circle is:
x2+y2=r2
where r is the radius of the circle. So, we can write a simple circle drawing algorithm by solving
the equation for y at unit x intervals using:
Disadvantage:-
This is not a brilliant solution. The calculations are not very efficient. It is inefficient because of the multiplications and square root operations. It also creates large gaps in the circle for values of x close to r.
Algorithm:-
Circle1 (xcenter, ycenter, radius)for x = radius - xcenter to radius + xcenter
y = xc +
drawpixel (x, y)
y = xc –
drawpixel (x, y)
Code in C++:-
#include<iostream.h>#include<graphics.h>#include<conio.h>#include<math.h>void circle1(int xc,int yc,int rad)
Computer Graphics 21
{ double x; float y; for(x=rad-xc;x<=rad+xc;x++) { y=yc+sqrt((rad*rad)-((x-xc)*(x-xc))); putpixel(x,y,9); y=yc-sqrt((rad*rad)-((x-xc)*(x-xc))); putpixel(x,y,7); } getch();}int main (void){ int gdriver=DETECT,gmode; initgraph(&gdriver,&gmode,"..../bgi"); cleardevice(); circle(270,250,225); moveto(400,100); for(int c=0;c<=4;c++) { settextstyle(0,0,c); outtextxy(100,10+c*40,"1292"); } getch(); closegraph(); return 0;}
Computer Graphics 22
Output:-
Computer Graphics 23
Circle Drawing Using Polar Coordinates:-
It is a better approach, to eliminate unequal spacing to calculate points along the circular boundary using polar coordinates r and θ. Expressing the circle equation in parametric polar form yields the pair of equationsx = xc + r cos θy = yc + r sin θUsing above equation circle can be plotted by calculating x and y coordinates as θ takes values from 0 to 360 degrees or 0 to 2π.
Advantage:-
This is very simple technique. It solves problem of unequal space. The shape of circle is similar in each quadrant.
Disadvantage:-
This method is computationally expensive. Polar Co-ordinates are non-Cartesian co-ordinates. Since most of the Graphics Package
do not support non-Cartesian co-ordinates, Polar co-ordinates should be converted to Cartesian form.
It is still inefficient in terms of calculations involves especially floating point calculations.
Algorithm:-
Circle2 (xcenter, ycenter, radius)for θ = 0 to π / 4 step 1/rx = xc+r * cos θy = yc+r * sin θDrawPixel (x, y)DrawSymmeticPoints (xcenter, ycenter, x, y)drawpixel (x + xcenter, y + ycenter)drawpixel (y + xcenter, x + ycenter)drawpixel (y + xcenter, -x + ycenter)drawpixel (x + xcenter, -y + ycenter)
Computer Graphics 24
drawpixel (-x + xcenter, -y + ycenter)drawpixel (-y + xcenter, -x + ycenter)drawpixel (-y + xcenter, x + ycenter)drawpixel (-x + xcenter, y + ycenter)
Computer Graphics 25
Output:-
Computer Graphics 26
Filled Area Primitive:-
Fill-Area algorithms are used to fill the interior of a polygonal shape. There are two basic
approaches to be filling on raster systems. One way is to draw straight lines between the edges of
polygon called scan-line polygon filling. Second way is to start from an interior point and paint
outward from this point till we reach the boundary called boundary-fill. A slight variation of this
technique is used to fill an area specified by cluster (having no specific boundary). The technique
is called flood-fill and having almost same strategy that is to start from an interior point and start
painting outward from this point till the end of cluster. Here we can discuss two techniques for
filling which are as follows;
Boundary-Fill Algorithm.
Flood-Fill Algorithm.
Computer Graphics 27
Boundary-Fill Algorithm:-
Boundary Fill is another algorithm used for the purpose of coloring figure in computer graphic.
Here area gets colored with pixels of a chosen color as boundary this giving the technique its
name. Boundary fill fills the chosen area with a color until the given colored boundary is found.
This algorithm is also recursive in nature as the function returns when the pixel to be colored is
the boundary color or is already the fill color. The Boundary fill algorithm performs the
following steps:
Check the pixel for boundary color.
Check the pixel for fill color.
Set the pixel in fill color.
Run the process for neighbors.
There are two methods for boundary filling algorithms which are as follows;
4- Connected. In which four neighboring points are connected.
8-connected. Which correctly fill the interior of the area defined.
Computer Graphics 28
Algorithm:-
For 4 Points:-
BoundaryFill4 (x, y, fillColor , boundaryColor)current = getpixel(x, y)if ((current != boundaryColor) && (current != fillColor))putpixel(fillColor, x, y)BoundaryFill (x+1, y, fillColor, boundaryColor)BoundaryFill (x, y+1, fillColor, boundaryColor)BoundaryFill (x-1, y, fillColor, boundaryColor)BoundaryFill (x, y-1, fillColor, boundaryColor)
For 8 Symmetry Points:-
BoundaryFill4 (x, y, fillColor, boundaryColor)current = getpixel(x, y)if ((current! = boundaryColor) && (current! = fillColor))putpixel(fillColor, x, y)BoundaryFill (x+1, y, fillColor, boundaryColor)BoundaryFill (x, y+1, fillColor, boundaryColor)BoundaryFill (x-1, y, fillColor, boundaryColor)BoundaryFill (x, y-1, fillColor, boundaryColor)BoundaryFill (x+1, y+1, fillColor, boundaryColor)BoundaryFill (x+1, y-1, fillColor, boundaryColor)BoundaryFill (x-1, y-1, fillColor, boundaryColor)BoundaryFill (x-, y+1, fillColor, boundaryColor)
Code in C++:-
#include<graphics.h>#include<stdio.h>#include<conio.h>#include<math.h>void boundaryfill4(int x,int y,int fill,int boundary)
Computer Graphics 29
{
int current;current=getpixel(x,y);if(current !=fill && current !=boundary){
putpixel(x,y,fill);boundaryfill4(x+1,y,fill,boundary);boundaryfill4(x-1,y,fill,boundary);boundaryfill4(x,y+1,fill,boundary);boundaryfill4(x,y-1,fill,boundary);
}}int main(void){
int gdriver=DETECT,gmode,errorcode;initgraph(&gdriver,&gmode,"...\bgi ");setcolor(4);moveto(100,100);lineto(200,100);lineto(250,120);lineto(250,180);lineto(200,120);lineto(150,180);lineto(100,120);lineto(100,100);boundaryfill4(120,120,2,4);getch();closegraph();
}
Computer Graphics 30
Output:-
Computer Graphics 31
Flood-Fill Algorithm:-
An area fill algorithm that replaces all connected pixels of a selected color with a fill color. Flood
fill colors an entire area in an enclosed figure through interconnected pixels using a single color.
It is an easy way to fill color in the graphics. One just takes the shape and starts flood fill. The
algorithm works in a manner so as to give all the pixels inside the boundary the same color
leaving the boundary and the pixels outside. Flood Fill is also sometimes referred to as Seed Fill.
There are two methods for flood filling algorithms which are as follows;
4- connected.In which four neighboring points are connected.
8-connected. Which correctly fill the interior of the area defined.
Computer Graphics 32
Algorithm:-
For 4 Points:-
FloodFill4 (x, y, fillcolor, oldColor)if (getpixel (x, y) == oldColor)setcolor(fillcolor)setpixel (fill, x, y)FloodFill4 (x+1, y, fillColor, oldColor)FloodFill4 (x, y+1, fillColor, oldColor)FloodFill4 (x-1, y, fillColor, oldColor)FloodFill4 (x, y-1, fillColor, oldColor)
For 8 Symmetry Points:-
FloodFill4 (x, y, fillcolor, oldColor)if (getpixel (x, y) == oldColor)setcolor(fillcolor)setpixel (fill, x, y)FloodFill4 (x+1, y, fillColor, oldColor)FloodFill4 (x, y+1, fillColor, oldColor)FloodFill4 (x-1, y, fillColor, oldColor)FloodFill4 (x, y-1, fillColor, oldColor)FloodFill4 (x+1, y+1, fillColor, oldColor)FloodFill4 (x-1, y+1, fillColor, oldColor)FloodFill4 (x-1, y-1, fillColor, oldColor)FloodFill4 (x+1, y-1, fillColor, oldColor)
Code in C++:-
#include<iostream.h>#include<graphics.h>#include<stdio.h>#include<math.h>#include<stdlib.h>#include<conio.h>void floodfill(int x,int y,int fillcolor,int oldcolor){
Computer Graphics 33
if(getpixel(x,y)==oldcolor) { floodfill(x+1,y,fillcolor,oldcolor); floodfill(x-1,y,fillcolor,oldcolor); floodfill(x,y+1,fillcolor,oldcolor); floodfill(x,y+1,fillcolor,oldcolor); }}int main(void){int gdriver = DETECT,gmode;initgraph(&gdriver,&gmode,"../bgi");setcolor(4);moveto(100,100);lineto(150,100);lineto(250,180);lineto(200,180);lineto(150,180);lineto(100,120);lineto(100,100);floodfill(150,150,0,4);getch();closegraph();return 0;}
Computer Graphics 34
Output:-
Computer Graphics 35
Line Clipping:-
Clipping is the method of cutting a graphics display to neatly fit a predefinedgraphics region or the view port. Line clipping is the process of removing lines or portions of lines outside of an area of interest.
Cohen–Sutherland Line Clipping:-
The algorithm divides a 2D space into 9 regions, of which only the middle part is visible. The Cohen-Sutherland algorithm uses a divide-and-conquer strategy. The Cohen-Sutherland line clipping algorithm quickly detects and dispenses with two common and trivial cases. To clip a line, we need to consider only its endpoints. If both endpoints of a line lie inside the window, the entire line lies inside the window. It is trivially accepted and needs no clipping. On the other hand, if both endpoints of a line lie entirely to one side of the window, the line must lie entirely outside of the window. It is trivially rejected and needs to be neither clipped nor displayed.
Algorithm:-
Compute region code for endpoints Check for trivial accept or reject. If step 2 unsuccessful then compute window intersections in order: Left, Right, Bottom,
Top (only do 1) Repeat steps 1, 2, and 3 until done.
Advantage:-
Clipping and testing are done in fixed order. Efficient when most of the lines to be clipped are either rejected or accepted (not so many
subdivisions). Easy to program. Most line segments are outside and can be eliminated.
Computer Graphics 36
Code in C++:-
#include <graphics.h>#include <stdlib.h>#include <stdio.h>#include <conio.h>#include<iostream.h>#include<conio.h>#define ROUND(a) ((int)(a+0.5))#define LEFT_EDGE 0x1#define RIGHT_EDGE 0x2#define BOTTOM_EDGE 0x4#define TOP_EDGE 0x8#define INSIDE(a) (!a)#define REJECT(a,b) (a&b)#define ACCEPT(a,b) (!(a|b))struct Point{
int x;int y;
};unsigned char encode (Point pt, Point winMin, Point winMax){unsigned char code=0X00;if (pt.x < winMin.x)
code=code | LEFT_EDGE;if (pt.x >winMax.x)
code=code | RIGHT_EDGE;if (pt.y <winMin.y)
code=code | BOTTOM_EDGE;if (pt.y >winMax.y)
code=code | TOP_EDGE;return code;}void swapPts(Point *p1, Point *p2){
Point tmp;tmp = *p1; *p1= *p2; *p2 = tmp;
}void swapCodes(unsigned char *c1, unsigned char *c2){
Computer Graphics 37
unsigned char tmp;tmp= *c1; *c1= *c2; *c2=tmp;
}void clipLine( Point winMin, Point winMax, Point p1, Point p2){
unsigned char code1, code2;int done =0, draw=0;float m;while(!done){
code1=encode(p1, winMin, winMax);
code2=encode(p2, winMin, winMax);if( ACCEPT(code1,code2) ){
done=1;draw=1;
}else if(REJECT(code1,code2))
done=1;else{
if(INSIDE(code1)){swapPts(&p1,&p2);swapCodes(&code1,&code2);
}if(p2.x!=p1.x)
m=(p2.y-p1.y)/(p2.x-p1.x);if(code1 & LEFT_EDGE){p1.y+=(winMin.x-p1.x)*m;p1.x=winMin.x;}else if(code1 & RIGHT_EDGE){p1.y+=(winMax.x-p1.x)*m;p1.x=winMax.x;}else if(code1 & BOTTOM_EDGE){p1.x+=(winMin.y-p1.y)/m;p1.y=winMin.y;}else if(code1 & TOP_EDGE){p1.x+=(winMax.y-p1.y)/m;p1.y=winMax.y;}
Computer Graphics 38
}}if(draw)
line(ROUND(p1.x),ROUND(p1.y),ROUND(p2.x),ROUND(p2.y));}void main(){ int gdriver = DETECT, gmode; initgraph(&gdriver, &gmode, "../bgi");Point winMin={10,20}, winMax={100,120},p1={30,40},p2={150,90},p3={70,40},p4={80,180};rectangle(winMin.x, winMin.y, winMax.x, winMax.y);line(p1.x, p1.y, p2.x,p2.y);line(p3.x, p3.y, p4.x,p4.y);getch();cleardevice();setcolor(4);rectangle(winMin.x, winMin.y, winMax.x, winMax.y);clipLine(winMin,winMax, p1,p2);clipLine(winMin,winMax, p3,p4);//line(p1.x, p1.y, p2.x,p2.y);getch();}
Computer Graphics 39
Output:-
Computer Graphics 40
Two Dimensional Geometric Transformations:-
2D computer graphics are the computer-based generation of digital images mostly from two-
dimensional models, such as 2D geometric models, text, and digital images, and by techniques
specific to them. Two-dimensional models are preferred, because they give more direct control
of the image than 3D geometric models. Geometric transformations have numerous applications
in geometric modeling, e.g., manipulation of size, shape, and location of an object. The basic 2D
geometric transformations are as follows;
Translation.
Rotation.
Scaling.
Computer Graphics 41
Translation Transformation:-
In translation, every point on an object translates exactly the same distance. The effect of a
translation transformation is that the original coordinate values increase or decrease by the
amount of the translation along the x, y, and z-axes. A geometric transformation that changes a
figure’s location, but its size and shape remain the same. Translation is a rigid-body
transformation that moves objects without deformation. A translation is displacement from
original place. This displacement happens to be along a straight line; where two distances
involves one is along x-axis that is tx and second is along y-axis that is ty.
x′ = x + tx, y′ = y + ty
Here (tx, ty) is translation vector or shift vector. We can express above equations
as a single matrix equation by using column vectors to represent coordinate
positions and the translation vector:
P′ = P + T
Where
P = P′= T =
Code in C++:-
#include <graphics.h>#include <conio.h>#include <iostream.h>int poly[16] ={100,50,150,50,300,50,300,25,250,12,200,25,100,25,100,50};void translate(int tx,int ty)
Computer Graphics 42
{ for(int i=0;i<2;i++)
{ // if(i==2) // {continue;}
poly[i] +=tx; poly[i+1] +=ty;}
}void scaling(float sx,float sy){ for(int i=0;i<16;i+=2) { if(i==2) {continue;} poly[i] *=sx; poly[i+1] *=sy; }}void main(){int gdriver = DETECT,gmode;initgraph(&gdriver,&gmode,"../bgi");
char ch;setcolor(6);drawpoly(8,poly); do{
//cleardevice();ch=getch();if(ch==0){ ch = getch();}switch(ch){
case 72://up//y--;
// translate(0,-2);scaling(1.1,1.1);translate(-1.1,-1.1);break;
case 80://below
Computer Graphics 43
//y++; // translate(0,2);
scaling(-1.1,-1.1);translate(-1.1,-1.1);break;
/* case 75://left//x--;translate(-2,0);break;
case 77://right//x++;translate(2,0);break; */
default:{}
}/*gotoxy(x,y);cout<<"*"; */cleardevice();drawpoly(8,poly);
}while(ch!=13);
// drawpoly(8,poly);
getch();closegraph();}
Computer Graphics 44
Output:-
Computer Graphics 45
Rotation Transformation:-
A two dimensional rotation is applied to an object by repositioning it along a
circular path in the xy plane. To rotate a point, its coordinates and rotation angle
is required. Rotation is performed around a fixed point called pivot point. For a positive angle the
rotation will be anticlockwise where for negative angle rotation will be clockwise. We can
represent above equations with the help of column vectors:
P′= R . P
Where the rotation matrix is
P′= R= P=
As with translation, rotation is a rigid-body transformation that moves objects without
deformation.
Code in C++:-
#include<iostream.h>#include<conio.h>#include<graphics.h>#include<math.h>#define pi 3.14#define round(a)(int (a+0.5))//int poly[16] = {100,50,150,50,300,50,300,25,250,12,200,25,100,25,100,50};int x = 100,y = 400,x1,y1;void translate(int tx,int ty)
Computer Graphics 46
{ for(int i=0;i<16;i+=2) { x +=tx; y +=ty; }}
void rotate(double theta,double phi){ int c,s,c1,s1; theta = theta* round((pi/180)); phi = phi * round((pi/180)); c = cos(theta); s = sin(phi); c1= cos(phi); s1= sin(theta); for(int i=0;i<16;i+=2) { x1 = x * c - y * s; y1 = y * c1 + x * s1; }}
void main(){int gdriver = DETECT,gmode;initgraph(&gdriver,&gmode,"../bgi");
char ch;//int x=100,y=50;setcolor(6);moveto(400,100);lineto(x,y); do{
//cleardevice();ch=getch();if(ch==0){ ch = getch();}switch(ch){
Computer Graphics 47
case 43://+translate(-x,-y);rotate(0,15);translate(x,y);break;
case 45://-translate(-x,-y);rotate(0,15);translate(x,y);break;
default:{}
}cleardevice();lineto(x1,y1);
}while(ch!=13);
getch();closegraph();}
Computer Graphics 48
Output:-
Computer Graphics 49
Scaling Transformation:-
A scaling transformation changes the size of an object. Scaling may be in any terms means either
increasing the original size or decreasing the original size. Scaling with respect to origin is
achieved by multiplying x coordinate with factor Sx and y coordinate with factor Sy. Therefore,
following equations can be expressed:
x′ = x.Sx , y′ = y.Sy
In matrix form it can be expressed as:
P′ = S.P
= .
If we have scaling factor > 1 then the object size will be increased than original size; whereas; in
reverse case that is scaling factor < 1
the object size will be decreased than original size
Code in C++:-
#include <graphics.h>#include <conio.h>#include <iostream.h>int poly[16] ={100,50,150,50,300,50,300,25,250,12,200,25,100,25,100,50};
void translate(int tx,int ty){ for(int i=0;i<16;i+=2) { /* if(i==2) {continue;} */ poly[i] +=tx; poly[i+1] +=ty; }}
Computer Graphics 50
void scaling(float sx,float sy){ for(int i=0;i<16;i+=2) { if(i==2) {continue;} poly[i] *=sx; poly[i+1] *=sy; }}void main(){int gdriver = DETECT,gmode;initgraph(&gdriver,&gmode,"../bgi");
char ch;int x=100,y=50;setcolor(6);drawpoly(8,poly); do{
//cleardevice();ch=getch();if(ch==0){ ch = getch();}switch(ch){
case 43://+translate(-x,-y);scaling(1.1,1.1);translate(x,y);break;
case 45://-translate(-x,-y);scaling(0.9,0.9);translate(x,y);break;
/* case 75://lefttranslate(-2,0);break;
case 77://right
Computer Graphics 51
translate(2,0);break; */
default:{}
}cleardevice();drawpoly(8,poly);
}while(ch!=13);
getch();closegraph();}
Computer Graphics 52
Output:-
Computer Graphics 53
3 Dimensional translation:-
Code in visual C:-
#include "stdafx.h"#include "rotat3D.h"#include "rotat3DDoc.h"#include "rotat3DView.h"#include "stdlib.h"#include "math.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif
IMPLEMENT_DYNCREATE(CRotat3DView, CView)BEGIN_MESSAGE_MAP(CRotat3DView, CView)
ON_WM_CREATE()ON_WM_SIZE()ON_WM_LBUTTONDOWN()ON_WM_KEYDOWN()ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()struct p{
float x;float y;float z;
}ptFace[10];POINT pt[10];int CxClient,CyClient;// CRotat3DView construction/destructionCRotat3DView::CRotat3DView(){
// TODO: add construction code here}
CRotat3DView::~CRotat3DView(){}
BOOL CRotat3DView::PreCreateWindow(CREATESTRUCT& cs)
Computer Graphics 54
{
return CView::PreCreateWindow(cs);}
void CRotat3DView::OnDraw(CDC* pDC){
CRotat3DDoc* pDoc = GetDocument();ASSERT_VALID(pDoc);int ar[2]={5,5};pDC->SetMapMode(MM_ISOTROPIC);
pDC->SetWindowExt(500,500);pDC->SetViewportExt(CxClient,CyClient);pDC->SetViewportOrg(CxClient/2,CyClient/2);pDC->SetBkColor(RGB(0,255,0));
pDC->PolyPolygon(pt,ar,2);pDC->TextOut(pt[9].x,pt[9].y,"1");for(int i=0;i<5;i++){
pDC->MoveTo(pt[i]);pDC->LineTo(pt[i+5]);
}
}
BOOL CRotat3DView::OnPreparePrinting(CPrintInfo* pInfo){
return DoPreparePrinting(pInfo);}
void CRotat3DView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/){
// TODO: add extra initialization before printing}
void CRotat3DView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/){
// TODO: add cleanup after printing}
#ifdef _DEBUGvoid CRotat3DView::AssertValid() const{
CView::AssertValid();}
Computer Graphics 55
void CRotat3DView::Dump(CDumpContext& dc) const{
CView::Dump(dc);}
CRotat3DDoc* CRotat3DView::GetDocument() // non-debug version is inline{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CRotat3DDoc)));return (CRotat3DDoc*)m_pDocument;
}#endif //_DEBUGint CRotat3DView::OnCreate(LPCREATESTRUCT lpCreateStruct) {
if (CView::OnCreate(lpCreateStruct) == -1)return -1;
ptFace[0].x=50;ptFace[0].y=150;ptFace[0].z=150;
ptFace[1].x=100;ptFace[1].y=150;ptFace[1].z=150;
ptFace[2].x=100;ptFace[2].y=100;ptFace[2].z=150;
ptFace[3].x=75;ptFace[3].y=50;ptFace[3].z=150;
ptFace[4].x=50;ptFace[4].y=100;ptFace[4].z=150;
//Front Face
ptFace[5].x=50;ptFace[5].y=150;ptFace[5].z=50;
ptFace[6].x=100;ptFace[6].y=150;ptFace[6].z=50;
ptFace[7].x=100;ptFace[7].y=100;
Computer Graphics 56
ptFace[7].z=50;
ptFace[8].x=75;ptFace[8].y=50;ptFace[8].z=50;
ptFace[9].x=50;ptFace[9].y=100;ptFace[9].z=50;
synchro();return 0;}
void CRotat3DView::OnSize(UINT nType, int cx, int cy) {
CView::OnSize(nType, cx, cy);
CxClient=cx;CyClient=cy;
}
void CRotat3DView::OnLButtonDown(UINT nFlags, CPoint point) {
CView::OnLButtonDown(nFlags, point);}
void CRotat3DView::Translation(int x, int y){
for(int i=0;i<10;i++){
pt[i].x+=x;pt[i].y+=y;}
Perspective();}
void CRotat3DView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) {switch(nChar)
{case VK_UP:
Translation(0, -5);break;
case VK_DOWN:Translation(0, 5);break;
case VK_LEFT:
Computer Graphics 57
Translation(-5, 0);break;
case VK_RIGHT:Translation(5, 0);break;
case VK_ADD:Scale(1.2,1.2,1.2);break;
case VK_SUBTRACT:Scale(0.8,0.8,0.8);break;
case 'E':RotateX(1);break;
case 'F':RotateX(-1);break;
case 'Q':RotateY(1);break;
case 'W':RotateY(-1);break;
case 'B':RotateZ(1);break;
case 'N':RotateZ(-1);break;
case '1':Perspective();break;
case '2':Cabinet();break;
case '3':Cavalier();break;
}Invalidate(true);CView::OnKeyDown(nChar, nRepCnt, nFlags);
}
void CRotat3DView::Perspective(){
for(int i=0;i<10;i++){
ptFace[i].x=ptFace[i].z * pt[i].x /50;
Computer Graphics 58
ptFace[i].y=ptFace[i].z * pt[i].y /50;}
}
void CRotat3DView::Scale(float dx, float dy , float dz){for(int i=0;i<10;i++)
{pt[i].x*=dx;pt[i].y*=dy;
}Perspective();
}
void CRotat3DView::RotateX(int along){
float angle=(5.0*22.0)/(7*180)*along;for(int i=0;i<10;i++){
ptFace[i].x=ptFace[i].x*cos(angle)-ptFace[i].y*sin(angle);ptFace[i].y=ptFace[i].x*sin(angle)+ptFace[i].y*cos(angle);
}synchro();Perspective();
}
void CRotat3DView::synchro(){
for(int i=0;i<10;i++){
pt[i].x=ceil(50*ptFace[i].x/ptFace[i].z);pt[i].y=ceil(50*ptFace[i].y/ptFace[i].z);
}
}
void CRotat3DView::RotateY(int along){
float angle=(5.0*22.0)/(7*180)*along;for(int i=0;i<10;i++){
ptFace[i].x=ptFace[i].x*cos(angle)+ptFace[i].z*sin(angle);ptFace[i].z=-ptFace[i].x*sin(angle)+ptFace[i].z*cos(angle);
}synchro();Perspective();
}
Computer Graphics 59
void CRotat3DView::RotateZ(int along){
float angle=(5.0*22.0)/(7*180)*along;for(int i=0;i<10;i++){
ptFace[i].y=ptFace[i].y*cos(angle)-ptFace[i].z*sin(angle);ptFace[i].z=ptFace[i].y*sin(angle)+ptFace[i].z*cos(angle);
}synchro();Perspective();
}
void CRotat3DView::Cavalier(){
for(int i=0;i<10;i++){
ptFace[i].x=ptFace[i].x+ptFace[i].z*cos(45.0f);ptFace[i].y=ptFace[i].y+ptFace[i].z*sin(45.0f);
}synchro();
}
void CRotat3DView::Cabinet(){
for(int i=0;i<10;i++){
ptFace[i].x=ptFace[i].x+ptFace[i].z*cos(45.0f)/2;ptFace[i].y=ptFace[i].y+ptFace[i].z*sin(45.0f)/2;
}synchro();
}
Computer Graphics 60
Output:-
Computer Graphics 61
Grayscale:-
#include "stdafx.h"#include "Greyscale.h"#include "MainFrm.h"#include "GreyscaleDoc.h"#include "GreyscaleView.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifBEGIN_MESSAGE_MAP(CGreyscaleApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()CGreyscaleApp::CGreyscaleApp(){}
CGreyscaleApp theApp;
BOOL CGreyscaleApp::InitInstance(){
AfxEnableControlContainer();
#ifdef _AFXDLLEnable3dControls();
#else#endif
SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings();
CSingleDocTemplate* pDocTemplate;pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,RUNTIME_CLASS(CGreyscaleDoc),RUNTIME_CLASS(CMainFrame), RUNTIME_CLASS(CGreyscaleView));
Computer Graphics 62
AddDocTemplate(pDocTemplate);CCommandLineInfo cmdInfo;ParseCommandLine(cmdInfo);if (!ProcessShellCommand(cmdInfo))
return FALSE;m_pMainWnd->ShowWindow(SW_SHOW);m_pMainWnd->UpdateWindow();
return TRUE;}class CAboutDlg : public CDialog{public:
CAboutDlg();enum { IDD = IDD_ABOUTBOX };
protected:virtual void DoDataExchange(CDataExchange* pDX);
protected:
DECLARE_MESSAGE_MAP()};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX){
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
void CGreyscaleApp::OnAppAbout(){
CAboutDlg aboutDlg;aboutDlg.DoModal();
}
Computer Graphics 63
Output:-
Computer Graphics 64
Sharpning:-
Code invisual c:-#include "stdafx.h"#include "SharpeningFilter.h"#include "MainFrm.h"#include "SharpeningFilterDoc.h"#include "SharpeningFilterView.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifBEGIN_MESSAGE_MAP(CSharpeningFilterApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()CSharpeningFilterApp::CSharpeningFilterApp(){
}
CSharpeningFilterApp theApp;BOOL CSharpeningFilterApp::InitInstance(){
AfxEnableControlContainer();#ifdef _AFXDLLEnable3dControls(); #elseEnable3dControlsStatic();
#endifSetRegistryKey(_T("Local AppWizard-Generated Applications"));
LoadStdProfileSettingsCSingleDocTemplate* pDocTemplate;pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,RUNTIME_CLASS(CSharpeningFilterDoc),RUNTIME_CLASS(CMainFrame), RUNTIME_CLASS(CSharpeningFilterView));
AddDocTemplate(pDocTemplate);CCommandLineInfo cmdInfo;ParseCommandLine(cmdInfo);if (!ProcessShellCommand(cmdInfo))
Computer Graphics 65
return FALSE;m_pMainWnd->ShowWindow(SW_SHOW);m_pMainWnd->UpdateWindow();return TRUE;
}class CAboutDlg : public CDialog
{public:CAboutDlg();enum { IDD = IDD_ABOUTBOX };protected:virtual void DoDataExchange(CDataExchange* pDX); Protected:
DECLARE_MESSAGE_MAP()};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){}
void CAboutDlg::DoDataExchange(CDataExchange* pDX){
CDialog::DoDataExchange(pDX);}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()void CSharpeningFilterApp::OnAppAbout(){
CAboutDlg aboutDlg;aboutDlg.DoModal();
}
Computer Graphics 66
Output:-
Computer Graphics 67
Stretchblt:-
Code in visual C:-
#include "stdafx.h"#include "Stretchblt.h"#include "MainFrm.h"#include "StretchbltDoc.h"#include "StretchbltView.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifBEGIN_MESSAGE_MAP(CStretchbltApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()CStretchbltApp::CStretchbltApp(){}CStretchbltApp theApp;BOOL CStretchbltApp::InitInstance(){AfxEnableControlContainer();#ifdef _AFXDLL
Enable3dControls();#else
Enable3dControlsStatic();#endif
SetRegistryKey(_T("Local AppWizard-Generated Applications")); LoadStdProfileSettings();
CSingleDocTemplate* pDocTemplate;pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,RUNTIME_CLASS(CStretchbltDoc), RUNTIME_CLASS(CMainFrame), RUNTIME_CLASS(CStretchbltView));
AddDocTemplate(pDocTemplate);CCommandLineInfo cmdInfo;ParseCommandLine(cmdInfo);if (!ProcessShellCommand(cmdInfo))
return FALSE;
Computer Graphics 68
m_pMainWnd->ShowWindow(SW_SHOW);m_pMainWnd->UpdateWindow();
return TRUE;}class CAboutDlg : public CDialog{public:
CAboutDlg(); enum { IDD = IDD_ABOUTBOX }; protected:
virtual void DoDataExchange(CDataExchange* pDX); protected:
DECLARE_MESSAGE_MAP()};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){}void CAboutDlg::DoDataExchange(CDataExchange* pDX){
CDialog::DoDataExchange(pDX);}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)END_MESSAGE_MAP()void CStretchbltApp::OnAppAbout(){
CAboutDlg aboutDlg;aboutDlg.DoModal();
}
Computer Graphics 69
Output:-
Computer Graphics 70
Tran_proj_3D:-
Code in visual C:-
#include "stdafx.h"#include "Tran_Proj_3D.h"#include "Tran_Proj_3DDoc.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endifIMPLEMENT_DYNCREATE(CTran_Proj_3DDoc, CDocument)BEGIN_MESSAGE_MAP(CTran_Proj_3DDoc, CDocument)END_MESSAGE_MAP()CTran_Proj_3DDoc::CTran_Proj_3DDoc(){}CTran_Proj_3DDoc::~CTran_Proj_3DDoc(){}BOOL CTran_Proj_3DDoc::OnNewDocument(){
if (!CDocument::OnNewDocument())return FALSE;
return TRUE;}void CTran_Proj_3DDoc::Serialize(CArchive& ar){
if (ar.IsStoring()){
}else{
}}
#ifdef _DEBUGvoid CTran_Proj_3DDoc::AssertValid() const{
CDocument::AssertValid();}
Computer Graphics 71
void CTran_Proj_3DDoc::Dump(CDumpContext& dc) const{
CDocument::Dump(dc);}#endif
Computer Graphics 72
Output:-
Computer Graphics 73