Intro

Although there are multiple resource managers in this wiki, I decided to provide my own because none of the others (so far) offer a thread safe implementation. An example of a font manager is included.

ResourceManager.hpp

/*
Copyright (c) 2009, Johannes S. Mueller-Roemer
All rights reserved.
 
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * The name of the author may not be used to endorse or promote products
      derived from this software without specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RESOURCE_MANAGER_HPP
#define RESOURCE_MANAGER_HPP
 
#include <map>
#include <string>
#include <stdexcept>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
 
template<typename T>
class ResourceManager {
public:
	typedef boost::shared_ptr<T> Resource;
	typedef std::map<std::string, Resource> ResourceMap;
 
	// Gets the resource described by the locator and loads it if it hasn't been loaded yet
	Resource GetResource(const std::string& locator)
	{
		boost::mutex::scoped_lock lock(resource_mutex);
 
		ResourceMap::iterator it = resources.find(locator);
		if(it == resources.end()) // not loaded yet, load now
		{
			Resource loaded = LoadResource(locator);
			if(loaded)
				it = resources.insert(std::make_pair(locator, loaded)).first;
			else
				throw std::runtime_error("Resource " + locator + " could not be loaded");
		}
 
		Resource result = it->second; // make a copy of the smart pointer before unlocking (increment use count)
 
		return result;
	}
 
	void ReleaseUnusedResources()
	{
		boost::mutex::scoped_lock lock(resource_mutex);
 
		ResourceMap::iterator it = resources.begin();
 
		while(it != resources.end())
		{
			ResourceMap::iterator cur = it++;
 
			if(cur->second.unique()) // the smart pointer in the resource map is the last one left
				resources.erase(cur);
		}
	}
 
protected:
	// must be implemented for the corresponding resource type
	virtual Resource LoadResource(const std::string& locator) = 0;
 
private:
	ResourceMap resources;
	boost::mutex resource_mutex;
};
 
#endif

Example.cpp

#include "ResourceManager.hpp"
 
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
 
#include <SFML/Graphics.hpp>
 
class FontManager : public ResourceManager<sf::Font>
{
	Resource LoadResource(const std::string& locator)
	{
		typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
		boost::char_separator<char> sep(";", "", boost::keep_empty_tokens);
 
		tokenizer tokens(locator,sep);
 
		tokenizer::iterator it = tokens.begin();
 
		Resource font = Resource(new sf::Font());
 
		// defaults
		std::string filename = "arial.ttf";
		unsigned int fontsize = 30;
 
		if(it != tokens.end()) // filename
		{
			if(!it->empty())
				filename = *it;
 
			++it;
		}
 
		if(it != tokens.end()) // font size
		{
			if(!it->empty())
				fontsize = boost::lexical_cast<unsigned int>(*it);
 
			++it;
		}
 
		if(!font->LoadFromFile(filename,fontsize))
			return Resource();
 
		return font;
	}
};
 
int main(int argc, char** argv)
{
	try {
		sf::RenderWindow App(sf::VideoMode(800, 600), "SFML Fonts");
		App.UseVerticalSync(true);
 
		FontManager fontManager;
 
		{
			FontManager::Resource font1 = fontManager.GetResource("arial.ttf;50");
			FontManager::Resource font2 = fontManager.GetResource("georgia.ttf;30");
 
			sf::String Hello;
			Hello.SetText("Hello !\nHow are you ?");
			Hello.SetFont(*font1);
			Hello.SetColor(sf::Color(0, 128, 128));
			Hello.SetPosition(100.f, 100.f);
			Hello.SetRotation(15.f);
			Hello.SetSize(50.f);
 
			sf::String Bonjour("Salut !\nComment ça va ?", *font2, 30.f);
			Bonjour.SetColor(sf::Color(200, 128, 0));
			Bonjour.SetPosition(200.f, 300.f);
 
			while (App.IsOpened())
			{
				Bonjour.Rotate(App.GetFrameTime() * 100.f);
				App.Clear();
 
				App.Draw(Hello);
				App.Draw(Bonjour);
 
				App.Display();
 
				sf::Event Event;
				while (App.GetEvent(Event))
				{
					if (Event.Type == sf::Event::Closed)
						App.Close();
				}
 
				fontManager.ReleaseUnusedResources(); // this won't do anything since all resources are in use
			}
		}
 
		fontManager.ReleaseUnusedResources();
	}
	catch(std::exception& e)
	{
		std::cerr << "An unhandled exception occurred: " << e.what() << "\n";
		return EXIT_FAILURE;
	}
	catch(...)
	{
		std::cerr << "An unknown exception occurred\n";
		return EXIT_FAILURE;
	}
 
	return EXIT_SUCCESS;
}
 
en/sources/resource_manager_l0calh05t.txt · Last modified: 2009/08/11 20:26 by l0calh05t
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki