简体   繁体   中英

Texture not appearing via stb_image

I have been working on a new project in C++ using GLFW for a OpenGL wrapper, and using the stb_image.h tool to load images.

I load the images using the following snippet:

this->width = width;
this->height = height;
int bpp;

unsigned char* image = stbi_load(("./res/textures/"+fileName).c_str(), &width, &height, &bpp, STBI_rgb_alpha);

if (image == nullptr) std::cerr << "Unable to load texture: " + fileName << std::endl;

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

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

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

if(bpp == 3) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
else if (bpp == 4) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image);
stbi_image_free(image);

And I render the texture via:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glEnable(GL_TEXTURE_2D);

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBindTexture(GL_TEXTURE_2D, texture->id);
glBegin(GL_QUADS);
glTexCoord2i(0, 0); glVertex3i(0, 0, -5);
glTexCoord2i(0, 1); glVertex3i(0, 1, -5);
glTexCoord2i(1, 1); glVertex3i(1, 1, -5);
glTexCoord2i(1, 0); glVertex3i(1, 0, -5);
glEnd();

I am swapping buffers, polling events, and have set the various color bits with glfwWindowHint()

To little avail. When I run, I simply receive the following result:

白色无纹理四边形

You have to call glActiveTexture(GL_TEXTURE0) before glBindTexture(GL_TEXTURE_2D, texture->id) . So, your last code should look like:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glEnable(GL_TEXTURE_2D);

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture->id);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(0, 0, -5);
glTexCoord2f(0, 1); glVertex3f(0, 1, -5);
glTexCoord2f(1, 1); glVertex3f(1, 1, -5);
glTexCoord2f(1, 0); glVertex3f(1, 0, -5);
glEnd();

Also, glActiveTexture(...) , does not have anything to do with GLFW. It is part of opengl.

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