I\'ve learned how to draw a cube using OpenGL from various tutorials.
For a cube, we consider each face to be composed of two triangles, and then appropriately set up th
Here is some code that I use when drawing spheres.
Note: This code uses C++, with the GLM math library.
// Calc The Vertices
for (int i = 0; i <= Stacks; ++i){
float V = i / (float) Stacks;
float phi = V * glm::pi <float> ();
// Loop Through Slices
for (int j = 0; j <= Slices; ++j){
float U = j / (float) Slices;
float theta = U * (glm::pi <float> () * 2);
// Calc The Vertex Positions
float x = cosf (theta) * sinf (phi);
float y = cosf (phi);
float z = sinf (theta) * sinf (phi);
// Push Back Vertex Data
vertices.push_back (glm::vec3 (x, y, z) * Radius);
}
}
// Calc The Index Positions
for (int i = 0; i < Slices * Stacks + Slices; ++i){
indices.push_back (i);
indices.push_back (i + Slices + 1);
indices.push_back (i + Slices);
indices.push_back (i + Slices + 1);
indices.push_back (i);
indices.push_back (i + 1);
}
This algorithm creates what is called a UV Sphere. The 'Slices' and 'Stacks' are the number of subdivisions on the X and Y axis.
For cylinders, it is convenient to work in cylindrical coordinates: (angle, radius, height). You will compute two polygons (constant angle increment, fixed radius, two height values) and create: two sets of triangles for the basis and a set of rectangles (split in two) for the lateral surface.
For spheres, you will use spherical coordinates: (inclination, elevation, radius). By varying the two angles (one at a time), you will describe parallels and meridians on the sphere. These define a meshing, such that every tile is a quadrilateral (except at the poles); split along a diagonal to get triangles.