1

我正在尝试向我的着色器添加一个统一的变量,这是我的着色器:

    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" //
            + "}";

问题随之而来

统一的 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

这是一个错误吗?. 知道我在做什么坏事吗?

4

1 回答 1

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。

于 2012-07-24T11:40:11.513 回答