diff --git a/src/gfx/render_text.cpp b/src/gfx/render_text.cpp index 3a27aae1..6c0ac67e 100644 --- a/src/gfx/render_text.cpp +++ b/src/gfx/render_text.cpp @@ -9,12 +9,13 @@ #include "render_text.hpp" #include +#include #include "fileio/resmgr/res_font.hpp" #include "gfx/render_shapes.hpp" #include #include "winutil.hpp" -void TextStyle::applyTo(sf::Text& text, double scale) { +void TextStyle::applyTo(sf::Text& text, double scale) const { switch(font) { case FONT_PLAIN: text.setFont(*ResMgr::fonts.get("plain")); @@ -319,13 +320,26 @@ std::vector draw_string_sel(sf::RenderTarget& dest_window,rectangle d return params.snippets; } -size_t string_length(std::string str, TextStyle style, short* height){ +std::set strings_to_cache = {" "}; + +size_t string_length(std::string str, const TextStyle& style, short* height){ size_t total_width = 0; + if(style.measurementCache.find(str) != style.measurementCache.end()){ + location measurement = style.measurementCache[str]; + if(height) *height = measurement.y; + return measurement.x; + } sf::Text text; style.applyTo(text); text.setString(str); total_width = text.getLocalBounds().width; + if(strings_to_cache.count(str)){ + location measurement; + measurement.x = total_width; + measurement.y = text.getLocalBounds().height; + style.measurementCache[str] = measurement; + } if(height) *height = text.getLocalBounds().height; return total_width; } diff --git a/src/gfx/render_text.hpp b/src/gfx/render_text.hpp index e1c4a7a1..1b61b041 100644 --- a/src/gfx/render_text.hpp +++ b/src/gfx/render_text.hpp @@ -36,7 +36,8 @@ struct TextStyle { int pointSize = 10, lineHeight = 10; sf::Color colour; TextStyle() : colour(sf::Color::Black) {} - void applyTo(sf::Text& text, double scale = 1.0); + void applyTo(sf::Text& text, double scale = 1.0) const; + mutable std::map measurementCache; }; // elements: std::make_tuple(last_line_break, last_word_break, line_width) @@ -63,6 +64,6 @@ void clear_scale_aware_text(sf::RenderTexture& texture); void win_draw_string(sf::RenderTarget& dest_window,rectangle dest_rect,std::string str,eTextMode mode,TextStyle style,bool right_align = false); void win_draw_string(sf::RenderTarget& dest_window,rectangle dest_rect,std::string str,eTextMode mode,TextStyle style, break_info_t break_info,bool right_align = false); break_info_t calculate_line_wrapping(rectangle dest_rect, std::string str, TextStyle style); -size_t string_length(std::string str, TextStyle style, short* height = nullptr); +size_t string_length(std::string str, const TextStyle& style, short* height = nullptr); #endif