+static void fghGenerateSphere(GLfloat radius, GLint slices, GLint stacks, GLfloat **vertices, GLfloat **normals, int* nVert)
+{
+ int i,j;
+ int idx = 0; /* idx into vertex/normal buffer */
+ GLfloat x,y,z;
+
+ /* Pre-computed circle */
+ GLfloat *sint1,*cost1;
+ GLfloat *sint2,*cost2;
+
+ /* number of unique vertices */
+ if (slices==0 || stacks<2)
+ {
+ /* nothing to generate */
+ *nVert = 0;
+ return;
+ }
+ *nVert = slices*(stacks-1)+2;
+
+ /* precompute values on unit circle */
+ fghCircleTable(&sint1,&cost1,-slices,FALSE);
+ fghCircleTable(&sint2,&cost2, stacks,TRUE);
+
+ /* Allocate vertex and normal buffers, bail out if memory allocation fails */
+ *vertices = malloc((*nVert)*3*sizeof(GLfloat));
+ *normals = malloc((*nVert)*3*sizeof(GLfloat));
+ if (!(vertices) || !(normals))
+ {
+ free(*vertices);
+ free(*normals);
+ fgError("Failed to allocate memory in fghGenerateSphere");
+ }
+
+ /* top */
+ (*vertices)[0] = 0.f;
+ (*vertices)[1] = 0.f;
+ (*vertices)[2] = radius;
+ (*normals )[0] = 0.f;
+ (*normals )[1] = 0.f;
+ (*normals )[2] = 1.f;
+ idx = 3;
+
+ /* each stack */
+ for( i=1; i<stacks; i++ )
+ {
+ for(j=0; j<slices; j++, idx+=3)
+ {
+ x = cost1[j]*sint2[i];
+ y = sint1[j]*sint2[i];
+ z = cost2[i];
+
+ (*vertices)[idx ] = x*radius;
+ (*vertices)[idx+1] = y*radius;
+ (*vertices)[idx+2] = z*radius;
+ (*normals )[idx ] = x;
+ (*normals )[idx+1] = y;
+ (*normals )[idx+2] = z;
+ }
+ }
+
+ /* bottom */
+ (*vertices)[idx ] = 0.f;
+ (*vertices)[idx+1] = 0.f;
+ (*vertices)[idx+2] = -radius;
+ (*normals )[idx ] = 0.f;
+ (*normals )[idx+1] = 0.f;
+ (*normals )[idx+2] = -1.f;
+
+ /* Done creating vertices, release sin and cos tables */
+ free(sint1);
+ free(cost1);
+ free(sint2);
+ free(cost2);
+}
+