# Liang Barsky Line Clipping Algorithm (C++)

#include <conio.h>
#include <iostream.h>
#include <graphics.h>
void main(){
int gdriver = DETECT, gmode;
initgraph(&gdriver,&gmode,”C:\TC\BGI”);
setcolor(BLUE);
int xl,yl,xh,yh;
cout<<“Enter bottom left and top right co-ordinates of the window: “;
cin>>xl>>yl>>xh>>yh;
rectangle(xl,yl,xh,yh);
int x1,y1,x2,y2;
cout<<“Enter endpoints of the line: “;
cin>>x1>>y1>>x2>>y2;
line(x1,y1,x2,y2);
getch();

int p,q,i,accept=1;                               // To decide if line has to be shown are not
float u,umin=0,umax=1;
p = -(x2-x1);
p = (x2-x1);
p = (y2-y1);                                                  //These two equations have to be inverted as in computer
p = -(y2-y1);                                               //we have y increasing as we go below, opp. to that on paper
q = x1-xl;
q = xh-x1;
q = yl-y1;                                                   //These two equations have to be inverted for same reason
q = y1-yh;

for(i=0;i<4;i++){
if(p[i]!=0){
u[i] = (float)q[i]/p[i];
if(p[i]<0 && u[i]>umin)                          //Line is entering and therefore check for umin
umin = u[i];
else if(p[i]>0 && u[i]<umax)               //Line is exiting and therefore check for umax
umax = u[i];
}else if(p[i]==0 && q[i]<0)                 //Line is invisible as pk=0 & qk<0
accept=0;
}
cout<<“After clipping: “;
if(accept==1 && umax>umin){
int x3,y3,x4,y4;
x3 = x1 + (x2-x1)*umin;
y3 = y1 + (y2-y1)*umin;
x4 = x1 + (x2-x1)*umax;
y4 = y1 + (y2-y1)*umax;
setcolor(WHITE);
line(x3,y3,x4,y4);
}
getch();
closegraph();
}