binpress

Creating a City Building Game with SFML Part 8: GUI System

Get started with this tutorial series here!

We have but two more classes to make, and our game will be done! First up is the Gui class, which we’ll use to draw (as you might expect) a graphical user interface. We could use a separate library dedicated to this task, but the task is simple enough (in this case) for us to roll our own. Actually, there are 4 classes, because gui.hpp contains 3; GuiStyleGuiEntry, and Gui. A Gui is made up of a series of GuiEntrys which each display some text and are styled according to a GuiStyle.

  1. #ifndef GUI_HPP
  2. #define GUI_HPP
  3.  
  4. #include <vector>
  5. #include <utility>
  6. #include <string>
  7.  
  8. class GuiStyle
  9. {
  10.     public:
  11.  
  12.     sf::Color bodyCol;
  13.     sf::Color bodyHighlightCol;
  14.     sf::Color borderCol;
  15.     sf::Color borderHighlightCol;
  16.     sf::Color textCol;
  17.     sf::Color textHighlightCol;
  18.     sf::Font* font;
  19.  
  20.     float borderSize;
  21.  
  22.     GuiStyle(sf::Font* font, float borderSize,
  23.         sf::Color bodyCol, sf::Color borderCol, sf::Color textCol,
  24.         sf::Color bodyHighlightCol, sf::Color borderHighlightCol, sf::Color textHighlightCol)
  25.     {
  26.         this->bodyCol = bodyCol;
  27.         this->borderCol = borderCol;
  28.         this->textCol = textCol;
  29.         this->bodyHighlightCol = bodyHighlightCol;
  30.         this->borderHighlightCol = borderHighlightCol;
  31.         this->textHighlightCol = textHighlightCol;
  32.         this->font = font;
  33.         this->borderSize = borderSize;
  34.     }
  35.     GuiStyle() { }
  36. };

This class is just one big data structure with a constructor slapped on. The only new code would be sf::Font, which contains a pointer to the font the style we’ll use. It’s a pointer because sf::Fonts are large things, and so should only be created once, like sf::Textures. As a quick overview of the GuiStylebodyCol is the background color of the entry, borderCol is the color of the entry’s outline, textCol is the color of the text written on the entry, and the highlight colors are used instead of the normal ones when the player hovers over the entry with their mouse (or selects it with the keyboard, etc.) Moving on to GuiEntry:

  1. class GuiEntry
  2. {
  3.     public:
  4.  
  5.     /* Handles appearance of the entry */
  6.     sf::RectangleShape shape;
  7.  
  8.     /* String returned when the entry is activated */
  9.     std::string message;
  10.  
  11.     /* Text displayed on the entry */
  12.     sf::Text text;
  13.  
  14.     GuiEntry(const std::string& message, sf::RectangleShape shape, sf::Text text)
  15.     {
  16.         this->message = message;
  17.         this->shape = shape;
  18.         this->text = text;
  19.     }
  20.     GuiEntry() { }
  21. };

