我开始学习着色器,遇到函数glGetAttribLocation返回-1的问题。
programId> = 0
顶点和片段着色器> = 0
位置和颜色属性== -1
这是我的代码:
着色器:
int[] shaderData = createShaderProgram(gl, "in vec3 color;\n" +
"\n" +
"out vec4 outColor;\n" +
"\n" +
"void main()\n" +
"{\n" +
" outColor = vec4(color.x, color.y, color.z, 1.0);\n" +
"}",
"in vec3 inColor;\n" +
"in vec3 inPosition;\n" +
"\n" +
"out vec3 color;\n" +
"\n" +
"void main()\n" +
"{\n" +
" gl_Position = vec4(inPosition, 1.0);\n" +
" color = inColor;\n" +
"}");
programId = shaderData[0];
vertexShader = shaderData[1];
fragmentShader = shaderData[2];
gl.glUseProgram(programId);
int positionAttribute = gl.glGetAttribLocation(programId, "inPosition");
int colorAttribute = gl.glGetAttribLocation(programId, "inColor");
System.out.println(positionAttribute + "; " + colorAttribute); // -1; -1
而createShaderProgram函数:
private int[] createShaderProgram(GL2 gl, String fragment, String vertex) {
int v = gl.glCreateShader(GL2.GL_VERTEX_SHADER);
int f = gl.glCreateShader(GL2.GL_FRAGMENT_SHADER);
gl.glShaderSource(v, 1, new String[] {vertex}, null);
gl.glCompileShader(v);
gl.glShaderSource(f, 1, new String[] {fragment}, null);
gl.glCompileShader(f);
int shaderprogram = gl.glCreateProgram();
gl.glAttachShader(shaderprogram, v);
gl.glAttachShader(shaderprogram, f);
gl.glLinkProgram(shaderprogram);
gl.glValidateProgram(shaderprogram);
return new int[] {shaderprogram, v, f};
}
解决方案:将#version
添加到着色器的开头。在这种情况下,这是#version 130