#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <math.h>
// this function initializes graphics mode
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function
void init_gr(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
/* initialize graphics mode */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) /* an error occurred */
{
printf("Graphics error: %s\n", grapherrormsg
(errorcode
));
printf("Press any key to halt:");
getch();
exit(1); /* return with error code */
}
}
// this function shuts graphics mode down
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function
void end_gr(void)
{
closegraph();
}
// this function puts pixel on the screen in (x,y) position using color 'color'
// it will work only if you're using Borland C++ compiler & BGI drivers
// if you're using another compiler you should overwrite body of this function
void PutPixel(int x, int y, int color)
{
putpixel(x,y,color);
}
void BLine(int x1,int y1,int x2, int y2, int color)
{
int delta_x,delta_y,incx,incy,t,distance;
int xerr=0,yerr=0;
// determine dx and dy
delta_x=x2-x1;
delta_y=y2-y1;
// determine steps by x and y axes (it will be +1 if we move in forward
// direction and -1 if we move in backward direction
if (delta_x>0) incx=1;
else if (delta_x==0) incx=0;
else incx=-1;
if (delta_y>0) incy=1;
else if (delta_y==0) incy=0;
else incy=-1;
delta_x=abs(delta_x);
delta_y=abs(delta_y);
// select largest from deltas and use it as a main distance
if (delta_x>delta_y) distance=delta_x;
else distance=delta_y;
for (t=0;t<=distance+1;t++)
{
PutPixel(x1,y1,color);
// increasing error
xerr+=delta_x;
yerr+=delta_y;
// if error is too big then we should decrease it by changing
// coordinates of the next plotting point to make it closer
// to the true line
if(xerr>distance)
{
xerr-=distance;
x1+=incx;
}
if (yerr>distance)
{
yerr-=distance;
y1+=incy;
}
}
}
int main(void)
{
// initializing graphics mode
init_gr();
/* examples */
BLine(0, 0, 640, 480,15);
BLine(320, 0, 320, 480,10);
BLine(0, 240, 640, 240,11);
BLine(0, 480, 640, 0,12);
BLine(320, 11, 10, 5,13);
BLine(320, 11, 630, 5,13);
/* clean up */
getch();
end_gr();
return 0;
}