/*
* THIS IS A C PROGRAM THAT IMPLEMENTS INTEGER BRESENHAM'S LINE DRAWING ALGORITHM
*/
#include"compgrap.h"
void modifiedbresenham(int, int, int, int) ;
int sign(int);
void swap(int *,int *);
int main(void)
{
int x1, y1, x2, y2 ;
initialize(); /* basic initialisation */
printf("\n Enter the coordinates of the first point: ");
scanf("%d%d",&x1,&y1) ;
printf("\n Enter the coordinates of the second point: ");
scanf("%d%d",&x2,&y2) ;
clrscr();
cleardevice() ;
/* creating a grid */
creategrid(DARKGRAY, DARKGRAY) ;
/* setting shading style and highlight color of a cell */
setfillstyle(1, DARKGRAY) ;
/* drawing approximated straight line by Integer Bresenham Line Rasterisation algorithm */
modifiedbresenham(x1, y1, x2, y2) ;
/* drawing an actual line segment from (x1,y1) to (x2,y2) */
setcolor(WHITE);
drawline(x1, y1, x2, y2) ;
getch();
closegraph(); /* closing the graph */
return 0;
}
/* Implementation of Modified Integer Bresenham Line Rasterisation algorithm */
void modifiedbresenham(int x1, int y1, int x2, int y2)
{
int i, x, y, dx, dy, e, s1, s2, inter ;
/* since drawing straight lines should be very rapid, we skip the overhead of
* computing the pixels, when the straight line will be an exact horizontal or
* vertical one. We keep provisions for checking whether a straight line will be
* vertical or horizontal one. */
if(y1==y2) { /* for a horizontal line */
x = min(x1, x2);
y = y1;
while(x<=max(x1,x2))
{
plot(x,y);
x+=1;
}
}
else if(x1==x2) { /* for a vertical line */
y = min(y1, y2);
x = x1;
while(y<=max(y1,y2))
{
plot(x,y);
y+=1;
}
}
else if(abs(x2-x1)==abs(y2-y1)) { /* for lines with slopes +1 and -1 */
x=x1;
y=y1;
do
{
plot(x,y);
x+=sign(x2-x1);
y+=sign(y2-y1);
}while(x!=x2 && y!=y2);
plot(x,y);
}
else { /* for straight lines with other slopes */
x = x1 ;
y = y1 ;
s1 = sign(x2-x1);
s2 = sign(y2-y1);
dx = abs(x2 - x1) ;
dy = abs(y2 - y1) ;
if(dy>dx) {
swap(&dx,&dy) ;
inter = 1;
}
else
inter = 0;
e = 2*dy - dx ;
for(i=1; i<=dx; i++) {
plot(x,y);
while(e>=0) {
if(inter==1)
x+=s1;
else
y+=s2;
e-=2*dx;
}
if(inter==1)
y+=s2;
else
x+=s1;
e+=2*dy ;
}
}
}
/* function returns +1, -1 or 0 according as the argument is
* positive, negative or zero */
int sign(int a)
{
return a>0 ? 1:(a<0 ? -1:0) ;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
No comments:
Post a Comment
Do you think this information useful or was not up to the mark? Comment if you have any advices or suggestions about the post.