SDL.cxx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "SDL.hxx"
  2. #include <cassert>
  3. #include <format>
  4. #include <SDL_image.h>
  5. #include <SDL_ttf.h>
  6. SDLError::SDLError(std::string_view const message, std::source_location location)
  7. :std::runtime_error{std::format(
  8. "{}:{}:{} - {} ({})",
  9. location.file_name(), location.line(), location.column(),
  10. message,
  11. SDL_GetError())}
  12. {
  13. }
  14. SDL* SDL::instance_ = nullptr;
  15. SDL::SDL(std::uint32_t const flags)
  16. {
  17. assert(instance_==nullptr);
  18. if (SDL_Init(flags)!=0) {
  19. throw SDLError{"Failed to initialize SDL."};
  20. }
  21. SDL_Log("Initialized SDL successfully.");
  22. auto const img_flags = IMG_INIT_PNG | IMG_INIT_JPG;
  23. if (IMG_Init(img_flags)!=img_flags) {
  24. throw SDLError{"Failed to initialize SDL_image."};
  25. }
  26. SDL_Log("Initialized SDL_image successfully.");
  27. if (TTF_Init()!=0) {
  28. throw SDLError{"Failed to initialize SDL_ttf."};
  29. }
  30. SDL_Log("Initialized SDL_ttf successfully.");
  31. instance_ = this;
  32. }
  33. SDL::~SDL() noexcept
  34. {
  35. assert(instance_!=nullptr);
  36. TTF_Quit();
  37. SDL_Log("Shut down SDL_ttf successfully.");
  38. IMG_Quit();
  39. SDL_Log("Shut down SDL_image successfully.");
  40. SDL_Quit();
  41. SDL_Log("Shut down SDL successfully.");
  42. instance_ = nullptr;
  43. }
  44. SDL& SDL::instance() noexcept
  45. {
  46. assert(instance_!=nullptr);
  47. return *instance_;
  48. }
  49. SDL& SDL::require(std::uint32_t const flags) noexcept
  50. {
  51. assert((SDL_WasInit(flags) | SDL_INIT_NOPARACHUTE)==(flags | SDL_INIT_NOPARACHUTE));
  52. return instance();
  53. }