clip_try.cpp
来自「数据结构实验课中的所有实验程序」· C++ 代码 · 共 133 行
CPP
133 行
// clip_try.cpp : Defines the entry point for the console application.
//
//进行各种与定义,便于程序编写
#define ROUND(a) ((int)(a+0.5))
//define bit mask for OR operation
#define LEFT_EDGE 0x1
#define RIGHT_EDGE 0x2
#define BOTTOM_EDGE 0x4
#define TOP_EDGE 0x8
//define the determine status
#define INSIDE(a) (!a)
#define REJECT(a,b) (a&b)
#define ACCEPT(a,b) (!(a|b))
//定义画线段的函数
#define drawOneLine(x1,y1,x2,y2) glBegin(GL_LINES); \
glVertex2f ((x1),(y1)); glVertex2f ((x2),(y2)); glEnd();
//-------------------------------
//My code!
//-------------------------------
//此函数实现确定给定的点在哪个区域
unsigned char encode(float x, float y, float minx, float maxx, float miny, float maxy)
{
//定义code在矩形区域内,即编码为0000
unsigned char code = 0x00;
//以下四个条件语句通过比较给定点的坐标与矩形区域的坐标得到所给定点//的编码
if (x<minx)
code = code|LEFT_EDGE;
if (x>maxx)
code = code|RIGHT_EDGE;
if (y<miny)
code = code|BOTTOM_EDGE;
if (y>maxy)
code = code|TOP_EDGE;
return code;
}
//此函数实现 sutherland algorithm
void myclip(float x1, float y1, float x2, float y2, float minx, float maxx, float miny, float maxy)
{
//TODO Code Application Logic here
unsigned char code1,code2,tempcode;
int done = false,draw = false;
float m,temp;
//当满足线段完全可见,完全不可见或者将在矩形外的点转化为线段与对应
//边的交点后结束循环
while(!done)
{
//调用encode函数找到给定点的逻辑编码
code1 = encode(x1, y1, minx, maxx, miny, maxy);
code2 = encode(x2, y2, minx, maxx, miny, maxy);
//如果线段完全在矩形内跳出循环,draw=true画出矩形内的线段 if (ACCEPT(code1, code2))
{
done = true;
draw = true;
}
//否则如果线段完全不可见跳出循环,draw=false没有线段在矩形内所以//不需要重新画线段
else
if (REJECT(code1, code2))
done = true;
//否则判断code1是否在矩形内,如果成立则交换code1和code2,然后//找沿code2的线段与边的交点,然后画出code1到交点的线段。
//如果code1不在矩形内,找到沿code1与对应边的交点,然后再用同样//的方法处理code2。最后画出在矩形内部的部分线段。
else
{
if (INSIDE(code1))
{
temp = x1;
x1=x2;
x2=temp;
temp = y1;
y1=y2;
y2=temp;
tempcode = code1;
code1 = code2;
code2 = tempcode;
}
if (x2!=x1)
m = (y2-y1)/(x2-x1);
//找沿矩形外的点与对应边的交点
if (code1 & LEFT_EDGE)
{
y1 += (minx-x1)*m;
x1 = minx;
}
else
if (code1 & RIGHT_EDGE)
{
y1 += (maxx-x1)*m;
x1 = maxx;
}
else
if (code1 & BOTTOM_EDGE)
{
if (x2!=x1)
x1 += (miny-y1)/m;
y1 = miny;
}
else
if (code1 & TOP_EDGE)
{
if (x2!=x1)
x1 += (maxy-y1)/m;
y1 = maxy;
}
}
}
if(draw)
{
//如果矩形区域内有线段则用蓝颜色画出裁减后在矩形区域内的线段
glColor3f (0.1, 0.1,1.0);
drawOneLine (x1, y1, x2, y2);
}
}
//显示函数
void CALLBACK display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
// The window
// we can change the window definition certainly.
glColor4f (0.0, 1.0, 1.0, 0.1);
//通过四个定点画出矩形区域
glBegin(GL_POLYGON);
glVertex2f( 0.2f, 0.3f); // Bottom Left
glVertex2f( 0.7f, 0.3f); // Bottom Left
glVertex2f( 0.7f, 0.65f); // Bottom Right
glVertex2f( 0.2f, 0.65f); // Bottom Right
glEnd();
//开始用白色的线画出原始线段
glColor3f (1.0, 1.0, 1.0); drawOneLine (0.4,0.4,0.6,0.68);
//在给定的矩形区域内进行裁减
myclip(0.4,0.4,0.6,0.68, 0.2, 0.7, 0.3, 0.65);
glFlush();
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?