Search code examples
c++opengltexture-mapping

OpenGL: Can't get textures to display


I'm trying to add a texture to a simple square for more than 5h now but I still don't manage to do so.

Here's the code I'm using in paintGL():

glEnable(GL_TEXTURE_2D);

GLuint id;
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);

float pixels[] = {
    0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
    1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f
};

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_FLOAT, pixels);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
    glTexCoord2f(0.0f, 0.0f); glVertex3f(0,0,0);
    glTexCoord2f(1.0f, 0.0f); glVertex3f(1,0,0);
    glTexCoord2f(1.0f, 1.0f); glVertex3f(1,1,0);
    glTexCoord2f(0.0f, 1.0f); glVertex3f(0,1,0);
glEnd();

if (glGetError() != 0)
{
    qDebug() << glGetError();
}

There is no errors nor OpenGL's ones. I initialized the clear color to grey. When I try to change color with glColor3f(...), it works.

I read about all tutorials that I could find with Google but no one helped.

SOLUTION: I never put

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

at the right place: just after the glTexImage2D! Code above is edited and now work like a charm.


Solution

  • You HAVE to specify filtering for your texture:

    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    

    Because default filter uses mipmaps, but you don't generate them.