0 Members and 1 Guest are viewing this topic.
In a more complex engine, images would be automatically handled by a manager. This is a more generic and easy way of handling resources. The idea is to make the manager store the images, associated to their filename (or whatever unique identifier), so that if the same image is requested several times, the same instance will actually always be returned by the manager.Code: [Select]sf::Sprite Sprite;// GetImage will always return the same image for the same filenameSprite.SetImage(ImageManager.GetImage("data/missile.png"));
sf::Sprite Sprite;// GetImage will always return the same image for the same filenameSprite.SetImage(ImageManager.GetImage("data/missile.png"));
class Image_manager{private: map<string, sf::Image> image_map;public: const sf::Image& GetImage(string image_path) // The filename is used as a key { // Is this image is not loaded - load it if(image_map.find(image_path) == image_map.end()) { sf::Image tmp; if(!tmp.LoadFromFile(image_path)) { exit(EXIT_FAILURE); } image_map.insert( pair<string,sf::Image>(image_path,tmp) ); } return image_map[image_path]; } void InformUs() const { cout << "These are the images we have loaded:" << endl; for(map<string, sf::Image>::const_iterator it = image_map.begin(); it != image_map.end(); ++it) { cout << it->first << endl; } }};
I would work with pointers: copying images is a high cost function.You could insert an empty image and then loading, instead.
image_map.insert( pair<string,sf::Image>(image_path,tmp) );
class Image_manager{private: map<string, sf::Image> image_map;public: const sf::Image& GetImage(string image_path) // The filename is used as a key { // Is this image is not loaded - load it if(image_map.find(image_path) == image_map.end()) { pair<string, sf::Image> path_image_pair; path_image_pair.first = image_path; if(!path_image_pair.second.LoadFromFile(image_path)) { exit(EXIT_FAILURE); } image_map.insert( path_image_pair ); } return image_map[image_path]; }};