Also a data structure meets constructor combo, we have an sf::RectangleShape to store what the entry looks like. We aren’t using sprites because everything is determined by the style, so instead we have a rectangle that can be displayed using the properties of a GuiStylesf::RectangleShapes can be drawn to the screen like a sprite however, as we will see. messageis what the Gui will return when that particular entry is activated (i.e. clicked), and sf::Text is a string given the ability to be drawn to the screen using an sf::Font. Now let’s examine the Guiclass.

  1. class Gui : public sf::Transformable, public sf::Drawable
  2. {
  3.     private:
  4.  
  5.     /* If true the menu entries will be horizontally, not vertically, adjacent */
  6.     bool horizontal;
  7.  
  8.     GuiStyle style;
  9.  
  10.     sf::Vector2f dimensions;
  11.  
  12.     int padding;
  13.  
  14.     public:
  15.  
  16.     std::vector<GuiEntry> entries;
  17.  
  18.     bool visible;
  19.  
  20.     /* Constructor */
  21.     Gui(sf::Vector2f dimensions, int padding, bool horizontal,
  22.         GuiStyle& style, std::vector<std::pair<std::string, std::string>> entries)
  23.     {
  24.         visible = false;
  25.         this->horizontal = horizontal;
  26.         this->style = style;
  27.         this->dimensions = dimensions;
  28.         this->padding = padding;
  29.  
  30.         /* Construct the background shape */
  31.         sf::RectangleShape shape;
  32.         shape.setSize(dimensions);
  33.         shape.setFillColor(style.bodyCol);
  34.         shape.setOutlineThickness(-style.borderSize);
  35.         shape.setOutlineColor(style.borderCol);
  36.  
  37.         /* Construct each gui entry */
  38.         for(auto entry : entries)
  39.         {
  40.             /* Construct the text */
  41.             sf::Text text;
  42.             text.setString(entry.first);
  43.             text.setFont(*style.font);
  44.             text.setColor(style.textCol);
  45.             text.setCharacterSize(dimensions.y-style.borderSize-padding);
  46.  
  47.             this->entries.push_back(GuiEntry(entry.second, shape, text));
  48.         }
  49.     }
  50.  
  51.     sf::Vector2f getSize();
  52.  
  53.     /* Return the entry that the mouse is hovering over. Returns
  54.      * -1 if the mouse if outside of the Gui */
  55.     int getEntry(const sf::Vector2f mousePos);
  56.  
  57.     /* Change the text of an entry. */
  58.     void setEntryText(int entry, std::string text);
  59.  
  60.     /* Change the entry dimensions. */
  61.     void setDimensions(sf::Vector2f dimensions);
  62.  
  63.     /* Draw the menu. */
  64.     virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
  65.  
  66.     void show();
  67.  
  68.     void hide();
  69.  
  70.     /* Highlights an entry of the menu. */
  71.     void highlight(const int entry);
  72.  
  73.     /* Return the message bound to the entry. */
  74.     std::string activate(const int entry);
  75.     std::string activate(const sf::Vector2f mousePos);
  76. };
  77.  
  78. #endif /* GUI_HPP */

Note that Gui inherits from two SFML classes, sf::Transformable and sf::Drawable. These allow us to move the Gui around (like we can a sprite) and also use the window.draw instead of draw(window) syntax. As arguments the constructors takes the dimensions of each GuiEntry, the padding (in pixels) that surrounds the text to stop it from overlapping the edges, whether the Gui should arrange the entries horizontally or vertically, which GuiStyle it should use, and an std::vector that contains a pair of std::strings, where the first is the text of the entry and the second is the message. The argument itself might look ugly but passing values to it isn’t too bad.

We then set the variables accordingly and create the sf::RectangleShape that will be used on each GuiEntry. The functions describe themselves but one thing to note is the - in the setOutlineThickness function. This is so that the outline expands inwards toward the center of the shape instead of outwards, preserving the size of the shape and stopping the borders of adjacent elements from overlapping.

We then iterate over each entry pair and create the text using the arguments and the GuiStyle. Here setCharacterSize is the function of note; so that the text fits inside the entry correctly we subtract the borderSize and the padding from the height of the entry shape. There can still be overlap due to the descender on ys and gs for example, but this works well enough for us. Feel free to improve of course, I encourage it!

We will now look at each of the functions in turn and examine their definitions inside gui.cpp. First is getSize, which simply returns the total dimensions of the Gui (these should be placed in gui.cpp).

  1. sf::Vector2f Gui::getSize()
  2. {
  3.     return sf::Vector2f(this->dimensions.x, this->dimensions.y * this->entries.size());
  4. }

We then have getEntry, which takes the mouse position (in screen coordinates, or really the coordinates for the sf::View that the Gui is displayed on) as an argument and returns the index of the entry that mouse is hovering over. If the mouse is outside of the Gui then it returns -1.

  1. int Gui::getEntry(const sf::Vector2f mousePos)
  2. {
  3.     /* If there are no entries then outside the menu. */
  4.     if(entries.size() == 0) return -1;
  5.     if(!this->visible) return -1;
  6.  
  7.     for(int i = 0; i < this->entries.size(); ++i)
  8.     {
  9.         /* Translate point to use the entry's local coordinates. */
  10.         sf::Vector2f point = mousePos;
  11.         point += this->entries[i].shape.getOrigin();
  12.         point -= this->entries[i].shape.getPosition();
  13.  
  14.         if(point.x < 0 || point.x > this->entries[i].shape.getScale().x*this->dimensions.x) continue;
  15.         if(point.y < 0 || point.y > this->entries[i].shape.getScale().y*this->dimensions.y) continue;
  16.         return i;
  17.     }
  18.  
  19.     return -1;
  20. }

