A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Resource.cc 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "Resource.h"
  2. #include <stdio.h>
  3. #include <SDL2/SDL_image.h>
  4. #include "log.h"
  5. #include "common.h"
  6. #include "Game.h"
  7. #include "Win.h"
  8. namespace Swan {
  9. ImageResource::ImageResource(
  10. SDL_Renderer *renderer, const std::string &name,
  11. const std::string &path, int frame_height) {
  12. surface_.reset(IMG_Load(path.c_str()));
  13. if (surface_ == nullptr) {
  14. warn << "Loading " << path << " failed: " << SDL_GetError();
  15. surface_.reset(SDL_CreateRGBSurface(
  16. 0, TILE_SIZE, TILE_SIZE, 32, 0, 0, 0, 0));
  17. SDL_FillRect(surface_.get(), NULL, SDL_MapRGB(surface_->format,
  18. PLACEHOLDER_RED, PLACEHOLDER_GREEN, PLACEHOLDER_BLUE));
  19. }
  20. if (frame_height < 0)
  21. frame_height = surface_->h;
  22. texture_.reset(SDL_CreateTexture(
  23. renderer, surface_->format->format, SDL_TEXTUREACCESS_STATIC,
  24. surface_->w, frame_height));
  25. frame_height_ = frame_height;
  26. num_frames_ = surface_->h / frame_height_;
  27. name_ = name;
  28. }
  29. ImageResource::ImageResource(
  30. SDL_Renderer *renderer, const std::string &name,
  31. int w, int h, uint8_t r, uint8_t g, uint8_t b) {
  32. surface_.reset(SDL_CreateRGBSurface(
  33. 0, TILE_SIZE, TILE_SIZE, 32, 0, 0, 0, 0));
  34. SDL_FillRect(surface_.get(), NULL, SDL_MapRGB(surface_->format, r, g, b));
  35. texture_.reset(SDL_CreateTexture(
  36. renderer, surface_->format->format, SDL_TEXTUREACCESS_STATIC, w, h));
  37. frame_height_ = h;
  38. num_frames_ = 1;
  39. name_ = name;
  40. }
  41. void ImageResource::tick(float dt) {
  42. switch_timer_ -= dt;
  43. if (switch_timer_ <= 0) {
  44. switch_timer_ += switch_interval_;
  45. frame_ += 1;
  46. if (frame_ >= num_frames_)
  47. frame_ = 0;
  48. }
  49. }
  50. std::unique_ptr<ImageResource> ImageResource::createInvalid(Win &win) {
  51. return std::make_unique<ImageResource>(
  52. win.renderer_, "@internal::invalid", TILE_SIZE, TILE_SIZE,
  53. PLACEHOLDER_RED, PLACEHOLDER_GREEN, PLACEHOLDER_BLUE);
  54. }
  55. ResourceManager::ResourceManager(Win &win) {
  56. invalid_image_ = ImageResource::createInvalid(win);
  57. }
  58. void ResourceManager::tick(float dt) {
  59. for (auto &[k, v]: images_) {
  60. v->tick(dt);
  61. }
  62. }
  63. ImageResource &ResourceManager::getImage(const std::string &name) const {
  64. auto it = images_.find(name);
  65. if (it == end(images_))
  66. return *invalid_image_;
  67. return *it->second;
  68. }
  69. }