OpenGL ES 2:使用额外的纹理单元将此图像与当前图像混合

时间:2013-07-26 20:15:10

标签: android opengl-es-2.0

我想找出一个关于OpenGL ES 2.0的教程

现在本书需要练习“尝试加载不同的图像,并使用额外的纹理单元将此图像与当前图像混合。您可以尝试在将值分配给gl_FragColor时将值相加或相乘你的片段着色器。“

但我迷失了......

这是代码:

@Override
public void onDrawFrame(GL10 gl) {
    // Clear the rendering surface.
    glClear(GL_COLOR_BUFFER_BIT);
    // Draw the table.
    textureProgram.useProgram();
    textureProgram.setUniforms(projectionMatrix, texture);
    table.bindData(textureProgram);
    table.draw();
}

,其中

textureProgram是:

public class TextureShaderProgram extends ShaderProgram {

// Uniform locations
private final int uMatrixLocation;
private final int uTextureUnitLocation;
private final int uTextureUnitLocation2;
// Attribute locations
private final int aPositionLocation;
private final int aTextureCoordinatesLocation;

public TextureShaderProgram(Context context) {
    super(context, R.raw.texture_vertex_shader,
    R.raw.texture_fragment_shader);
    // Retrieve uniform locations for the shader program.
    uMatrixLocation = glGetUniformLocation(program, U_MATRIX);
    uTextureUnitLocation2 = glGetUniformLocation(program, "u_TextureUnit2");

    uTextureUnitLocation = glGetUniformLocation(program, U_TEXTURE_UNIT);
    // Retrieve attribute locations for the shader program.
    aPositionLocation = glGetAttribLocation(program, A_POSITION);
    aTextureCoordinatesLocation =
    glGetAttribLocation(program, A_TEXTURE_COORDINATES);
    }

public void setUniforms(float[] matrix, int textureId) {
    // Pass the matrix into the shader program.
    glUniformMatrix4fv(uMatrixLocation, 1, false, matrix, 0);
    glActiveTexture(GL_TEXTURE0);
    // Bind the texture to this unit.
    glBindTexture(GL_TEXTURE_2D, textureId);
    // Tell the texture uniform sampler to use this texture in the shader by
    // telling it to read from texture unit 0.
    glUniform1i(uTextureUnitLocation, 0);
    }

public int getPositionAttributeLocation() {
    return aPositionLocation;
    }
    public int getTextureCoordinatesAttributeLocation() {
    return aTextureCoordinatesLocation;
    }
}

这是片段着色器

precision mediump float;
uniform sampler2D u_TextureUnit;

varying vec2 v_TextureCoordinates;
void main()
{
gl_FragColor = texture2D(u_TextureUnit, v_TextureCoordinates);
}

这是顶点着色器:

uniform mat4 u_Matrix;
attribute vec4 a_Position;
attribute vec2 a_TextureCoordinates;
varying vec2 v_TextureCoordinates;
void main()
{
v_TextureCoordinates = a_TextureCoordinates;
gl_Position = u_Matrix * a_Position;
}

1 个答案:

答案 0 :(得分:3)

OpenGL ES能够对2个或更多纹理进行采样,以生成最终的gl_FragColor。您的Java代码似乎设置正常,但您的片段着色器仅使用其中一个纹理。它应该像这样添加两个:

uniform sampler2D u_TextureUnit_0;
uniform sampler2D u_TextureUnit_1;
varying vec2 v_TextureCoordinates;

void main()
{
    vec4 vColor_0 = texture2D(u_TextureUnit_0, v_TextureCoordinates);
    vec4 vColor_1 = texture2D(u_TextureUnit_1, v_TextureCoordinates);
    gl_FragColor = vColor_0 + vColor_1;  
}

这将2个vec4颜色样本加在一起:(R0 + R1,G0 + G1,B0 + B1,A0 + A1)