Proper Image Resource Management in SDL2?


Working on an update to our “GT-R Twin TurboCharged” SDL2 cross-platform 2-D game engine…
We are using SDL2_Image for PNG image support.
PNG Image resource management is a mess in our current source code.

Any suggestions?
I own a license to
Would the above system work in SDL2 with SDL2_Image?

Please let me know, thanks!


Do you have any code examples on how you’re currently doing it? The reason I’m asking is that it might help checking out how you’re doing it now to find issues, help with improvement etc.

First of all, in your Loading* functions, there’s A LOT of switch cases, magic numbers etc that you really need to get rid of.

One option is having a text/settings file containing all the image filenames that should be loaded and then just loop through the text/settings file’s rows and load each corresponding filename that is found in each row. By doing this, you will end up with just 1 for loop, without any weird switch cases with those magic numbers.

The second (and probably the best) option is to pack every small texture (like buttons etc) into a combined texture atlas, which you can create with the software you’ve linked to. By having a texture atlas, you only need to load 1 image, instead of loading like 20-30 images.
Then, when it’s time to render one of the images, you just need to clip the texture and only render that specific clipped area of the texture. And yes, texture atlases works perfect with SDL_Image (and any other image loading library for that matters).

Also, you should stop using a fixed sized array for you images. If you want to have a more dynamic (and less strict) image loading approach, consider using a list/vector/map (whatever you’re most comfortable with) which you add images into and at the shutdown stage of your program/game, just loop through the list and destroy the content in it.
You can do the same for other types of data aswell, like fonts, music files etc.

In your LoadCharacterTilesIntoMemory function, you’re looping through the characters A-Z, a-z and the numbers 0-9. You should be able to create the asci characters you need to by just looping through each character and type cast the loop index into a char to get the character representation.

Example code:

// 0 - 32 are just control codes, which are mostly never used, so start from 32
for(int i = 32; i < 256; ++i)
   strcpy(buttonText, (char)i);

I haven’t tested the above code properly but you should be able to make it work with some experimentation.


Thanks for the response…
You have some interesting suggestions that I will implement.
I particularly like the string array of image file names.

I have to clean my apartment today, but will jump back to the project later.