I need to draw a sphere in my project, without using the openGL function, because my project is to implement the openGL graphics pipe-line.
I use this code for drawing the sphere:
typedef vector<Vector3> vectors;
void mygluSphere(float radius, int slices, int stacks)
{
if (slices < 3 || stacks < 2 || radius <= 0.0) {
cout<<"MyGluSphere() - bad parameters";
return;
}
// calculate all the x,y coordinates (at radius 1)
vector<vectors> N(stacks - 1);
int k, s, i;
double z, a, r;
for (k=0; k<stacks-1; ++k) {
N[k].resize(slices);
a = PI * (-0.5 + (1.0 + k) / stacks);
z = sin(a);
r = cos(a);
for (s=0; s<slices; ++s) {
a = PI * 2 * s / slices;
N[k][s].set(cos(a) * r, sin(a) * r, z);
}
}
// bottom triangle fan
myglBegin(MYGL_POLYGON);
myglNormal3f(0.0, 0.0, -1.0);
myglVertex3f(0.0, 0.0, -radius);
for (s=slices; s>=0; --s) {
i = (s == slices) ? 0 : s;
const Vector3& n = N[0][i];
myglNormal3f(n.x, n.y, n.z);
myglVertex3f(n.x * radius, n.y * radius, n.z * radius);
}
myglEnd();
// middle quad strips
for (k=0; k<stacks-2; ++k) {
myglBegin(MYGL_POLYGON);
for (s=slices; s>=0; --s) {
i = (s == slices) ? 0 : s;
const Vector3& n1 = N[k][i];
myglNormal3f(n1.x, n1.y, n1.z);
myglVertex3f(n1.x * radius, n1.y * radius, n1.z * radius);
const Vector3& n2 = N[k + 1][i];
myglNormal3f(n2.x, n2.y, n2.z);
myglVertex3f(n2.x * radius, n2.y * radius, n2.z * radius);
}
myglEnd();
}
// top triangle fan
myglBegin(MYGL_POLYGON);
myglVertex3f(0.0, 0.0, radius);
for (s=0; s<=slices; ++s) {
i = (s == slices) ? 0 : s;
const Vector3& n = N[stacks - 2][i];
myglNormal3f(n.x, n.y, n.z);
myglVertex3f(n.x * radius, n.y * radius, n.z * radius);
}
myglEnd();
}
But when i’m using it, after some rotation operation, some of the sphere’s polygons, are hidden.
Can some one check this code and found what is wrong, or perhaps suggest a better one?
Chen