Skip to content

Instantly share code, notes, and snippets.

@clckwrkbdgr
Created April 21, 2014 15:04
Show Gist options
  • Save clckwrkbdgr/11145266 to your computer and use it in GitHub Desktop.
Save clckwrkbdgr/11145266 to your computer and use it in GitHub Desktop.
Loading XPM data into SDL2 texture.
SDL_Texture * Sprite::load(SDL_Renderer * renderer, const char ** xpm, int size)
{
SDL_Texture * result = 0;
try {
std::vector<std::string> xpm_lines(xpm, xpm + size);
Chthon::Pixmap pixmap;
pixmap.load(xpm_lines);
SDL_Surface * surface = SDL_CreateRGBSurface(SDL_SWSURFACE,
pixmap.pixels.width(), pixmap.pixels.height(), 32,
0x00ff0000,
0x0000ff00,
0x000000ff,
0xff000000
);
if(SDL_MUSTLOCK(surface)) {
SDL_LockSurface(surface);
}
for(unsigned x = 0; x < pixmap.pixels.width(); ++x) {
for(unsigned y = 0; y < pixmap.pixels.height(); ++y) {
Uint8 * pixel = (Uint8*)surface->pixels;
pixel += (y * surface->pitch) + (x * sizeof(Uint32));
Uint32 c = pixmap.palette[(pixmap.pixels.cell(x, y))];
*((Uint32*)pixel) = c;
}
}
if(SDL_MUSTLOCK(surface)) {
SDL_UnlockSurface(surface);
}
result = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC, pixmap.pixels.width(), pixmap.pixels.height());
SDL_UpdateTexture(result, 0, surface->pixels, surface->pitch);
SDL_SetTextureBlendMode(result, SDL_BLENDMODE_BLEND);
} catch(const Chthon::Pixmap::Exception & e) {
std::cerr << e.what << std::endl;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment