【计算机图形学】四、B样条曲线的生成

1.算法


【计算机图形学】四、B样条曲线的生成_第1张图片


2. 源代码

#include "stdafx.h"


#include "GL/glut.h"
#include "stdlib.h"

void init()
{
	glClearColor(1.0,1.0,1.0,0.0);
	
	glMatrixMode(GL_PROJECTION);
	gluOrtho2D(0.0,600.0,0.0,400.0);
}

typedef struct point
{
	float x,y;
}point;

void setPixel(point BsplinePt)
{
	glBegin(GL_POINTS);
	glVertex2f(BsplinePt.x,BsplinePt.y);
	glEnd();
}

float polyNomial(int k,int d,float u)
{
	if(d==1)
	{
		if(u>=float(k)&&u<=float (k+1))
			return 1.0;
		else
			return 0.0;
	}
	else
		return (u-k)/(d-1)*polyNomial(k,d-1,u)+(k+d-u)/(d-1)*polyNomial(k+1,d-1,u);
}

void computeBsplinePt(point* BsplinePt,point* CtrlPt,float u,int nCtrlPt,int degree)
{
	int k;
	float Bkd;
	BsplinePt->x=0.0;
	BsplinePt->y=0.0;
	for(k=0;k<=nCtrlPt-1;k++)
	{
		Bkd=polyNomial(k,degree,u);
		BsplinePt->x+=CtrlPt[k].x*Bkd;
		BsplinePt->y+=CtrlPt[k].y*Bkd;
	}
}

void Bspline(point* CtrlPt,int nCtrlPt,int degree)
{
	float u,du=0.001;
	point BsplinePt;
    
	for(u=degree-1;u<=nCtrlPt;)
	{
		computeBsplinePt(&BsplinePt,CtrlPt,u,nCtrlPt,degree);
		setPixel(BsplinePt);
		u+=du;
	}

}

void render()
{
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(1.0,0.0,0.0);
	
	point CtrlPt[5]={{50.0,50.0},{150.0,300.0},{250.0,150.0},{300.0,350.0},{500.0,50.0}};
	int nCtrlPts=5,degree=3;
	
	Bspline(CtrlPt,nCtrlPts,degree);
	
	glFlush();
}

int main(int argc, char* argv[])
{
	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
	glutInitWindowPosition(50,100);
	glutInitWindowSize(600,400);
	glutCreateWindow("B Spline");
	
	init();
	glutDisplayFunc(render);
	glutMainLoop();
	
	return 0;
}

3. 结果

【计算机图形学】四、B样条曲线的生成_第2张图片

你可能感兴趣的:(【计算机图形学】四、B样条曲线的生成)