opengl es 如何在着色器中设置布尔值

opengl es how to set boolean in shader

我想在我的片段着色器中设置布尔值,因为我需要识别何时通过乘法为对象着色。但我不知道如何访问这个从 java 代码构造的布尔变量。项目是在 java 中为 android 创建的,使用 opengl es 3.0。

precision mediump float;
uniform vec4 vColor;
uniform bool textured;
uniform sampler2D uTexture;
varying vec2 vTexCoordinate;

void main(){
    if(textured){
        gl_FragColor = texture2D(uTexture, vTexCoordinate);
        gl_FragColor *= vColor;
    } else {
        gl_FragColor = vColor;
    }
}

我建议使用 int 而不是 boolif (textured != 0)

或者,您可以传递一个对纹理进行加权的浮点值:

precision mediump float;
uniform vec4 vColor;
uniform float textured;
uniform sampler2D uTexture;
varying vec2 vTexCoordinate;

void main()
{
    gl_FragColor = 
       vColor * mix(vec4(1.0), texture2D(uTexture, vTexCoordinate), textured);
}

mix 在两个值之间进行线性插值。看表达式:

gl_FragColor = 
    vColor * mix(vec4(1.0), texture2D(uTexture, vTexCoordinate), textured);

如果textured == 0.0,颜色乘以vec4(1.0)

gl_FragColor = vColor * vec4(1.0);

如果textured == 1.0,则颜色乘以从纹理查找返回的颜色:

gl_FragColor = vColor * texture2D(uTexture, vTexCoordinate);

如果0.0 < textured < 1.0,则vec4(1.0)和贴图颜色线性插值


此外,在条件语句中查找纹理时要小心。见 OpenGL ES 1.1 Full Specification - 6 Texture Accesses; page 110:

Accessing mip-mapped textures within the body of a non-uniform conditional block gives an undefined value. A non-uniform conditional block is a block whose execution cannot be determined at compile time.