1
votes

I'm working on a small pet project and I have a 1d array of RGB colours that are packed using this method:

int rgb = (((unsigned int)r) << 16) | (((unsigned int)g) << 8) | b

And the image data is stored in the array like this

int x, y;
for (x = 0; x < img->w; ++x) {
    for (y = 0; y < img->h; ++y) {
        img->buf[(y) * img->w + (x)] = color;
    }
}

I don't understand OpenGL well enough to understand how to get the data into a texture buffer. This is what I use to get the data uploaded, but obvious this just results in a weird looking black and white mess.

GLuint texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, test->w, test->h, 0, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)test->buf);

I tried messing around with glPixelStorei(GL_UNPACK_ALIGNMENT, 1) and different texture format options for glTexImage2D but nothing seems to work. I've seen this thread: Colour bit-wise shift in OpenGL shader GLSL which seems to be similar, I just don't understand how to get to that point.

Can anyone help?

1

1 Answers

0
votes

You're not showing the type of img->buf, but it seems likely that you're storing 32-bit integers. That means that there are 8 extra (unused) bits per pixel, which needs to be part of the format. The simplest way is to tell OpenGL it's alpha. (With an internal format of GL_RGB, any alpha input will be ignored anyway.) With blue in the low bits and alpha in the high bits, this suggests you must use format GL_BGRA.

If you're using GL_UNSIGNED_BYTE as type, then byte order of these integers also matter. I'm guessing you're using a little-endian platforms (x86), in which case GL_UNSIGNED_BYTE will work, but it becomes more portable if you use GL_UNSIGNED_INT_8_8_8_8_REV. Hence, I'm guessing you want

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, test->w, test->h, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, (GLvoid*)test->buf);

(Updated to suggest GL_UNSIGNED_INT_8_8_8_8_REV)