cohen-sutherland算法c++代码
时间: 2023-10-18 19:05:22 浏览: 147
以下是C语言实现的Cohen-Sutherland算法代码:
#include <stdio.h>
#include <graphics.h>
#define INSIDE 0
#define LEFT 1
#define RIGHT 2
#define BOTTOM 4
#define TOP 8
int xmin, ymin, xmax, ymax;
int ComputeOutCode(int x, int y) {
int code = INSIDE;
if (x < xmin) {
code |= LEFT;
} else if (x > xmax) {
code |= RIGHT;
}
if (y < ymin) {
code |= BOTTOM;
} else if (y > ymax) {
code |= TOP;
}
return code;
}
void CohenSutherland(int x1, int y1, int x2, int y2) {
int outcode1 = ComputeOutCode(x1, y1);
int outcode2 = ComputeOutCode(x2, y2);
while (1) {
if (!(outcode1 | outcode2)) {
// Both points inside window
line(x1, y1, x2, y2);
break;
} else if (outcode1 & outcode2) {
// Both points outside window and same region
break;
} else {
int x, y, outcode;
// At least one endpoint is outside the window
if (outcode1) {
outcode = outcode1;
} else {
outcode = outcode2;
}
// Find intersection point
if (outcode & TOP) {
x = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1);
y = ymax;
} else if (outcode & BOTTOM) {
x = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1);
y = ymin;
} else if (outcode & RIGHT) {
y = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1);
x = xmax;
} else if (outcode & LEFT) {
y = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1);
x = xmin;
}
// Update the point and outcode
if (outcode == outcode1) {
x1 = x;
y1 = y;
outcode1 = ComputeOutCode(x1, y1);
} else {
x2 = x;
y2 = y;
outcode2 = ComputeOutCode(x2, y2);
}
}
}
}
int main() {
int gd = DETECT, gm;
initgraph(&gd, &gm, "");
xmin = 50;
ymin = 50;
xmax = 200;
ymax = 200;
rectangle(xmin, ymin, xmax, ymax);
// Test cases
CohenSutherland(10, 10, 300, 300);
CohenSutherland(0, 150, 250, 150);
CohenSutherland(150, 0, 150, 250);
CohenSutherland(250, 250, 350, 350);
getch();
closegraph();
return 0;
}
阅读全文