typedef struct _Point{
float x;
float y;
}Point;
float Fac(int n)
{
if(n == 0)
{
return 1;
}
return n * Fac(n-1);
}
float pow(float x,int y)
{
if(y == 0)
{
return 1;
}
return x*pow(x,y-1);
}
float F_k_n(int k,int n,float t)
{
int j = 0 ;
float tmp = 0.0f;
for ( ; j <= n-k; j++)
{
tmp += pow(-1,j)*(Fac(n+1)/(Fac(j)*Fac(n+1-j)))*pow(t+n-k-j,n);
}
return tmp/Fac(n);
}
Point P_i_n(Point* pt,int i,int n,float t)
{
Point tmpPT = {0};
int k = 0;
for ( ;k < n+1; k++)
{
tmpPT.x += pt[i+k].x * F_k_n(k,n,t);
tmpPT.y += pt[i+k].y * F_k_n(k,n,t);
}
return tmpPT;
}
Point calCrtlPoint(Point p0,Point p1,bool isTopPoint)
{
Point vertex;
if(isTopPoint)
{
vertex.x = p0.x + (p0.x - p1.x);
vertex.y = p0.y + (p0.y - p1.y);
}
else
{
vertex.x = p1.x + (p1.x - p0.x);
vertex.y = p1.y + (p1.y - p0.y);
}
return vertex;
}
void initPoint(Point* p,Point* pt,int crtlPointSize,int size)
{
int i;
// 计算第一个结点 和 最后一个结点
p[0] = calCrtlPoint(pt[0],pt[1],TRUE);
p[crtlPointSize-1] = calCrtlPoint(pt[size-2],pt[size-1],FALSE);
for ( i = 1; i < crtlPointSize - 1; i++)
{
p[i] = pt[i-1];
}
}
void drawSpline(Point* pt,int size)
{
int i = 0 ;
float t = 0.0f;
int crtlPointSize = size + 2;
Point* p = malloc(sizeof(Point)*crtlPointSize);
initPoint(p,pt,crtlPointSize,size);
for ( i = 0 ; i < crtlPointSize - 3 ; i++)
{
Point oldPT = P_i_n(p,i,3,0);
for ( t = 0.0f ; t < 1; t+=0.01)
{
Point newPT = P_i_n(p,i,3,t);
drawLine(oldPT.x,oldPT.y,newPT.x,newPT.y,255,0,0);
oldPT = newPT;
}
}
free(p);
p = NULL;
}
void main()
{
Point pt[5] = {{40,0},{80,100},{120,0},{160,100},{200,0}};
drawSpline(pt,sizeof(pt)/sizeof(pt[0]));
}
样条曲线
最新推荐文章于 2024-05-05 22:32:48 发布