1 /* sphere, Copyright (c) 2002 Paul Bourke <pbourke@swin.edu.au>,
2 * Copyright (c) 2010-2014 Jamie Zawinski <jwz@jwz.org>
3 * Utility function to create a unit sphere in GL.
5 * Permission to use, copy, modify, distribute, and sell this software and its
6 * documentation for any purpose is hereby granted without fee, provided that
7 * the above copyright notice appear in all copies and that both that
8 * copyright notice and this permission notice appear in supporting
9 * documentation. No representations are made about the suitability of this
10 * software for any purpose. It is provided "as is" without express or
13 * 8-Oct-98: dek Released initial version of "glplanet"
14 * 21-Mar-01: jwz@jwz.org Broke sphere routine out into its own file.
15 * 28-Feb-02: jwz@jwz.org New implementation from Paul Bourke:
16 * http://astronomy.swin.edu.au/~pbourke/opengl/sphere/
17 * 21-Aug-10 jwz@jwz.org Converted to use glDrawArrays, for OpenGL ES.
28 #elif defined(HAVE_ANDROID)
36 #endif /* HAVE_JWZGLES */
40 typedef struct { GLfloat x, y, z; } XYZ;
43 unit_sphere_1 (int stacks, int slices, int wire_p, int half_p)
47 double theta1, theta2, theta3;
49 XYZ la = { 0, -1, 0 }, lb = { 0, -1, 0 };
50 XYZ c = {0, 0, 0}; /* center */
51 double r = 1.0; /* radius */
52 int stacks2 = stacks * 2;
53 int end = (half_p ? stacks/2 : stacks);
55 int mode = (wire_p ? GL_LINE_STRIP : GL_TRIANGLE_STRIP);
58 struct { XYZ p; XYZ n; GLfloat s, t; } *array;
65 arraysize = (stacks+1) * (slices+1) * (wire_p ? 4 : 2);
66 array = (void *) calloc (arraysize, sizeof(*array));
70 if (slices < 4 || stacks < 2 || r <= 0)
77 for (j = 0; j < end; j++)
79 theta1 = j * (M_PI+M_PI) / stacks2 - M_PI_2;
80 theta2 = (j + 1) * (M_PI+M_PI) / stacks2 - M_PI_2;
82 for (i = slices; i >= 0; i--)
84 theta3 = i * (M_PI+M_PI) / slices;
88 array[out++].p = lb; /* vertex */
89 array[out++].p = la; /* vertex */
92 n.x = cos (theta2) * cos(theta3);
94 n.z = cos (theta2) * sin(theta3);
99 array[out].p = p; /* vertex */
100 array[out].n = n; /* normal */
101 array[out].s = i / (GLfloat) slices; /* texture */
102 array[out].t = 2*(j+1) / (GLfloat) stacks2;
107 n.x = cos(theta1) * cos(theta3);
109 n.z = cos(theta1) * sin(theta3);
114 array[out].p = p; /* vertex */
115 array[out].n = n; /* normal */
116 array[out].s = i / (GLfloat) slices; /* texture */
117 array[out].t = 2*j / (GLfloat) stacks2;
120 if (out >= arraysize) abort();
129 glEnableClientState (GL_VERTEX_ARRAY);
130 glEnableClientState (GL_NORMAL_ARRAY);
131 glEnableClientState (GL_TEXTURE_COORD_ARRAY);
133 glVertexPointer (3, GL_FLOAT, sizeof(*array), &array[0].p);
134 glNormalPointer ( GL_FLOAT, sizeof(*array), &array[0].n);
135 glTexCoordPointer (2, GL_FLOAT, sizeof(*array), &array[0].s);
137 glDrawArrays (mode, 0, out);
146 unit_sphere (int stacks, int slices, int wire_p)
148 return unit_sphere_1 (stacks, slices, wire_p, 0);
152 unit_dome (int stacks, int slices, int wire_p)
154 return unit_sphere_1 (stacks, slices, wire_p, 1);