AssetStore.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * 2D Game Engine
  3. * AssetStore.cpp:
  4. * Based on pikuma.com 2D game engine in C++ and Lua course
  5. * Copyright (c) 2021 986-Studio. All rights reserved.
  6. *
  7. * Created by Manoël Trapier on 12/02/2021.
  8. */
  9. #include <SDL.h>
  10. #include <SDL_image.h>
  11. #include <SDL_ttf.h>
  12. #include <Logger.h>
  13. #include <AssetStore.h>
  14. void AssetStore::clearStore()
  15. {
  16. for(auto texture: this->textures)
  17. {
  18. SDL_DestroyTexture(texture.second);
  19. }
  20. this->textures.clear();
  21. for(auto font: this->fonts)
  22. {
  23. TTF_CloseFont(font.second);
  24. }
  25. this->fonts.clear();
  26. }
  27. void AssetStore::addTexture(SDL_Renderer *renderer, const std::string &assetId, const std::string &filePath)
  28. {
  29. SDL_Surface *surface = IMG_Load(filePath.c_str());
  30. if (!surface)
  31. {
  32. Logger::Error("Error opening texture '%s' (path: '%s')", assetId.c_str(), filePath.c_str());
  33. return;
  34. }
  35. SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surface);
  36. SDL_FreeSurface(surface);
  37. Logger::Info("New texture added to the Asset Store id=%s", assetId.c_str());
  38. this->textures.emplace(assetId, texture);
  39. }
  40. SDL_Texture *AssetStore::getTexture(const std::string &assetId)
  41. {
  42. if (!this->textures[assetId])
  43. {
  44. Logger::Warning("Asset texture '%s' requested but can't be found.", assetId.c_str());
  45. }
  46. return this->textures[assetId];
  47. }
  48. void AssetStore::addFont(const std::string &assetId, const std::string &filePath, uint32_t fontSize)
  49. {
  50. TTF_Font *font = TTF_OpenFont(filePath.c_str(), fontSize);
  51. if (!font)
  52. {
  53. Logger::Error("Error opening font '%s' (path: '%s') Error: %d", assetId.c_str(), filePath.c_str(), TTF_GetError);
  54. return;
  55. }
  56. Logger::Info("New font added to the Asset Store id=%s (size: %d)", assetId.c_str(), fontSize);
  57. this->fonts.emplace(assetId, font);
  58. }
  59. TTF_Font *AssetStore::getFont(const std::string &assetId)
  60. {
  61. if (!this->fonts[assetId])
  62. {
  63. Logger::Warning("Asset font '%s' requested but can't be found.", assetId.c_str());
  64. }
  65. return this->fonts[assetId];
  66. }