片段着色器引发的 OpenGL 错误

OpenGL error thrown by fragment shader

我正在使用 OpenGL 4.4 在 OpenTK 中编写 2D 游戏。使用颜色和纹理 UV 坐标以及矩阵,我可以使用顶点着色器在顶点之间成功绘制纹理:

public const string vertexShaderDefaultSrc = @” #版本 330

        uniform mat4 MVPMatrix;

        layout (location = 0) in vec2 Position;
        layout (location = 1) in vec2 Texture;
        layout (location = 2) in vec4 Colour;

        out vec2 InTexture;
        out vec4 OutColour;

        void main()
        {
            gl_Position = MVPMatrix * vec4(Position, 0, 1);
            InTexture = Texture;
            OutColour = Colour;
        }";

和片段着色器:

public const string fragmentShaderDefaultSrc =
    @"
    #version 330

    uniform sampler2D Sampler;

    in vec2 InTexture;
    in vec4 OutColour;

    out vec4 OutFragColor;

    void main()
    {
        OutFragColor = texture(Sampler, InTexture) * OutColour;

        //Alpha test
        if(OutFragColor.a <= 0) 
            discard;
    }
    ";

但是如果我只想绘制纯色而不是纹理,我会使用此着色器(具有相同的顶点,传递不会被使用的 UV 坐标):

 public const string fragmentShaderSolidColourSrc =
    @"
    #version 330

    uniform sampler2D Sampler;

    in vec2 InTexture;
    in vec4 OutColour;

    out vec4 OutFragColor;

    void main()
    {
        OutFragColor = OutColour;

        //Alpha test
        if(OutFragColor.a <= 0) 
            discard;
    }
    ";

现在效果很好,但 OpenGL 报告错误 - GL_INVALID_VALUE。它画得很好,一切似乎都正常,但理想情况下,我希望 OpenGL 在那种情况下没有错误,这样我就可以捕捉到真正的错误。我将不胜感激任何帮助,如果有帮助,我可以分享有关如何编译或使用着色器的更多详细信息 - 我不明白的是默认着色器如何工作但纯色不工作。

我已经在我的渲染调用中找到了错误的确切来源(着色器构建没有问题)

GL.EnableVertexAttribArray(shader.LocationPosition);
        GL.VertexAttribPointer(shader.LocationPosition, 2, VertexAttribPointerType.Float, false, Stride, 0);
        //-----everything up to here is fine

        //this line throws an error
        GL.EnableVertexAttribArray(shader.LocationTexture);
        //as does this line
        GL.VertexAttribPointer(shader.LocationTexture, 2, VertexAttribPointerType.Float, false, Stride, 8);


        //this is all ok
        GL.EnableVertexAttribArray(shader.LocationColour);
        GL.VertexAttribPointer(shader.LocationColour, 4, VertexAttribPointerType.UnsignedByte, true, Stride, 16);

        //ok
        GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBuffer);
        GL.DrawArrays(DrawType, 0, Vertices.Length);

        //ok
        GL.DisableVertexAttribArray(shader.LocationPosition);

        //this line throws error
        GL.DisableVertexAttribArray(shader.LocationTexture);

        //this is ok
        GL.DisableVertexAttribArray(shader.LocationColour);

在我看来,经过一些测试(最好能验证这一点),如果着色器不使用诸如纹理坐标之类的变量,编译器会删除它,因此调用获取它的位置returns-1。只需在此处检查 locationTexture 是否为 -1,如果这样解决了我的问题,则不绑定 locationTexture 等。