OpenGL渲染:所有顶点均移至单位球体的边界

时间:2018-12-31 18:30:55

标签: c# opengl opentk opengl-4

我正在使用C#中的OpenTK为玩具游戏引擎编写渲染器。由于它将仅由我使用,因此我正在使用OpenGL 4.5。实施基础知识后,我尝试渲染犹他州茶壶。这就是我得到的:Attempt to render the Utah Teapot

当我渲染一个简单的立方体时,它可以很好地渲染。一旦添加了更多的顶点,一切都会开始像一个球体。我使用.obj文件格式。我的加载器没有引起问题,我将所有顶点位置记录到控制台中,并手动创建了另一个具有这些位置的.obj文件,将它们导入Blender并显示良好。我的顶点着色器仅传递所有数据,而片段着色器仅分配白色。我浏览了整个互联网,但没有人遇到这个问题。我只是加载.obj文件,创建顶点和索引数组,创建VAO,带有顶点的VBO,创建带有索引的EBO。 GL.GetError()没有给我任何东西。我认为问题出在将模型数据加载到VBO中,但是我只是找不到问题所在。这是我用于加载网格数据的代码:

private bool _initialized = false;
public readonly int _id, _vertexCount, _indexCount;
private readonly int _vboID, _iboID;
public Mesh(Vertex[] vertices, int[] indices)
{
    _vertexCount = vertices.Length;
    _indexCount = indices.Length;
    GL.CreateVertexArrays(1, out _id);

    GL.CreateBuffers(1, out _vboID);   
    GL.NamedBufferStorage(
        _vboID,
        Vertex.Size * _vertexCount,   // Vertex is a struct with Vector3 position, Vector2 texCoord, Vector3 normal
        vertices,
        BufferStorageFlags.MapReadBit);

    GL.EnableVertexArrayAttrib(_id, 0); // _id is the VAO id provided by GL.CreateVertexArrays()
    GL.VertexArrayAttribFormat( 
        _id,
        0,                      
        3,                      // Vector3 - position
        VertexAttribType.Float, 
        false,                  
        0);                     // first item, offset 0
    GL.VertexArrayAttribBinding(_id, 0, 0);

    GL.EnableVertexArrayAttrib(_id, 1);
    GL.VertexArrayAttribFormat(
        _id,
        1,
        2,                      // Vector2 - texCoord
        VertexAttribType.Float,
        false,
        12);                    // sizeof(float) * (3) = (Size of Vector3)
    GL.VertexArrayAttribBinding(_id, 1, 0);

    GL.EnableVertexArrayAttrib(_id, 2);
    GL.VertexArrayAttribFormat(
        _id,
        0,
        3,                      // Vector3 - normal
        VertexAttribType.Float,
        false,
        20);                    // sizeof(float) * (3 + 2) = (Size of Vector3 + Vector2)
    GL.VertexArrayAttribBinding(_id, 2, 0);

    GL.VertexArrayVertexBuffer(_id, 0, _vboID, IntPtr.Zero, Vertex.Size);

    GL.CreateBuffers(1, out _iboID);
    GL.NamedBufferStorage(
        _iboID,
        sizeof(int) * _indexCount,
        indices,
        BufferStorageFlags.MapReadBit);
    GL.VertexArrayElementBuffer(_id, _iboID);
    _initialized = true;
}

1 个答案:

答案 0 :(得分:1)

问题在于设置法线向量属性数组时。 GL.VertexArrayAttribFormat的第二个参数是属性索引,在您的情况下,必须为2而不是0:

GL.EnableVertexArrayAttrib(_id, 2);
GL.VertexArrayAttribFormat(
    _id,
    2,  // <----------------------- 2 instead of 0
    3,                     
    VertexAttribType.Float,
    false,
    20);                    
GL.VertexArrayAttribBinding(_id, 2, 0);

属性索引0导致顶点坐标指定被法向矢量覆盖。法线向量为Unit vectors(长度== 1),如果将其视为顶点坐标,则它们将形成球形。