• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
keyforge

Game 'Resource Manager' Design

8 posts in this topic

Hello! I'm currently working on a game project with SFML and C++ and I'm writing my games resource manager, if you don't know what that is it's basically a class to take care of storing game assets that can be reused without reloading, and takes care of cleaning them up (RAII).

My design plan is to create a main template interface (or base) class called ResourceManager, the template parameter being the type of resource you want it to manage. It would have a function Get, which would take a std::string argument filename, and which would load the resource if not loaded, and then return it, or just return it if it's already loaded. It would have a typedef T* Resource (T being the template parameter.) It would have a std::map<std::string, Resource> which would store the resources and the key being the filename. The destructor would take care of the resources of cleaning up the resources (SFML's resource types use RAII already anyway, so this is unnecessary for some of them). Lastly it would have a pure virtual function called LoadResource(const std::string& filename);

Next I would create classes like ImageManager, SoundManager, MusicManager, etc. Those would inherit ResourceManager<ResourceType> (Resource type being sf::Image for SFML Images, sf::Sound for SFML sounds, etc.) and Singleton<ManagerClassName> (ManagerClassName being ImageManager for ImageManager, etc.). These classes would then implement the virtual LoadResource() function and load the resource for it's specific resource type, then return the resource for the Get function.

Accessing a resource would be simple, for example I could assign it to ImageManager::Resource logo_image = ImageManager::GetInstance().Get("Data/Textures/Logo.jpg"), which could then be applied to an sf::Sprite via sprite.SetImage(*logo_image). Or I could assign and play music by going ImageManager::GetInstance().Get("Data/Music/Music.ogg")->Play();. Simple as that!
(Resource again being the typedef T*)
0

Share this post


Link to post
Share on other sites
[quote name='KeyGames' timestamp='1315873078' post='4860910']
Hello! I'm currently working on a game project with SFML and C++ and I'm writing my games resource manager, if you don't know what that is it's basically a class to take care of storing game assets that can be reused without reloading, and takes care of cleaning them up (RAII).

My design plan is to create a main template interface (or base) class called ResourceManager, the template parameter being the type of resource you want it to manage. It would have a function Get, which would take a std::string argument filename, and which would load the resource if not loaded, and then return it, or just return it if it's already loaded. It would have a typedef T* Resource (T being the template parameter.) It would have a std::map<std::string, Resource> which would store the resources and the key being the filename. The destructor would take care of the resources of cleaning up the resources (SFML's resource types use RAII already anyway, so this is unnecessary for some of them). Lastly it would have a pure virtual function called LoadResource(const std::string& filename);

Next I would create classes like ImageManager, SoundManager, MusicManager, etc. Those would inherit ResourceManager<ResourceType> (Resource type being sf::Image for SFML Images, sf::Sound for SFML sounds, etc.) and Singleton<ManagerClassName> (ManagerClassName being ImageManager for ImageManager, etc.). These classes would then implement the virtual LoadResource() function and load the resource for it's specific resource type, then return the resource for the Get function.

Accessing a resource would be simple, for example I could assign it to ImageManager::Resource logo_image = ImageManager::GetInstance().Get("Data/Textures/Logo.jpg"), which could then be applied to an sf::Sprite via sprite.SetImage(*logo_image). Or I could assign and play music by going ImageManager::GetInstance().Get("Data/Music/Music.ogg")->Play();. Simple as that!
(Resource again being the typedef T*)

Sorry if any of this is unclear, I'm no prize winning author and I will clarify it if needed (just ask me)! What I'm curious is if there's any major design flaws in this, or anything I shouldn't be doing that I am planning to do. It worked on paper, and I don't want to create an memory leaks with this. Before coding this I want to make sure it will work and that I don't mess up badly or anything like that. Thanks!
[/quote]

I've done this many many times, and over the years have settled on a simple solution. The basic principle is that everything, rather than using ResourceType *, uses a sikngle layer wrapper, a ResourceHandle. I don't have my c++ code to hand, but here is my c# implementation,
[code]

public class ResourceHolder <Type>
{
protected string name;
protected Type item;
protected bool linked;

public ResourceHolder(string name, Type t)
{
this.name = name;
this.item = t;
this.linked = true;
}

public virtual Type Item { get { return this.item;} set { this.item = value; this.linked = true; } }

public virtual bool Linked { get { return this.linked; } }

}

public class ResourceTable<Type>
{
public ResourceTable(string prefix, ContentManager content)
{
this.prefix = prefix;
this.content = content;
}

public virtual void linkReference(ref ResourceReference<Type> reference)
{
reference.link(this.getResource(reference.Name, true));
}

public virtual Type loadResource(string name)
{
int pos = items.Count;

Type r = content.Load<Type>(prefix + "/" + name);
ResourceHolder<Type> handle = new ResourceHolder<Type>(name, r);

items[name] = new ResourceHolder<Type>(name, r);
return handle.Item;
}

public virtual Type getResource(string name, bool loadIfNotLoaded)
{
ResourceHolder<Type> item;
bool exists = items.TryGetValue(name, out item);

if (exists)
{
return item.Item;
}
else if (loadIfNotLoaded)
{
return loadResource(name);
}
else
{
throw new Exception("No resource could be loaded with the name" + name);
}
}

public virtual Type getResource(string name)
{
return getResource(name, true);
}

protected Dictionary<string, ResourceHolder<Type>> items= new Dictionary<string, ResourceHolder<Type>>();

protected string prefix;
protected ContentManager content;

}
[/code]


The main difference in c++ is that you would use std::map<string, ResourceHolder<Type>> rather than a dictionary, but otherwise the code is almost the same.

the idea is that resources can be loaded at runtime if they were not pre-cached (during development, you can't always load resources during initialization, although it is better to avoid stuttering later on). Now, you are able to decouple ordinary objects which might need access to a resource from your resource manager - the linking of objects with their resources can take place at any time, e.g. during the first time that object is rendered. If a resource has been precached, the step to link an object with its resource is trivial.

Beware of very complicated implementations, especially implementations which make assumptions about usage, because these will bring you more pain than pleasure. A simple and reliable solution, for most games, is often the best considering that resource management is such a core principle.
0

Share this post


Link to post
Share on other sites
So basically it's like what I was doing with a wrapper layer around the resource type? Sorry I'm a little confused, I'm not sure if there's anything I missed there. Would I still create other classes like ImageManager, etc.?
0

Share this post


Link to post
Share on other sites
[quote name='KeyGames' timestamp='1315876102' post='4860926']
So basically it's like what I was doing with a wrapper layer around the resource type? Sorry I'm a little confused, I'm not sure if there's anything I missed there. Would I still create other classes like ImageManager, etc.?
[/quote]

Every type of resource goes in a ResourceHolder; you can also have a series of tables. What you don't do is have an abstract system of resource managers, because every resource loads differently. Some load themselves, and others are loaded from within some kind of table. SFML has a series of tables already implemented for some of its resource types. Most of the time, you will be able to store loaded resources in a table, like the one in my code sample, (i don't call everything a manager because that is just a lazy naming convention). You will have to extend the resource table class to cater for the differences between individual resource types.
0

Share this post


Link to post
Share on other sites
[quote name='speciesUnknown' timestamp='1315876674' post='4860929']
[quote name='KeyGames' timestamp='1315876102' post='4860926']
So basically it's like what I was doing with a wrapper layer around the resource type? Sorry I'm a little confused, I'm not sure if there's anything I missed there. Would I still create other classes like ImageManager, etc.?
[/quote]

Every type of resource goes in a ResourceHolder; you can also have a series of tables. What you don't do is have an abstract system of resource managers, because every resource loads differently. Some load themselves, and others are loaded from within some kind of table. SFML has a series of tables already implemented for some of its resource types. Most of the time, you will be able to store loaded resources in a table, like the one in my code sample, (i don't call everything a manager because that is just a lazy naming convention). You will have to extend the resource table class to cater for the differences between individual resource types.
[/quote]

Sorry, but I'm still slightly confused. I understand that the table stores all the resources and resourceholder wraps around a specific resource, but I'm not sure how you would Load each resource since they have different methods for loading.
0

Share this post


Link to post
Share on other sites
I agree with SpeciesUnknown, you don't need inheritance here. For C++, I'd recommend using something like std::shared_ptr or boost::shared_ptr rather than raw pointers.

I generally go with having a ResourceLocator<>, ResourceLoader<> and a ResourceCache<> as template classes. There is no universal Resource interface, a Resource is really any immutable class. The ResourceLocator worries about getting the bytes that make up the resource into memory in a form that can be consumed. The ResourceLoader uses a ResourceLocator to obtain the bytes, and whatever in-memory API function exists to create a resource from these bytes. The ResourceCache is concerned with avoiding loading a Resource multiple times, but uses a ResourceLoader to generate a resource.

As a result of this separation of concerns, each class is relatively small and focused.

I don't use singletons for these. In my simpler games, I might just use global pointers that point at auto-allocated objects in main(). In more complex games, these objects are often bundled into some kind of "context" structure which is passed through whatever layers until it gets to where objects are loaded.

More complex games often use chained resource caching. Each game "level" has its own cache, which is purged. To avoid re-loading common resources between levels, the previous level's cache is temporarily set as a "parent" to the next level's cache (each cache will look locally, then to its parent, before creating a new resource). Once loading is complete, I undo the parental relationship and drop the old cache, which unloads any unused resources.
0

Share this post


Link to post
Share on other sites
[quote name='rip-off' timestamp='1315922397' post='4861077']
I agree with SpeciesUnknown, you don't need inheritance here. For C++, I'd recommend using something like std::shared_ptr or boost::shared_ptr rather than raw pointers.

I generally go with having a ResourceLocator<>, ResourceLoader<> and a ResourceCache<> as template classes. There is no universal Resource interface, a Resource is really any immutable class. The ResourceLocator worries about getting the bytes that make up the resource into memory in a form that can be consumed. The ResourceLoader uses a ResourceLocator to obtain the bytes, and whatever in-memory API function exists to create a resource from these bytes. The ResourceCache is concerned with avoiding loading a Resource multiple times, but uses a ResourceLoader to generate a resource.

As a result of this separation of concerns, each class is relatively small and focused.

I don't use singletons for these. In my simpler games, I might just use global pointers that point at auto-allocated objects in main(). In more complex games, these objects are often bundled into some kind of "context" structure which is passed through whatever layers until it gets to where objects are loaded.

More complex games often use chained resource caching. Each game "level" has its own cache, which is purged. To avoid re-loading common resources between levels, the previous level's cache is temporarily set as a "parent" to the next level's cache (each cache will look locally, then to its parent, before creating a new resource). Once loading is complete, I undo the parental relationship and drop the old cache, which unloads any unused resources.
[/quote]

SFML's resource classes already take care of loading the resource into memory, what I want is something to take care of all of the resources after they are loaded that can be globally accessed. Would this eliminate the need for a resource loader and locator?
0

Share this post


Link to post
Share on other sites
Sure. I'm just describing how I have done this in the past. The point I was trying to illustrate is how the design features no inheritance.

Global access is a separate concern. The ResourceCache shouldn't need to care about this.
0

Share this post


Link to post
Share on other sites
They way I designed my resource manager is similar to rip-off and SpeciesUnknown have done. I have a ResourceDescriptor, Resource, and ResourceManager. The ResourceManager maintains a list of resources that have already been loaded. When you want something, create a ResourceDescriptor and use it to ask theResourceManager for the resource. If the resource doesn't exist yet, the ResourceManager uses the ResourceDescriptor to do the actual load of the resource. It's a kind of double dispatch pattern to get the resource specific loading behavior.

The nice thing about this is that the ResourceManager doesn't need to know how to load the specific types of resources since it's the resource descriptor that handles that. The resource manager probably should have some memory tracking functions and priority system, but I haven't needed them yet.


Below is how I implemented my ResourceManager, ResourceDescriptors and a texture resource descriptor in C#.


Cheers,

Bob


[code]

using System;
using System.Collections.Generic;

namespace SimEngine
{
public static class ResourceManager
{
static Dictionary<String, IResource> myResources;

static ResourceManager()
{
myResources = new Dictionary<String, IResource>();
}

public static bool init(Initializer init)
{
return true;
}

public static IResource getResource(ResourceDescriptor desc)
{
IResource res;
if (myResources.TryGetValue(desc.filename, out res))
{
return res;
}

//need to try and load the IResource here
res = load(desc);

return res;
}

static IResource load(ResourceDescriptor desc)
{
IResource res;

if (System.IO.File.Exists(desc.filename) == false)
{
Warn.print("Cannot find file {0}", desc.filename);
return null;
}

res = desc.create();

if (res != null)
{
myResources[desc.filename] = res;
}

return res;
}

}
}
[/code]


[code]

using System;

namespace SimEngine
{
public interface IResource
{
}

public abstract class ResourceDescriptor
{
public ResourceDescriptor()
{
}

public ResourceDescriptor(String name)
{
filename = name;
}

public string filename { get; set; }

public abstract IResource create();
}
}
[/code]


[code]

public class TextureDescriptor : ResourceDescriptor
{
bool myFlip=false;

public TextureDescriptor(string name) : this(name, false) { }
public TextureDescriptor(string name, bool flip)
: base(name)
{
myFlip = flip;
}

public override IResource create()
{
Texture t = new Texture(filename, myFlip);
if (t.isValid == false)
{
return null;
}
return t;
}
}

[/code]
2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0