Skip to content

Instantly share code, notes, and snippets.

@vittorioromeo
Created June 24, 2013 15:06
Show Gist options
  • Save vittorioromeo/5850735 to your computer and use it in GitHub Desktop.
Save vittorioromeo/5850735 to your computer and use it in GitHub Desktop.
Optimizations to sf::Text - adding a "must update geometry" flag to avoid unnecessary recalculations
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Text.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <cassert>
namespace sf
{
////////////////////////////////////////////////////////////
Text::Text() :
m_string (),
m_font (NULL),
m_characterSize(30),
m_style (Regular),
m_color (255, 255, 255),
m_vertices (Quads),
m_bounds (),
m_mustUpdate (true)
{
}
////////////////////////////////////////////////////////////
Text::Text(const String& string, const Font& font, unsigned int characterSize) :
m_string (string),
m_font (&font),
m_characterSize(characterSize),
m_style (Regular),
m_color (255, 255, 255),
m_vertices (Quads),
m_bounds (),
m_mustUpdate (true)
{
}
////////////////////////////////////////////////////////////
void Text::setString(const String& string)
{
if (m_string != string)
{
m_string = string;
m_mustUpdate = true;
}
}
////////////////////////////////////////////////////////////
void Text::setFont(const Font& font)
{
if (m_font != &font)
{
m_font = &font;
m_mustUpdate = true;
}
}
////////////////////////////////////////////////////////////
void Text::setCharacterSize(unsigned int size)
{
if (m_characterSize != size)
{
m_characterSize = size;
m_mustUpdate = true;
}
}
////////////////////////////////////////////////////////////
void Text::setStyle(Uint32 style)
{
if (m_style != style)
{
m_style = style;
m_mustUpdate = true;
}
}
////////////////////////////////////////////////////////////
void Text::setColor(const Color& color)
{
if (color != m_color)
{
m_color = color;
for (unsigned int i = 0; i < m_vertices.getVertexCount(); ++i)
m_vertices[i].color = m_color;
}
}
////////////////////////////////////////////////////////////
const String& Text::getString() const
{
return m_string;
}
////////////////////////////////////////////////////////////
const Font* Text::getFont() const
{
return m_font;
}
////////////////////////////////////////////////////////////
unsigned int Text::getCharacterSize() const
{
return m_characterSize;
}
////////////////////////////////////////////////////////////
Uint32 Text::getStyle() const
{
return m_style;
}
////////////////////////////////////////////////////////////
const Color& Text::getColor() const
{
return m_color;
}
////////////////////////////////////////////////////////////
Vector2f Text::findCharacterPos(std::size_t index) const
{
const_cast<Text*>(this)->checkGeometryUpdate();
// Make sure that we have a valid font
if (!m_font)
return Vector2f();
// Adjust the index if it's out of range
if (index > m_string.getSize())
index = m_string.getSize();
// Precompute the variables needed by the algorithm
bool bold = (m_style & Bold) != 0;
float hspace = static_cast<float>(m_font->getGlyph(L' ', m_characterSize, bold).advance);
float vspace = static_cast<float>(m_font->getLineSpacing(m_characterSize));
// Compute the position
Vector2f position;
Uint32 prevChar = 0;
for (std::size_t i = 0; i < index; ++i)
{
Uint32 curChar = m_string[i];
// Apply the kerning offset
position.x += static_cast<float>(m_font->getKerning(prevChar, curChar, m_characterSize));
prevChar = curChar;
// Handle special characters
switch (curChar)
{
case L' ' : position.x += hspace; continue;
case L'\t' : position.x += hspace * 4; continue;
case L'\n' : position.y += vspace; position.x = 0; continue;
case L'\v' : position.y += vspace * 4; continue;
}
// For regular characters, add the advance offset of the glyph
position.x += static_cast<float>(m_font->getGlyph(curChar, m_characterSize, bold).advance);
}
// Transform the position to global coordinates
position = getTransform().transformPoint(position);
return position;
}
////////////////////////////////////////////////////////////
FloatRect Text::getLocalBounds() const
{
const_cast<Text*>(this)->checkGeometryUpdate();
return m_bounds;
}
////////////////////////////////////////////////////////////
FloatRect Text::getGlobalBounds() const
{
const_cast<Text*>(this)->checkGeometryUpdate();
return getTransform().transformRect(getLocalBounds());
}
////////////////////////////////////////////////////////////
void Text::draw(RenderTarget& target, RenderStates states) const
{
const_cast<Text*>(this)->checkGeometryUpdate();
if (m_font)
{
states.transform *= getTransform();
states.texture = &m_font->getTexture(m_characterSize);
target.draw(m_vertices, states);
}
}
////////////////////////////////////////////////////////////
void Text::checkGeometryUpdate()
{
// If the geometry is outdated, update it
if (m_mustUpdate)
{
updateGeometry();
m_mustUpdate = false;
}
}
////////////////////////////////////////////////////////////
void Text::updateGeometry()
{
// Clear the previous geometry
m_vertices.clear();
m_bounds = FloatRect();
// No font: nothing to draw
if (!m_font)
return;
// No text: nothing to draw
if (m_string.isEmpty())
return;
// Compute values related to the text style
bool bold = (m_style & Bold) != 0;
bool underlined = (m_style & Underlined) != 0;
float italic = (m_style & Italic) ? 0.208f : 0.f; // 12 degrees
float underlineOffset = m_characterSize * 0.1f;
float underlineThickness = m_characterSize * (bold ? 0.1f : 0.07f);
// Precompute the variables needed by the algorithm
float hspace = static_cast<float>(m_font->getGlyph(L' ', m_characterSize, bold).advance);
float vspace = static_cast<float>(m_font->getLineSpacing(m_characterSize));
float x = 0.f;
float y = static_cast<float>(m_characterSize);
// Create one quad for each character
Uint32 prevChar = 0;
for (std::size_t i = 0; i < m_string.getSize(); ++i)
{
Uint32 curChar = m_string[i];
// Apply the kerning offset
x += static_cast<float>(m_font->getKerning(prevChar, curChar, m_characterSize));
prevChar = curChar;
// If we're using the underlined style and there's a new line, draw a line
if (underlined && (curChar == L'\n'))
{
float top = y + underlineOffset;
float bottom = top + underlineThickness;
m_vertices.append(Vertex(Vector2f(0, top), m_color, Vector2f(1, 1)));
m_vertices.append(Vertex(Vector2f(x, top), m_color, Vector2f(1, 1)));
m_vertices.append(Vertex(Vector2f(x, bottom), m_color, Vector2f(1, 1)));
m_vertices.append(Vertex(Vector2f(0, bottom), m_color, Vector2f(1, 1)));
}
// Handle special characters
switch (curChar)
{
case L' ' : x += hspace; continue;
case L'\t' : x += hspace * 4; continue;
case L'\n' : y += vspace; x = 0; continue;
case L'\v' : y += vspace * 4; continue;
}
// Extract the current glyph's description
const Glyph& glyph = m_font->getGlyph(curChar, m_characterSize, bold);
int left = glyph.bounds.left;
int top = glyph.bounds.top;
int right = glyph.bounds.left + glyph.bounds.width;
int bottom = glyph.bounds.top + glyph.bounds.height;
float u1 = static_cast<float>(glyph.textureRect.left);
float v1 = static_cast<float>(glyph.textureRect.top);
float u2 = static_cast<float>(glyph.textureRect.left + glyph.textureRect.width);
float v2 = static_cast<float>(glyph.textureRect.top + glyph.textureRect.height);
// Add a quad for the current character
m_vertices.append(Vertex(Vector2f(x + left - italic * top, y + top), m_color, Vector2f(u1, v1)));
m_vertices.append(Vertex(Vector2f(x + right - italic * top, y + top), m_color, Vector2f(u2, v1)));
m_vertices.append(Vertex(Vector2f(x + right - italic * bottom, y + bottom), m_color, Vector2f(u2, v2)));
m_vertices.append(Vertex(Vector2f(x + left - italic * bottom, y + bottom), m_color, Vector2f(u1, v2)));
// Advance to the next character
x += glyph.advance;
}
// If we're using the underlined style, add the last line
if (underlined)
{
float top = y + underlineOffset;
float bottom = top + underlineThickness;
m_vertices.append(Vertex(Vector2f(0, top), m_color, Vector2f(1, 1)));
m_vertices.append(Vertex(Vector2f(x, top), m_color, Vector2f(1, 1)));
m_vertices.append(Vertex(Vector2f(x, bottom), m_color, Vector2f(1, 1)));
m_vertices.append(Vertex(Vector2f(0, bottom), m_color, Vector2f(1, 1)));
}
// Recompute the bounding rectangle
m_bounds = m_vertices.getBounds();
}
} // namespace sf
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2013 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_TEXT_HPP
#define SFML_TEXT_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Transformable.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Rect.hpp>
#include <SFML/Graphics/VertexArray.hpp>
#include <SFML/System/String.hpp>
#include <string>
#include <vector>
namespace sf
{
////////////////////////////////////////////////////////////
/// \brief Graphical text that can be drawn to a render target
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API Text : public Drawable, public Transformable
{
public :
////////////////////////////////////////////////////////////
/// \brief Enumeration of the string drawing styles
///
////////////////////////////////////////////////////////////
enum Style
{
Regular = 0, ///< Regular characters, no style
Bold = 1 << 0, ///< Bold characters
Italic = 1 << 1, ///< Italic characters
Underlined = 1 << 2 ///< Underlined characters
};
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Creates an empty text.
///
////////////////////////////////////////////////////////////
Text();
////////////////////////////////////////////////////////////
/// \brief Construct the text from a string, font and size
///
/// \param string Text assigned to the string
/// \param font Font used to draw the string
/// \param characterSize Base size of characters, in pixels
///
////////////////////////////////////////////////////////////
Text(const String& string, const Font& font, unsigned int characterSize = 30);
////////////////////////////////////////////////////////////
/// \brief Set the text's string
///
/// The \a string argument is a sf::String, which can
/// automatically be constructed from standard string types.
/// So, the following calls are all valid:
/// \code
/// text.setString("hello");
/// text.setString(L"hello");
/// text.setString(std::string("hello"));
/// text.setString(std::wstring(L"hello"));
/// \endcode
/// A text's string is empty by default.
///
/// \param string New string
///
/// \see getString
///
////////////////////////////////////////////////////////////
void setString(const String& string);
////////////////////////////////////////////////////////////
/// \brief Set the text's font
///
/// The \a font argument refers to a font that must
/// exist as long as the text uses it. Indeed, the text
/// doesn't store its own copy of the font, but rather keeps
/// a pointer to the one that you passed to this function.
/// If the font is destroyed and the text tries to
/// use it, the behaviour is undefined.
///
/// \param font New font
///
/// \see getFont
///
////////////////////////////////////////////////////////////
void setFont(const Font& font);
////////////////////////////////////////////////////////////
/// \brief Set the character size
///
/// The default size is 30.
///
/// \param size New character size, in pixels
///
/// \see getCharacterSize
///
////////////////////////////////////////////////////////////
void setCharacterSize(unsigned int size);
////////////////////////////////////////////////////////////
/// \brief Set the text's style
///
/// You can pass a combination of one or more styles, for
/// example sf::Text::Bold | sf::Text::Italic.
/// The default style is sf::Text::Regular.
///
/// \param style New style
///
/// \see getStyle
///
////////////////////////////////////////////////////////////
void setStyle(Uint32 style);
////////////////////////////////////////////////////////////
/// \brief Set the global color of the text
///
/// By default, the text's color is opaque white.
///
/// \param color New color of the text
///
/// \see getColor
///
////////////////////////////////////////////////////////////
void setColor(const Color& color);
////////////////////////////////////////////////////////////
/// \brief Get the text's string
///
/// The returned string is a sf::String, which can automatically
/// be converted to standard string types. So, the following
/// lines of code are all valid:
/// \code
/// sf::String s1 = text.getString();
/// std::string s2 = text.getString();
/// std::wstring s3 = text.getString();
/// \endcode
///
/// \return Text's string
///
/// \see setString
///
////////////////////////////////////////////////////////////
const String& getString() const;
////////////////////////////////////////////////////////////
/// \brief Get the text's font
///
/// If the text has no font attached, a NULL pointer is returned.
/// The returned reference is const, which means that you
/// cannot modify the font when you get it from this function.
///
/// \return Pointer to the text's font
///
/// \see setFont
///
////////////////////////////////////////////////////////////
const Font* getFont() const;
////////////////////////////////////////////////////////////
/// \brief Get the character size
///
/// \return Size of the characters, in pixels
///
/// \see setCharacterSize
///
////////////////////////////////////////////////////////////
unsigned int getCharacterSize() const;
////////////////////////////////////////////////////////////
/// \brief Get the text's style
///
/// \return Text's style
///
/// \see setStyle
///
////////////////////////////////////////////////////////////
Uint32 getStyle() const;
////////////////////////////////////////////////////////////
/// \brief Get the global color of the text
///
/// \return Global color of the text
///
/// \see setColor
///
////////////////////////////////////////////////////////////
const Color& getColor() const;
////////////////////////////////////////////////////////////
/// \brief Return the position of the \a index-th character
///
/// This function computes the visual position of a character
/// from its index in the string. The returned position is
/// in global coordinates (translation, rotation, scale and
/// origin are applied).
/// If \a index is out of range, the position of the end of
/// the string is returned.
///
/// \param index Index of the character
///
/// \return Position of the character
///
////////////////////////////////////////////////////////////
Vector2f findCharacterPos(std::size_t index) const;
////////////////////////////////////////////////////////////
/// \brief Get the local bounding rectangle of the entity
///
/// The returned rectangle is in local coordinates, which means
/// that it ignores the transformations (translation, rotation,
/// scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// entity in the entity's coordinate system.
///
/// \return Local bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getLocalBounds() const;
////////////////////////////////////////////////////////////
/// \brief Get the global bounding rectangle of the entity
///
/// The returned rectangle is in global coordinates, which means
/// that it takes in account the transformations (translation,
/// rotation, scale, ...) that are applied to the entity.
/// In other words, this function returns the bounds of the
/// sprite in the global 2D world's coordinate system.
///
/// \return Global bounding rectangle of the entity
///
////////////////////////////////////////////////////////////
FloatRect getGlobalBounds() const;
private :
////////////////////////////////////////////////////////////
/// \brief Draw the text to a render target
///
/// \param target Render target to draw to
/// \param states Current render states
///
////////////////////////////////////////////////////////////
virtual void draw(RenderTarget& target, RenderStates states) const;
////////////////////////////////////////////////////////////
/// \brief Checks if the current geometry is outdated - if
/// it is, updates it
///
////////////////////////////////////////////////////////////
void checkGeometryUpdate();
////////////////////////////////////////////////////////////
/// \brief Update the text's geometry
///
////////////////////////////////////////////////////////////
void updateGeometry();
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
String m_string; ///< String to display
const Font* m_font; ///< Font used to display the string
unsigned int m_characterSize; ///< Base size of characters, in pixels
Uint32 m_style; ///< Text style (see Style enum)
Color m_color; ///< Text color
VertexArray m_vertices; ///< Vertex array containing the text's geometry
FloatRect m_bounds; ///< Bounding rectangle of the text (in local coordinates)
bool m_mustUpdate; ///< Is the current geometry outdated?
};
} // namespace sf
#endif // SFML_TEXT_HPP
////////////////////////////////////////////////////////////
/// \class sf::Text
/// \ingroup graphics
///
/// sf::Text is a drawable class that allows to easily display
/// some text with custom style and color on a render target.
///
/// It inherits all the functions from sf::Transformable:
/// position, rotation, scale, origin. It also adds text-specific
/// properties such as the font to use, the character size,
/// the font style (bold, italic, underlined), the global color
/// and the text to display of course.
/// It also provides convenience functions to calculate the
/// graphical size of the text, or to get the global position
/// of a given character.
///
/// sf::Text works in combination with the sf::Font class, which
/// loads and provides the glyphs (visual characters) of a given font.
///
/// The separation of sf::Font and sf::Text allows more flexibility
/// and better performances: indeed a sf::Font is a heavy resource,
/// and any operation on it is slow (often too slow for real-time
/// applications). On the other side, a sf::Text is a lightweight
/// object which can combine the glyphs data and metrics of a sf::Font
/// to display any text on a render target.
///
/// It is important to note that the sf::Text instance doesn't
/// copy the font that it uses, it only keeps a reference to it.
/// Thus, a sf::Font must not be destructed while it is
/// used by a sf::Text (i.e. never write a function that
/// uses a local sf::Font instance for creating a text).
///
/// Usage example:
/// \code
/// // Declare and load a font
/// sf::Font font;
/// font.loadFromFile("arial.ttf");
///
/// // Create a text
/// sf::Text text("hello", font);
/// text.setCharacterSize(30);
/// text.setStyle(sf::Text::Bold);
/// text.setColor(sf::Color::Red);
///
/// // Draw it
/// window.draw(text);
/// \endcode
///
/// \see sf::Font, sf::Transformable
///
////////////////////////////////////////////////////////////
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment