graphics.h
class Graphics
{
public:
void renderBMP(std::string path, int posX, int posY);
private:
// the textures container. The strings will be the file paths
map<string, SDL_Texture*> textures;
SDL_Texture *textureToLoad; // temporary texture holder for the loading function. The workaround.
};
graphics.cpp
/* Search for this BMP's path on the textures container.
* If it doesn't exist, load it to the container.
* If it already exists, retrieve the texture from the container. */
void Graphics::renderBMP(std::string path, int posX, int posY)
{
if (textures.find(path) == textures.end()) // If this texture isn't loaded yet
{
SDL_Surface *tempSurface = SDL_LoadBMP(path.c_str());
textureToLoad = SDL_CreateTextureFromSurface(renderer, tempSurface);
SDL_FreeSurface(tempSurface);
textures[path] = textureToLoad;
}
else
{
textureToLoad = textures[path];
}
// the rest doesn't matter
}
This is how I have it, after a little workaround.
I was trying to avoid the need of a class member (in this case, textureToLoad) to hold the new SDL_Texture after the renderBMP() function has gone out of scope.
What I was trying was this:
void Graphics::renderBMP(std::string path, int posX, int posY)
{
if (textures.find(path) == textures.end()) // If this texture isn't loaded yet
{
SDL_Surface *tempSurface = SDL_LoadBMP(path.c_str());
textures[path] = new SDL_Texture(SDL_CreateTextureFromSurface(renderer, tempSurface));
SDL_FreeSurface(tempSurface);
}
// blablabla
I was getting the error again this way.
In the meantime I found out that SDL isn't prepared to be used in such a way that means creating SDL_Textures directly (without the pointer interface). Quoting a site I found http://stackoverflow.com/questions/18897076/sdl-texture-incomplete-type):
SDL_Texture is an opaque type by design (that is, designed to only be operated on by SDL2 internally), you can "pass it around" as a pointer, but you can't access the internals (or create a SDL_Texture yourself, for example by doing a malloc, because you don't know the size of the structure). If you stick to SDL_Texture *blah;
pointers and pass them around to the SDL2 functions you should be fine.
This I why I decided to use the workaround.