Practical-No:-12
-Write a C program for Line Clipping using Cohen- Sutherland algorithm.
Code:-
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#define LEFT 1
#define RIGHT 2
#define BOTTOM 4
#define TOP 8
typedef struct {
int x, y;
} Point;
int xmin = 100, ymin = 100, xmax = 300, ymax = 300;
int computeRegionCode(Point p) {
int code = 0;
if (p.x < xmin)
code |= LEFT;
else if (p.x > xmax)
code |= RIGHT;
if (p.y < ymin)
code |= BOTTOM;
else if (p.y > ymax)
code |= TOP;
return code;
}
void cohenSutherlandClip(Point p1, Point p2) {
int code1 = computeRegionCode(p1);
int code2 = computeRegionCode(p2);
int accept = 0;
while (1) {
if ((code1 == 0) && (code2 == 0)) {
accept = 1;
break;
} else if ((code1 & code2) != 0) {
break;
} else {
int codeOut;
float x, y;
if (code1 != 0) {
codeOut = code1;
} else {
codeOut = code2;
}
if (codeOut & TOP) {
x = p1.x + (p2.x - p1.x) * (ymax - p1.y) / (p2.y - p1.y);
y = ymax;
} else if (codeOut & BOTTOM) {
x = p1.x + (p2.x - p1.x) * (ymin - p1.y) / (p2.y - p1.y);
y = ymin;
} else if (codeOut & RIGHT) {
y = p1.y + (p2.y - p1.y) * (xmax - p1.x) / (p2.x - p1.x);
x = xmax;
} else if (codeOut & LEFT) {
y = p1.y + (p2.y - p1.y) * (xmin - p1.x) / (p2.x - p1.x);
x = xmin;
}
if (codeOut == code1) {
p1.x = x;
p1.y = y;
code1 = computeRegionCode(p1);
} else {
p2.x = x;
p2.y = y;
code2 = computeRegionCode(p2);
}
}
}
if (accept) {
setcolor(WHITE);
line(p1.x, p1.y, p2.x, p2.y);
printf("Line accepted from (%d, %d) to (%d, %d)\n", p1.x, p1.y, p2.x, p2.y);
} else {
printf("Line rejected\n");
}
}
void main() {
int gd = DETECT, gm;
Point p1, p2;
initgraph(&gd, &gm, "");
setcolor(RED);
rectangle(xmin, ymin, xmax, ymax);
printf("Enter the coordinates of the first point (x1, y1): ");
scanf("%d %d", &p1.x, &p1.y);
printf("Enter the coordinates of the second point (x2, y2): ");
scanf("%d %d", &p2.x, &p2.y);
setcolor(GREEN);
line(p1.x, p1.y, p2.x, p2.y);
cohenSutherlandClip(p1, p2);
getch();
closegraph();
}
Output:-