CGR Allunits Notes Ankushhh
CGR Allunits Notes Ankushhh
Pixel:
A pixel (short for picture element, using the common abbreviation "pix" for
"picture") is one of the many tiny dots that make up the representation of a
picture in a computer's memory.
The intensity of each pixel is variable; in color systems, each pixel has
typically three or four dimensions of variability such as red, green and blue,
or cyan, magenta, yellow and black.
Resolution
• Resolution is the number of rows that appear from top to bottom of a screen
and in turn the number of pixels or pixel elements that appear from left to
right on each scanline.
1
UNIT 1: BASICS OF COMPUTER GRAPHICS
Text mode
• Text mode is a personal computer display setting that divides the display
screen into 25 rows and 80 columns in order to display text without images.
• In text mode, each box can contain one character. Text mode is also known as
character mode or alphanumeric mode. In character mode, the display screen
is treated as an array of blocks, each of which can hold one ASCII character.
Graphics Mode
The graphics-mode functions allow you to draw dots, lines, and shapes (like
circles, rectangles, and ellipse etc.), add color to lines and areas, and perform
many other graphics-related activities.
detectgraph() : This function checks the system and returns two integer
parameters: a value representing the system's graphics driver and a value for the
recommended graphics mode if an adapter is installed.
The mode value is the highest resolution possible with that adapter. Syntax:
detectgraph(int *gdriver, int *gmode); initgraph (): This library function must be
executed before any other graphics mode functions can be used.
This requires the GRAPHICS.Hheaderfile. Syntax: initgraph(int*driver, int
*mode, char *path); where *driver is the graphics driver,
given by an integer.
*mode is the graphics mode, given by an integer.
2
UNIT 1: BASICS OF COMPUTER GRAPHICS
*path is a string indicating where the driver is available note:The Driver
is a file extention BGI.Each type of hardware requires a different driver.A
null string ("") indicates sriver is in the current directory.
Graphics Pipeline
• A graphics pipeline can be divided into three main parts: Application, Geometry
and Rasterization.
The application step is executed by the software on the main processor (CPU), it cannot
be divided into individual steps, which are executed in a pipelined manner. However, it
is possible to parallelize it on multi-core processors or multi-processor systems. In the
application step, changes are made to the scene as required, for example, by user
interaction by means of input devices or during an animation. The new scene with all
its primitives, usually triangles, lines and points, is then passed on to the next step in
the pipeline.
The geometry step (with Geometry pipeline), which is responsible for the majority of
the operations with polygons and their vertices (with Vertex pipeline), can be divided
into the following five tasks. It depends on the particular implementation of how these
tasks are organized as actual parallel pipeline steps.
3
UNIT 1: BASICS OF COMPUTER GRAPHICS
The Rasterization step is the task of taking an image described in a vector graphics
format (shapes) and converting it into a raster image (pixels or dots) for output on a
video display or printer, or for storage in a bitmap file format. It refers to both
rasterization of models and 2D rendering primitives such as polygons, line segments,
etc.
Bitmap (or raster) images are stored as a series of tiny dots called pixels. Each pixel
is actually a very small square that is assigned a color, and then arranged in a pattern
to form the image. When you zoom in on a bitmap image you can see the individual
pixels that make up that image. The three most popular image formats used on the
Web (PNG, JPEG, and GIF) are bitmap formats. The bitmap format is excellent for
creating backgrounds and overlay elements.
Vector images are not based on pixel patterns, but instead use mathematical formulas
to draw lines and curves that can be combined to create an image from geometric
objects such as circles and polygons. All major browsers support the SVG (Scalable
Vector Graphics) format. Vector graphics are more flexible than bit- maps because
they can be easily re-sized. Vector-based graphics can be very useful when creating
large illustrations, as these graphics are resolution independent.
4
UNIT 1: BASICS OF COMPUTER GRAPHICS
• Cartography − Drawing maps.
• Weather Maps −Real-timemapping, symbolic representations.
• Satellite Imaging − Geodesic images.
• Photo Enhancement − Sharpening blurred photos.
• Medical imaging − MRIs, CAT scans, etc. - Non-invasive internal
examination.
• Engineering drawings − mechanical, electrical, civil, etc. - Replacing the
blueprints of thepast.
• Architecture − Construction plans, exterior sketches - replacing the blueprints
and hand drawings of the past.
• Art − Computers provide a new medium for artists.
• Entertainment − Movies and games.
• Simulationandmodeling−Replacingphysicalmodelingandenactments
RASTER-SCAN DISPLAYS
In a raster scan system, the electron beam is swept across the screen, one
row at a time from top to bottom. As the electron beam moves across each
row, the beam intensity is turned on and off to create a pattern of illuminated
spots.
5
UNIT 1: BASICS OF COMPUTER GRAPHICS
Each screen point is referred to as a pixel (picture element) or pel. At the end
of each scan line, the electron beam returns to the left side of the screen to
begin displaying the next scan line.
Random-Scan Display
In this technique, the electron beam is directed only to the part of the screen
where the picture is to be drawn rather than scanning from left to right and
top to bottom as in raster scan. It is also called vector display, stroke- writing
display, orcalligraphic display.
To display a specified picture, the system cycles through the set of commands
in the display file, drawing each component line in turn.
6
UNIT 1: BASICS OF COMPUTER GRAPHICS
After all the line-drawing commands are processed, the system cycles back to
the first line command in the list.
The term flat–panel displays refers to a class of video devices that have
reduced volume, weight, and power requirements compared to a CRT. A
significant feature of flat-panel displayed is that they are thinner than CRTs,
and we can hang them on walls or wear them on our wrists.
7
UNIT 1: BASICS OF COMPUTER GRAPHICS
Light-emitting diode (LED)
A matrix of diodes is arranged to form the pixel positions in the display, and picture
definition is stored in refresh buffer. As in scan- line refreshing of a CRT, information
is read from the refresh buffer and converted to voltage levels that are applied to the
diodes to produce the light patterns in the display.
• The working of the LED depends on the quantum theory.The energy of the
photons is equal to the gap between the higher and lower level.
• The LED is connected in the forward biased, which allows the current to flows
in the forward direction. The flow of current is because of the movement of
electrons in the opposite direction.
• The recombination shows that the electrons move from the conduction band to
valence band and they emit electromagnetic energy in the form of photons. The
energy of photons is equal to the gap between the valence and the conduction
band.
Advantages of LED’s
8
UNIT 1: BASICS OF COMPUTER GRAPHICS
Disadvantages of LED
• The LED consumes more power as compared to LCD, and their cost is high. Also,
it is not used for making the large display.
Advantages of an LCD’s:
Disadvantages of an LCD’s:
9
UNIT 1: BASICS OF COMPUTER GRAPHICS
Applications of Liquid Crystal Display
• Liquid crystal thermometer ,Optical imaging, Used in the medical applications
Touch Screen
• A touch screen is a computer display screen that is also an input device. The
screens are sensitive to pressure; a user interacts with the computer by touching
pictures or words on the screen.
• There are three types oftouch screen technology:
Output primitives
• The Primitives are the simple geometric functions that are used to generate
various Computer Graphics required by the User. Some most basic Output
primitives are point-position (pixel), and a straight line.
• Line, polygon , marker , text.
Line Attributes
• A straight-line segment can be displayed with three basic attributes: color, width,
and style. Additionally, lines may be generated with other effects, such as pen and
brush strokes.
• To set line type attributes in a PHICS application program, a user invokes the
function :setLinetype (It)
where parameter It is assigned a positive integer value of 1,2,3, or 4 to generate lines
that are, respectively, solid, dashed, dotted, or dash-dotted.
10
UNIT 1: BASICS OF COMPUTER GRAPHICS
Marker Attributes
• A marker symbol display single character in a different color and in different sizes.
• We select marker type using the function. setMarkerType (mt) Where marker
type parameter mt set to an integer code.
• Typical codes for marker type are the integers 1 through 5, specifying,
respectively, a dot (.), a vertical cross (+), an asterisk (*), a circle (o), and a
diagonal cross (x). Displayed marker types centered on the marker coordinates.
Text Attributes
The attributes that can be assigned to text are common knowledge nowadays: Font
(e.g. Courier, Arial, Times, Broadway, …), style (normal, bold, italic, underlined, …),
size, text direction, color, alignment (left, right, centered, justified) and so on.
Attributes of Polygons
Graphics Functions
Standard graphics formats allow images to be moved from machine to machine, while
standard graphics languages let graphics programs be moved from machine to
machine. For example, GKS, PHIGS and OpenGL are major graphics languages .
GDI and DirectX are the graphics languages in Windows.
11
UNIT 1: BASICS OF COMPUTER GRAPHICS
Putpixel function is to draw the pixel on the screen. Pixel is small dot on the screen.
Example: – putpixel(100,100,BLUE);
Rectangle function is used to draw the rectangle on the screen. X1,y1 are the lower
left co-ordinates of the rectangle and the x2,y2 are the upper right co- ordinates of the
rectangle.
Syntax: line(x1,y1,x2,y2);
Example:-line(100,100,200,100);
Example:-ellipse(100,100,90,200,20,20);
Virtual reality
12
UNIT 1: BASICS OF COMPUTER GRAPHICS
Types of Virtual reality (VR) System
1. Windows on World(WoW)
2. Immersive VR
3. Telepresence
13
UNIT 1: BASICS OF COMPUTER GRAPHICS
▪ Input Processor
– Control the devices used to input information to the computer. The
object is to get the coordinate data to the rest of the system with minimal
lagtime.
▪ Simulation Processor
– Core of a VR system.
– Takes the user inputs along with any tasks programmed into the world
and determine the actions that will take place in thevirtual world.
▪ Rendering Processor
– Separate rendering processes are used for visual, auditory, haptic and
other sensory systems. Each renderer takes a description of the world
stat from the simulation process for each time step.
Applications
▪ Entertainment
▪ Medicine
▪ Manufacturing
14
UNIT 1: BASICS OF COMPUTER GRAPHICS
▪ Education & Training
– Head-mounted display
– Tracking system
• Military:
• Medical:
– Superimpose an image from an MRI onto a patient’s body.
• Education:
– Used in labs where students can learn more about the experiments they
are participatingin.
• Gaming:
15
UNIT 1: BASICS OF COMPUTER GRAPHICS
16
UNIT 2: RASTER SCAN GRAPHICS
dx = X2 – X1 dy
= Y2 – Y1
length = abs(dx);
else length =
abs(dy);
1
UNIT 2: RASTER SCAN GRAPHICS
2
UNIT 2: RASTER SCAN GRAPHICS
(18 Marks)
3
UNIT 2: RASTER SCAN GRAPHICS
DDA Algorithm
Digital Differential Analyzer (DDA) algorithm is the simple line generation algorithm which is explained
step by step here.
Step 1 − Get the input of two end points (X1, Y1) and (X2, Y2).
Step 2 − Calculate the difference between two end points.
Step 3 − Based on the calculated difference in step-2, you need to identify the number of steps to put
pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate.
Step 5 − Put the pixel by successfully incrementing x and y coordinates accordingly and complete the
drawing of the line.
4
{ x = x + Xinc;
UNIT 2: RASTER SCAN GRAPHICS
y = y + Yinc;
putpixel(Round(x), Round(y));
5
UNIT 2: RASTER SCAN GRAPHICS
6
UNIT 2: RASTER SCAN GRAPHICS
#include<stdio.h>
#include<conio.h>
#include<graphics.h> void main()
{ int x1,y1,x2,y2,dx,dy,length,i; float
x,y,xinc,yinc;
int gd=DETECT,gm;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("Enter the starting coordinates");
scanf("%d%d",&x1,&y1); printf("Enter the
ending coordinates"); scanf("%d%d",&x2,&y2);
dx=x2-x1; dy=y2-y1; if(abs(dx)>abs(dy))
length=abs(dx); else length=abs(dy);
xinc=dx/(float)length; yinc=dy/(float)length;
x=x1; y=y1; putpixel(x,y,10);
for(i=0;i<length;i++)
{
7
UNIT 2: RASTER SCAN GRAPHICS
putpixel(x,y,10); x=x+xinc; y=y+yinc;
8
UNIT 2: RASTER SCAN GRAPHICS
delay(10);
} getch();
closegraph();
}
Advantages of DDA Algorithm
1. It is the simplest algorithm and it does not require special skills for implementation.
2. It is a faster method for calculating pixel positions.
Disadvantages of DDA Algorithm
1. Floating point arithmetic in DDA algorithm is still time-consuming.
2. The algorithm is orientation dependent. Hence end point accuracy is poor.
e=e-2*dx
}
x=x+1
9
UNIT 2: RASTER SCAN GRAPHICS
e=e+2*dy
10
UNIT 2: RASTER SCAN GRAPHICS
8. i=i+1
9. if(i<dx) then goto step 6. 10. Stop.
11
UNIT 2: RASTER SCAN GRAPHICS
12
UNIT 2: RASTER SCAN GRAPHICS
y=y+1; e=e+2*(dy-dx);
} putpixel(x,y,15);
} getch();
closegraph();
}
Problem: - Consider the line from (5, 5) to (13, 9). Use the Bresenham's algorithm to rasterize
the line. Solution:-
Evaluating steps 1 through 4 in the Bresenham’s algorithm we have, Given: - step 1:-
x1 = 5, y1 = 5 and x2 = 13, y2 = 9.
Step 2:- Δx = | 13 - 5| =8 Δy = | 9 - 5 | = 4
Step 3:- x = 5, y = 5
Step 4:- e = 2 * Δy - Δx = 2 * 4 - 8 = 0.
Tabulating the results of each iteration in the step 5 through 10.
13
UNIT 2: RASTER SCAN GRAPHICS
14
Round Off DDA algorithm round off the Bresenhams algorithm does not
coordinates to integer that is nearest round off but takes the incremental
to the line. value in its operation.
Drawing a circle: To draw a circle we need two things, the coordinates of the centre and the radius
of the circle.
Here r is the radius of the circle. If the circle has origin (0,0) as its centre then the above
equation can be reduced to x2 + y2 = r2
Bresenham’s Algorithm
We cannot display a continuous arc on the raster display. Instead, we have to choose the nearest
pixel position to complete the arc.
From the following illustration, you can see that we have put the pixel at (X, Y) location and
now need to decide where to put the next pixel − at N (X+1, Y) or at S (X+1, Y-1).
16
7
UNIT 2: RASTER SCAN GRAPHICS
18
1. Read the radius of circle.
UNIT 2: RASTER SCAN GRAPHICS
2. Calculate initial decision parameter di=3-2r
3. x=0 and y=r [initialize the starting point]
4. Do
{
5. Plot(x,y)//plot point(x,y) and other 7 points in all octant
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<dos.h>
#include<graphics.h> void bressn(int,int,int); void plot(int,int,int,int); void plot(int xc,int yc,int x,int y)
{
putpixel(xc+x,yc+y,WHITE); putpixel(xc-x,yc+y,RED); putpixel(xc-x,yc-y,GREEN); putpixel(xc+x,yc-
y,YELLOW); putpixel(xc+y,yc+x,WHITE); putpixel(xc-y,yc+x,GREEN); putpixel(xc-y,yc-x,YELLOW);
putpixel(xc+y,yc-x,RED);
}
void bressn(int r,int xc,int yc)
20
UNIT 2: RASTER SCAN GRAPHICS
21
UNIT 2: RASTER SCAN GRAPHICS
{ int d,x,y; d=3-
(2*r); x=0; y=r;
while(x<y)
{ plot(xc,yc,x,y); x=x+1;
if(d<0)
{ d=d+(4*x)+6;
} else { y=y-1; d=d+4*(x-
y)+10;
} plot(xc,yc,x,y);
} } void main()
{ int gd,gm; int xc,yc,radius;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("\n enter xc,yc,radius");
scanf("%d%d%d",&xc,&yc,&radius);
bressn(xc,yc,radius); getch(); closegraph();
}
Example :
x y d
0 10 -17
1 10 -11
2 10 -1
3 10 13
4 9 -5
5 9 17
6 8 11
7 7 13
22
UNIT 2: RASTER SCAN GRAPHICS
Calculate the pixel position along the circle path with radius r=10 centered on the origin using
23
UNIT 2: RASTER SCAN GRAPHICS
Bresenham’s circle drawing algorithm from point (0,10) to point x=y. Solution:
The value of d is d=3-2r=3-2*10=-17
Tabulating results of step 4
Polygon:
A polygon is any 2-dimensional shape formed with straight lines. Triangles, quadrilaterals, pentagons,
and hexagons are all examples of polygons.
Types of polygon:
Every polygon is either convex or concave.
The difference between convex and concave polygons lies in the measures of their angles. For a
polygon to be convex, all of its interior angles must be less than 180 degrees.
Otherwise, the polygon is concave.
Inside-Outside Test
This method is also known as counting number method. While filling an object, we often need to
identify whether particular point is inside the object or outside it. There are two methods by which we
can identify whether particular point is inside an object or outside. -Even Rule
mber rule
Odd-Even Rule
24
UNIT 2: RASTER SCAN GRAPHICS
In this technique, we will count the edge crossing along the line from any point (x,y) to infinity. If the
25
UNIT 2: RASTER SCAN GRAPHICS
number of interactions is odd, then the point (x,y) is an interior point; and if the number of interactions
is even, then the point (x,y) is an exterior point. The following example depicts this concept.
From the above figure, we can see that from the point (x,y), the number of interactions point on the left
side is 5 and on the right side is 3. From both ends, the number of interaction points is odd, so the point
is considered within the object. Nonzero Winding Number Rule
This method is also used with the simple polygons to test the given point is interior or not.
Give the value 1 to all the edges which are going to upward direction and all other -1 as direction
values.
• Check the edge direction values from which the scan line is passing and sum up them.
• If the total sum of this direction value is non-zero, then this point to be tested is an interior point,
otherwise it is an exterior point.
• In the above figure, we sum up the direction values from which the scan line is passing then the
total is 1 – 1 + 1 = 1; which is non-zero. So the point is said to be an interior point.
Polygon filling:
• Polygon filling algorithms are classified as: seed fill algorithm and scan line algorithm.
26
UNIT 2: RASTER SCAN GRAPHICS
27
UNIT 2: RASTER SCAN GRAPHICS
• One way to fill polygon is to start from given “seed”, point known to be inside the polygon and
highlight outward from this point i.e. neighboring pixels until we encounter the boundary pixels.
This approach is called seed fill.
• Seed fill algorithm further classified as flood fill and boundary fill algorithm.
• Algorithms the fill interior defined regions are flood fill algorithms; those that fill boundary defined
regions are called boundary fill algorithm.
• Another approach to fill the polygon is to apply the inside test i.e. to check whether the pixels is
inside the polygon or outside the polygon and then highlight pixels which lie inside the polygon.
This approach is known as scan-line algorithm.
4−Connected Regions From a given pixel, the region that you can get to by a series of 4 way moves
(north, south, east, west)
void fillcolor(int x,int y,int old_color,int new_color)
{
if(getpixel(x,y)==old_color)
{ delay(5);
putpixel(x,y,new_color);
fillcolor(x+1,y,old_color,new_color); fillcolor(x-1,y,old_color,new_color);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y-1,old_color,new_color);
}
}
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h> #include<dos.h>
void fillcolor(int,int,int,int);
void main()
{ int gd,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
rectangle(50,50,100,100); fillcolor(55,55,0,11);
getch();
28
UNIT 2: RASTER SCAN GRAPHICS
closegraph();
29
UNIT 2: RASTER SCAN GRAPHICS
}
void fillcolor(int x,int y,int old_color,int new_color)
{
if(getpixel(x,y)==old_color)
{ delay(5);
putpixel(x,y,new_color); fillcolor(x+1,y,old_color,new_color);
fillcolor(x-1,y,old_color,new_color);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y-
1,old_color,new_color);
}
}
8−Connected Regions From a given pixel, the region that you can get to by a series of 8-way moves
(north, south, east, west, NE, NW, SE, SW) void fillcolor(int x,int y,int old_color,int new_color)
{
if(getpixel(x,y)==old_color)
{ delay(5);
putpixel(x,y,new_color); fillcolor(x+1,y,old_color,new_color);
fillcolor(x-1,y,old_color,new_color);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y-
1,old_color,new_color); fillcolor(x+1,y+1,old_color,new_color);
fillcolor(x+1,y-1,old_color,new_color); fillcolor(x-1,y-
1,old_color,new_color); fillcolor(x-1,y+1,old_color,new_color);
}
}
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h> #include<dos.h>
void fillcolor(int,int,int,int);
void main()
{ int gd,gm;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
rectangle(50,50,100,100); fillcolor(55,55,0,11);
getch(); closegraph();
}
void fillcolor(int x,int y,int old_color,int new_color) {
30
UNIT 2: RASTER SCAN GRAPHICS
if(getpixel(x,y)==old_color)
31
UNIT 2: RASTER SCAN GRAPHICS
{ delay(5);
putpixel(x,y,new_color); fillcolor(x+1,y,old_color,new_color);
fillcolor(x-1,y,old_color,new_color);
fillcolor(x,y+1,old_color,new_color); fillcolor(x,y-
1,old_color,new_color); fillcolor(x+1,y+1,old_color,new_color);
fillcolor(x+1,y-1,old_color,new_color); fillcolor(x-1,y-
1,old_color,new_color); fillcolor(x-1,y+1,old_color,new_color);
}
}
32
UNIT 2: RASTER SCAN GRAPHICS
getch(); closegraph(); }
33
UNIT 2: RASTER SCAN GRAPHICS
void boundary_fill(int x,int y,int fcolor,int bcolor)
{
if((getpixel(x,y)!=bcolor)&&(getpixel(x,y)!=fcolor))
{ delay(5); putpixel(x,y,fcolor);
boundary_fill(x+1,y,fcolor,bcolor);
boundary_fill(x-1,y,fcolor,bcolor);
boundary_fill(x,y+1,fcolor,bcolor);
boundary_fill(x,y-1,fcolor,bcolor);
}
}
8-connected boundary fill Algorithm:- boundary_fill(x, y,
f_colour, b_colour)
{
if(getpixel(x, y)! = b_colour && getpixel(x, y)! = f_colour)
{
putpixel(x, y, f_colour); boundary_fill(x + 1, y, f_colour,
b_colour); boundary_fill(x - 1, y, f_colour, b_colour);
boundary_fill(x, y + 1, f_colour, b_colour);
boundary_fill(x, y - 1, f_colour, b_colour);
boundary_fill(x + 1, y + 1, f_colour, b_colour);
boundary_fill (x - 1, y - 1, f_colour, b_colour);
boundary_fill(x + 1, y - 1, f_colour, b_colour);
boundary_fill(x - 1, y + 1, f_colour, b_colour);
}
}
Program:
#include<stdio.h>
#include<conio.h>
#include<graphics.h> #include<dos.h>
void boundary_fill(int,int,int,int);
void main() { int gd,gm; detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
rectangle(50,50,100,100);
boundary_fill(55,55,6,15);
getch(); closegraph(); }
void boundary_fill(int x,int y,int fcolor,int bcolor) {
34
UNIT 2: RASTER SCAN GRAPHICS
if((getpixel(x,y)!=bcolor)&&(getpixel(x,y)!=fcolor))
{
delay(5);
putpixel(x,y,fcolor);
boundary_fill(x+1,y,fcolor,bcolor);
boundary_fill(x-1,y,fcolor,bcolor);
boundary_fill(x,y+1,fcolor,bcolor);
boundary_fill(x,y-1,fcolor,bcolor);
boundary_fill(x+1,y+1,fcolor,bcolor);
boundary_fill(x-1,y+1,fcolor,bcolor);
boundary_fill(x+1,y-1,fcolor,bcolor);
boundary_fill(x-1,y-1,fcolor,bcolor);
}
}
35
UNIT 2: RASTER SCAN GRAPHICS
• These components will contain an edge’s information, hold all of the edges that compose the
figure and maintain the current edges being used to fill in the polygon, respectively.
• When a scan line intersects an edge endpoint, it intersects two edges. Consider, Two cases: –
Case A: edges are monotonically increasing or decreasing, we should consider this as only ONE edge
intersection
– Case B: edges reverse direction at endpoint; we should consider this as TWO edge intersections
Stepwise Procedure
1. Read n, the number of vertices of polygon.
2. Read x and y coordinates of all vertices in array X[n] and y[n].
3. Find y max and y min
4. Store the initial x value (x1),y values (y1 and y2) and x increment dx from scan line to scan line for each edge
in the array edges[n] [4].
a. While doing this check that y1> y2, if not , interchange y1 and y2 corresponding x1 and x2 so that for
each edge, y1 represents its maximum y coordinate and y2 represents its minimum y coordinate.
36
UNIT 2: RASTER SCAN GRAPHICS
5. Sort the rows of array, edges[n] [4] in descending order of y1, descending order of y2, and ascending order of
37
UNIT 2: RASTER SCAN GRAPHICS
x2
6. Set y=y max
7. Find the active edges and update active edge list:
a. if ( y>y2 and y<y1) i {edge is active} b. Else i {edge is not active}
8. Compute the x intersects for all active edges for current y value. Initially x intersect is x1 and x intersects for
successive y values can be given as a. x(i+1)dxi+dx
b. where dx=-1/m and m=y2-y1/x2-x1 i.e. .slope of a line segment.
9. if x intersect is vertex i.e. x intersect =x1 and y=y1 then apply vertex test to check whether to consider one
intersect or two intersects. Store all x intersects in the x intersects array.
10. Store x intersects array in the ascending order.
11. Extract pairs of intersects from the sorted x intersect array.
12. Pass pairs of x values to line drawing routine to draw corresponding line segments.
13.-set y=y-1
14. Repeat steps 7 through 13 until y> ymin
15. Stop
Program:
Program:
#include <stdio.h>
#include <conio.h> #include <graphics.h> main()
{ int n,i,j,k,gd,gm,dy,dx; int x,y,temp;
int a[20][2],xi[20];
float slope[20]; clrscr(); printf("\n\n\tEnter the no. of edges of polygon : ");
scanf("%d",&n);
printf("\n\n\tEnter the cordinates of polygon :\n\n\n "); for(i=0;i<n;i++)
{
printf("\tX%d Y%d : ",i,i); scanf("%d %d",&a[i][0],&a[i][1]);
} a[n][0]=a[0][0]; a[n][1]=a[0][1]; detectgraph(&gd,&gm);
initgraph(&gd,&gm,"c:\\turboc3\\bgi"); /*- draw polygon -*/ for(i=0;i<n;i++)
{ line(a[i][0],a[i][1],a[i+1][0],a[i+1][1]);
38
UNIT 2: RASTER SCAN GRAPHICS
} getch(); for(i=0;i<n;i++) { dy=a[i+1][1]-a[i][1]; dx=a[i+1][0]-a[i][0];
39
UNIT 2: RASTER SCAN GRAPHICS
if(dy==0) slope[i]=1.0; if(dx==0) slope[i]=0.0;
if((dy!=0)&&(dx!=0)) /*- calculate inverse slope -*/
{ slope[i]=(float) dx/dy;
}
} for(y=0;y< 480;y++)
{ k=0; for(i=0;i<n;i++)
{ if( ((a[i][1]<=y)&&(a[i+1][1]>y))|| ((a[i][1]>y)&&(a[i+1][1]<=y)))
{ xi[k]=(int)(a[i][0]+slope[i]*(y-a[i][1])); k++;
}
} for(j=0;j<k-1;j++) /*- Arrange x-intersections in order -*/ for(i=0;i<k-1;i++)
{ if(xi[i]>xi[i+1])
{ temp=xi[i]; xi[i]=xi[i+1]; xi[i+1]=temp;
} } setcolor(35); for(i=0;i<k;i+=2)
{
line(xi[i],y,xi[i+1]+1,y); getch();
}
}
}
Scan conversion
• The process of representing continuous graphics objects as a collection of discrete pixels is called scan
conversion. Scan conversion serves as a bridge between TV and computer graphics technology.
• Scan conversion or scan converting rate is a video processing technique for changing the vertical / horizontal
scan frequency of video signal for different purposes and applications.
• The application of scan conversion: video projectors, cinema equipment, TV and video capture cards, standard
and HDTV televisions, LCD monitors, radar displays and many different aspects of picture processing.
40
UNIT 2: RASTER SCAN GRAPHICS
• There are two distinct methods for changing a picture's data rate:
41
UNIT 2: RASTER SCAN GRAPHICS
• This conversion is done using large numbers of delay cells and is appropriate for analog video.It may also be
performed using a specialized scan converter vacuum tube.
• In this case polar coordinates (angle and distance) data from a source such as a radar receiver, so that it can be
displayed on a raster scan (TV type) display.
• In this method, a picture is stored in a line or frame buffer with n1 speed (data rate) and is read with n2 speed.
Frame buffer:
• Each screen pixel corresponds to a particular entry in a 2D array residing in memory. This memory is called a
frame buffer or a bit map.
• The number of rows in the frame buffer equals to the number of raster lines on the display screen. The number
of columns in this array equals to the number of pixels on each raster line.
• Frame buffer is a large part of computer memory used to store display image. Different kind of memory can be
used for frame buffers like drums, disk or IC – shift registers.
• To generate a pixel of desired intensity to read the disk or drum. The information stored in disk or drum is in
digital for, hence it is necessary to convert it into analog from using DAC and then this analog signal is used to
generate the pixel.
Character Generation
42
UNIT 2: RASTER SCAN GRAPHICS
• Most of the times characters are builts into the graphics display devices, usallay as hardware but sometimes
43
UNIT 2: RASTER SCAN GRAPHICS
through software.
• The small series of line segments are drawn like a strokes of a pen to form a character as shown in figure.
• Here it is necessary to decide which line segments are needed for each character and
2. Starbust method
• In this method a fix pattern of line segments are used to generate characters.
• Out of 24 line segments, segments required to display for particular character, are highlighted
44
UNIT 2: RASTER SCAN GRAPHICS
45
UNIT 2: RASTER SCAN GRAPHICS
This method of character generation has some disadvantages. They are
46
UNIT 2: RASTER SCAN GRAPHICS
1. The 24-bits are required to represent a character. Hence more memory is required 2. Requires code conversion
software to display character from its 24-bit code
3. Character quality is poor. It is worst for curve shaped characters.
3. Bitmap Method
• Also known as dot matrix because in this method characters are represented by an array of dots in the matrix
form.
• It’s a two dimensional array having columns and rows: 5 X 7 as shown in figure.
47
UNIT 3: OVERVIEW OF TRANSFORMATION
Q. What is meant by transformations?
2D Translation
Q. What is 2d translation?
[1 0 tx]
[0 1 ty]
Matrix Representation
OR P’ = P + T
Program: Write a program for 2D Translation of a Triangle.
#include<stdio.h>
#include<conio.h> #include<graphics.h>
#include<process.h> #include<math.h>
int x1,y1,x2,y2,x3,y3,mx, my;
UNIT 3: OVERVIEW OF TRANSFORMATION
void draw();
void tri(); void
main()
{
int gd=DETECT,gm; int c; initgraph(&gd,&gm,"c:\\turboc3\\bgi ");
printf("Enter the 1st point for the triangle:");
scanf("%d%d",&x1,&y1); printf("Enter the 2nd
point for the triangle:"); scanf("%d%d",&x2,&y2);
printf("Enter the 3rd point for the triangle:");
scanf("%d%d",&x3,&y3);
void draw()
{
line(x1,y1,x2,y 2);
line(x2,y2,x3,y
3); line(x3,y3,x1,y
1);
} void tri() {
int x,y,a1,a2,a3,b1,b2,b3; printf("Enter the
Transaction coordinates");
scanf("%d%d",&x, &y);
cleardevice(); a1=x1+x;
b1=y1+y; a2=x2+x;
b2=y2+y;
UNIT 3: OVERVIEW OF TRANSFORMATION
a3=x3+x; b3=y3+y;
line(a1,b1,a2,b
2);
line(a2,b2,a3,b
3);
line(a3,b3,a1,b
1); }
Ans.
1. Rotation is a fundamental transformation in computer graphics that
involves rotating an object around a fixed point by a certain angle. It
is commonly used to create animations, simulate physical systems,
and manipulate images.
2. In 2D graphics, rotation can be achieved by multiplying the
coordinates of each point in the object by a rotation matrix.
3. The rotation matrix is defined by the angle of rotation and the axis
of rotation.
4. For example, a 90-degree clockwise rotation can be achieved by
multiplying the coordinates by the matrix [0 -1; 1 0]. This will flip the
x and y coordinates and rotate the object by 90 degrees. x = r cos
(φ)
y = r sin (φ)
x’ = r cos (φ + θ)
y’ = r sin (φ + θ)
x’ = r cos (φ + θ)
= r cos(φ) cos(θ) – r sin(φ) sin(θ)
= x cos(θ) – y sin(θ)
P’ = P. R
For positive rotation angle, we can use the above rotation matrix.
However, for negative angle rotation, the matrix will change as shown
below.
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<process.h> #include<math.h>
void triangle(int x1,int y1,int x2,int y2,int x3,int y3);
void Rotate(int x1,int y1,int x2,int y2,int x3,int y3); void
main()
{
int gd=DETECT,gm;
int x1,y1,x2,y2,x3,y3;
initgraph(&gd,&gm,"c:\\turboc3\\bgi");
printf("Enter the 1st point for the triangle:"); scanf("%d%d",&x1,&y1);
printf("Enter the 2nd point for the triangle:"); scanf("%d%d",&x2,&y2);
printf("Enter the 3rd point for the triangle:");
scanf("%d%d",&x3,&y3);
triangle(x1,y1,x2,y2,x3,y3);
getch(); cleardevice();
Rotate(x1,y1,x2,y2,x3,y3);
setcolor(1);
triangle(x1,y1,x2,y2,x3,y3);
getch();
}
void triangle(int x1,int y1,int x2,int y2,int x3,int y3)
{
line(x1,y1,x2,y2); line(x2,y2,x3,y3);
line(x3,y3,x1,y1);
}
void Rotate(int x1,int y1,int x2,int y2,int x3,int y3)
{
int x,y,a1,b1,a2,b2,a3,b3,p=x2,q=y2; float
Angle;
printf("Enter the angle for rotation:");
scanf("%f",&Angle); cleardevice();
Angle=(Angle*3.14)/180; a1=p+(x1-
p)*cos(Angle)-(y1-q)*sin(Angle);
b1=q+(x1-p)*sin(Angle)+(y1-q)*cos(Angle);
a2=p+(x2-p)*cos(Angle)-(y2-q)*sin(Angle);
b2=q+(x2-p)*sin(Angle)+(y2-q)*cos(Angle);
a3=p+(x3-p)*cos(Angle)-(y3-q)*sin(Angle);
b3=q+(x3-p)*sin(Angle)+(y3-q)*cos(Angle);
printf("Rotate"); triangle(a1,b1,a2,b2,a3,b3);
}
Let us suppose you want to rotate it at the angle θ. After rotating it to a
new location, you will get a new point P’ (X’, Y’).
Counter clockwise(anticlockwise) rotation
Clockwise Rotation
Shear
A transformation that slants the shape of an object is called the shear
transformation. There are two shear transformations X-Shear and
YShear. One shifts X coordinates values and other shifts Y coordinate
values. However; in both the cases only one coordinate changes its
coordinates and other preserves its values. Shearing is also termed as
Skewing.
X-Shear
The X-Shear preserves the Y coordinate and changes are made to X
coordinates, which causes the vertical lines to tilt right or left as shown in
below figure.
X' = X + Shx . Y
Y’ = Y
Y-Shear
The Y-Shear preserves the X coordinates and changes the Y coordinates
which causes the horizontal lines to transform into lines which slopes up
or down as shown in the following figure.
1 00 shx 1 0
X shear with y reference line: - shx*yref 0 1
Scaling
Sx 0 0 0
S= 0 Sy 0 0
0 0 Sz 0
0 0 0 1
0 -sinθ cosθ 0
0 0 0 1
Rotation about Y
axis
Projection
Projection in computer graphics means the transformation of a
threedimensional (3D) area into a two-dimensional (2D) area.
Parallel Projection
Parallel projection discards z-coordinate and parallel lines from each
vertex on the object are extended until they intersect the view plane. In
parallel projection, we specify a direction of projection instead of center of
projection.
In parallel projection, the distance from the center of projection to project
plane is infinite. In this type of projection, we connect the projected
vertices by line segments which correspond to connections on the
original object.
Perspective Projection
The perspective projection on the other hand produces realistic views but
does not preserve relative proportions. In perspective projection, the lines
of projections are not parallel. Instead they all converge at a single point
called center of projection or projection reference point.
Orthographic Projection
In orthographic projection the direction of projection is normal
(perpendicular) to the projection of the plane.
Classified as Axonometric orthographic projection
The orthographic projection can display more than one face of an object
is called axonometric orthographic projection.
Isometric: - All the principle axis are foreshortened equally.
Dimetric :- Two principle axis are foreshortened equally.
Trimetric: - All the three principle axis are foreshortened unequally.
Multi-view orthographic projection
Top view
Front view
Side view
Oblique Projection
In oblique projection, the direction of projection is not normal to the
projection of plane. In oblique projection, we can view the object better
than orthographic projection.
There are two types of oblique projections − Cavalier and Cabinet. The
Cavalier projection makes 45° angle with the projection plane. The
projection of a line perpendicular to the view plane has the same length
as the line itself in Cavalier projection. In a cavalier projection, the
foreshortening factors for all three principal directions are equal.
The Cabinet projection makes 63.4° angle with the projection plane. In
Cabinet projection, lines perpendicular to the viewing surface are
projected at ½ their actual length. Both the projections are shown in the
following figure −
.
Perspective Projection
In perspective projection, the distance from the center of projection to
project plane is finite and the size of the object varies inversely with
distance which looks more realistic.
The distance and angles are not preserved and parallel lines do not
remain parallel. Instead, they all converge at a single point called
Vanishing point. There are 3 types of perspective projections which are
shown in the following chart.
• One point perspective projection is simple to draw.
• Two point perspective projection gives better impression of depth.
• Three point perspective projection is most difficult to draw.
The following figure shows all the three types of perspective projection −
UNIT IV : Windowing And Clipping (14 Marks)
The picture is stored in the computer memory using any convenient Cartesian co-ordinate system,
referred to as World Co-Ordinate System (WCS). However, when picture is displayed on the display
device it is measured in Physical Device Co-Ordinate System (PDCS) corresponding to the
displaydevice.
The viewing transformation which maps picture co-ordinates in the WCS to display co-ordinates in
PDCS is performed by the following transformations.
Line clipping:
In line clipping, we will cut the portion of line which is outside of window and keep only
the portion that is inside the window.
As shown in fig three lines are given in which one line is inside window so that is displayed,
second line is completely outside so it is discarded after clipping, and third line is clipped as it
is partially in so that much part is displayed and remaining part is discarded.
Line clipping in given window.
Algorithm:
2. Read 2 corner points of the clipping window (left-top and right-bottom) as (wx1,wy1) and
(wx2,wy2) 3. Assign the region codes for 2 endpoints p1 and p2 using following steps:- initialize
Set bit 1 if
y>wy1
a. If region codes for both endpoints are zero then line is completely visible. Draw the line
go to step 9.
b. If region codes for endpoints are not zero and logical ANDing of them is also nonzero
then line is invisible. Discard the line and move to step 9.
c. If it does not satisfy 4.a and 4.b then line is partially visible.
b. If region codes for any one end point is non zero then find intersection point p1’ or p2’.
9. Stop.
Program:
#include<stdio.h>
#include<graphics.h
> void main()
{
int gd=DETECT, gm; float
i,xmax,ymax,xmin,ymin,x11,y11,x22,y22,m;
float a[4],b[4],c[4],x1,y1; clrscr();
initgraph(&gd,&gm,"c:\\turboc3\\bgi"
);
printf("\nEnter the bottom-left coordinate of viewport:
"); scanf("%f %f",&xmin,&ymin); printf("\nEnter the
top-right coordinate of viewport: ");
scanf("%f %f",&xmax,&ymax);
rectangle(xmin,ymin,xmax,ymax); printf("\nEnter the
coordinates of 1st end point of line:
"); scanf("%f %f",&x11,&y11); printf("\nEnter the
coordinates of 2nd endpoint of line: "); scanf("%f
%f",&x22,&y22); line(x11,y11,x22,y22);
for(i=0;i<4;i++)
{ a[i]=0;
b[i]=0;
}
m=(y22-y11)/(x22-x11);
if(x11<xmin) a[3]=1;
if(x11>xmax) a[2]=1;
if(y11<ymin) a[1]=1;
if(y11>ymax) a[0]=1;
if(x22<xmin) b[3]=1;
if(x22>xmax) b[2]=1;
if(y22<ymin) b[1]=1;
if(y22>ymax) b[0]=1;
printf("\nRegion code of 1st pt
"); for(i=0;i<4;i++)
{printf("%f",a[i]);}
printf("\nRegion code of 2nd pt
"); for(i=0;i<4;i++)
{printf("%f",b[i]);
} printf("\nAnding
: ");
for(i=0;i<4;i++)
{c[i]=a[i]&&b[i];}
for(i=0;i<4;i++)
printf("%f",c[i]);
getch();
if((c[0]==0)&&(c[1]==0)&&(c[2]==0)&&(c[3]==0))
{
if((a[0]==0)&&(a[1]==0)&&(a[2]==0)&&(a[3]==0)&&
(b[0]==0)&&(b[1]==0)&&(b[2]==0)&&(b[3]==0))
{ clrscr(); clearviewport(); printf("\nThe line is totally
visible\nand not a clipping candidate");
rectangle(xmin,ymin,xmax,ymax); line(x11,y11,x22,y22);
getch();
} else
{
clrscr();
clearviewport(); printf("\nLine is
partially visible");
rectangle(xmin,ymin,xmax,ymax);
line(x11,y11,x22,y22); getch();
if((a[0]==0)&&(a[1]==1))
{
x1=x11+(ymin-
y11)/m; x11=x1;
y11=ymin;
}
else if((b[0]==0)&&(b[1]==1))
{
x1=x22+(ymin-y22)/m;
x22=x1;
y22=ymin;
}
if((a[0]==1)&&(a[1]==0))
{
x1=x11+(ymax-y11)/m;
x11=x1; y11=ymax;
}
else if((b[0]==1)&&(b[1]==0))
{
x1=x22+(ymax-y22)/m; x22=x1;
y22=ymax;
}
if((a[2]==0)&&(a[3]==1))
{
y1=y11+m*(xmin-x11);
y11=y1; x11=xmin;
}
else if((b[2]==0)&&(b[3]==1))
{
y1=y22+m*(xmin-
x22); y22=y1; x22=xmin;
}
if((a[2]==1)&&(a[3]==
0))
{
y1=y11+m*(xmax-x11); y11=y1;
x11=xmax;
}
else if((b[2]==1)&&(b[3]==0))
{
y1=y22+m*(xmax-x22);
y22=y1;
x22=xmax; } clrscr();
clearviewport(); printf("\nAfter
clippling:");
rectangle(xmin,ymin,xmax,ymax);
line(x11,y11,x22,y22);
getch();
}
} else
{
clrscr(); clearviewport();
printf("\nLine is
invisible");
rectangle(xmin,ymin,xmax,ymax);
getch();
}
closegraph(); getch();
}
Cyrus–Beck algorithm
Cyrus and Beck developed an algorithm for clipping to arbitrary convex regions. Cyrus-
Beck algorithm uses the normal vector for determining whether a point is inside, on, or
outside a window. Consider a convex planar polygon R. Consider the parametric
representation of a line from P1 to P2.
If ‘f ’ is a boundary point of the convex region R and n is an inner normal for one of its
boundaries, then for any particular value of t, i.e. any particular point on line P1P2.
Together these conditions show that for a convex polygon, an infinite line, which
intersects the boundary of the region, does so at precisely two points. Further, these
two points do not lie on the same boundary edge. Thus n• [P(t) –f] = 0 has only one
solution. If the point ‘f ’ lies in the boundary edge for which n is the inner normal,
then that point (t) on the line P(t) which satisfies this condition is the intersection
of the line and the boundary edge.
Algorithm:
Liang-Barsky Line Clipping
• The ideas for clipping line of Liang-Barsky and Cyrus-Beck are the same.
The only difference is Liang-Barsky algorithm has been optimized for an
upright rectangular clip window.
• Liang and Barsky have created an algorithm that uses floating-point
arithmetic but finds the appropriate end points with at most four
computations.
• This algorithm uses the parametric equations for a line and solves four
inequalities to find the range of the parameter for which the line is in the
viewport.
4. In the Liang-Barsky approach we first the point clipping condition in parametric form:
Xmin≤X1+UΔX≤XmaxXmin≤X1+UΔX≤Xmax
Ymin≤Y1+UΔY≤YmaxYmin≤Y1+UΔY≤Ymax
5. Each of these four inequalities can be expressed as: μpk ≤ qk for k=1,2,3,4
6. The parameters p & q are defined as:
p1 = -ΔX and q1 = X1 – Xmin (Left Boundary)
p2 = ΔX and q2 = Xmax - x1 (Right Boundary)
P3 = -ΔY and q3 = Y1- Ymin (Bottom Boundary)
P4 = ΔY and q4 = Ymax - y1 (TopBoundary)
7. If a line is parallel to a view window boundary, the p value for that boundary is zero.
8. If the line is parallel to the X axis, for example then p1 and p2 must be zero.
o Given pk = 0, if qk < 0 then line is trivially invisible because it is outside view
window.
o Given pk = 0, if qk > 0 then the line is inside the corresponding window
boundary.
9. When pk < 0, as U increase line goes from the outside to inside i.e. entering.
10. When pk > 0, linegoes from inside to outside i.e. exiting.
11. If there is a segment of line inside the clip region, a sequence of infinite line
intersections must go entering, entering, exiting, and exiting as shown in figure.
Algorithm:
Advantages
1. More efficient than other algorithms as line intersection with boundaries calculations are reduced.
#include<stdio.h>
#include<conio.h>
#include< graphics.h>
#include<dos.h>
#define ROUND(a)((int)(a+0.5))
int cliptest(float p,float q,float *u1,float *u2)
{ float r; int
retval=1;
if(p<0.0)
{
r=q/p;
if(r>*u2
)
retval=0;
if(r>*u1)
*u1=r;
}
else if(p>0.0)
{
r=q/p;
if(r<*u1
)
retval=0 ;
if(r<*u2)
*u2=r;
}
else if(q<0.0)
retval=0
; return(retval);
}
void clipline(int minx,int miny,int maxx,int maxy,int x1,int y1,int x2,int y2)
{
float u1=0.0,u2=1.0,dx=x2-x1,dy;
if(cliptest(-dx,x1- minx,&u1,&u2))
if(cliptest(dx,maxx- x1,&u1,&u2))
{
dy=y2-y1; if(cliptest(-dy,y1-
miny,&u1,&u2))
if(cliptest(dy,maxy-
y1,&u1,&u2))
{
if(u2<1.0)
{
x2=x1+u2*dx; y2=y1+u2*dy;
}
if(u1>0.0)
{
x1+=u1*dx;
y1+=u1*dy
;
}
line(x1,y1,x2,y2);
}
}
}
void main()
{ int
gdriver=DETECT,gmode,x1,y1,x2,y2,minx,miny,maxx,maxy;
initgraph(&gdriver,&gmode,"c:\\turboc3\\bgi"); clrscr();
printf("Enter the min & max x values: "); scanf("%d
%d",&minx,&maxx); printf("Enter the min & max y values:
"); scanf("%d %d",&miny,&maxy);
printf("Enter the first endpoint: ");
scanf("%d %d",&x1,&y1);
printf("Enter the second endpoint:
");
scanf("%d %d",&x2,&y2);
clrscr();
printf("Before Clipping");
line(x1,y1,x2,y2);
rectangle(minx,maxy,maxx,miny
); getch(); clrscr(); printf("After
Clipping");
clipline(minx,miny,maxx,maxy,x1,y1,x2,y2 );
rectangle(minx,maxy,maxx,miny); getch();
}
Midpoint subdivision algorithm is an extension of the Cyrus Beck algorithm. This algorithm is
mainly used to compute visible areas of lines that are present in the view port are of the sector or
the image.
Algorithm :
Program:
Each edge of the polygon must be tested against each edge of the clip rectangle.
New edges must be added, and existing edges must be discarded, retained, or divided.
Multiple polygons may result from clipping a single polygon. We need an organized way to
deal with all these cases.
Program:
// Sutherland Hodgeman Polygon Clipping
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>
void clip(float,float,float);
int i,j=0,n; int
rx1,rx2,ry1,ry2;
float x1[8],y1[8];
void main()
{
int gd=DETECT,gm;
int i,n; float
x[8],y[8],m;
clrscr();
initgraph(&gd,&gm,"c:\\turboc3\\bgi"); printf("coordinates
for rectangle : ");
scanf("%d%d%d%d",&rx1,&ry1,&rx2,&ry2);
printf("no. of sides for polygon : ");
scanf("%d",&n); printf("coordinates
: ");
for(i=0;i<n;i++)
{
scanf("%f%f",&x[i],&y[i]);
}
cleardevice();
outtextxy(10,10,"Before clipping");
outtextxy(10,470,"Press any key. ..
"); rectangle(rx1,ry1,rx2,ry2);
for(i=0;i<n-1;i++)
line(x[i],y[i],x[i+1],y[i+1]);
line(x[i],y[i],x[0],y[0]); getch();
cleardevice();
for(i=0;i<n-1;i++)
{
m=(y[i+1]-y[i])/(x[i+1]-x[i]);
clip(x[i],y[i],m); clip(x[i+1],y[i+1],m);
}
m=(y[i]-y[0])/(x[i]-x[0]);
clip(x[i],y[i],m); clip(x[0],y[0],m);
outtextxy(10,10,"After clipping");
outtextxy(10,470,"Press any key. ..
"); rectangle(rx1,ry1,rx2,ry2);
for(i=0;i<j-1;i++)
line(x1[i],y1[i],x1[i+1],y1[i+1]);
getch();
}