By adding the origin of the entry’s shape to the mouse position and subtracting the position of the shape we convert point from view coordinates to ‘local’ coordinates, where (0,0) is the top left of the GuiEntry in question and the coordinates extend up to its dimensions. It’s then very easy to check if the cursor lies within the current entry. Next we have setEntryText, which of course takes an std::string as an argument and sets the text of the specified entry accordingly.

  1. void Gui::setEntryText(int entry, std::string text)
  2. {
  3.     if(entry >= entries.size() || entry < 0) return;
  4.  
  5.     entries[entry].text.setString(text);
  6.  
  7.     return;
  8. }

setDimensions simply changes the size of all the entries

  1. void Gui::setDimensions(sf::Vector2f dimensions)
  2. {
  3.     this->dimensions = dimensions;
  4.  
  5.     for(auto& entry : entries)
  6.     {
  7.         entry.shape.setSize(dimensions);
  8.         entry.text.setCharacterSize(dimensions.y-style.borderSize-padding);
  9.     }
  10.  
  11.     return;
  12. }

Now draw is far more interesting. We are overriding the pure virtual function draw in the sf::Drawable class that Gui inherits from, and by doing this we can use the window.draw(gui)syntax as I said before. The function itself is very simple, and we don’t have to worry about the sf::RenderTarget and sf::RenderStates classes; for our purposes sf::RenderTarget is just the window we are drawing to. If you haven’t seen it before the const at the end denotes that the function does not change any member variables of the class it belongs to. This is necessary for us to override draw:

  1. void Gui::draw(sf::RenderTarget& target, sf::RenderStates states) const
  2. {
  3.     if(!visible) return;
  4.  
  5.     /* Draw each entry of the menu. */
  6.     for(auto entry : this->entries)
  7.     {
  8.         /* Draw the entry. */
  9.         target.draw(entry.shape);
  10.         target.draw(entry.text);
  11.     }
  12.  
  13.     return;
  14. }

The show and hide functions change the visibility of the Gui; if it isn’t visible, it won’t be drawn. show does more than that however, and is used to calculate the position that each GuiEntry should be in; we could put that in draw but we aren’t allowed to because of the const!

  1. void Gui::show()
  2. {
  3.     sf::Vector2f offset(0.0f, 0.0f);
  4.  
  5.     this->visible = true;
  6.  
  7.     /* Draw each entry of the menu. */
  8.     for(auto& entry : this->entries)
  9.     {
  10.         /* Set the origin of the entry. */
  11.         sf::Vector2f origin = this->getOrigin();
  12.         origin -= offset;
  13.         entry.shape.setOrigin(origin);
  14.         entry.text.setOrigin(origin);
  15.  
  16.         /* Compute the position of the entry. */
  17.         entry.shape.setPosition(this->getPosition());
  18.         entry.text.setPosition(this->getPosition());
  19.  
  20.         if(this->horizontal) offset.x += this->dimensions.x;
  21.         else offset.y += this->dimensions.y;
  22.     }
  23.  
  24.     return;
  25. }
  26.  
  27. void Gui::hide()
  28. {
  29.     this->visible = false;
  30.  
  31.     return;
  32. }

As we iterate over the entries we maintain an offset variable that is used to modify the origin of each entry in order to place it in the correct place. At the end of each iteration we modify the offsetdepending on whether the Gui is displayed horizontally or vertically.

Lastly, we have the highlight and activate functions. highlight simply changes the colors of each entry to use the highlighted or normal versions from the GuiStyle depending on whether they are marked as highlighted or not, and activate returns the message associated with the entry. The second activate combines the first activate and getEntry together into a more handy function.

  1. /* Highlights an entry of the menu. */
  2. void Gui::highlight(const int entry)
  3. {
  4.     for(int i = 0; i < entries.size(); ++i)
  5.     {
  6.         if(i == entry)
  7.         {
  8.             entries[i].shape.setFillColor(style.bodyHighlightCol);
  9.             entries[i].shape.setOutlineColor(style.borderHighlightCol);
  10.             entries[i].text.setColor(style.textHighlightCol);
  11.         }
  12.         else
  13.         {
  14.             entries[i].shape.setFillColor(style.bodyCol);
  15.             entries[i].shape.setOutlineColor(style.borderCol);
  16.             entries[i].text.setColor(style.textCol);
  17.         }
  18.     }
  19.  
  20.     return;
  21. }
  22.  
  23. /* Return the message bound to the entry. */
  24. std::string Gui::activate(const int entry)
  25. {
  26.     if(entry == -1) return "null";
  27.     return entries[entry].message;
  28. }
  29.  
  30. std::string Gui::activate(sf::Vector2f mousePos)
  31. {
  32.     int entry = this->getEntry(mousePos);
  33.     return this->activate(entry);
  34. }

