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.2KB

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