#include "widgets.h" #include "util.h" #include #include #include Widget::Widget(SDL_Renderer* renderer, SDL_Rect rect) : renderer{renderer}, dest_rect{rect} {} void Widget::update_rect(SDL_Rect new_rect) { dest_rect = new_rect; } TextureWidget::TextureWidget(SDL_Renderer* renderer, SDL_Rect dest_rect, std::optional texture) : Widget{renderer, dest_rect}, texture{texture} {} TextureWidget::~TextureWidget() { if (texture) { SDL_DestroyTexture(*texture); texture = nullptr; } } void TextureWidget::draw() { if (texture) { SDL_RenderCopy(renderer, *texture, NULL, &dest_rect); } } void TextureWidget::update_texture(SDL_Texture* new_texture) { if (texture) { SDL_DestroyTexture(*texture); } texture = new_texture; } ImageWidget::ImageWidget(SDL_Renderer* renderer, SDL_Rect dest_rect, const std::string& path) : TextureWidget{renderer, dest_rect, util::load_img(renderer, path)} {} TextWidget::TextWidget(SDL_Renderer* renderer, SDL_Rect dest_rect, const std::string& font_path, const std::string& initial_text) : TextureWidget{renderer, dest_rect, std::nullopt}, font{util::load_font(font_path, 28)}, text{initial_text} { if (text != "") { update_texture(generate_text(text)); } } TextWidget::~TextWidget() { TTF_CloseFont(font); } void TextWidget::update_text(const std::string& new_text) { if (text != new_text) { update_texture(generate_text(new_text)); text = new_text; } } SDL_Texture* TextWidget::generate_text(const std::string& text) { SDL_Surface* surf = TTF_RenderText_Solid(font, text.c_str(), {0xFF, 0xFF, 0XFF, 0xFF}); if (surf == nullptr) { throw std::runtime_error( fmt::format("Unable to render text surface: {}", TTF_GetError())); } SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surf); if (texture == nullptr) { throw std::runtime_error(fmt::format( "Unable to create texture from text surface: {}", SDL_GetError())); } return texture; }