【发布时间】:2020-08-29 12:54:00
【问题描述】:
我正在尝试在我的迷你 OpenGL 程序中使用纹理。由于使用 OpenGL 需要大量重复的代码,所以我将代码抽象为一个类。但我在窗户上看不到任何东西。 OpenGL 不会抛出任何错误。我正在使用来自https://github.com/nothings/stb/ 的stb_image.h 来处理图像文件。我做错了什么?我正在使用 Ubuntu 20.04。
类声明:
class texture {
protected:
unsigned int textureid;
unsigned char* localbuf;
int length, width, pixelbit;
std::string srcpath;
public:
texture(std::string file);
~texture();
int getwidth() const;
int getlength() const;
void bind(unsigned int slot = 0) const;
void unbind() const;
};
类实现:
texture::texture(std::string file) {
srcpath = file;
stbi_set_flip_vertically_on_load(1);
localbuf = stbi_load(file.c_str(), &width, &length, &pixelbit, 4);
glcall(glGenTextures(1, &textureid));
glcall(glBindTexture(GL_TEXTURE_2D, textureid));
glcall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
glcall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
glcall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
glcall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
glcall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, length, 0, GL_RGBA, GL_UNSIGNED_BYTE, localbuf))
glcall(glBindTexture(GL_TEXTURE_2D, 0));
if (localbuf) stbi_image_free(localbuf);
}
texture::~texture() {
glcall(glDeleteTextures(1, &textureid));
}
void texture::bind(unsigned int slot) const {
glcall(glActiveTexture(GL_TEXTURE0 + slot));
glcall(glBindTexture(GL_TEXTURE_2D, textureid));
}
void texture::unbind() const {
glcall(glBindTexture(GL_TEXTURE_2D, 0));
}
int texture::getwidth() const {
return width;
}
int texture::getlength() const {
return length;
}
顶点着色器:
#version 330 core
layout(location = 0) in vec4 position;
layout(location = 1) in vec2 texpos;
out vec2 v_texpos;
void main() {
gl_Position = position;
v_texpos = texpos;
};
片段着色器:
#version 330 core
layout(location = 0) out vec4 color;
in vec2 v_texpos;
uniform sampler2D u_texture;
void main() {
vec4 texcolor = texture2D(u_texture, v_texpos);
color = texcolor;
};
main函数:
int main() {
...
texture mytexture("path/to/image/file.png");
texture.bind();
glUniform1i(glGetUniformLocation(shader, "u_texture"), 0);
...
while (window_open) {
...
glDrawElements(...);
...
}
...
}
【问题讨论】:
-
仅出于调试原因:当您执行
color = texcolor + 0.5;时,您是否“看到”了什么 -
@Rabbid76 是的,我可以看到淡黄色。
-
这段代码没有明显错误。
-
@Rabbid76 你想说问题出在
stb_image.h还是图像文件中? -
该错误很可能不在
stb_image.h中。可能图像路径不正确(尝试绝对路径)。无论如何,我不知道您的主程序中到底发生了什么。这是来自实际代码的 sn-p 吗?
标签: c++ opengl shader textures