【发布时间】:2012-04-08 14:03:23
【问题描述】:
我要做的是将纹理从单通道数据数组加载到硬件中,并使用它的 alpha 通道将文本绘制到对象上。我正在使用 opengl 4。
如果我尝试使用 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 之前将数据转换为浮点数来实现这一点。我相信我需要使用 4 个字节的倍数的数据格式。这就是为什么 RGBA 到 RGBA 有效(即使它是 4x 字节)以及浮点数据也有效的原因。似乎我无法使用 GL_UNSIGNED_BYTE 除非它同时具有 4 通道数据的输入和输出。也许这是 ATI 驱动程序中的错误??
-
好的,我知道了。我的代码没有任何问题,驱动程序中也没有错误。 GL_UNPACK_ALINGMENT 需要设置为 1 才能工作。默认设置为 4。运行“glPixelStorei(GL_UNPACK_ALIGNMENT, 1);”解决了我所有的问题。我不确定为什么将其设置为 4 可能是出于性能原因。我会调查的。