Program To Implement Cohen-Sutherland Line Clipping Algorithm
Program To Implement Cohen-Sutherland Line Clipping Algorithm
#include <graphics.h> #include<iostream> #include <stdlib.h> #include <stdio.h> #include <conio.h> int round(int a) { return((int)(a+0.5)); } using namespace std; void lineclip(int xmin,int xmax,int ymin,int ymax,int x1,int x2,int y1,int y2) { int a[4]={0,0,0,0},b[4]={0,0,0,0}; float m=(y2-y1)/(x2-x1); float c=y1-(m*x1); cleardevice(); rectangle(xmin,ymin,xmax,ymax); if(x1<xmin) { a[3]=1; x1=xmin; y1=m*x1+c; } if(x1>xmax) { a[2]=1; x1=xmax; y1=m*x1+c; } if(y1<ymin) { a[1]=1; y1=ymin; x1=(y1-c)/m; } if(y1>ymax) { a[0]=1; y1=ymax; x1=(y1-c)/m;
} if(x2>xmax) { b[2]=1; x2=xmax; y2=x2*m+c; } if(y2<ymin) { b[1]=1; y2=ymin; x2=(y2-c)/m; } if(y2>ymax) { b[0]=1; y2=ymax; x2=(y2-c)/m; } for(int i=0;i<4;i++) { if(a[i]*b[i]==1) { cout<<"Line not Visible..!!"; getch(); exit(1); } } line(round(x1),round(y1),round(x2),round(y2)); }
int main(void) { /* request auto detection */ // int gdriver = DETECT, gmode, int errorcode; int xmin,xmax,ymin,ymax,x1,y1,x2,y2; /* initialize graphics, local variables */ //initgraph(&gdriver, &gmode, ""); initwindow(700,700); /* 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); /* terminate with an error code */ } cout<<"Enter coordinates of Window:"; cout<<"\n\n Enter X min:";
cin>>xmin; cout<<"\nEnter Y min:"; cin>>ymin; cout<<"\nEnter X max:"; cin>>xmax; cout<<"\nEnter Y max:"; cin>>ymax; cout<<"\nEnter coordinates of Line to clip:"; cout<<"\n\nEnter starting coordinates:"; cout<<"\n\nEnter X coordinate:"; cin>>x1; cout<<"\nEnter Y coordinate:"; cin>>y1; cout<<"\nEnter ending coordinates:"; cout<<"\n\nEnter X coordinate:"; cin>>x2; cout<<"\nEnter Y coordinate:"; cin>>y2; cleardevice(); rectangle(xmin,ymin,xmax,ymax); line(x1,y1,x2,y2); getch(); lineclip(xmin,xmax,ymin,ymax,x1,x2,y1,y2); /* clean up */ getch(); closegraph(); return 0; }