Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get original texture color in a Fragment Shader in OpenGL

So, I need to make a shader to replace the gray colors in the texture with a given color. The fragment shader works properly if I set the color to a given specific one, like

gl_FragColor = vec4(1, 1, 0, 1);

However, I'm getting an error when I try to retrieve the original color of the texture. It always return black, for some reason.

uniform sampler2D texture; //texture to change

void main() {
  vec2 coords = gl_TexCoord[0].xy;
  vec3 normalColor = texture2D(texture, coords).rgb; //original color

  gl_FragColor = vec4(normalColor.r, normalColor.g, normalColor.b, 1);
}

Theoretically, it should do nothing - the texture should be unchanged. But it gets entirely black instead. I think the problem is that I'm not sure how to pass the texture as a parameter (to the uniform variable). I'm currently using the ID (integer), but it seems to return always black. So I basically don't know how to set the value of the uniform texture (or to get it in any other way, without using the parameters). The code (in Java):

program.setUniform("texture", t.getTextureID());

I'm using the Program class, that I got from here, and also SlickUtils Texture class, but I believe that is irrelevant.

like image 514
Luan Nico Avatar asked Feb 17 '23 06:02

Luan Nico


1 Answers

program.setUniform("texture", t.getTextureID());
                              ^^^^^^^^^^^^^^^^

Nope nope nope.

Texture object IDs never go in uniforms.

Pass in the index of the texture unit you want to sample from.

So if you want to sample from the nth texture unit (GL_TEXTURE0 + n) pass in n:

program.setUniform("texture", 0);
                              ^ or whatever texture unit you've bound `t` to
like image 183
genpfault Avatar answered Apr 28 '23 10:04

genpfault