使用了通用的法向量计算方法来指定球体上各多边形(三角形)面片的法向量。
注意要对法向量进行单位化处理!
(在练习11.2中则是直接使用球体的vertex的坐标直接作为法向量,那样渲染出来的效果更加平滑。但是那种方法不通用!)
#include<gl/glut.h>
#include<math.h>
#include<stdlib.h>
//窗口大小
int width = 600;
int height = 600;
//a point data type
typedef GLfloat point3[3];
point3 v[] = {{0.0, 0.0, 1.0}, {0.0, 0.942809, -0.333333}, {-0.816497, -0.471405, -0.333333}, {0.816497, -0.471405, -0.333333}};
point3 v1, v2, n;
static int k = 5;
/*|x1 y1 z1| × |x2 y2 z2| = (y1z2-y2z1,z1x2-x1z2,x1y2-x2y1)*/
//|v1[0] v1[1] v1[2]| × |v2[0] v2[1] v2[2]| = (v1[1]v2[2]-v2[1]v1[2],v1[2]v2[0]-v1[0]v2[2],v1[0]v2[1]-v2[0]v1[1])
void triangle(point3 a, point3 b, point3 c)
{
v1[0] = a[0] - b[0];
v1[1] = a[1] - b[1];
v1[2] = a[2] - b[2];
v2[0] = c[0] - a[0];
v2[1] = c[1] - a[1];
v2[2] = c[2] - a[2];
n[0] = v1[1] * v2[2] - v2[1] * v1[2];
n[1] = v1[2] * v2[0] - v1[0] * v2[2];
n[2] = v1[0] * v2[1] - v2[0] * v1[1];
float r = sqrt( n[0] * n[0] + n[1] * n[1] + n[2] * n[2]);
n[0] = n[0] / r;
n[1] = n[1] / r;
n[2] = n[2] / r;
glNormal3fv(n);
glVertex3fv(a);
//glNormal3fv(b);
glVertex3fv(b);
//glNormal3fv(c);
glVertex3fv(c);
}
void normalize(point3 v1, point3 v2, point3 &v3)
{
float len = sqrt((v1[0]+v2[0])*(v1[0]+v2[0])+(v1[1]+v2[1])*(v1[1]+v2[1])+(v1[2]+v2[2])*(v1[2]+v2[2]));
v3[0] = (v1[0]+v2[0])/len;
v3[1] = (v1[1]+v2[1])/len;
v3[2] = (v1[2]+v2[2])/len;
}
void divide_triangle(point3 a, point3 b, point3 c, int k)
{
point3 ab, ac, bc;
normalize(a, b, ab);
normalize(a, c, ac);
normalize(b, c, bc);
if (k > 0)
{
divide_triangle(a, ac, ab, k-1);
divide_triangle(c, bc, ac, k-1);
divide_triangle(b, ab, bc, k-1);
divide_triangle(ab, ac, bc, k-1);
}
else {
triangle(a, b, c);
}
}
void tetra()
{
divide_triangle(v[0], v[1], v[2], k);
divide_triangle(v[3], v[2], v[1], k);
divide_triangle(v[0], v[3], v[1], k);
divide_triangle(v[0], v[2], v[3], k);
}