我正在尝试为我的着色器添加一个统一的var,这是我的着色器:
String vertexShader = "attribute vec4 " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" //
+ "attribute vec4 " + ShaderProgram.COLOR_ATTRIBUTE + ";\n" //
+ "attribute vec2 " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" //
+ "uniform mat4 u_projTrans;\n" //
+ "varying vec4 v_color;\n" //
+ "varying vec2 v_texCoords;\n" //
+ "\n" //
+ "void main()\n" //
+ "{\n" //
+ " v_texCoords = " + ShaderProgram.TEXCOORD_ATTRIBUTE + "0;\n" //
+ " gl_Position = u_projTrans * " + ShaderProgram.POSITION_ATTRIBUTE + ";\n" //
+ "}\n";
String fragmentShader = "#ifdef GL_ES\n" //
+ "#define LOWP lowp\n" //
+ "precision mediump float;\n" //
+ "#else\n" //
+ "#define LOWP \n" //
+ "#endif\n" //
+ "varying vec2 v_texCoords;\n" //
+ "uniform sampler2D u_texture;\n" //
+ "uniform sampler2D u_texturePalette;\n" //
+ "void main()\n"//
+ "{\n" //
+ " vec4 textureColor = texture2D(u_texture, v_texCoords).rgba;\n"
+ " vec4 paletteColor = texture2D(u_texturePalette, vec2(textureColor.b,0)).rgba;\n"
+ " gl_FragColor = paletteColor;\n" //
+ "}";
问题来自
uniform sampler2D u_texturePalette;
ShaderProgram无法识别着色器中的新制服。我也这样做了:
shader = new ShaderProgram(vertexShader, fragmentShader);
shader.setUniformi("u_texturePalette", 0);
Texture text = new Texture(Gdx.files.internal("./data/palette.png"));
text.bind(shader.getUniformLocation("u_texturePalette"));
batch = new SpriteBatch();
batch.setShader(shader);
当我调用函数shader.hasUniform("u_texturePalette")
时,它会解析为true,但当我去看shader.getUniformLocation("u_texturePalette")
时它会解析为-1
这是一个错误吗? 。我知道自己做得不好吗?
答案 0 :(得分:1)
着色器代码看起来很好。
一般来说,你这样做:
shader = new ShaderProgram(vertexShader, fragmentShader);
Texture text = new Texture(Gdx.files.internal("./data/palette.png"));
text.bind(0);
shader.setUniformi("u_texturePalette", 0);
因此,您将纹理绑定到活动纹理单元,然后通过setUniformi()
传递该单元。
getUniformLocation()
实际上有所不同:https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGetUniformLocation.xml
但是你会在这里遇到更多问题,因为SpriteBatch
在内部使用自定义着色器做了一些非常具体的事情。我建议你看一下代码:
https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/SpriteBatch.java
具体来说,它会期望默认纹理始终位于单位0。