Cohen Sutherland算法

主要是 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);
}

参考: 计算机图形学基础教程 孙家广 胡事民 编

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值