简体   繁体   English

纹理未通过stb_image出现

[英]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. 我一直在使用GLFW进行OpenGL包装并使用stb_image.h工具加载图像来进行C ++中的新项目。

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() 我交换缓冲区,轮询事件,并使用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) . 您必须在glBindTexture(GL_TEXTURE_2D, texture->id)之前调用glActiveTexture(GL_TEXTURE0) 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. 另外, glActiveTexture(...)与GLFW没有任何关系。 It is part of opengl. 它是opengl的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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