Search code examples
c#openglglslopentk

OpenTK get uniform location always -1


I have been trying to learn OpenTk so that i can easily use OpenGl in c#. My problem now is that when i try to get the location of my two uniforms it returns -1 for both.

Vertex Shader:

#version 440 core

uniform vec3 position

void main(void)
{
    gl_Position = position;
}

Fragment Shader:

#version 440 core

uniform vec4 frag_Color;
out vec4 color;

void main(void)
{
    color = frag_Color;
}

Code:

GL.BindVertexArray(pointVertexArray);
GL.UseProgram(program);

int a = GL.GetUniformLocation(program, "position");
int b = GL.GetUniformLocation(program, "frag_Color");

Debug.WriteLine(a + ", " + b);

GL.DrawArrays(PrimitiveType.Points, 0, 1);
GL.PointSize(size);

Edit: Here is where i created the program:

public int CreateShader(string path) {
        var vertexShader = GL.CreateShader(ShaderType.VertexShader);

        GL.ShaderSource(vertexShader, File.ReadAllText(".\\shaders\\" + path + ".vert"));
        GL.CompileShader(vertexShader);

        var fragmentShader = GL.CreateShader(ShaderType.FragmentShader);
        GL.ShaderSource(fragmentShader, File.ReadAllText(".\\shaders\\" + path + ".frag"));
        GL.CompileShader(fragmentShader);

        var program = GL.CreateProgram();
        GL.AttachShader(program, vertexShader);
        GL.AttachShader(program, fragmentShader);
        GL.LinkProgram(program);

        GL.DetachShader(program, vertexShader);
        GL.DetachShader(program, fragmentShader);
        GL.DeleteShader(vertexShader);
        GL.DeleteShader(fragmentShader);

        programs.Add(program);
        return program;
    }

Solution

  • Remember to check the compile status of your shaders.

    int status;
    GL.GetShader(shader, ShaderParameter.CompileStatus, out status);
    if (status == 0)
        throw new Exception(
            String.Format("Error compiling {0} shader: {1}",
                type.ToString(), GL.GetShaderInfoLog(shader)));
    

    Because your vertex shader just has two typos that the compile status would have told you.

    0(5) : error C0000: syntax error, unexpected reserved word "void", expecting ',' or ';' at token "void"

    0(7) : error C1035: assignment of incompatible types

    You're missing a semicolon and gl_Position is a vec4 not a vec3 and the compile status would have told you that.

    uniform vec3 position;
                         ^ Missing
    [...]
    
    gl_Position = vec4(position, 1.0);