OpenGL 灰度纹理作为浮点格式错误

OpenGL grayscale texture as float wrong format

我得到了一个浮点值在 0.0 - 1.0 范围内的数组(高度图),但纹理返回时要么是黑色,要么只是红色我已经尝试了多种内部格式和源格式的组合,但似乎没有任何效果.我当前的代码只是给我一个红色纹理是:

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

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RED, GL_FLOAT, data);

[编辑] 图像输出: 任何想法出了什么问题?

在 glTexImage2D 函数的第 7 个参数中,您假设设置了图像的格式。您将其设置为 GL_RED。您应该将其设置为图片的格式,可能是 GL_RGB 或 GL_RGBA.

请阅读the documentation

如果它不能使用正确的纹理格式,则有其他问题。虽然不可能说没有看到你的代码的其余部分。

您确定您的数据加载正确吗? 您是否将正确的纹理坐标发送到片段着色器? 你记得设置活动纹理吗? 您是否将片段着色器中的 Sampler2D 设置为与活动着色器相同的值?

您必须设置纹理混合参数,以便在查找纹理时将 OpenGL 从红色通道读取绿色和蓝色通道 - 请参阅 glTexParameteri

glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_RED );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED );

参见OpenGL 4.6 API Compatibility Profile Specification; 16.1 Texture Environments and Texture Functions; page 595:

They are derived by computing the base color Cb and Ab from the filtered texture values Rt, Gt, Bt, At, Lt, and It as shown in table 16.1, ...

Texture Base Texture base color Internal Format    Cb              Ab
...
RED                                                (Rt, 0, 0)      1
RG                                                 (Rt, Gt, 0)     1
RGB                                                (Rt, Gt, Bt)    1
RGBA                                               (Rt, Gt, Bt)    At

Table 16.1: Correspondence of filtered texture components to texture base components.

...followed by swizzling the components of Cb, controlled by the values of the texture parameters TEXTURE_SWIZZLE_R, TEXTURE_SWIZZLE_G, TEXTURE_SWIZZLE_B, and TEXTURE_SWIZZLE_A. If the value of TEXTURE_SWIZZLE_R is denoted by swizzler, swizzling computes the first component of Cs according to

if (swizzler == RED)
    Cs[0] = Cb[0];
else if (swizzler == GREEN)
    Cs[0] = Cb[1];
else if (swizzler == BLUE)
    Cs[0] = Cb[2];
else if (swizzler == ALPHA)
    Cs[0] = Ab;
else if (swizzler == ZERO)
    Cs[0] = 0;
else if (swizzler == ONE)
    Cs[0] = 1; // float or int depending on texture component type

如果您使用着色器程序,则可以在片段着色器中执行类似的操作,Swizzling:

in vec3 uv;

out vec4 frag_color;

uniform sampler2D u_texture;

void main()
{
   frag_color = texture(u_texture, uv).rrra;
}