## Generating a sphere

Member
Posts: 148
Joined: 2003.03
Post: #1
I would like to know how to generate a sphere (using pure math, no OpenGL routines). I have this basic code:

[sourcecode]
for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
u[0] = i * 360 / N
v[0] = 90 - j * 180 / N
u[1] = ((i+1)%N) * 360 / N
v[1] = 90 - j * 180 / N
u[2] = ((i+1)%N) * 360 / N
v[2] = 90 - ((j+1)%N) * 180 / N
u[3] = i * 360 / N
v[3] = 90 - ((j+1)%N) * 180 / N
}
}
[/sourcecode]

That is used to generate a sphere out of quads, however, I need to know how to get the vertex coordinates from that. Any takers? Thanks.
Member
Posts: 148
Joined: 2003.03
Post: #2
I got some code going, but its not right.

[sourcecode]
int i,j,N=50,R=2,u[4],v[4];

sphere_model.vertices = (vertex*)malloc(N*N * sizeof(vertex) * 4);

for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
u[0] = i * 360 / N;
v[0] = 90 - j * 180 / N;
u[1] = ((i+1)%N) * 360 / N;
v[1] = 90 - j * 180 / N;
u[2] = ((i+1)%N) * 360 / N;
v[2] = 90 - ((j+1)%N) * 180 / N;
u[3] = i * 360 / N;
v[3] = 90 - ((j+1)%N) * 180 / N;

sphere_model.vertices[i*j+0].x = R*cos(u[0])*cos(v[1]);
sphere_model.vertices[i*j+0].y = R*cos(u[0])*sin(v[1]);
sphere_model.vertices[i*j+0].z = R*sin(u[0]);
sphere_model.vertices[i*j+1].x = R*cos(u[1])*cos(v[1]);
sphere_model.vertices[i*j+1].y = R*cos(u[1])*sin(v[1]);
sphere_model.vertices[i*j+1].z = R*sin(u[1]);
sphere_model.vertices[i*j+2].x = R*cos(u[2])*cos(v[2]);
sphere_model.vertices[i*j+2].y = R*cos(u[2])*sin(v[2]);
sphere_model.vertices[i*j+2].z = R*sin(u[2]);
sphere_model.vertices[i*j+3].x = R*cos(u[3])*cos(v[3]);
sphere_model.vertices[i*j+3].y = R*cos(u[3])*sin(v[3]);
sphere_model.vertices[i*j+3].z = R*sin(u[3]);
}
}
[/sourcecode]

When I draw the model with GL_QUADS, the above makes a wierd, spiked shape...but its in the general shape of a sphere (if you were to put the shape inside a sphere). If I draw with GL_POINTS, it looks like a sphere. Any ideas what I am doing wrong? thanks.

[sourcecode]
glBegin(GL_POINTS);
for (i=0;i<50*50*4;i++)
{
glVertex3f(sphere_model.vertices[i].x,sphere_model.vertices[i].y,sphere_model.vertices[i].z);
}
glEnd();
[/sourcecode]
Mars_999
Unregistered

Post: #3
Use GL_TRIANGLES
Member
Posts: 446
Joined: 2002.09
Post: #4
When it comes to geometry, Paul Bourke saves the day: http://astronomy.swin.edu.au/~pbourke/opengl/

At the bottom of that page are links to opengllib.h and opengllib.c, which have a few sphere/ellipsoid routines. They draw directly with OpenGL, but you should be able to abstract those bits into your own data formats if you want to submit it to OpenGL seperately.
Member
Posts: 148
Joined: 2003.03
Post: #5
Hmm, I don't know how I missed that, but you're right Frank C. Paul Bourke is DA MAN. Lot's of useful info on there. Thanks.