TextureCache/TextureCache.cc
Josh Holtrop 4349f3f82c remove GLU/TextureLoader/FileLoader dependance
no longer generating mipmaps
2011-05-19 16:54:10 -04:00

71 lines
1.7 KiB
C++

#include <stdlib.h>
#include <SDL.h>
#include <SDL_image.h>
#include <iostream>
#include "TextureCache.h"
using namespace std;
GLuint TextureCache::load(const char *fname)
{
string filename = fname;
map<string,GLuint>::iterator it = m_cache.find(filename);
if (it != m_cache.end())
{
return it->second;
}
GLuint texture;
SDL_Surface * temp = IMG_Load(filename);
if (!temp)
{
fprintf(stderr, "Failed to load image '%s'!\n", filename);
return 0;
}
SDL_PixelFormat fmt;
fmt.palette = NULL;
fmt.BitsPerPixel = 32;
fmt.BytesPerPixel = 4;
fmt.Rmask = 0x000000FF;
fmt.Gmask = 0x0000FF00;
fmt.Bmask = 0x00FF0000;
fmt.Amask = 0xFF000000;
fmt.Rshift = 0;
fmt.Gshift = 8;
fmt.Bshift = 16;
fmt.Ashift = 24;
SDL_Surface * texsurf = SDL_ConvertSurface(temp, &fmt, SDL_SWSURFACE);
SDL_FreeSurface(temp);
if (!texsurf)
{
fprintf(stderr, "'%s' was not converted properly!\n", filename);
return 0;
}
unsigned int * pixels =
malloc(sizeof(unsigned int) * texsurf->w * texsurf->h);
int y;
unsigned int dstOffset = texsurf->w * (texsurf->h - 1);
unsigned int srcOffset = 0;
for (y = 0; y < texsurf->h; y++)
{
memcpy(pixels + dstOffset,
((unsigned int *)texsurf->pixels) + srcOffset,
texsurf->w << 2);
dstOffset -= texsurf->w;
srcOffset += texsurf->w;
}
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texsurf->w, texsurf->h, 0,
GL_RGBA, GL_UNSIGNED_BYTE, pixels);
SDL_FreeSurface(texsurf);
free(pixels);
m_cache[filename] = texture;
return texture;
}