Search code examples
openglopengl-3opentk

How do I draw a cylinder in OpenTK(.Glu.Cylinder)?


How do I draw a cylinder with OpenGL in OpenTK?


Solution

  • Sample code from an older project of mine. This creates an "uncapped" cylinder (top and bottom are empty).

    int segments = 10; // Higher numbers improve quality 
    int radius = 3;    // The radius (width) of the cylinder
    int height = 10;   // The height of the cylinder
    
    var vertices = new List<Vector3>();
    for (double y = 0; y < 2; y++)
    {
        for (double x = 0; x < segments; x++)  
        {
            double theta = (x / (segments - 1)) * 2 * Math.PI;
    
            vertices.Add(new Vector3()
            {
                X = (float)(radius * Math.Cos(theta)),
                Y = (float)(height * y),
                Z = (float)(radius * Math.Sin(theta)),
            });
        }
    }
    
    var indices = new List<int>();
    for (int x = 0; x < segments - 1; x++)
    {
        indices.Add(x);
        indices.Add(x + segments);
        indices.Add(X + segments + 1);
    
        indices.Add(x + segments + 1);
        indices.Add(x + 1);
        indices.Add(x);
    }
    

    You can now render the cylinder like this:

    GL.Begin(BeginMode.Triangles);
    foreach (int index in indices)
        GL.Vertex3(vertices[index]);
    GL.End();
    

    You can also upload vertices and indices into a vertex buffer object to improve performance.