如何在Opentk用OpenGL绘制圆柱体?

有帮助吗?

解决方案

我的一个旧项目的示例代码。这会产生一个“无盖”圆柱体(顶部和底部为空)。

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);
}

您现在可以这样渲染这样的圆柱体:

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

您还可以将顶点和索引上传到顶点缓冲对象中以提高性能。

其他提示

生成圆柱体的几何形状非常简单(让我们考虑一个Z对准的圆柱体)。让我使用伪代码:

points = list of (x,y,z)
    where x = sin(a)*RADIUS, y = cos(a)*RADIUS, z = b,
    for each a in [0..2*PI) with step StepA,
    for each b in [0..HEIGHT] with step StepB

关于指数:让我们假设 N 等于圆柱体的“水平”或“切片”数(取决于高度和步骤),并且 M 等于每个“切片”(取决于Stepa)上的点数。

圆柱体包含一些四边形,每个四个跨越2个相邻的切片,因此索引看起来像:

indices = list of (a,b,c,d)
    where a = M * slice + point,
          b = M * slice + (point+1) % M,
          c = (M+1) * slice + (point+1) % M,
          d = (M+1) * slice + point
    for each slice in [0..N-2]
    for each point in [0..M-1]

如果您需要圆柱体的正:它们很容易生成:

normals = (x/RADIUS,y/RADIUS,0)
    for each (x,y,z) in points

就是这样,在气缸的圆形部分中,您可能还想要“帽子”,但我相信它们很容易做到。

我将为您留下有趣的部分,将我的伪代码转化为您选择的语言。 :)

其余的是创建/绑定VBO,加载几何形状,设置指针,使用您选择的着色器并调用Gldrawarrays(...) - 任何OpenGL 3教程都应覆盖此;您熟悉这部分吗?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top