如何将浮点值传递给片段着色器?
这是我在android上的代码:
int aUseTexture = GLES20.glGetAttribLocation(program, "uUseTexture");
GLES20.glUniform1f(aUseTexture, 1.0f);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
这是我的着色器:
String verticesShader =
"uniform mat4 uScreen;\n" +
"attribute vec2 aPosition;\n" +
"attribute vec3 aColor;\n" +
"attribute vec2 aTexPos; \n" +
"varying vec2 vTexPos; \n" +
"varying vec3 vColor;\n" +
"void main() {\n" +
" vTexPos = aTexPos; \n" +
" gl_Position = uScreen * vec4(aPosition.xy, 0.0, 1.0);\n" +
" vColor = aColor;\n" +
"}";
// Our fragment shader. Just return vColor.
// If you look at this source and just said 'WTF?', remember
// that all the attributes are defined in the VERTEX shader and
// all the 'varying' vars are considered OUTPUT of vertex shader
// and INPUT of the fragment shader. Here we just use the color
// we received and add a alpha value of 1.
String fragmentShader =
"uniform float uUseTexture; \n" +
"uniform sampler2D uTexture;\n" +
"precision mediump float;\n"+
"varying vec2 vTexPos; \n" +
"varying vec3 vColor;\n" +
"void main(void)\n" +
"{\n" +
" if ( uUseTexture != 1.0 ) \n" +
" gl_FragColor = vec4(vColor.xyz, 1); \n" +
" else \n" +
" gl_FragColor = texture2D(uTexture, vTexPos); \n" +
//" gl_FragColor = vec4(vColor.xyz, 1);\n" +
"}";
您可以在片段着色器中看到if语句,即我试图检查是否传入1.0它应该做纹理,否则使用颜色。
答案 0 :(得分:1)
您可能正在使用错误的函数调用“uniform variable”。尝试glGetUniformLocation()如下:
int aUseTexture = GLES20.glGetUniformLocation(program, "uUseTexture");
此外,浮点测试(uUseTexture!= 1.0)可能并不总是可靠的。您可能想要使用整数类型。
答案 1 :(得分:0)
据我所知,你必须先通过顶点着色器传递值才能进入片段着色器。例如在顶点着色器的顶部添加“uniform float uUseTexture_in; \ n”和“vary float uUseTexture; \ n”,在main函数中添加“uUseTexture = uUseTexture_in;”。你的着色器应该可以工作