主要是 Cohen Sutherland直线段裁剪算法,建议先了解该算法基本原理后在看算法的具体实现,其中直线的绘制可采用上个博客写的 bresenham算法完成
#include"tgaimage.h"
#define LEFT 1
#define RIGHT 2
#define BOTTOM 4
#define TOP 8
const TGAColor white = TGAColor(255, 255, 255, 255);
const TGAColor red = TGAColor(255, 0, 0, 255);
const TGAColor blue = TGAColor(0, 0, 255, 255);
int left = 0, right = 200;
int bottom = 0, top = 300;
int encode(int x, int y);
void CSLineClip(int x1, int y1, int x2, int y2, TGAImage image, TGAColor color);
void Line(int x1, int y1, int x2, int y2, TGAImage image, TGAColor color);
int main(int argc, char** argv) {
TGAImage image(right - left, top - bottom, TGAImage::RGB);
CSLineClip(0, 0, 100, 100, image, red);
image.flip_vertically();
image.write_tga_file("output.tga");
return 0;
}
void Line(int x1, int y1, int x2, int y2, TGAImage image, TGAColor color)
{
// TODO 直线算法
}
int encode(int x, int y)
{
int c = 0;
if (y > top) c |= TOP;
if (y < bottom) c |= BOTTOM;
if (x > right) c |= RIGHT;
if (x < left) c |= LEFT;
return c;
}
void CSLineClip(int x1, int y1, int x2, int y2, TGAImage image, TGAColor color)
{
int code1, code2, code;
int x, y;
code1 = encode(x1, y1);
code2 = encode(x2, y2);
while (code1 != 0 || code2 != 0)
{
if ((code1 & code2) != 0) return; // 两点在同一外侧
if (code1 != 0) code = code1; // code1 在外侧 ,否则 code2 在外侧
else code = code2; // 此时我们需要 将外侧这个点给分割删去
if ((LEFT & code) != 0) // 此时某一侧外点在左侧, 亦可写(LEFT & code) == 1 同理
{
x = left;
y = y1 + (y2 - y1) * (x - x1) / (x2 - x1);
}
else if ((RIGHT & code) != 0)
{
x = right;
y = y1+ (y2 - y1) * (x - x1) / (x2 - x1);
}else if((TOP& code)!= 0)
{
y = top;
x = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
}
else if ((BOTTOM & code) != 0)
{
y = bottom;
x = x1 + (x2 - x1) * (y - y1) / (y2 - y1);
}
if (code == code1) // 裁剪完一边后, 继续判断另一边
{
x1 = x, y1 = y;
code1 = encode(x1, y1);
}
else
{
x2 = x, y2 = y;
code1 = encode(x2, y2);
}
}
Line(x1, y1, x2, y2, image, color);
}
参考: 计算机图形学基础教程 孙家广 胡事民 编