我想要做的是从单通道数据数组中加载纹理到硬件中,并使用它的alpha通道将文本绘制到对象上。我使用的是opengl 4.Opengl:使用单通道纹理作为alpha通道来显示文本
如果我尝试使用4通道RGBA纹理来做到这一点,它的工作原理非常好,但无论什么原因,当我尝试在单个通道中加载时,我只能看到一个乱码图像,而我无法找出原因。 我通过梳理纹理位图数据的一系列用下面的代码字形到一个单一的纹理创建纹理:
int texture_height = max_height * new_font->num_glyphs;
int texture_width = max_width;
new_texture->datasize = texture_width * texture_height;
unsigned char* full_texture = new unsigned char[new_texture->datasize];
// prefill texture as transparent
for (unsigned int j = 0; j < new_texture->datasize; j++)
full_texture[j] = 0;
for (unsigned int i = 0; i < glyph_textures.size(); i++) {
// set height offset for glyph
new_font->glyphs[i].height_offset = max_height * i;
for (unsigned int j = 0; j < new_font->glyphs[i].height; j++) {
int full_disp = (new_font->glyphs[i].height_offset + j) * texture_width;
int bit_disp = j * new_font->glyphs[i].width;
for (unsigned int k = 0; k < new_font->glyphs[i].width; k++) {
full_texture[(full_disp + k)] =
glyph_textures[i][bit_disp + k];
}
}
}
然后我加载纹理数据调用:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture->x, texture->y, 0, GL_RED, GL_UNSIGNED_BYTE, reinterpret_cast<void*>(full_texture));
我的片段着色器执行下面的代码:
#version 330
uniform sampler2D texture;
in vec2 texcoord;
in vec4 pass_colour;
out vec4 out_colour;
void main()
{
float temp = texture2D(texture, texcoord).r;
out_colour = vec4(pass_colour[0], pass_colour[1], pass_colour[2], temp);
}
我得到一个图像,我可以告诉是从纹理生成,但它非常扭曲,我不确定为什么。顺便说一句,我使用GL_RED,因为GL_ALPHA从Opengl 4中删除。 真正让我困惑的是,为什么这个工作正常,当我从字形生成4 RGBA纹理,然后使用它的alpha通道?
最后,我通过在调用glTexImage2D之前将数据转换为float来完成此工作。我相信我需要使用4字节倍数的数据格式。这就是为什么RGBA转RGBA的原因(即使它是4x字节)以及为什么浮动数据也起作用。看来我无法使用GL_UNSIGNED_BYTE,除非它具有4通道数据的输入和输出。也许这是ATI驱动程序中的一个错误? – 2012-03-24 05:16:14
好吧,我已经明白了这一点。我的代码没有错,也没有驱动程序中的错误。 GL_UNPACK_ALINGMENT需要设置为1才能工作。它默认设置为4。运行“glPixelStorei(GL_UNPACK_ALIGNMENT,1);”解决了我所有的问题。由于性能原因,我不确定它为什么设置为4。我会调查。 – 2012-03-24 05:27:36