Creating an OpenGL texture from sdl palette surface (SDL_PIXELFORMAT_INDEX8)
Asked Answered
C

1

5

I created a bmp and I load it using SDL_LoadBMP when inspecting the generated SDL_Surface I can see it is of format SDL_PIXELFORMAT_INDEX8.

I want to use the SDL surface to generate a texture using glTexImage2D.

Normally I could just inspect the surface Something close to this:

SDL_Surface * surface = SDL_LoadBMP(filename.c_str()); 
GLenum mode = 0;
Uint8 bpp = surface->format->BytesPerPixel;
Uint32 rm = surface->format->Rmask;
if (bpp == 3 && rm == 0x000000ff) mode = GL_RGB;
if (bpp == 3 && rm == 0x00ff0000) mode = GL_BGR;
if (bpp == 4 && rm == 0x000000ff) mode = GL_RGBA;
if (bpp == 4 && rm == 0xff000000) mode = GL_BGRA;

GLsizei width = surface->w;
GLsizei height = surface->h;
GLenum format = mode;
GLvoid * pixels = surface->pixels;

/*insert gl texture magic*/

glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, format, GL_UNSIGNED_BYTE, pixels);

However SDL_PIXELFORMAT_INDEX8 has a BytesPerPixel of 1 and all masks are 0. From the SDL Code Examples I read that: "A pixel format has either a palette or masks. If a palette is used Rmask, Gmask, Bmask, and Amask will be 0."

So I assume that my data has a palette instead of masks.

The glTexImage2D states that it would only accept GL_ALPHA, GL_RGB, GL_RGBA, GL_LUMINANCE, and GL_LUMINANCE_ALPHA.

Can I create a texture directly from any surface even if it is based on a palette? Is there a way to use SDL to transform any Image into GL_RGBA? Am I missing an even better way?

Cankerous answered 3/10, 2017 at 14:48 Comment(0)
C
6

I was able to convert into a known format so it is accepted by OpenGL.

GLenum mode = GL_RGBA;
SDL_PixelFormat * target = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA32);
SDL_Surface * surface = SDL_ConvertSurface(tmp, target, 0);
SDL_FreeSurface(tmp);
SDL_FreeFormat(target);
Cankerous answered 3/10, 2017 at 15:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.