Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Smart Resource manager  (Read 5384 times)

0 Members and 1 Guest are viewing this topic.

Groogy

  • Hero Member
  • *****
  • Posts: 1469
    • MSN Messenger - groogy@groogy.se
    • View Profile
    • http://www.groogy.se
    • Email
Smart Resource manager
« on: December 22, 2010, 02:33:51 pm »
Aight I've made a "smart" resource manager that knows when a resource is in use and will unload the resources if it's getting short on space(the max space you can set yourself but it defaults to the size of 10 000 resources).

Wiki article: http://www.sfml-dev.org/wiki/en/sources/smart_resource_manager

Anyway here's a example of it in use:
Code: [Select]
class ImageManager : public ResourceManager<sf::Image, std::string, 100>
{
protected:
bool Load(sf::Image &resource, const std::string &path) const
{
return resource.LoadFromFile(path);
}
};

typedef Resource<sf::Image, std::string, 100> ImageResource;

int main()
{
std::string paths[1000] = {/* Define a 1000 paths */};
ImageManager manager;
for(unsigned int index = 0; index < 1000; index++)
{
ImageResource test = manager.Get(paths[index]);
std::cout << test->GetWidth() << ", " << test->GetHeight() << std::endl;
sf::Sprite sprite(*test);
}
return 0;
}


This manager will hold the images and can only contain 100 of them but if we look at the for-loop we distinctively can see that we will load all images specified by the array paths. The image is loaded and kept track of, then returned trough it's Resource handle. We can interact with the image just like if the resource handle was a pointer to the image. And at the end of the for-loop the resource object will be destructed and the only reference to it terminated. And thus the memory is free'd up for grabs again if we need it. In reality the image will stay in memory until we run out of space which we will at image 100. If we would have saved another handle outside the for-loop that doesn't get destructed then the image can't be loaded out of memory until that resource handle is also gone thus giving us the "smart" in this resource manager.
Developer and Maker of rbSFML and Programmer at Paradox Development Studio