Reader small image

You're reading from  SFML Game Development

Product typeBook
Published inJun 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781849696845
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
 Artur Moreira
Artur Moreira
author image
Artur Moreira

Artur Moreira is a game development enthusiast who ultimately aims to start a new game development company in his home country. He has been programming games and game-related software for over 4 years. Most of the effort in that time was put in creating an open source game-making library with lots of flexibility and portability. The library is called Nephilim and is known for supporting all major desktop and mobile operating systems, making game development fully crossplatform and fast. Alongside this big project, he keeps making his own prototypes and games for educational and commercial purposes. Aside from the programming, he also puts some focus in creative areas such as 3D modeling, digital painting, and music composing.
Read more about Artur Moreira

 Henrik Vogelius Hansson
Henrik Vogelius Hansson
author image
Henrik Vogelius Hansson

Henrik Vogelius Hansson has always been in love with both games and programming. He started his education fairly early and continued on into the indie scene with Defrost Games and their game Project Temporality. The next company that hired him was Paradox Development Studio where he got to work on titles such as Crusader Kings 2. Beside the game companies, Henrik has also been very active in the SFML community and has even provided a binding for Ruby called rbSFML.
Read more about Henrik Vogelius Hansson

Jan Haller
Jan Haller
Henrik Valter Vogelius
Henrik Valter Vogelius
View More author details
Right arrow

Chapter 2. Keeping Track of Your Textures – Resource Management

In the previous chapter, you have learned how to load a texture, and display a sprite that uses the texture. During the process of game development, you encounter such situations again and again: you need to load data from the hard disk, be it images, fonts, or sounds. This chapter intends to give you a broader understanding of the following points:

  • What is the motivation behind external resources

  • Which classes for resource handling and manipulation does Simple and Fast Multimedia Library (SFML) provide

  • What might a typical use case in a game look like

  • How do we cope with the constantly recurring need to manage resources in a simple way

Defining resources


In game development, the term resource denotes an external component, which the application loads during runtime. Another often-used term for a resource is asset.

Mostly, resources are heavyweight multimedia items, such as images, music themes, or fonts. "Heavyweight" refers to the fact that those objects occupy a lot of memory, and that operations on them, especially copying, perform slowly. This affects the way we use them in our application, as we try to restrict slow operations on them to a minimum.

Non-multimedia items such as scripts that describe the in-game world, menu content, or artificial intelligence are also considered resources. Configuration files containing user settings such as the screen resolution and the music volume are good examples of resources as well. However, when we mention resources in the book, we mostly refer to multimedia resources.

Resources are usually loaded from a file on the hard disk. Although being the most common approach, it is not...

Resources in SFML


SFML offers classes to deal with a wide variety of resources. Often, the resource classes are not directly used to output multimedia on the periphery. Instead, there is an intermediate front-end class, which refers to the resource. In contrast to the resource class which holds all the data, the front-end class is lightweight and can be copied without severe performance impacts.

All resource classes contain member functions to load from different places. Depending on the exact resource type, there may be slight deviations. A typical method to load a resource from a file has the following signature:

bool loadFromFile(const std::string& filename);

The function parameter contains the path to the file, where the resource is stored, and the return value is a bool, which is true if loading was successful, and false if it failed. It is important to check return values in order to react to possible errors, such as invalid file paths.

SFML resources also provide methods to load resources...

A typical use case


Now we have seen what kinds of different resources there are, but we do not know yet how to apply this knowledge to our game. While the approach you have seen in Chapter 1, Making a Game Tick, may work for simple examples, it does not scale well to a bigger project. As our game grows, we have to reflect about how the resources are going to be used. This is explained in the next sections.

Graphics

In our game, a crucial part will be the visual representation of the world and different objects in it. We need to think about how we get from an image on the hard disk to its visualization on the screen.

  • Game entities such as the player's airplane, enemies, or the landscape are represented with sprites and possibly texts. They do not own the heavy textures and fonts; instead they use the front-end classes to refer to them.

  • As a consequence, the resources (textures and fonts) need to be accessible by the entities. We must make sure that the resource objects stay alive as long as any...

An automated approach


Our goal is to encapsulate the just mentioned functionality into a class that relieves us from managing resources again and again. For resource management, the C++ idiom Resource Acquisition Is Initialization (RAII) comes in handy.

Note

RAII describes the principle that resources are acquired in a class' constructor and released in its destructor. Since both constructor and destructor are invoked automatically when the object is created or goes out of scope, there is no need to track resources manually. RAII is mostly used for automatic memory management (as in smart pointers), but it can be applied to any kind of resources. A great advantage of RAII over manual allocation and deallocation (such as new/delete pairs) is that deallocation is guaranteed to take place, even when there are multiple return statements or exceptions in a function. To achieve the same safety with manual memory management, every possible path would have to be protected with a delete operator. As...

Error handling


The basic steps are done, the main functionality is implemented. However, there may be errors which we have to recognize and handle meaningfully. The first error can occur during the loading of the texture. For example, the specified file might not exist, or the file might have an invalid image format, or be too big for the video memory of the graphics card. To handle such errors, the method sf::Texture::loadFromFile() returns a Boolean value that is true in case of success, and false in case of failure.

There are several strategies to react to resource loading errors. In our case, we have to consider that the texture is later needed by sprites that are rendered on the screen—if such a sprite requests the texture, we must give something back. One possibility would be to provide a default texture (for example, plain white), so the sprites are just drawn as a white rectangle. However, we do not want the player of our game to fiddle around with rectangles; he should either have...

Generalizing the approach


We have implemented everything we need for textures, but we would like to handle other resources such as fonts and sound buffers too. As the implementation looks extremely similar for them, it would be a bad idea to write new classes FontHolder and SoundBufferHolder with exactly the same functionality. Instead, we write a class template, which we instantiate for different resource classes.

We call our template ResourceHolder and equip it with two template parameters:

  • Resource: The type of resource, for example, sf::Texture. We design the class template to work the SFML classes, but if you have your own resource class which conforms to the required interface (providing loadFromFile() methods), nothing keeps you from using it together with ResourceHolder.

  • Identifier: The ID type for resource access, for example, Textures::ID. This will usually be an enum, but the type is not restricted to enumerations. Any type that supports an operator< can be used as identifier...

Summary


In this chapter, we have learned the important points about resource management. By now, we know the ideas behind resources and the facilities SFML provides to work with them. We have taken a look at a possible way resources are used in a bigger project, and implemented a generic resource holder that helps us with passing resources to different parts of the application. We also investigated possible error sources as well as techniques to handle them appropriately.

In the next chapter, we are going to develop the game world with a variety of objects in it. Most of these objects require different resources, which is a good opportunity to show our resource holder in a real-world example.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
SFML Game Development
Published in: Jun 2013Publisher: PacktISBN-13: 9781849696845
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Artur Moreira

Artur Moreira is a game development enthusiast who ultimately aims to start a new game development company in his home country. He has been programming games and game-related software for over 4 years. Most of the effort in that time was put in creating an open source game-making library with lots of flexibility and portability. The library is called Nephilim and is known for supporting all major desktop and mobile operating systems, making game development fully crossplatform and fast. Alongside this big project, he keeps making his own prototypes and games for educational and commercial purposes. Aside from the programming, he also puts some focus in creative areas such as 3D modeling, digital painting, and music composing.
Read more about Artur Moreira

author image
Henrik Vogelius Hansson

Henrik Vogelius Hansson has always been in love with both games and programming. He started his education fairly early and continued on into the indie scene with Defrost Games and their game Project Temporality. The next company that hired him was Paradox Development Studio where he got to work on titles such as Crusader Kings 2. Beside the game companies, Henrik has also been very active in the SFML community and has even provided a binding for Ruby called rbSFML.
Read more about Henrik Vogelius Hansson