Now we have a completed Gui class! Before we can add any Gui systems though it would make sense to create some GuiStyles. It will look better if we have a consistent theme across the entire game, and so we should add the GuiStyles to the Game class to keep them in an easy to access place. Inside of game.hpp we’ll create an std::map of std::strings to GuiStyles called stylesheets to store the styles and then we’ll also add a loadStylesheets function to fill that map, like we did with loadTiles. We will also requrie a loadFonts function and an std::map to go with it. Don’t forget to include gui.hpp!

  1. private:
  2.  
  3. void loadTextures();
  4. void loadTiles();
  5. void loadStylesheets();
  6. void loadFonts();
  7.  
  8. public:
  9.  
  10. const static int tileSize = 8;
  11.  
  12. std::stack<GameState*> states;
  13.  
  14. sf::RenderWindow window;
  15. TextureManager texmgr;
  16. sf::Sprite background;
  17.  
  18. std::map<std::string, Tile> tileAtlas;
  19. std::map<std::string, GuiStyle> stylesheets;
  20. std::map<std::string, sf::Font> fonts;

In game.cpp we’ll define the two new functions.

  1. void Game::loadFonts()
  2. {
  3.     sf::Font font;
  4.     font.loadFromFile("media/font.ttf");
  5.     this->fonts["main_font"] = font;
  6.  
  7.     return;
  8. }
  9.  
  10. void Game::loadStylesheets()
  11. {
  12.     this->stylesheets["button"] = GuiStyle(&this->fonts.at("main_font"), 1,
  13.         sf::Color(0xc6,0xc6,0xc6), sf::Color(0x94,0x94,0x94), sf::Color(0x00,0x00,0x00),
  14.         sf::Color(0x61,0x61,0x61), sf::Color(0x94,0x94,0x94), sf::Color(0x00,0x00,0x00));
  15.     this->stylesheets["text"] = GuiStyle(&this->fonts.at("main_font"), 0,
  16.         sf::Color(0x00,0x00,0x00,0x00), sf::Color(0x00,0x00,0x00), sf::Color(0xff,0xff,0xff),
  17.         sf::Color(0x00,0x00,0x00,0x00), sf::Color(0x00,0x00,0x00), sf::Color(0xff,0x00,0x00));
  18.  
  19.     return;
  20. }

Sadly SFML does not allow us to create a new sf::Font directly from a file so we have to go through a variable instead, but both functions are quite self-explanatory. Just note that the backgroundCol and backgroundHighlightCol for the text stylesheet have 4 arguments and not 3; the last is an optional alpha value, so by setting it to 0 we remove the background and are left with just some text. Very handy! All that’s left now is to call both functions in the Game constructor. Make sure you call loadFonts before loadStylesheets!

