原理
编码裁剪算法中,为了快速判断一条直线段与矩形窗口的位置关系,采用了如图A.4所示的空间划分和编码方案。
裁剪一条线段时,先求出两端点所在的区号code1和code2,若code1 = 0且code2 = 0,则说明线段的两个端点均在窗口内,那么整条线段必在窗口内,应取之;若code1和code2经按位与运算的结果不为0,则说明两个端点同在窗口的上方、下方、左方或右方。这种情况下,对线段的处理是弃之。如果上述两种条件都不成立,则按第三种情况处理。求出线段与窗口某边的交点,在交点处把线段一分为二,其中必有一段完全在窗口外,可弃之,对另一段则重复上述处理。
代码示例和结果
1.Cohen-Surtherland算法
代码:
#include "stdafx.h"
#include <glut.h>
#include <stdio.h>
#include <stdlib.h>
#define LEFT_EDGE 1
#define RIGHT_EDGE 2
#define BOTTOM_EDGE 4
#define TOP_EDGE 8
void LineGL(int x0,int y0,int x1,int y1)
{
glBegin (GL_LINES);
glColor3f (1.0f, 0.0f, 0.0f); glVertex2f (x0,y0);
glColor3f (0.0f, 1.0f, 0.0f); glVertex2f (x1,y1);
glEnd ();
}
struct Rectangle
{
float xmin,xmax,ymin,ymax;
};
Rectangle rect;
int x0,y0,x1,y1;
int CompCode(int x,int y,Rectangle rect)
{
int code=0x00;
if(y<rect.ymin)
code=code|4;
if(y>rect.ymax)
code=code|8;
if(x>rect.xmax)
code=code|2;
if(x<rect.xmin)
code=code|1;
return code;
}
int cohensutherlandlineclip(Rectangle rect, int &x0,int & y0,int &x1,int &y1)
{
int accept,done;
float x,y;
accept=0;
d