简体   繁体   中英

Cannot get RGB texture to display in OpenGL ES2

I can get 1 channel of the texture to display with this code:

    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, image_width, image_height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, image_grayscale);
    point bbox[4] = {
        { -0.5, 0.5, 0, 0 },
        { 0.5, 0.5, 1, 0 },
        { -0.5, -0.5, 0, 1 },
        { 0.5, -0.5, 1, 1 },
    };
    glBufferData(GL_ARRAY_BUFFER, sizeof bbox, bbox, GL_DYNAMIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0); 
    glVertexAttribPointer(uniform_color, 4, GL_FLOAT, GL_FALSE, 0, bbox);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

But when I change to

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, button_image_width, button_image_height, 0, GL_RGB, GL_UNSIGNED_BYTE, image_rgb);

I get a solid color instead of the image

Below is the fragment shader

    GLbyte fShaderStr[] =  
       "varying vec2 texpos;                                                \n"
       "uniform sampler2D tex;                                              \n"
       "uniform vec4 color;                                                 \n"
       "void main()                                                         \n"
       "{                                                                   \n"
       "   gl_FragColor = vec4(1, 1, 1, texture2D(tex, texpos).a) * color;  \n"
       "}         

How can I draw an RGB texture?

When you do

glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, image_width, image_height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, image_grayscale);

the the result is a texture image, with an alpha channel only. texture2D return 0 for the red, green and blue channel. The alpha channel returns the corresponding value to the texture coordinate.
Because of that in the fragment shader the alpha channel of the sampler is read:
(See Swizzling )

texture2D(tex, texpos).a

But when you do

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, button_image_width, button_image_height, 0, >GL_RGB, GL_UNSIGNED_BYTE, image_rgb)

Then the texture image has 3 color channels, but the alpha channel is 1 for all texels.

You have to adapt the fragment shader for the 2nd case:

gl_FragColor = vec4(texture2D(tex, texpos).rgb, 1.0);

or

gl_FragColor = texture2D(tex, texpos);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM