Why do I need to specify image format as GL_RED instead of GL_ALPHA when loading single-byte alpha value texture?
Asked Answered
S

1

7

I'm loading a texture that consists just of the alpha channel. When sending the data, I need to use GL_RED for both the image format and internal format when calling glTexImage2D, such as the following

glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, temp_bitmap);

If I use GL_ALPHA for either/both of those instead, nothing will get rendered (changing the shader appropriately to use the alpha channel as well).

I was told that GL_RED is supposed to be used for alpha channels, but why is this the case, and why is there still GL_ALPHA?

Stanchion answered 4/5, 2016 at 12:16 Comment(3)
Are you using a Core context?Waxplant
"OpenGL 4.4" does not imply core. You could be using a compatibility context. In fact, unless you specifically requested a core context, you won't get one.Monde
What I meant is "yes core context in 4.4" :P But yeah, I understand the difference, and I explicitly request core.Stanchion
G
10

I'm loading a texture that consists just of the alpha channel.

No, you're not. You're loading a texture that consists of one color channel.

"Alpha" is merely an interpretation of your data. And you are free to interpret data however you wish. But to OpenGL, "one color channel" is spelled "red". Two color channels are spelled "red/green". And so forth.

If you want to make a one channel shader look like it is alpha-only to your shader, then you should use a texture swizzle:

GLint swizzleMask[] = {GL_ZERO, GL_ZERO, GL_ZERO, GL_RED};
glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask);

why is there still GL_ALPHA?

Are you asking why the enumerator exists? If so, then you may not understand the separation between the internal format of a texture (the third parameter) and the pixel transfer format (the third-to-last parameter). The former defines what data exists in the texture. GL_RED means that the texture will have one color channel with unsigned, normalized values of an indeterminate size (stop using unsized image formats).

The latter defines how data from your application is read into the image. It is legal (though nobody would call it fast) to only upload data to specific color channels of an image. For example, if you have a 4-channel image, you could upload data to just the green channels in it using the GL_GREEN transfer format.

Gaelan answered 4/5, 2016 at 13:32 Comment(1)
No, you can't transfer only the green channel for the pixel transfer format. The specification lays out how OpenGL pads out the rest of the values into RGBA format, from which the internal format is then derived. Colors pad to 0, alpha pads to 1. Transfer format is not similar to color channel write masks.Glantz

© 2022 - 2024 — McMap. All rights reserved.