4次Bezier曲线--计算机图形学 opengl

#include "GL\glut.h"

#include <math.h>

class Point//一个点类，含有x，y坐标

{

public:

intx, y;

voidinit(int x1, int y1) {

x= x1;

y= y1;

}

};

//点的数量

static int PointSum = 0;

//四次的bezier曲线共有五个点

static Point points[5];

void init(void)

{

glEnable(GL_DEPTH_TEST);

glMatrixMode(GL_PROJECTION);

gluOrtho2D(0.0,500.0, 0.0, 500.0);

glMatrixMode(GL_MODELVIEW);

}

//画点

void setPoint(Point p) {

glBegin(GL_POINTS);

glVertex2f(p.x,p.y);

glEnd();

glFlush();

}

// 画线

void setline(Point p1, Point p2) {

glBegin(GL_LINES);

glVertex2f(p1.x,p1.y);

glVertex2f(p2.x,p2.y);

glEnd();

glFlush();

}

// 计算bezier曲线

Point calculateBezier(Point p0, Point p1,Point p2, Point p3, Point p4, double a) {

Pointp;

doubleb1 = pow((1 - a), 4);

doubleb2 = pow((1 - a), 3) * 4 * a;

doubleb3 = pow((1 - a), 2) * 6 * a * a;

doubleb4 = (1 - a)*a*a*a * 4;

doubleb5 = a * a*a*a;

p.x= b1 * p0.x + b2 * p1.x + b3 * p2.x + b4 * p3.x + b5 * p4.x;

p.y= b1 * p0.y + b2 * p1.y + b3 * p2.y + b4 * p3.y + b5 * p4.y;

returnp;

}

//display函数

void display()

{

glClearColor(0.88,0.71, 0.71, 0); //设背景为粉色

glClear(GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT); //用glClearClolr设定的颜色值清除缓存区

glColor3f(0.0,0.0, 0.0);

glPointSize(5);

glFlush();

}

// 鼠标事件

void MouseFunction(int button, int state,int x, int y) {

if(state == GLUT_DOWN)

{

points[PointSum].init(x,500 - y);

glColor3f(0.86,0.25, 0.0);     // 设置点的颜色，绘制点

setPoint(points[PointSum]);

glColor3f(0.12,0.8, 0.25);// 设置线的颜色，绘制线

if(PointSum > 0) setline(points[PointSum - 1], points[PointSum]);

//如果达到了4个绘制bezier曲线，并在之后给计数器清零

if(PointSum == 4) {

glColor3f(0.0,0.0, 0.0); // 设定bezier曲线为黑色

Pointp_current = points[0]; //设为起点

for(double t = 0.0; t <= 1.0; t += 0.05)

{

PointP = calculateBezier(points[0], points[1], points[2], points[3], points[4], t);

setline(p_current,P);

p_current= P;

}

PointSum= 0;

}

else{

PointSum++;

}

}

}

int main(int argc, char *argv[])

{

glutInit(&argc,argv);

glutInitDisplayMode(GLUT_SINGLE| GLUT_RGB | GLUT_DEPTH);

glutInitWindowPosition(0,0);

glutInitWindowSize(500,500); //确定显示框的大小

glutCreateWindow("ZZJ的图形学作业1.0");

init();

glutMouseFunc(MouseFunction);// 鼠标事件

glutDisplayFunc(display);

glutMainLoop();

return0;

}