OpenGL Computer Graphics Experiment - Clipping of Line Segments

1. Purpose of the experiment

1. Master the basic method of using the OpenGL graphics library for graphics programming.

2. Master the message processing method in the Windows environment.

3. Understand the operating mechanism of OpenGL.

2. Experimental content

Using OpenGL to Realize Clipping of Line Segments

Three, the main code

//判断位置
void chopLine(Point& p, unsigned char code, double dely, double delx) {
	if (code & 1) { //0001 左方,位与运算,结果不为0时证明在窗口左方有交点
		p.y += (myWindow.l - p.x) * dely / delx;
		p.x = myWindow.l;
	}
	else if (code & 2) { //0010 右方
		p.y += (myWindow.r - p.x) * dely / delx;
		p.x = myWindow.r;
	}
	else if (code & 4) { //0100 下方
		p.x += (myWindow.b - p.y) * delx / dely;
		p.y = myWindow.b;
	}
	else { //1000 上方
		p.x += (myWindow.t - p.y) * delx / dely;
		p.y = myWindow.t;
	}
}

//按位或,生成编号
void generateCode(Point& p, unsigned char& code) {
	if (p.x < myWindow.l)	code |= 1;
	if (p.y > myWindow.t)	code |= 8;
	if (p.x > myWindow.r)	code |= 2;
	if (p.y < myWindow.b)	code |= 4;
}

//裁剪
int cut(pair<Point, Point>& tmp) {
	unsigned char code1;
	unsigned char code2;
	int k = 0;
	do {
		code1 = 0;
		code2 = 0;
		generateCode(tmp.first, code1);
		generateCode(tmp.second, code2);
		if ((code1 | code2) == 0) {  //完全在窗口里面(0000|0000)
			return 1;
		}
		else if ((code1 & code2) != 0) { //在某条边界同侧,即完全在窗口外面
			return 0;
		}
		if (code1 != 0) {
			chopLine(tmp.first, code1, tmp.second.y - tmp.first.y, tmp.second.x - tmp.first.x);
		}
		if (code2 != 0) {
			chopLine(tmp.second, code2, tmp.second.y - tmp.first.y, tmp.second.x - tmp.first.x);
		}
		k++;
	} while (1);
}

void func() {
	pair<Point, Point> tmp(Point(vertice[0].x, vertice[0].y), Point(vertice[1].x, vertice[1].y));
	V.push_back(tmp);

	glBegin(GL_LINES);
	glColor3f(0.0f, 0.0f, 0.0f);
	glVertex2f(V[0].first.x, V[0].first.y);
	glVertex2f(V[0].second.x, V[0].second.y);
	glColor3f(1.0f, 0.0f, 0.0f);
	int a = cut(V[0]);
	if (a == 1) {
		glVertex2f(V[0].first.x, V[0].first.y);
		glVertex2f(V[0].second.x, V[0].second.y);
	}
	glEnd();
	glFlush();
	//V.pop_back();
	//vertice.pop_back();
	V.clear();
	vertice.clear();

}

void mydisplay(void)
{
	glClear(GL_COLOR_BUFFER_BIT);  //clear the screen
	glColor3f(0.0f, 0.0f, 0.0f);
	glLineWidth(3.0);
	draw();
	//func();
	glFlush();
}
void mymouse(int button, int state, int x, int y)
{
	if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
	{
		draw_a_point(x, screenHeight - y);
		Point p(x, screenHeight - y);
		vertice.push_back(p);
		cout << "起点" << ": (" << x << ", " << y << ")" << endl;
	}

	if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
	{
		draw_a_point(x, screenHeight - y);
		Point p(x, screenHeight - y);
		vertice.push_back(p);
		cout << "终点" << ": (" << x << ", " << y << ")" << endl;
		cout << "开始剪裁" << endl;
		func();
	}
}

 

Guess you like

Origin blog.csdn.net/y0205yang/article/details/129803527