Now we can finally add a Gui to GameStateEditor and GameStateStart. First then let’s go into game_state_start.hpp

  1. #include <SFML/Graphics.hpp>
  2. #include <map>
  3. #include <string>
  4.  
  5. #include "game_state.hpp"
  6. #include "gui.hpp"
  7.  
  8. class GameStateStart : public GameState
  9. {
  10.     private:
  11.  
  12.     sf::View view;
  13.  
  14.     std::map<std::string, Gui> guiSystem;
  15.  
  16.     void loadgame();

By using an std::map instead of an std::vector we can refer to the Guis by name instead of by an index, which makes things much simpler for us! Inside of GameStateStart‘s constructor we will create the Gui

  1. this->guiSystem.emplace("menu", Gui(sf::Vector2f(192, 32), 4, false, game->stylesheets.at("button"),
  2.     { std::make_pair("Load Game", "load_game") }));
  3.  
  4. this->guiSystem.at("menu").setPosition(pos);
  5. this->guiSystem.at("menu").setOrigin(96, 32*1/2);
  6. this->guiSystem.at("menu").show();

This Gui will act as a main menu for the game. To add new elements to every othe std::map we’ve used the [] syntax, but we can’t do that here and must use emplace instead. This is because []works by first creating an empty object of the type you are trying to add (thereby calling an empty constructor), then copying the object to the right of the = into std::mapGui doesn’t have an empty constructor so we use emplace, which works differently.

Remember to include the <utility> header so that we can use std::make_pair. We then place the Gui in the center of the screen before setting the Gui‘s origin to its center. setOrigin uses local coordinates ((0,0) is the top left of the Gui) unlike setPosition that uses world coordinates. Finally we show the Gui to make it visible and place all the entries in the correct location.

If we were to run the game now nothing new will appear, even though we’ve shown the Gui! We need to call its draw function first, which we will do in GameStateStart‘s draw function.

  1. this->game->window.draw(this->game->background);
  2.  
  3. for(auto gui : this->guiSystem) this->game->window.draw(gui.second);
  4.  
  5. return;

Simple as that! Unlike in our previous for each loops, we are iterating over an std::map which has both a key and a value. We want to access the value and so we pass gui.second to the drawfunction instead of gui. Try running the program, and hopefully there will be a big “Load Game” button in the middle of the screen! To add some interactivity to the button we will have to go to the handleInput function

  1. void GameStateStart::handleInput()
  2. {
  3.     sf::Event event;
  4.  
  5.     sf::Vector2f mousePos = this->game->window.mapPixelToCoords(sf::Mouse::getPosition(this->game->window), this->view);
  6.  
  7.     while(this->game->window.pollEvent(event))
  8.     {
  9.         switch(event.type)
  10.         {
  11.             /* Close the window. */
  12.             case sf::Event::Closed:
  13.             {
  14.                 game->window.close();
  15.                 break;
  16.             }
  17.             /* Resize the window. */
  18.             case sf::Event::Resized:
  19.             {
  20.                 this->view.setSize(event.size.width, event.size.height);
  21.                 this->game->background.setPosition(this->game->window.mapPixelToCoords(sf::Vector2i(0, 0), this->view));
  22.                 sf::Vector2f pos = sf::Vector2f(event.size.width, event.size.height);
  23.                 pos *= 0.5f;
  24.                 pos = this->game->window.mapPixelToCoords(sf::Vector2i(pos), this->view);
  25.                 this->guiSystem.at("menu").setPosition(pos);
  26.                 this->game->background.setScale(
  27.                     float(event.size.width) / float(this->game->background.getTexture()->getSize().x),
  28.                     float(event.size.height) / float(this->game->background.getTexture()->getSize().y));
  29.                 break;
  30.             }
  31.             /* Highlight menu items. */
  32.             case sf::Event::MouseMoved:
  33.             {
  34.                 this->guiSystem.at("menu").highlight(this->guiSystem.at("menu").getEntry(mousePos));
  35.                 break;
  36.             }
  37.             /* Click on menu items. */
  38.             case sf::Event::MouseButtonPressed:
  39.             {
  40.                 if(event.mouseButton.button == sf::Mouse::Left)
  41.                 {
  42.                     std::string msg = this->guiSystem.at("menu").activate(mousePos);
  43.  
  44.                     if(msg == "load_game")
  45.                     {
  46.                         this->loadgame();
  47.                     }
  48.                 }
  49.                 break;
  50.             }
  51.             case sf::Event::KeyPressed:
  52.             {
  53.                 if(event.key.code == sf::Keyboard::Escape) this->game->window.close();
  54.                 break;
  55.             }
  56.             default: break;
  57.         }
  58.     }
  59.  
  60.     return;
  61. }

Note the new mousePos variable that saves us a lot of typing and some really long lines. We’ve also made sure to re-center the Gui when the window changes size, and have removed the ability to press the space bar to move to the next state. Instead the player hovers over the Gui (highlighting it) and then left clicks. If the load_game message is received (i.e. the player has pressed the “Load Game” entry) then the game will move to the next state. Try it and see!

Source code for this section

Author: Daniel Mansfield

Scroll to Top