SDL.cxx 1.7 KB

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