What's the difference betweem Towers.clear() and a resource manager? |
Textures are very big. They consume a lot of memory.
Right now your Tower class owns its texture. This is a bad idea because it's very likely that you will have multiple towers, all of which have the same graphic. This means that you are loading the entire image into memory for each tower. As a result, the same image has 6 or 7 copies of it loaded. This is a huge waste.
The idea behind having a resource manager is that nothing in your code
owns a texture. But when you need a texture in your code... you can just ask the resource manager for it.
The resource manager would keep track of which resources/textures are loaded, and make sure that one image is only ever loaded once. If multiple different areas of the code request the same image... it can give them all the same copy. That way it doesn't matter how many dozens/hundreds of similar towers you have, they all share the same texture -- the texture only is in memory once.
A simple resource manager is very easy to implement. Something along these lines works well:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <map>
#include <string>
class TextureManager
{
private:
static std::map< std::string, sf::Texture > textures; // the map of all loaded textures
public:
static sf::Texture& get(const std::string& filename)
{
if( /* texture isn't loaded yet */ )
{
// load texture. Put it in textures[filename]
}
return textures[ filename ];
}
// call this before the OpenGL context ends to avoid the crashing problem.
static void clear()
{
textures.clear();
}
};
|
Also, is a global vector good practice? Or should I put it somewhere else? |
Global anything is almost always a bad idea. With very few exceptions --- one of which is resource managers (since the whole point is to only have one of them to avoid duplicate resources).
I typically would have a "Game" class which has the vector of towers as one of its members.