[英]OpenGL error thrown by fragment shader
我正在使用 OpenGL 4.4 在 OpenTK 中编写 2D 游戏。 使用颜色和纹理 UV 坐标和矩阵,我可以成功地使用顶点着色器在顶点之间绘制纹理:
公共常量字符串 vertexShaderDefaultSrc = @" #version 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);
在我看来,经过一些测试(验证这一点会很好),如果着色器未使用诸如纹理坐标之类的变量,则编译器将其删除,因此获取其位置的调用将返回 -1。 只需在这里检查 locationTexture 是否为 -1,然后不绑定 locationTexture 等,如果这样解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.