简体   繁体   中英

OpenGL texture is all black when rendered with shader

I have a very simple OpenGL application that renders only one textured quad. This is my code, which works just fine (the textured quad appears just fine):

// Bind the test texture
glBindTexture(GL_TEXTURE_2D, mTestTexture);


// Draw the quad
glBegin(GL_QUADS);

glTexCoord2f(0.0f, 0.0f);
glVertex3f(x, y + (float)height, 0.0f);

glTexCoord2f(1.0f, 0.0f);
glVertex3f(x + (float)width, y + (float)height, 0.0f);

glTexCoord2f(1.0f, 1.0f);
glVertex3f(x + (float)width, y, 0.0f);

glTexCoord2f(0.0f, 1.0f);
glVertex3f(x, y, 0.0f);

glEnd();

Then I wanted to intoduce a simple shader. So I modified my code a little:

// Use shader and point it to the right texture
auto texLocation = glGetUniformLocation(mProgram, "tex");
glUseProgram(mProgram);
glUniform1i(texLocation, mTestTexture);

// Draw the quad
// Same drawing code as before...

Vertex shader:

void main(void)
{
 gl_Position     = ftransform();
 gl_TexCoord[0]  = gl_MultiTexCoord0;
}

Fragment shader:

uniform sampler2D tex;

void main()
{
    vec4 color = texture2D(tex, gl_TexCoord[0].st);
    gl_FragColor = color;
}

Now all I get is a black quad :-(

I already tried and tested a lot of things:

  • The shaders compile fine (no errors)
  • The quad is visible (vertex shader seems OK)
  • If I change the shader to produce a fixed color ("gl_FragColor = vec4(1,0,0,1);") my quad becomes red -> fragment shader is doing something!
  • glGetError() does not return any errors
  • My texLocation, mProgram and mTestTexture all seem to be valid IDs

Does anyone have an idea why I won't see my texture when using the shader?

glUniform1i(texLocation, mTestTexture);
                         ^^^^^^^^^^^^ texture object

Texture unit indexes are bound to samplers, not texture objects.

Use texture unit zero instead:

glUniform1i(texLocation, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM