Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Mastering SFML Game Development
Mastering SFML Game Development

Mastering SFML Game Development: Inject new life and light into your old SFML projects by advancing to the next level.

eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Mastering SFML Game Development

Introduction

What is the heart of any given piece of software? The answer to this question becomes apparent gradually while building a full-scale project, which can be a daunting task to undertake, especially when starting from scratch. It’s the design and capability of the back-end that either drives a game forward with full force by utilizing its power, or crashes it into obscurity through unrealized potential. Here, we’re going to be talking about that very foundation that keeps any given project up and standing.

In this chapter, we're going to be covering the following topics:

  • Utility functions and filesystem specifics for Windows and Linux operating systems
  • The basics of the entity component system pattern
  • Window, event, and resource management techniques
  • Creating and maintaining application states
  • Graphical user interface basics
  • Essentials for the 2D RPG game project

There's a lot to cover, so let's not waste any time!

Pacing and source code examples

All of the systems we're going to be talking about here could have entire volumes dedicated to them. Since time, as well as paper, is limited, we're only going to be briefly reviewing their very basics, which is just enough to feel comfortable with the rest of the information presented here.

Note

Keep in mind that, although we won't be going into too much detail in this particular chapter, the code that accompanies this book is a great resource to look through and experiment with for more detail and familiarity. It's greatly recommended to review it while reading this chapter in order to get a full grasp of it.

Common utility functions

Let's start by taking a look at a common function, which is going to be used to determine the full absolute path to the directory our executable is in. Unfortunately, there is no unified way of doing this across all platforms, so we're going to have to implement a version of this utility function for each one, starting with Windows:

#ifdef RUNNING_WINDOWS 
#define WIN32_LEAN_AND_MEAN 
#include <windows.h> 
#include <Shlwapi.h> 

First, we check if the RUNNING_WINDOWS macro is defined. This is the basic technique that can be used to actually let the rest of the code base know which OS it's running on. Next, another definition is made, specifically for the Windows header files we're including. It greatly reduces the number of other headers that get included in the process.

With all of the necessary headers for the Windows OS included, let us take a look at how the actual function can be implemented:

inline std::string GetWorkingDirectory() 
{ 
   HMODULE hModule = GetModuleHandle(nullptr); 
   if (!hModule) { return ""; } 
   char path[256]; 
   GetModuleFileName(hModule,path,sizeof(path)); 
   PathRemoveFileSpec(path); 
   strcat_s(path,""); 
   return std::string(path); 
} 

First, we obtain the handle to the process that was created by our executable file. After the temporary path buffer is constructed and filled with the path string, the name, and extension of our executable is removed. We top it off by adding a trailing slash to the end of the path and returning it as a std::string.

It will also come in handy to have a way of obtaining a list of files inside a specified directory:

inline std::vector<std::string> GetFileList( 
   const std::string& l_directory, 
   const std::string& l_search = "*.*") 
{ 
   std::vector<std::string> files; 
   if(l_search.empty()) { return files; } 
   std::string path = l_directory + l_search; 
   WIN32_FIND_DATA data; 
   HANDLE found = FindFirstFile(path.c_str(), &data); 
   if (found == INVALID_HANDLE_VALUE) { return files; } 
   do{ 
       if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
       { 
          files.emplace_back(data.cFileName); 
       } 
     }while (FindNextFile(found, &data)); 
   FindClose(found); 
   return files; 
} 

Just like the directory function, this is specific to the Windows OS. It returns a vector of strings that represent file names and extensions. Once one is constructed, a path string is cobbled together. The l_search argument is provided with a default value, in case one is not specified. All files are listed by default.

After creating a structure that will hold our search data, we pass it to another Windows specific function that will find the very first file inside a directory. The rest of the work is done inside a do-while loop, which checks if the located item isn't in fact a directory. The appropriate items are then pushed into a vector, which gets returned later on.

The Linux version

As mentioned previously, both of the preceding functions are only functional on Windows. In order to add support for systems running Linux-based OSes, we're going to need to implement them differently. Let's start by including proper header files:

#elif defined RUNNING_LINUX 
#include <unistd.h> 
#include <dirent.h> 

As luck would have it, Linux does offer a single-call solution to finding exactly where our executable is located:

inline std::string GetWorkingDirectory() 
{ 
   char cwd[1024]; 
   if(!getcwd(cwd, sizeof(cwd))){ return ""; } 
   return std::string(cwd) + std::string("/"); 
} 

Note that we're still adding a trailing slash to the end.

Obtaining a file list of a specific directory is slightly more complicated this time around:

inline std::vector<std::string> GetFileList( 
   const std::string& l_directory, 
   const std::string& l_search = "*.*") 
{ 
   std::vector<std::string> files; 
    
   DIR *dpdf; 
   dpdf = opendir(l_directory.c_str()); 
   if (!dpdf) { return files; } 
   if(l_search.empty()) { return files; } 
   std::string search = l_search; 
   if (search[0] == '*') { search.erase(search.begin()); } 
   if (search[search.length() - 1] == '*') { search.pop_back(); } 
  struct dirent *epdf; 
  while (epdf = readdir(dpdf)) { 
    std::string name = epdf->d_name; 
    if (epdf->d_type == DT_DIR) { continue; } 
    if (l_search != "*.*") { 
      if (name.length() < search.length()) { continue; } 
      if (search[0] == '.') { 
        if (name.compare(name.length() - search.length(), 
          search.length(), search) != 0) 
        { continue; } 
      } else if (name.find(search) == std::string::npos) { 
        continue; 
      } 
    } 
    files.emplace_back(name); 
  } 
  closedir(dpdf); 
  return files; 
} 

We start off in the same fashion as before, by creating a vector of strings. A pointer to the directory stream is then obtained through the opendir() function. Provided it isn't NULL, we begin modifying the search string. Unlike the fancier Windows alternative, we can't just pass a search string into a function and let the OS do all of the matching. In this case, it falls more under the category of matching a specific search string inside a filename that gets returned, so star symbols that mean anything need to be trimmed out.

Next, we utilize the readdir() function inside a while loop that's going to return a pointer to directory entry structures one by one. We also want to exclude any directories from the file list, so the entry's type is checked for not being equal to DT_DIR.

Finally, the string matching begins. Presuming we're not just looking for any file with any extension (represented by "*.*"), the entry's name will be compared to the search string by length first. If the length of the string we're searching is longer than the filename itself, it's safe to assume we don't have a match. Otherwise, the search string is analyzed again to determine whether the filename is important for a positive match. Its first character being a period would denote that it isn't, so the file name's ending segment of the same length as the search string is compared to the search string itself. If, however, the name is important, we simply search the filename for the search string.

Once the procedure is complete, the directory is closed and the vector of strings representing files is returned.

Other miscellaneous helper functions

Sometimes, as text files are being read, it's nice to grab a string that includes spaces while still maintaining a whitespace delimiter. In cases like that, we can use quotes along with this special function that helps us read the entire quoted segment from a whitespace delimited file:

inline void ReadQuotedString(std::stringstream& l_stream, 
  std::string& l_string) 
{ 
  l_stream >> l_string; 
  if (l_string.at(0) == '"'){ 
    while (l_string.at(l_string.length() - 1) != '"' || 
      !l_stream.eof()) 
    { 
      std::string str; 
      l_stream >> str; 
      l_string.append(" " + str); 
    } 
  } 
  l_string.erase(std::remove( 
    l_string.begin(), l_string.end(), '"'), l_string.end()); 
} 

The first segment of the stream is fed into the argument string. If it does indeed start with a double quote, a while loop is initiated to append to said string until it ends with another double quote, or until the stream reaches the end. Lastly, all double quotes from the string are erased, giving us the final result.

Interpolation is another useful tool in a programmer's belt. Imagine having two different values of something at two different points in time, and then wanting to predict what the value would be somewhere in between those two time frames. This simple calculation makes that possible:

template<class T> 
inline T Interpolate(float tBegin, float tEnd, 
   const T& begin_val, const T& end_val, float tX) 
{ 
   return static_cast<T>(( 
      ((end_val - begin_val) / (tEnd - tBegin)) * 
      (tX - tBegin)) + begin_val); 
} 

Next, let's take a look at a few functions that can help us center instances of sf::Text better:

inline float GetSFMLTextMaxHeight(const sf::Text& l_text) { 
  auto charSize = l_text.getCharacterSize(); 
  auto font = l_text.getFont(); 
  auto string = l_text.getString().toAnsiString(); 
  bool bold = (l_text.getStyle() & sf::Text::Bold); 
  float max = 0.f; 
  for (size_t i = 0; i < string.length(); ++i) { 
    sf::Uint32 character = string[i]; 
    auto glyph = font->getGlyph(character, charSize, bold); 
    auto height = glyph.bounds.height; 
    if (height <= max) { continue; } 
    max = height; 
  } 
  return max; 
} 
 
inline void CenterSFMLText(sf::Text& l_text) { 
  sf::FloatRect rect = l_text.getLocalBounds(); 
  auto maxHeight = Utils::GetSFMLTextMaxHeight(l_text); 
  l_text.setOrigin( 
    rect.left + (rect.width * 0.5f), 
    rect.top + ((maxHeight >= rect.height ? 
      maxHeight * 0.5f : rect.height * 0.5f))); 
} 

Working with SFML text can be tricky sometimes, especially when centering it is of paramount importance. Some characters, depending on the font and other different attributes, can actually exceed the height of the bounding box that surrounds the sf::Text instance. To combat that, the first function iterates through every single character of a specific text instance and fetches the font glyph used to represent it. Its height is then checked and kept track of, so that the maximum height of the entire text can be determined and returned.

The second function can be used for setting the absolute center of a sf::Text instance as its origin, in order to achieve perfect results. After its local bounding box is obtained and the maximum height is calculated, this information is used to move the original point of our text to its center.

Generating random numbers

Most games out there rely on some level of randomness. While it may be tempting to simply use the classical approach of rand(), it can only take you so far. Generating random negative or floating point numbers isn't straightforward, to say the least, plus it has a very lousy range. Luckily, newer versions of C++ provide the answer in the form of uniform distributions and random number engines:

#include <random> 
#include <SFML/System/Mutex.hpp> 
#include <SFML/System/Lock.hpp> 
 
class RandomGenerator { 
public: 
  RandomGenerator() : m_engine(m_device()){} 
  ... 
  float operator()(float l_min, float l_max) { 
    return Generate(l_min, l_max); 
  } 
  int operator()(int l_min, int l_max) { 
    return Generate(l_min, l_max); 
  } 
private: 
  std::random_device m_device; 
  std::mt19937 m_engine; 
  std::uniform_int_distribution<int> m_intDistribution; 
  std::uniform_real_distribution<float> m_floatDistribution; 
  sf::Mutex m_mutex; 
}; 

First, note the include statements. The random library provides us with everything we need as far as number generation goes. On top of that, we're also going to be using SFML's mutexes and locks, in order to prevent a huge mess in case our code is being accessed by several separate threads.

The std::random_device class is a random number generator that is used to seed the engine, which will be used for further generations. The engine itself is based on the Marsenne Twister algorithm, and produces high-quality random unsigned integers that can later be filtered through a uniform distribution object in order to obtain a number that falls within a specific range. Ideally, since it is quite expensive to keep constructing and destroying these objects, we're going to want to keep a single copy of this class around. For this very reason, we have integer and float distributions together in the same class.

For convenience, the parenthesis operators are overloaded to take in ranges of numbers of both integer and floating point types. They invoke the Generate method, which is also overloaded to handle both data types:

int Generate(int l_min, int l_max) { 
  sf::Lock lock(m_mutex); 
  if (l_min > l_max) { std::swap(l_min, l_max); } 
  if (l_min != m_intDistribution.min() || 
    l_max != m_intDistribution.max()) 
  { 
    m_intDistribution = 
      std::uniform_int_distribution<int>(l_min, l_max); 
  } 
  return m_intDistribution(m_engine); 
} 
 
float Generate(float l_min, float l_max) { 
  sf::Lock lock(m_mutex); 
  if (l_min > l_max) { std::swap(l_min, l_max); } 
  if (l_min != m_floatDistribution.min() || 
    l_max != m_floatDistribution.max()) 
  { 
    m_floatDistribution = 
      std::uniform_real_distribution<float>(l_min, l_max); 
  } 
  return m_floatDistribution(m_engine); 
} 

Before generation can begin, we must establish a lock in order to be thread-safe. Because the order of l_min and l_max values matters, we must check if the provided values aren't in reverse, and swap them if they are. Also, the uniform distribution object has to be reconstructed if a different range needs to be used, so a check for that is in place as well. Finally, after all of that trouble, we're ready to return the random number by utilizing the parenthesis operator of a distribution, to which the engine instance is fed in.

Service locator pattern

Often, one or more of our classes will need access to another part of our code base. Usually, it's not a major issue. All you would have to do is pass a pointer or two around, or maybe store them once as data members of the class in need. However, as the amount of code grows, relationships between classes get more and more complex. Dependencies can increase to a point, where a specific class will have more arguments/setters than actual methods. For convenience's sake, sometimes it's better to pass around a single pointer/reference instead of ten. This is where the service locator pattern comes in:

class Window; 
class EventManager; 
class TextureManager; 
class FontManager; 
... 
struct SharedContext{ 
  SharedContext(): 
    m_wind(nullptr), 
    m_eventManager(nullptr), 
    m_textureManager(nullptr), 
    m_fontManager(nullptr), 
    ... 
  {} 
 
  Window* m_wind; 
  EventManager* m_eventManager; 
  TextureManager* m_textureManager; 
  FontManager* m_fontManager; 
  ... 
}; 

As you can see, it's just a struct with multiple pointers to the core classes of our project. All of those classes are forward-declared in order to avoid unnecessary include statements, and thus a bloated compilation process.

Entity component system core

Let's get to the essence of how our game entities are going to be represented. In order to achieve highest maintainability and code compartmentalization, it's best to use composition. The entity component system allows just that. For the sake of keeping this short and sweet, we're not going to be delving too deep into the implementation. This is simply a quick overview for the sake of being familiar with the code that will be used down the line.

The ECS pattern consists of three cornerstones that make it possible: entities, components, and systems. An entity, ideally, is simply an identifier, as basic as an integer. Components are containers of data that have next to no logic inside them. There would be multiple types of components, such as position, movable, drawable, and so on, that don't really mean much by themselves, but when composed, will form complex entities. Such composition would make it incredibly easy to save the state of any entity at any given time.

There are many ways to implement components. One of them is simply having a base component class, and inheriting from it:

class C_Base{ 
public: 
  C_Base(const Component& l_type): m_type(l_type){} 
  virtual ~C_Base(){} 
 
  Component GetType() const { return m_type; } 
 
  friend std::stringstream& operator >>( 
    std::stringstream& l_stream, C_Base& b) 
    { 
      b.ReadIn(l_stream); 
      return l_stream; 
    } 
 
  virtual void ReadIn(std::stringstream& l_stream) = 0; 
protected: 
  Component m_type; 
}; 

The Component type is simply an enum class that lists different types of components we can have in a project. In addition to that, this base class also offers a means of filling in component data from a string stream, in order to load them more easily when files are being read.

In order to properly manage sets of components that belong to entities, we would need some sort of manager class:

class EntityManager{ 
public: 
  EntityManager(SystemManager* l_sysMgr, 
    TextureManager* l_textureMgr); 
  ~EntityManager(); 
 
  int AddEntity(const Bitmask& l_mask); 
  int AddEntity(const std::string& l_entityFile); 
  bool RemoveEntity(const EntityId& l_id); 
 
  bool AddComponent(const EntityId& l_entity, 
    const Component& l_component); 
 
  template<class T> 
  void AddComponentType(const Component& l_id) { ... } 
 
  template<class T> 
  T* GetComponent(const EntityId& l_entity, 
    const Component& l_component){ ... } 
 
  bool RemoveComponent(const EntityId& l_entity, 
    const Component& l_component); 
  bool HasComponent(const EntityId& l_entity, 
    const Component& l_component) const; 
  void Purge(); 
private: 
  ... 
}; 

As you can see, this is a fairly basic approach at managing these sets of data we call entities. The EntityId data type is simply a type definition for an unsigned integer. Creation of components happens by utilizing a factory pattern, lambdas and templates. This class is also responsible for loading entities from files that may look a little like this:

Name Player 
Attributes 255 
|Component|ID|Individual attributes| 
Component 0 0 0 1 
Component 1 Player 
Component 2 0 
Component 3 128.0 1024.0 1024.0 1 
Component 4 
Component 5 20.0 20.0 0.0 0.0 2 
Component 6 footstep:1,4 
Component 7 

The Attributes field is a bit mask, the value of which is used to figure out which component types an entity has. The actual component data is stored in this file as well, and later loaded through the ReadIn method of our component base class.

The last piece of the puzzle in ECS design is systems. This is where all of the logic happens. Just like components, there can be many types of systems responsible for collisions, rendering, movement, and so on. Each system must inherit from the system's base class and implement all of the pure virtual methods:

class S_Base : public Observer{ 
public: 
  S_Base(const System& l_id, SystemManager* l_systemMgr); 
  virtual ~S_Base(); 
 
  bool AddEntity(const EntityId& l_entity); 
  bool HasEntity(const EntityId& l_entity) const; 
  bool RemoveEntity(const EntityId& l_entity); 
 
  System GetId() const; 
 
  bool FitsRequirements(const Bitmask& l_bits) const; 
  void Purge(); 
 
  virtual void Update(float l_dT) = 0; 
  virtual void HandleEvent(const EntityId& l_entity, 
    const EntityEvent& l_event) = 0; 
protected: 
  ... 
}; 

Systems have signatures of components they use, as well as a list of entities that meet the requirements of said signatures. When an entity is being modified by the addition or removal of a component, every system runs a check on it in order to add it to or remove it from itself. Note the inheritance from the Observer class. This is another pattern that aids in communication between entities and systems.

An Observer class by itself is simply an interface with one purely virtual method that must be implemented by all derivatives:

class Observer{ 
public: 
  virtual ~Observer(){} 
  virtual void Notify(const Message& l_message) = 0; 
}; 

It utilizes messages that get sent to all observers of a specific target. How the derivative of this class reacts to the message is completely dependent on what it is.

Systems, which come in all shapes and sizes, need to be managed just as entities do. For that, we have another manager class:

class SystemManager{ 
public: 
  ... 
  template<class T> 
  void AddSystem(const System& l_system) { ... } 
 
  template<class T> 
  T* GetSystem(const System& l_system){ ... } 
  void AddEvent(const EntityId& l_entity, const EventID& l_event); 
 
  void Update(float l_dT); 
  void HandleEvents(); 
  void Draw(Window* l_wind, unsigned int l_elevation); 
 
  void EntityModified(const EntityId& l_entity, 
    const Bitmask& l_bits); 
  void RemoveEntity(const EntityId& l_entity); 
   
  void PurgeEntities(); 
  void PurgeSystems(); 
private: 
  ... 
  MessageHandler m_messages; 
}; 

This too utilizes the factory pattern, in that types of different classes are registered by using templates and lambdas, so that they can be constructed later, simply by using a System data type, which is an enum class. Starting to see the pattern?

The system manager owns a data member of type MessageHandler. This is another part of the observer pattern. Let us take a look at what it does:

class MessageHandler{ 
public: 
  bool Subscribe(const EntityMessage& l_type, 
    Observer* l_observer){ ... } 
  bool Unsubscribe(const EntityMessage& l_type, 
    Observer* l_observer){ ... } 
  void Dispatch(const Message& l_msg){ ... } 
private: 
  Subscribtions m_communicators; 
}; 

Message handlers are simply collections of Communicator objects, as shown here:

using Subscribtions = 
  std::unordered_map<EntityMessage,Communicator>; 

Each possible type of EntityMessage, which is just another enum class, is tied to a communicator that is responsible for sending out a message to all of its observers. Observers can subscribe to or unsubscribe from a specific message type. If they are subscribed to said type, they will receive the message when the Dispatch method is invoked.

The Communicator class itself is fairly simple:

class Communicator{ 
public: 
  virtual ~Communicator(){ m_observers.clear(); } 
  bool AddObserver(Observer* l_observer){ ... } 
  bool RemoveObserver(Observer* l_observer){ ... } 
  bool HasObserver(const Observer* l_observer) const { ... } 
  void Broadcast(const Message& l_msg){ ... } 
private: 
  ObserverContainer m_observers; 
}; 

As you can gather, it supports the addition and removal of observers, and offers a way to broadcast a message to all of them. The actual container of observers is simply a vector of pointers:

// Not memory-owning pointers. 
using ObserverContainer = std::vector<Observer*>; 

Resource management

Another vital part of larger projects is an efficient way of managing resources. Since we're going to have several types of resources, such as textures, fonts, and sounds, it would make sense to have separate managers for all of them. It's time for a base class:

template<typename Derived, typename T> 
class ResourceManager{ 
public: 
  ResourceManager(const std::string& l_pathsFile){ 
    LoadPaths(l_pathsFile); 
  } 
  virtual ~ResourceManager(){ ... } 
  T* GetResource(const std::string& l_id){ ... } 
  std::string GetPath(const std::string& l_id){ ... } 
  bool RequireResource(const std::string& l_id){ ... } 
  bool ReleaseResource(const std::string& l_id){ ... } 
  void PurgeResources(){ ... } 
protected: 
  bool Load(T* l_resource, const std::string& l_path) { 
    return static_cast<Derived*>(this)->Load(l_resource, l_path); 
  } 
private: 
  ... 
}; 

The idea behind this particular resource management system is certain segments of code requiring and later releasing a certain resource identifier. The first time a resource is required it will be loaded into memory and kept there. Every time it's required after that will simply increment an integer that gets stored with it. The integer represents how many instances of code rely on this resource being loaded. Once they are done using the resource, it begins being released, which brings the counter down each time. When it reaches zero, the resource is removed from memory.

It's fair to point out that our resource manager base class utilizes the Curiously Recurring Template Pattern for setting up the resource instances after they're created. As manager classes don't really need to be stored together in the same container anywhere, static polymorphism makes a lot more sense than using virtual methods. Since textures, fonts, and sounds may be loaded in different ways, each subsequent manager must implement their own version of the Load method, like so:

class TextureManager : public ResourceManager<TextureManager, 
  sf::Texture> 
{ 
public: 
  TextureManager() : ResourceManager("textures.cfg"){} 
 
  bool Load(sf::Texture* l_resource, const std::string& l_path){ 
    return l_resource->loadFromFile( 
      Utils::GetWorkingDirectory() + l_path); 
  } 
}; 

Each single manager also has its own file, listing the relationships between names of resources and their paths. For textures, it can look something like this:

Intro media/Textures/intro.png 
PlayerSprite media/Textures/PlayerSheet.png 
... 

It simply avoids the need to pass around paths and filenames, by instead relating a name to each resource.

Windows system

There's a lot that goes on behind the scenes when it comes to dealing with open windows. Everything from window dimensions and titles to keeping track of and dealing with special events is centralized within a designated window class:

class Window{
public:
  Window(const std::string& l_title = "Window",
    const sf::Vector2u& l_size = {640,480},
    bool l_useShaders = true);
  ~Window();

  void BeginDraw();
  void EndDraw();

  void Update();

  bool IsDone() const;
  bool IsFullscreen() const;
  bool IsFocused() const;

  void ToggleFullscreen(EventDetails* l_details);
  void Close(EventDetails* l_details = nullptr);

  sf::RenderWindow* GetRenderWindow();
  Renderer* GetRenderer();
  EventManager* GetEventManager();
  sf::Vector2u GetWindowSize();
  sf::FloatRect GetViewSpace();
private:
  ...
};

Note the two highlighted methods. They will be used as call-backs in the event manager we'll discuss in the near future. Also note the return method for an object type Renderer. It’s a utility class that simply invokes the .draw call on a RenderWindow, thus localizing it and making it much easier to use shaders. More information on that will be revealed in Chapter 6Adding Some Finishing Touches – Using Shaders.

Application states

Another important aspect of a more complex application is keeping track of and managing its states. Whether the player is in the thick of the game, or simply browsing through the main menu, we want it to be handled seamlessly, and more importantly, be self-contained. We can start this by first defining different types of states we'll be dealing with:

enum class StateType { Intro = 1, MainMenu, Game, Loading }; 

For seamless integration, we want each state to behave in a predictable manner. This means that a state has to adhere to an interface we provide:

class BaseState{ 
friend class StateManager; 
public: 
  BaseState(StateManager* l_stateManager)  
    :m_stateMgr(l_stateManager), m_transparent(false), 
    m_transcendent(false){} 
  virtual ~BaseState(){} 
 
  virtual void OnCreate() = 0; 
  virtual void OnDestroy() = 0; 
 
  virtual void Activate() = 0; 
  virtual void Deactivate() = 0; 
 
  virtual void Update(const sf::Time& l_time) = 0; 
  virtual void Draw() = 0; 
  ... 
  sf::View& GetView(){ return m_view; } 
  StateManager* GetStateManager(){ return m_stateMgr; } 
protected: 
  StateManager* m_stateMgr; 
  bool m_transparent; 
  bool m_transcendent; 
  sf::View m_view; 
}; 

Every state in the game will have its own view that it can alter. In addition to that, it is given the hooks to implement logic for various different scenarios, such as the state's creation, destruction, activation, deactivation, updating, and rendering. Lastly, it enables the possibility of being blended with other states during updating and rendering, by providing the m_transparent and m_transcendent flags.

Managing these states is pretty straightforward:

class StateManager{ 
public: 
  StateManager(SharedContext* l_shared); 
  ~StateManager(); 
  void Update(const sf::Time& l_time); 
  void Draw(); 
  void ProcessRequests(); 
  SharedContext* GetContext(); 
  bool HasState(const StateType& l_type) const; 
  StateType GetNextToLast() const; 
  void SwitchTo(const StateType& l_type); 
  void Remove(const StateType& l_type); 
  template<class T> 
  T* GetState(const StateType& l_type){ ... } 
  template<class T> 
  void RegisterState(const StateType& l_type) { ... } 
  void AddDependent(StateDependent* l_dependent); 
  void RemoveDependent(StateDependent* l_dependent); 
private: 
  ... 
  State_Loading* m_loading; 
  StateDependents m_dependents; 
}; 

The StateManager class is one of the few classes in the project that utilizes the shared context, since the states themselves may need access to any part of the code base. It also uses the factory pattern to dynamically create any state that is bound to a state type during runtime.

In order to keep things simple, we're going to be treating the loading state as a special case, and only allow one instance of it to be alive at all times. Loading might happen during the transition of any state, so it only makes sense.

One final thing that's worth noting about the state manager is it's keeping a list of state dependants. It's simply an STL container of classes that inherit from this interface:

class StateDependent { 
public: 
  StateDependent() : m_currentState((StateType)0){} 
  virtual ~StateDependent(){} 
  virtual void CreateState(const StateType& l_state){} 
  virtual void ChangeState(const StateType& l_state) = 0; 
  virtual void RemoveState(const StateType& l_state) = 0; 
protected: 
  void SetState(const StateType& l_state){m_currentState=l_state;} 
  StateType m_currentState; 
}; 

Because classes that deal with things such as sounds, GUI elements, or entity management need to support different states, they must also define what happens inside them as a state is created, changed, or removed, in order to properly allocate/de-allocate resources, stop updating data that is not in the same state, and so on.

Loading state

So, how exactly are we going to implement this loading state? Well, for flexibility and easy progress tracking by means of rendering fancy loading bars, threads are going to prove invaluable. Data that needs to be loaded into memory can be loaded in a separate thread, while the loading state itself continues to get updated and rendered in order to show us that things are indeed happening. Just knowing that the application did not hang on us should create a warm and fuzzy feeling.

First, let us implement the very basics of this system by providing an interface any threaded worker can use:

class Worker { 
public: 
  Worker() : m_thread(&Worker::Work, this), m_done(false), 
    m_started(false) {} 
  void Begin() { 
    if(m_done || m_started) { return; } 
    m_started = true; 
    m_thread.launch(); 
  } 
  bool IsDone() const { return m_done; } 
  bool HasStarted() const { return m_started; } 
protected: 
  void Done() { m_done = true; } 
  virtual void Work() = 0; 
  sf::Thread m_thread; 
  bool m_done; 
  bool m_started; 
}; 

It has its own thread, which is bound to the pure virtual method called Work. The thread is launched whenever the Begin() method is invoked. In order to protect the data from being accessed from multiple threads at once, a sf::Mutex class is used by creating a lock during sensitive calls. Everything else within this very basic class is simply there to provide information to the outside world about the worker’s state.

File loader

With threads out of the way, we can focus on actually loading some files now. This method is going to focus on working with text files. However, using binary formats should work in pretty much the exact same way, minus all the text processing.

Let's take a look at the base class for any file loading class we can think of:

using LoaderPaths = std::vector<std::pair<std::string, size_t>>; 
 
class FileLoader : public Worker { 
public: 
  FileLoader(); 
  void AddFile(const std::string& l_file);
  virtual void SaveToFile(const std::string& l_file);
  
  size_t GetTotalLines() const; 
  size_t GetCurrentLine() const; 
protected: 
  virtual bool ProcessLine(std::stringstream& l_stream) = 0; 
  virtual void ResetForNextFile(); 
  void Work(); 
  void CountFileLines(); 
 
  LoaderPaths m_files; 
  size_t m_totalLines; 
  size_t m_currentLine; 
}; 

It's a distinct possibility that two or more files may need to be loaded at some point. The FileLoader class keeps track of all of the paths that get added to it, along with a number that represents the number of lines within that file. This is useful for determining the amount of progress that has been made while loading. In addition to the line count for each individual file, a total line count is also kept track of.

This class provides a single purely virtual method, called ProcessLine. It will be the way derivatives can define exactly how the file is loaded and processed.

First, let us get the basic stuff out of the way:

FileLoader::FileLoader() : m_totalLines(0), m_currentLine(0) {}
void FileLoader::AddFile(const std::string& l_file) {
  m_files.emplace_back(l_file, 0);
}
size_t FileLoader::GetTotalLines()const {
  sf::Lock lock(m_mutex);
  return m_totalLines;
}
size_t FileLoader::GetCurrentLine()const {
  sf::Lock lock(m_mutex);
  return m_currentLine;
}
void FileLoader::SaveToFile(const std::string& l_file) {}
void FileLoader::ResetForNextFile(){}

The ResetForNextFile() virtual method is optional to implement, but can be used in order to clear the state of some internal data that needs to exist while a file is being loaded. Since file loaders that implement this class will only have the ability to process one line at a time inside a single method, any temporary data that would normally be stored as a local variable within that method would instead need to go somewhere else. This is why we must make sure that there is actually a way to know when we're done with one file and start loading another, as well as to perform some sort of action, if necessary.

Note

Note the mutex locks in the two getter methods above. They’re there to make sure those variables aren’t written to and read from at the same time.

Now, let's get into the code that is going to be executed in a different thread:

void FileLoader::Work() { 
  CountFileLines(); 
  if (!m_totalLines) { Done(); return; } 
  for (auto& path : m_files) { 
    ResetForNextFile(); 
    std::ifstream file(path.first); 
    std::string line; 
    std::string name; 
    auto linesLeft = path.second; 
    while (std::getline(file, line)) { 
      { 
        sf::Lock lock(m_mutex); 
        ++m_currentLine; 
        --linesLeft; 
      } 
      if (line[0] == '|') { continue; } 
      std::stringstream keystream(line); 
      if (!ProcessLine(keystream)) { 
        std::cout << 
          "File loader terminated due to an internal error." 
          << std::endl; 
        { 
          sf::Lock lock(m_mutex); 
          m_currentLine += linesLeft; 
        } 
        break; 
      } 
    } 
    file.close(); 
  } 
  Done(); 
} 

A private method for counting all the lines in whatever files are about to be loaded is called first. If, for any reason, the total line count is zero, there is no purpose in proceeding, so the Worker::Done() method is invoked just before a return. This little bit of code is really easy to forget, but is extremely important in order for this to work. All it does is set the m_done flag of the Worker base class to true, which lets outside code know that the process is finished. Since there is currently no way to check if an SFML thread is actually finished, this is pretty much the only option.

We begin looping through different files that need to get loaded and invoke the reset method before work begins. Note the lack of checking as we're attempting to open a file. This will be explained when we cover the next method.

As each line of the file is being read, it's important to make sure that all the line count information is updated. A temporary lock for the current thread is established, in order to prevent two threads from accessing the line count as its modified. In addition to that, lines that start with a pipe symbol are excluded, since this is our standard comment pragma.

Finally, a stringstream object is constructed for the current line, and passed into the ProcessLine() method. For extra points, it returns a boolean value that can signal an error and stop the current file from being processed any further. If that happens, the remaining lines within that specific file are added to the total count, and the loop is broken.

The final piece of the puzzle is this chunk of code, responsible for verifying file validity and determining the amount of work ahead of us:

void FileLoader::CountFileLines() {
  m_totalLines = 0;
  m_currentLine = 0;
  for (auto path = m_files.begin(); path != m_files.end();) {
    if (path->first.empty()) { m_files.erase(path); continue; }
    std::ifstream file(path->first);
    if (!file.is_open()) {
      std::cerr << “Failed to load file: “ << path->first
        << std::endl;
      m_files.erase(path);
      continue;
    }
    file.unsetf(std::ios_base::skipws);
    {
      sf::Lock lock(m_mutex);
      path->second = static_cast<size_t>(std::count(
        std::istreambuf_iterator<char>(file),
        std::istreambuf_iterator<char>(), ‘\n’));
      m_totalLines += path->second;
    }
    ++path;
    file.close();
  }
}

After initial zero values for line counts are set up, all added paths are iterated over and checked. We first trim out any paths that are empty. Each path is then attempted to be opened, and erased if that operation fails. Finally, in order to achieve accurate results, the file input stream is ordered to ignore empty lines. After a lock is established, std::count is used to count the amount of lines in a file. That number is then added to the amount of total lines we have, the path iterator is advanced, and the file is properly closed.

Since this method eliminates files that were either non-existent or unable to be opened, there is no reason to check for that again anywhere else.

Implementing the loading state

Everything is now in place in order for us to successfully implement the loading state:

using LoaderContainer = std::vector<FileLoader*>; 
 
class State_Loading : public BaseState { 
public: 
  ... 
  void AddLoader(FileLoader* l_loader); 
  bool HasWork() const; 
  void SetManualContinue(bool l_continue); 
  void Proceed(EventDetails* l_details); 
private: 
  void UpdateText(const std::string& l_text, float l_percentage); 
  float CalculatePercentage(); 
  LoaderContainer m_loaders; 
  sf::Text m_text; 
  sf::RectangleShape m_rect; 
  unsigned short m_percentage; 
  size_t m_originalWork; 
  bool m_manualContinue; 
}; 

The state itself will keep a vector of pointers to different file loader classes, which will have lists of their own files respectively. It also provides a way for these objects to be added. Also, note the Proceed() method. This is another call-back that will be used in the event manager we're about to cover soon.

For the visual portion, we will be using the bare essentials of graphics: a bit of text for the progress percentage, and a rectangle shape that represents a loading bar.

Let's take a look at all of the setup this class will do once it's constructed:

void State_Loading::OnCreate() { 
  auto context = m_stateMgr->GetContext(); 
  context->m_fontManager->RequireResource("Main"); 
  m_text.setFont(*context->m_fontManager->GetResource("Main")); 
  m_text.setCharacterSize(14); 
  m_text.setStyle(sf::Text::Bold); 
 
  sf::Vector2u windowSize = m_stateMgr->GetContext()-> 
    m_wind->GetRenderWindow()->getSize(); 
 
  m_rect.setFillColor(sf::Color(0, 150, 0, 255)); 
  m_rect.setSize(sf::Vector2f(0.f, 32.f)); 
  m_rect.setOrigin(0.f, 16.f); 
  m_rect.setPosition(0.f, windowSize.y / 2.f); 
 
  EventManager* evMgr = m_stateMgr->GetContext()->m_eventManager; 
  evMgr->AddCallback(StateType::Loading, "Key_Space", 
    &State_Loading::Proceed, this); 
} 

First, a font manager is obtained through the shared context. The font with a name "Main" is required and used to set up the text instance. After all of the visual bits are set up, the event manager is used to register a call-back for the loading state. This will be covered soon, but it's quite easy to deduce what's happening by simply looking at the arguments. Whenever the spacebar is pressed, the Proceed method of the State_Loading class is going to be invoked. The actual instance of the class is passed in as the last argument.

Remember that, by design, the resources we require must also be released. A perfect place to do that for the loading state is exactly as it is destroyed:

void State_Loading::OnDestroy() { 
  auto context = m_stateMgr->GetContext(); 
  EventManager* evMgr = context->m_eventManager; 
  evMgr->RemoveCallback(StateType::Loading, "Key_Space"); 
  context->m_fontManager->ReleaseResource("Main"); 
} 

In addition to the font being released, the call-back for the spacebar is also removed.

Next, let us actually write some code that's going to bring the pieces together into a cohesive, functional whole:

void State_Loading::Update(const sf::Time& l_time) 
  if (m_loaders.empty()) {
    if (!m_manualContinue) { Proceed(nullptr); }
    return;
  }
  auto windowSize = m_stateMgr->GetContext()->
    m_wind->GetRenderWindow()->getSize();
  if (m_loaders.back()->IsDone()) {
    m_loaders.back()->OnRemove();
    m_loaders.pop_back();
    if (m_loaders.empty()) {
      m_rect.setSize(sf::Vector2f(
        static_cast<float>(windowSize.x), 16.f));
      UpdateText(".Press space to continue.", 100.f);
      return;
    }
  }
  if (!m_loaders.back()->HasStarted()) {
    m_loaders.back()->Begin();
  }

  auto percentage = CalculatePercentage();
  UpdateText("", percentage);
  m_rect.setSize(sf::Vector2f(
    (windowSize.x / 100) * percentage, 16.f));
}

The first check is used to determine if all of the file loaders have been removed from the vector due to finishing. The m_manualContinue flag is used to let the loading state know if it should wait for the spacebar to be pressed, or if it should just dispel itself automatically. If, however, we still have some loaders in the vector, the top one is checked for having concluded its work. Given that's the case, the loader is popped and the vector is checked again for being empty, which would require us to update the loading text to represent completion.

To keep this process fully automated, we need to make sure that after the top file loader is removed, the next one is started, which is where the following check comes in. Finally, the progress percentage is calculated, and the loading text is updated to represent that value, just before the loading bar's size is adjusted to visually aid us.

Drawing is going to be extremely straightforward for this state:

void State_Loading::Draw() { 
  sf::RenderWindow* wind = m_stateMgr->GetContext()-> 
    m_wind->GetRenderWindow(); 
  wind->draw(m_rect); 
  wind->draw(m_text); 
} 

The render window is first obtained through the shared context, and then used to draw the text and rectangle shape that represent the loading bar together.

The Proceed call-back method is equally straightforward:

void State_Loading::Proceed(EventDetails* l_details){ 
  if (!m_loaders.empty()) { return; } 
  m_stateMgr->SwitchTo(m_stateMgr->GetNextToLast()); 
} 

It has to make a check first, to make sure that we don't switch states before all the work is through. If that's not the case, the state manager is used to switch to a state that was created before the loading commenced.

All of the other loading state logic pretty much consists of single lines of code for each method:

void State_Loading::AddLoader(FileLoader* l_loader) {
 m_loaders.emplace_back(l_loader);
  l_loader->OnAdd();
}
bool State_Loading::HasWork() const { return !m_loaders.empty(); }
void State_Loading::SetManualContinue(bool l_continue) {
  m_manualContinue = l_continue;
}
void State_Loading::Activate(){m_originalWork = m_loaders.size();}

Although this looks fairly simple, the Activate() method holds a fairly important role. Since the loading state is treated as a special case here, one thing has to be kept in mind: it is never going to be removed before the application is closed. This means that every time we want to use it again, some things have to be reset. In this case, it's the m_originalWork data member, that's simply the count of all the loader classes. This number is used to calculate the progress percentage accurately, and the best place to reset it is inside the method, which gets called every time the state is activated again.

Managing application events

Event management is one of the cornerstones that provide us with fluid control experience. Any key presses, window changes, or even custom events created by the GUI system we'll be covering later are going to be processed and handled by this system. In order to effectively unify event information coming from different sources, we first must unify their types by enumerating them correctly:

enum class EventType { 
  KeyDown = sf::Event::KeyPressed, 
  KeyUp = sf::Event::KeyReleased, 
  MButtonDown = sf::Event::MouseButtonPressed, 
  MButtonUp = sf::Event::MouseButtonReleased, 
  MouseWheel = sf::Event::MouseWheelMoved, 
  WindowResized = sf::Event::Resized, 
  GainedFocus = sf::Event::GainedFocus, 
  LostFocus = sf::Event::LostFocus, 
  MouseEntered = sf::Event::MouseEntered, 
  MouseLeft = sf::Event::MouseLeft, 
  Closed = sf::Event::Closed, 
  TextEntered = sf::Event::TextEntered, 
  Keyboard = sf::Event::Count + 1, Mouse, Joystick, 
  GUI_Click, GUI_Release, GUI_Hover, GUI_Leave 
}; 
 
enum class EventInfoType { Normal, GUI }; 

SFML events come first, since they are the only ones following a strict enumeration scheme. They are then followed by the live SFML input types and four GUI events. We also enumerate event information types, which are going to be used inside this structure:

struct EventInfo { 
  EventInfo() : m_type(EventInfoType::Normal), m_code(0) {} 
  EventInfo(int l_event) : m_type(EventInfoType::Normal), 
    m_code(l_event) {} 
  EventInfo(const GUI_Event& l_guiEvent): 
    m_type(EventInfoType::GUI), m_gui(l_guiEvent) {} 
  EventInfo(const EventInfoType& l_type) { 
    if (m_type == EventInfoType::GUI) { DestroyGUIStrings(); } 
    m_type = l_type; 
    if (m_type == EventInfoType::GUI){ CreateGUIStrings("", ""); } 
  } 
 
  EventInfo(const EventInfo& l_rhs) { Move(l_rhs); } 
 
  EventInfo& operator=(const EventInfo& l_rhs) { 
    if (&l_rhs != this) { Move(l_rhs); } 
    return *this; 
  } 
 
  ~EventInfo() { 
    if (m_type == EventInfoType::GUI) { DestroyGUIStrings(); } 
  } 
  union { 
    int m_code; 
    GUI_Event m_gui; 
  }; 
   
  EventInfoType m_type; 
private: 
  void Move(const EventInfo& l_rhs) { 
    if (m_type == EventInfoType::GUI) { DestroyGUIStrings(); } 
    m_type = l_rhs.m_type; 
    if (m_type == EventInfoType::Normal){ m_code = l_rhs.m_code; } 
    else { 
      CreateGUIStrings(l_rhs.m_gui.m_interface, 
        l_rhs.m_gui.m_element); 
      m_gui = l_rhs.m_gui; 
    } 
  } 
 
  void DestroyGUIStrings() { 
    m_gui.m_interface.~basic_string(); 
    m_gui.m_element.~basic_string(); 
  } 
 
  void CreateGUIStrings(const std::string& l_interface, 
    const std::string& l_element) 
  { 
    new (&m_gui.m_interface) std::string(l_interface); 
    new (&m_gui.m_element) std::string(l_element); 
  } 
}; 

Because we care about more than just the event type that took place, there needs to be a good way of storing additional data that comes with it. C++11's unrestricted union is a perfect candidate for that. The only downside is that now we have to worry about manually managing the data inside the union, which comes complete with data allocations and direct invocation of destructors.

As event call-backs are being invoked, it's a good idea to provide them with the actual event information. Because it's possible to construct more complex requirements for specific call-backs, we can't get away with unions this time. Any possible information that may be relevant needs to be stored, and that's precisely what is done here:

struct EventDetails { 
  EventDetails(const std::string& l_bindName): m_name(l_bindName){ 
    Clear(); 
  } 
   
  std::string m_name; 
  sf::Vector2i m_size; 
  sf::Uint32 m_textEntered; 
  sf::Vector2i m_mouse; 
  int m_mouseWheelDelta; 
  int m_keyCode; // Single key code. 
 
  std::string m_guiInterface; 
  std::string m_guiElement; 
  GUI_EventType m_guiEvent; 
 
  void Clear() { ... } 
}; 

This structure is filled with every single bit of information that is available as the events are processed, and then passed as an argument to the call-back that gets invoked. It also provides a Clear() method, because instead of being created only for the time during the call-back, it lives inside the binding structure:

using Events = std::vector<std::pair<EventType, EventInfo>>; 
 
struct Binding { 
  Binding(const std::string& l_name) : m_name(l_name), 
    m_details(l_name), c(0) {} 
  void BindEvent(EventType l_type, EventInfo l_info = EventInfo()) 
  { ... } 
 
  Events m_events; 
  std::string m_name; 
  int c; // Count of events that are "happening". 
 
  EventDetails m_details; 
}; 

A binding is what actually allows events to be grouped together in order to form more complex requirements. Think of it in terms of multiple keys needing to be pressed at once in order to perform an action, such as Ctrl + C for copying a piece of text. A binding for that type of situation would have two events it's waiting for: the Ctrl key and the C key.

Event manager interface

With all of the key pieces being covered, all that's left is actually managing everything properly. Let's start with some type definitions:

using Bindings = std::unordered_map<std::string, 
  std::unique_ptr<Binding>>; 
using CallbackContainer = std::unordered_map<std::string, 
  std::function<void(EventDetails*)>>; 
enum class StateType; 
using Callbacks = std::unordered_map<StateType, 
  CallbackContainer>; 

All bindings are attached to specific names that get loaded from a keys.cfg file when the application is started. It follows a basic format like this:

Window_close 0:0 
Fullscreen_toggle 5:89 
Intro_Continue 5:57 
Mouse_Left 9:0 

Of course these are very basic examples. More complex bindings would have multiple events separated by white spaces.

Call-backs are also stored in an unordered map, as well as tied to the name of a binding that they're watching. The actual call-back containers are then grouped by state, in order to avoid multiple functions/methods getting called when similar keys are pressed. As you can imagine, the event manager is going to be inheriting from a StateDependent class for this very reason:

class EventManager : public StateDependent{ 
public: 
  ... 
  bool AddBinding(std::unique_ptr<Binding> l_binding); 
  bool RemoveBinding(std::string l_name); 
  void ChangeState(const StateType& l_state); 
  void RemoveState(const StateType& l_state); 
  void SetFocus(bool l_focus); 
   
  template<class T> 
  bool AddCallback(const StateType& l_state, 
    const std::string& l_name,  
    void(T::*l_func)(EventDetails*), T* l_instance) 
  { ... } 
   
  template<class T> 
  bool AddCallback(const std::string& l_name, 
    void(T::*l_func)(EventDetails*), T* l_instance) 
  { ... } 
 
  bool RemoveCallback(const StateType& l_state, 
    const std::string& l_name){ ... } 
  void HandleEvent(sf::Event& l_event); 
  void HandleEvent(GUI_Event& l_event); 
  void Update(); 
  sf::Vector2i GetMousePos(sf::RenderWindow* l_wind = nullptr) 
    const { ... } 
private: 
  ... 
  Bindings m_bindings; 
  Callbacks m_callbacks; 
}; 

Once again, this is quite simple. Since this is a state-dependent class, it needs to implement the ChangeState() and RemoveState() methods. It also keeps track of when the window focus is obtained/lost, in order to avoid polling events of minimized/unfocused windows. Two versions of AddCallback are provided: one for a specified state, and one for the current state. Separate HandleEvent() methods are also available for every event type supported. So far, we only have two: SFML events, and GUI events. The latter is going to be used in the upcoming section.

Use of graphical user interfaces

A friendly way of interfacing with applications in a day and age where computers are basically a necessity inside every household is a must. The entire subject of GUIs could fill multiple books by itself, so for the sake of keeping this simple, we are only going to scratch the surface of what we have to work with:

class GUI_Manager : public StateDependent{ 
  friend class GUI_Interface; 
public: 
  ... 
  bool AddInterface(const StateType& l_state, 
    const std::string& l_name); 
  bool AddInterface(const std::string& l_name); 
  GUI_Interface* GetInterface(const StateType& l_state, 
    const std::string& l_name); 
  GUI_Interface* GetInterface(const std::string& l_name); 
  bool RemoveInterface(const StateType& l_state, 
    const std::string& l_name); 
  bool RemoveInterface(const std::string& l_name); 
  bool LoadInterface(const StateType& l_state, 
    const std::string& l_interface, const std::string& l_name); 
  bool LoadInterface(const std::string& l_interface, 
    const std::string& l_name); 
  void ChangeState(const StateType& l_state); 
  void RemoveState(const StateType& l_state); 
  SharedContext* GetContext() const; 
  void DefocusAllInterfaces(); 
  void HandleClick(EventDetails* l_details); 
  void HandleRelease(EventDetails* l_details); 
  void HandleTextEntered(EventDetails* l_details); 
  void AddEvent(GUI_Event l_event); 
  bool PollEvent(GUI_Event& l_event); 
  void Update(float l_dT); 
  void Render(sf::RenderWindow* l_wind); 
  template<class T> 
  void RegisterElement(const GUI_ElementType& l_id){ ... } 
private: 
  ... 
}; 

Interface management, quite predictably, is also dependent on application states. The interfaces themselves are also assigned names, which is how they are loaded and stored. Mouse input, as well as text enter events, are both utilized in making the GUI system work, which is why this class actually uses the event manager and registers three call-backs with it. Not unlike other classes we have discussed, it also uses the factory method, in order to be able to dynamically create different types of elements that populate our interfaces.

Interfaces are described as groups of elements, like so:

Interface MainMenu MainMenu.style 0 0 Immovable NoTitle "Main menu" 
Element Label Title 100 0 MainMenuTitle.style "Main menu:" 
Element Label Play 0 32 MainMenuLabel.style "PLAY" 
Element Label Credits 0 68 MainMenuLabel.style "CREDITS" 
Element Label Quit 0 104 MainMenuLabel.style "EXIT" 

Each element also supports styles for the three different states it can be in: neutral, hovered, and clicked. A single style file describes what an element would look like under all of these conditions:

State Neutral 
Size 300 32 
BgColor 255 0 0 255 
TextColor 255 255 255 255 
TextSize 14 
Font Main 
TextPadding 150 16 
TextOriginCenter 
/State 
 
State Hover 
BgColor 255 100 0 255 
/State 
 
State Clicked 
BgColor 255 150 0 255 
/State 

The Neutral style serves as a base for the other two, which is why they only define attributes that are different from it. Using this model, interfaces of great complexity can be constructed and customized to do almost anything.

Representing a 2D map

Maps are another crucial part of having a decently complex game. For our purposes, we're going to be representing 2D maps that support different layers in order to fake 3D depth:

class Map : public FileLoader{ 
public: 
  ... 
  Tile* GetTile(unsigned int l_x, unsigned int l_y, 
    unsigned int l_layer); 
  TileInfo* GetDefaultTile(); 
  TileSet* GetTileSet(); 
  unsigned int GetTileSize()const; 
  sf::Vector2u GetMapSize()const; 
  sf::Vector2f GetPlayerStart()const; 
  int GetPlayerId()const; 
  void PurgeMap(); 
  void AddLoadee(MapLoadee* l_loadee); 
  void RemoveLoadee(MapLoadee* l_loadee); 
  void Update(float l_dT); 
  void Draw(unsigned int l_layer); 
protected: 
  bool ProcessLine(std::stringstream& l_stream); 
  ... 
}; 

As you can see, this class is actually inheriting from the FileLoader, which we covered earlier. It also supports something that's referred to as MapLoadee*, which are simply classes that will store certain data inside map files, and need to be notified when such data is encountered during the loading process. It's simply an interface that they have to implement:

class MapLoadee { 
public: 
  virtual void ReadMapLine(const std::string& l_type, 
    std::stringstream& l_stream) = 0; 
}; 

The map files themselves are fairly straightforward:

SIZE 64 64 
DEFAULT_FRICTION 1.0 1.0 
|ENTITY|Name|x|y|elevation| 
ENTITY Player 715 360 1 
ENTITY Skeleton 256.0 768.0 1 
|TILE|ID|x|y|layer|solid| 
TILE 0 0 0 0 0 
TILE 0 0 1 0 0 
TILE 0 0 2 0 0 
... 

A good candidate for a MapLoadee here would be a class that handles entities being spawned. The two entity lines would be directly handled by it, which creates a nice level of separation between codes that shouldn't really overlap.

Sprite system

Since we're working on a 2D game, the most likely candidate for the way graphics are going to be done is a sprite sheet. Unifying the way sprite sheet cropping and animations are handled is key to not only minimizing code, but also creating a simple, neat interface that's easy to interact with. Let us take a look at how that can be done:

class SpriteSheet{ 
public: 
  ... 
  void CropSprite(const sf::IntRect& l_rect); 
  const sf::Vector2u& GetSpriteSize()const; 
  const sf::Vector2f& GetSpritePosition()const; 
  void SetSpriteSize(const sf::Vector2u& l_size); 
  void SetSpritePosition(const sf::Vector2f& l_pos); 
  void SetDirection(const Direction& l_dir); 
  Direction GetDirection() const; 
  void SetSheetPadding(const sf::Vector2f& l_padding); 
  void SetSpriteSpacing(const sf::Vector2f& l_spacing); 
  const sf::Vector2f& GetSheetPadding()const; 
  const sf::Vector2f& GetSpriteSpacing()const; 
  bool LoadSheet(const std::string& l_file); 
  void ReleaseSheet(); 
  Anim_Base* GetCurrentAnim(); 
  bool SetAnimation(const std::string& l_name, 
    bool l_play = false, bool l_loop = false); 
  void Update(float l_dT); 
  void Draw(sf::RenderWindow* l_wnd); 
private: 
  ... 
  Animations m_animations; 
}; 

The SpriteSheet class itself isn't really that complex. It offers helper methods for cropping the sheet down to a specific rectangle, altering the stored direction, defining different attributes, such as spacing, padding, and so on, and manipulating the animation data.

Animations are stored in this class by name:

using Animations = std::unordered_map<std::string, 
  std::unique_ptr<Anim_Base>>; 

The interface of an animation class looks like this:

class Anim_Base{ 
  friend class SpriteSheet; 
public: 
  ... 
  void SetSpriteSheet(SpriteSheet* l_sheet); 
  bool SetFrame(Frame l_frame); 
  void SetStartFrame(Frame l_frame); 
  void SetEndFrame(Frame l_frame); 
  void SetFrameRow(unsigned int l_row); 
  void SetActionStart(Frame l_frame); 
  void SetActionEnd(Frame l_frame); 
  void SetFrameTime(float l_time); 
  void SetLooping(bool l_loop); 
  void SetName(const std::string& l_name); 
  SpriteSheet* GetSpriteSheet(); 
  Frame GetFrame() const; 
  Frame GetStartFrame() const; 
  Frame GetEndFrame() const; 
  unsigned int GetFrameRow() const; 
  int GetActionStart() const; 
  int GetActionEnd() const; 
  float GetFrameTime() const; 
  float GetElapsedTime() const; 
  bool IsLooping() const; 
  bool IsPlaying() const; 
  bool IsInAction() const; 
  bool CheckMoved(); 
  std::string GetName() const; 
  void Play(); 
  void Pause(); 
  void Stop(); 
  void Reset(); 
  virtual void Update(float l_dT); 
  friend std::stringstream& operator >>( 
    std::stringstream&l_stream, Anim_Base& a){ ... } 
protected: 
  virtual void FrameStep() = 0; 
  virtual void CropSprite() = 0; 
  virtual void ReadIn(std::stringstream& l_stream) = 0; 
  ... 
}; 

First, the Frame data type is simply a type definition of an integer. This class keeps track of all necessary animation data, and even provides a way to set up specific frame ranges (also referred to as actions), which can be used for something such as an entity only attacking something if the attack animation is within that specific action range.

The obvious thing about this class is that it does not represent any single type of animation, but rather all the common elements of every type. This is why three different purely virtual methods are provided, so that different types of animation can define how the frame step is handled, define the specific method, the location of cropping, and the exact process of the animation being loaded from a file. This helps us separate directional animations, where every row represents a character facing a different way, from simple, sequential animations of frames following each other in a linear order.

Sound system

Last, but definitely not least, the sound system deserves a brief overview. It probably would be a surprise to nobody at this point to learn that sounds are also reliant upon application states, which is why we're inheriting from StateDependent again:

class SoundManager : public StateDependent{ 
public: 
  SoundManager(AudioManager* l_audioMgr); 
  ~SoundManager(); 
 
  void ChangeState(const StateType& l_state); 
  void RemoveState(const StateType& l_state); 
 
  void Update(float l_dT); 
 
  SoundID Play(const std::string& l_sound, 
    const sf::Vector3f& l_position, 
    bool l_loop = false, bool l_relative = false); 
  bool Play(const SoundID& l_id); 
  bool Stop(const SoundID& l_id); 
  bool Pause(const SoundID& l_id); 
 
  bool PlayMusic(const std::string& l_musicId, 
    float l_volume = 100.f, bool l_loop = false); 
  bool PlayMusic(const StateType& l_state); 
  bool StopMusic(const StateType& l_state); 
  bool PauseMusic(const StateType& l_state); 
 
  bool SetPosition(const SoundID& l_id, 
    const sf::Vector3f& l_pos); 
  bool IsPlaying(const SoundID& l_id) const; 
  SoundProps* GetSoundProperties(const std::string& l_soundName); 
 
  static const int Max_Sounds = 150; 
  static const int Sound_Cache = 75; 
private: 
  ... 
  AudioManager* m_audioManager; 
}; 

The AudioManager class is responsible for managing auditory resources, in the same way textures and fonts are managed elsewhere. One of the bigger differences here is that we can actually play sounds in 3D space, hence the use of a sf::Vector3f structure wherever a position needs to be represented. Sounds are also grouped by specific names, but there is a slight twist to this system. SFML can only handle about 255 different sounds playing all at once, which includes sf::Music instances as well. It's because of this that we have to implement a recycling system that utilizes discarded instances of sounds, as well as a static limit of the maximum number of sounds allowed all at once.

Every different sound that is loaded and played has specific set up properties that can be tweaked. They are represented by this data structure:

struct SoundProps{ 
  SoundProps(const std::string& l_name): m_audioName(l_name), 
    m_volume(100), m_pitch(1.f), m_minDistance(10.f), 
    m_attenuation(10.f){} 
  std::string m_audioName; 
  float m_volume; 
  float m_pitch; 
  float m_minDistance; 
  float m_attenuation; 
}; 

audioName is simply the identifier of the audio resource that is loaded in memory. The volume of a sound can obviously be tweaked, as well as its pitch. The last two properties are slightly more intricate. A sound at a point in space would begin to grow quieter and quieter, as we begin to move away from it. The minimum distance property describes the unit distance from the sound source, after which the sound begins to lose its volume. The rate at which this volume is lost after that point is reached is described by the attenuation factor.

Summary

That was quite a lot of information to take in. In the span of around forty pages we have managed to summarize the better part of the entire code base that would make any basic to intermediate complexity game tick. Keep in mind that although many topics got covered here, all of the information was rather condensed. Feel free to look through the code files we provide until you feel comfortable to proceed to actually building a game, which is precisely what's coming in the next chapter. See you there!

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build custom tools, designed to work with your specific game.
  • Use raw modern OpenGL and go beyond SFML.
  • Revamp your code for better structural design, faster rendering, and flashier graphics.
  • Use advanced lighting techniques to add that extra touch of sophistication.
  • Implement a very fast and efficient particle system by using a cache-friendly design.

Description

SFML is a cross-platform software development library written in C++ with bindings available for many programming languages. It provides a simple interface to the various components of your PC, to ease the development of games and multimedia applications. This book will help you become an expert of SFML by using all of its features to its full potential. It begins by going over some of the foundational code necessary in order to make our RPG project run. By the end of chapter 3, we will have successfully picked up and deployed a fast and efficient particle system that makes the game look much more ‘alive’. Throughout the next couple of chapters, you will be successfully editing the game maps with ease, all thanks to the custom tools we’re going to be building. From this point on, it’s all about making the game look good. After being introduced to the use of shaders and raw OpenGL, you will be guided through implementing dynamic scene lighting, the use of normal and specular maps, and dynamic soft shadows. However, no project is complete without being optimized first. The very last chapter will wrap up our project by making it lightning fast and efficient.

Who is this book for?

This book is ideal for game developers who have some basic knowledge of SFML and also are familiar with C++ coding in general. No knowledge of OpenGL or even more advanced rendering techniques is required. You will be guided through every bit of code step by step.

What you will learn

  • Dive deep into creating complex and visually stunning games using SFML, as well as advanced OpenGL rendering and shading techniques
  • Build an advanced, dynamic lighting and shadowing system to add an extra graphical kick to your games and make them feel a lot more dynamic
  • Craft your own custom tools for editing game media, such as maps, and speed up the process of content creation
  • Optimize your code to make it blazing fast and robust for the users, even with visually demanding scenes
  • Get a complete grip on the best practices and industry grade game development design patterns used for AAA projects
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jan 30, 2017
Length: 442 pages
Edition : 1st
Language : English
ISBN-13 : 9781786469885
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to United States

Economy delivery 10 - 13 business days

Free $6.95

Premium delivery 6 - 9 business days

$21.95
(Includes tracking information)

Product Details

Publication date : Jan 30, 2017
Length: 442 pages
Edition : 1st
Language : English
ISBN-13 : 9781786469885
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
SFML Blueprints
$43.99
SFML Game Development By Example
$54.99
Mastering SFML Game Development
$48.99
Total $ 147.97 Stars icon
Banner background image

Table of Contents

10 Chapters
1. Under the Hood - Setting up the Backend Chevron down icon Chevron up icon
2. Its Game Time! - Designing the Project Chevron down icon Chevron up icon
3. Make It Rain! - Building a Particle System Chevron down icon Chevron up icon
4. Have Thy Gear Ready - Building Game Tools Chevron down icon Chevron up icon
5. Filling the Tool Belt - a few More Gadgets Chevron down icon Chevron up icon
6. Adding Some Finishing Touches - Using Shaders Chevron down icon Chevron up icon
7. One Step Forward, One Level Down - OpenGL Basics Chevron down icon Chevron up icon
8. Let There Be Light - An Introduction to Advanced Lighting Chevron down icon Chevron up icon
9. The Speed of Dark - Lighting and Shadows Chevron down icon Chevron up icon
10. A Chapter You Shouldnt Skip - Final Optimizations Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
Kamal johnson Dec 06, 2017
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
the price on the book is only 599Rs but the price on amazon is 1079Rsthe quality of the book is also very low.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela