使用 (3x3) 颜色数组对 GL_QUADS 进行纹理化会忽略每行中的第 4 种颜色

Texturing GL_QUADS with (3x3) color array ignores the 4th color in each row

我正在尝试从字节数组生成 3x3 纹理。

我的问题是我需要在每一行的最后一个额外的颜色来得到我想要的,我想知道为什么。

我忽略的字节数是否有问题或类似问题?

这是我的数组:

GLubyte data[33] = { 
                    //bottom row
                    0, 0, 150,
                    150, 10, 220,
                    150, 150, 56,

                    0, 0, 0,        //must be here to get what I want but don't render

                    //middle row
                    150, 150, 150,
                    150, 0, 21,
                    0, 255, 0,

                    0, 0, 0,        //must be here to get what I want but don't render

                    //top row
                    250, 150, 0,
                    250, 0, 150,
                    0, 150, 0 };

我的纹理生成:

GLuint texture;

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

//I thing the problem is right here
glTexImage2D(GL_TEXTURE_2D, 0, 3, 3, 3, 0, GL_RGB, GL_UNSIGNED_BYTE, data);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

return texture;

我正在像这样应用纹理:

GLuint texture = genTexture(0);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);

glBegin(GL_QUADS);
    glTexCoord2f(1.0f, 0.0f); glVertex2f(0.5f, -0.5f);
    glTexCoord2f(1.0f, 1.0f); glVertex2f(0.5f, 0.5f);
    glTexCoord2f(0.0f, 1.0f); glVertex2f(-0.5f, 0.5f);
    glTexCoord2f(0.0f, 0.0f); glVertex2f(-0.5f, -0.5f);
glEnd();

结果是忽略每行的这 24 位:

我会调查 GL_UNPACK_ALIGNMENT 像素存储参数的环境值。 The manual 说:

GL_UNPACK_ALIGNMENT

Specifies the alignment requirements for the start of each pixel row in memory. The allowable values are 1 (byte-alignment), 2 (rows aligned to even-numbered bytes), 4 (word-alignment), and 8 (rows start on double-word boundaries).

该手册页说 "initial value" 确实是 4

使用合适的 glGetInteger() 调用来读取值。

您需要设置 GL_UNPACK_ALIGNMENT 像素存储参数才能使其工作:

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

这控制传递给 glTexImage2D() 的数据中行的对齐方式。默认值为 4。在您的情况下,由于每行包含 9 个字节的数据(3 种颜色,每种颜色 3 个字节),对齐值为 4 会将行大小四舍五入为 12。这意味着将读取 12 个字节每行,并解释为什么在每行末尾添加额外的 3 个字节时它会起作用。

将对齐设置为 1,您将不需要额外的填充。