Question

I need to pass 2(or more) textures to one shader. Also I have to bind textures in render method, because I use FrameBuffer and try to bind textures on fly. So, my code is below:

@Override
public void show () {
      fbo = new FrameBuffer(Format.RGB565, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);

      shader = new ShaderProgram(Gdx.files.internal("shaders/vertex.glsl"), Gdx.files.internal("shaders/test_fragment.glsl"));
    ...
}

@Override
public void render(float delta) {

    fbo.begin();        
    Gdx.graphics.getGL20().glClearColor( 0.0f, 0.0f, 0.0f, 1f );
    Gdx.graphics.getGL20().glClear( GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT );      

    cam.update();

    spriteBatch.setProjectionMatrix(cam.combined);

    spriteBatch.begin();        
    spriteBatch.draw(someImage, 0, 0, width, height);                   
    spriteBatch.end();
    fbo.end();

    Texture texture = fbo.getColorBufferTexture();

    time+=Gdx.graphics.getDeltaTime();      

    shader.begin();

     shader.setUniformMatrix(u_wview, cam.projection);
     Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE0);
     texture.bind(0);

     shader.setUniformi("u_texture", 0); //passing first texture!!!

     Gdx.graphics.getGL20().glActiveTexture(GL20.GL_TEXTURE1);       
     tex2.bind(1);
     shader.setUniformi("u_texture2", 1); //passing second texture!!!


    shader.setUniformf(u_res, new Vector2(Gdx.graphics.getWidth(),Gdx.graphics.getHeight())); 
    shader.setUniformf(u_time, time);


    mesh.render(shader, GL20.GL_TRIANGLES);

      shader.end();
}

Fragment shader:

#ifdef GL_ES
precision mediump float;
#endif

varying vec2 v_texCoords;
uniform vec2 resolution;
uniform float u_time;
uniform sampler2D u_texture;
uniform sampler2D u_texture2;
uniform float u_temp;
const float pi = 3.14159265;

void main() 
{
vec2 p = gl_FragCoord.xy / resolution.xy;

vec4 i = texture2D(u_texture2, p);
gl_FragColor = texture2D(u_texture, p)+i;
}

If I pass only one texture everything is ok. Otherwise, I get unexpected result as if the first texture(u_texture) is the second one(u_texture2). What is the proper way to pass more than one texture to shader?

Was it helpful?

Solution

I had to pass textures in back order like below:

 texture.bind(1);
 shader.setUniformi("u_texture", 1); //passing first texture!!!

 texture2.bind(0);
 shader.setUniformi("u_texture2", 0); //passing second texture!!! 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top