0
votes

In libgdx, I have a shader loaded, and I want to make my Stage object use that shader to draw. I tried setting a SpriteBatch's shader to my shader, and then the Stage's sprite batch to that one, but it shows up as a black screen. Why doesn't this work:

ShaderProgram shader = new ShaderProgram(Gdx.files.internal("shader.vert"), Gdx.files.internal("shader.frag"));
SpriteBatch batch = new SpriteBatch();
batch.setShader(shader);
Stage stage = new Stage(new StretchViewport(768, 576), batch);
...
stage.act();
shader.begin();
stage.draw();
shader.end();

My shaders look like:

shader.vert

attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord;

uniform mat4 u_projTrans;

varying vec4 v_color;
varying vec2 v_texCoords;

void main()
{
    v_color = a_color;
    v_color.a = v_color.a * (256.0/255.0);
    v_texCoords = a_texCoord + 0;
    gl_Position =  u_projTrans * a_position;
}

shader.frag

#ifdef GL_ES
#define LOWP lowp
    precision mediump float;
#else
#define LOWP
#endif

varying LOWP vec4 v_color;
varying vec2 v_texCoords;

uniform sampler2D u_texture;

void main()
{
    gl_FragColor = v_color * texture2D(u_texture, v_texCoords);
}

It seems to only work with one texture. Every other texture doesn't render. And also, making textures power of 2 doesn't make a difference.

1

1 Answers

0
votes

SpriteBatch has certain expected attribute names. You are using a_texCoord, but it expects a_texCoord0, so the shader is going to treat all the UV's as if they are 0,0.

You mention setting the shader on both the SpriteBatch and the Stage's SpriteBatch, but in your code, they are one and the same.

You don't need to call begin and end on the shader, because SpriteBatch (and therefore Stage) does this automatically. I'm not sure if that could cause problems.

I can't explain why what you did would have worked with one of your textures. I would expect it to just draw everything as the same color as the lower left pixel of the texture.

There might be other issues afoot, but I'm assuming it was drawing correctly before you inserted your own shader.