学习完绘制Bezier曲线之后,我开始探索绘制B样条曲线,因为B样条曲线是之后好多东西的基础,所以一定得学会用opengl绘制B样条曲线
这里我先只考虑均匀B样条
先考虑二次均匀B样条,
根据计算公式,其实然后把之前做Bezier曲线的例子挪过来即可,两段B样条一拼,OK
上代码
#include<GL/GLUT.H>
#include <windows.h>
#include <math.h>
#include <gl/GL.h>
GLint num = 4;
GLfloat p1[] = { -0.8f, 0.1f };
GLfloat p2[] = { -0.4f, 0.6f };
GLfloat p3[] = { 0.2f, 0.8f };
GLfloat p4[] = { 0.7f, 0.2f };
void myDisplay(void){
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(2);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POINTS);
glVertex2fv(p1);
glVertex2fv(p2);
glVertex2fv(p3);
glVertex2fv(p4);
glEnd();
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_LINE_STRIP);
glVertex2fv(p1);
glVertex2fv(p2);
glVertex2fv(p3);
glVertex2fv(p4);
glEnd();
GLfloat ps1[11][2];
GLfloat ps2[11][2];
GLint i = 0;
for (double t = 0.0; t <= 1.0; t += 0.1)
{
double a1 = pow((1 - t), 2)/2;
double a2 = (1 + 2 * t - 2 * t*t)/2;
double a3 = t*t/2;
ps1[i][0] = a1*p1[0] + a2*p2[0] + a3*p3[0];
ps1[i][1] = a1*p1[1] + a2*p2[1] + a3*p3[1];
ps2[i][0] = a1*p2[0] + a2*p3[0] + a3*p4[0];
ps2[i][1] = a1*p2[1] + a2*p3[1] + a3*p4[1];
i = i + 1;
}
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_LINE_STRIP);
for (int i = 0; i < 11; i++)
{
glVertex2fv(ps1[i]);
}
glEnd();
glBegin(GL_LINE_STRIP);
for (int i = 0; i < 11; i++)
{
glVertex2fv(ps2[i]);
}
glEnd();
glFlush();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(400, 400);
glutCreateWindow("opengl1");
glutDisplayFunc(&myDisplay);
glutMainLoop();
return 0;
}
其实也就这一块是真正涉及计算的公式
GLfloat ps1[11][2];
GLfloat ps2[11][2];
GLint i = 0;
for (double t = 0.0; t <= 1.0; t += 0.1)
{
double a1 = pow((1 - t), 2)/2;
double a2 = (1 + 2 * t - 2 * t*t)/2;
double a3 = t*t/2;
ps1[i][0] = a1*p1[0] + a2*p2[0] + a3*p3[0];
ps1[i][1] = a1*p1[1] + a2*p2[1] + a3*p3[1];
ps2[i][0] = a1*p2[0] + a2*p3[0] + a3*p4[0];
ps2[i][1] = a1*p2[1] + a2*p3[1] + a3*p4[1];
i = i + 1;
}
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_LINE_STRIP);
for (int i = 0; i < 11; i++)
{
glVertex2fv(ps1[i]);
}
glEnd();
glBegin(GL_LINE_STRIP);
for (int i = 0; i < 11; i++)
{
glVertex2fv(ps2[i]);
}
glEnd();
后面的分别绘制两段,上效果
然后考虑三次B样条
其实也就是换换计算公式,很容易的,计算部分是
GLint i = 0;
for (double t = 0.0; t <= 1.0; t += 0.1)
{
double a1 = pow((1 - t), 3)/6;
double a2 = (3*t*t*t - 6 * t*t +4)/6;
double a3 = (-3 * t*t*t + 3 * t*t + 3 * t + 1) / 6;
double a4 = t*t*t / 6;
ps[i][0] = a1*p1[0] + a2*p2[0] + a3*p3[0]+a4*p4[0];
ps[i][1] = a1*p1[1] + a2*p2[1] + a3*p3[1]+a4*p4[1];
i = i + 1;
}
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_LINE_STRIP);
for (int i = 0; i < 11; i++)
{
glVertex2fv(ps[i]);
}
glEnd();
直接替换二次那里的计算公式就好了
效果如下
怎么样,看来挺容易,然后下一步用opengl实现B样条曲面,应该很容易,然后就可以进行细分部分的实现啦哈哈哈