2
\$\begingroup\$

I'm trying to implement a Shader that turns any RGB values below 190 into black.


LIBGDX code:

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.utils.ScreenUtils;

import static com.badlogic.gdx.Gdx.gl;

public class Main extends ApplicationAdapter {
    SpriteBatch batch;
    Texture img;
    OrthographicCamera camera;
    
    @Override
    public void create () {
        ShaderProgram.pedantic=true;
        camera=new OrthographicCamera(1920, 1080);
        batch = new SpriteBatch();
        ShaderProgram sp= new ShaderProgram(Gdx.files.internal("normal.vert").readString(),
                Gdx.files.internal("threshold.frag").readString());
        sp.setUniformi("threshold", 190);    
        batch.setShader(sp);
        img = new Texture("badlogic.jpg");
    }

    @Override
    public void render () {
        ScreenUtils.clear(1, 0, 0, 1);
        batch.begin();
        batch.draw(img, 0, 0);
        batch.end();
    }
    
    @Override
    public void dispose () {
        batch.getShader().dispose();
        batch.dispose();
        img.dispose();
    }
}

Vertex Shader:

attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_projTrans;

varying vec4 v_color;
varying vec2 v_texCoords;

void main() {
    v_color = a_color;
    v_texCoords = a_texCoord0;
    gl_Position = u_projTrans * a_position;
}

and Frag Shader:

#ifdef GL_ES
precision mediump float;
#endif

varying vec4 v_color;
varying vec2 v_texCoords;
uniform int threshold;
uniform sampler2D u_texture;
uniform mat4 u_projTrans;


void main() {
    float t=float(threshold)/255.;
    vec3 color = texture2D(u_texture, v_texCoords,0.).rgb;

    if(color.r<=t||color.g<=t||color.g<=t){
        color=vec3(0,0,0);
    }
    if(threshold==0){
        color=vec3(1);

    }
    gl_FragColor = vec4(color, texture2D(u_texture, v_texCoords,0.).a);
}

expected output(directly setting "threshold" to be 190 in Frag shader file): expected
actual output(if threshold==0: color=vec3(1)): actual output
which can only mean that Uniform is not passed into the Frag shader correctly.
any help in fixing this weirdness will be greatly appreciated.
Thanks!

\$\endgroup\$
0
\$\begingroup\$

Adding sp.bind() before setting Uniforms solved the issue.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .