PDA

View Full Version : Generating a sphere


MacFiend
2003.05.07, 09:42 AM
I would like to know how to generate a sphere (using pure math, no OpenGL routines). I have this basic code:


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
}
}


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.

MacFiend
2003.05.07, 12:09 PM
I got some code going, but its not right.


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]);
}
}


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.


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();

Mars_999
2003.05.07, 02:45 PM
Use GL_TRIANGLES

Frank C.
2003.05.07, 07:56 PM
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.

MacFiend
2003.05.07, 10:38 PM
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.