Modern OpenGL : Draw a sphere and cylinder

前端 未结 2 899
-上瘾入骨i
-上瘾入骨i 2021-02-06 19:24

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

2条回答
  •  走了就别回头了
    2021-02-06 19:59

    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  ();
    
        // Loop Through Slices
        for (int j = 0; j <= Slices; ++j){
    
            float U = j / (float) Slices;
            float theta = U * (glm::pi  () * 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.

提交回复
热议问题