Symphony Of Empires
ttf.cpp
Go to the documentation of this file.
1 // Eng3D - General purpouse game engine
2 // Copyright (C) 2021, Eng3D contributors
3 //
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <https://www.gnu.org/licenses/>.
16 //
17 // ----------------------------------------------------------------------------
18 // Name:
19 // ttf.cpp
20 //
21 // Abstract:
22 // Does some important stuff.
23 // ----------------------------------------------------------------------------
24 
25 #include <cassert>
26 #include <stdexcept>
27 #include <SDL_ttf.h>
28 #include "eng3d/ttf.hpp"
29 #include "eng3d/io.hpp"
30 #include "eng3d/string.hpp"
31 #include "eng3d/utils.hpp"
32 
33 Eng3D::TrueType::Font::Font(std::shared_ptr<Eng3D::IO::Asset::Base> asset, int dpi) {
34  this->sdl_font = static_cast<void*>(TTF_OpenFont(asset->get_abs_path().c_str(), dpi));
35  if(this->sdl_font == nullptr)
36  CXX_THROW(std::runtime_error, translate_format("Failed to load font %s", asset->get_abs_path().c_str()));
37 }
38 
40  if(this->sdl_font != nullptr)
41  TTF_CloseFont(static_cast<TTF_Font*>(this->sdl_font));
42 }
43 
45  : s{ _s }
46 {
47  if(TTF_Init() < 0)
48  CXX_THROW(std::runtime_error, translate_format("Failed to initialize TTF %s", TTF_GetError()));
49 }
50 
52  // It's important to first destroy all fonts then quite the TTF subsystem
53  // otherwise we will encounter some nasty sigsegvs
54  this->fonts.clear();
55  TTF_Quit();
56 }
57 
58 std::shared_ptr<Eng3D::TrueType::Font> Eng3D::TrueType::Manager::load(std::shared_ptr<Eng3D::IO::Asset::Base> asset) {
59  const std::string path = asset.get() != nullptr ? asset->get_abs_path() : "";
60  const auto it = this->fonts.find(path);
61  if(it != this->fonts.cend())
62  return it->second;
63 
64  auto font = std::make_shared<Eng3D::TrueType::Font>(asset, 16);
65  this->fonts[path] = font;
66  return this->fonts[path];
67 }
68 
std::shared_ptr< Eng3D::TrueType::Font > load(std::shared_ptr< Eng3D::IO::Asset::Base > asset)
Definition: ttf.cpp:58
std::string translate_format(const std::string_view format, Args &&... args)
String formatter, with translation.
Definition: string.hpp:128
#define CXX_THROW(class,...)
Definition: utils.hpp:98