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.h 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #pragma once
  2. #include <SDL2/SDL.h>
  3. #include <stdint.h>
  4. #include <string>
  5. #include <memory>
  6. #include <unordered_map>
  7. #include "common.h"
  8. namespace Swan {
  9. class ImageResource {
  10. public:
  11. struct Builder {
  12. std::string name;
  13. std::string path;
  14. int frame_height = -1;
  15. std::string modpath = "";
  16. };
  17. ImageResource(SDL_Renderer *renderer, const Builder &builder);
  18. ImageResource(
  19. SDL_Renderer *renderer, const std::string &name,
  20. int w, int h, uint8_t r, uint8_t g, uint8_t b);
  21. void tick(float dt);
  22. static std::unique_ptr<ImageResource> createInvalid(Win &win);
  23. std::unique_ptr<SDL_Surface, void (*)(SDL_Surface *)> surface_{nullptr, &SDL_FreeSurface};
  24. std::unique_ptr<SDL_Texture, void (*)(SDL_Texture *)> texture_{nullptr, &SDL_DestroyTexture};
  25. int frame_height_;
  26. int num_frames_;
  27. std::string name_;
  28. int frame_ = 0;
  29. private:
  30. float switch_interval_ = 1;
  31. float switch_timer_ = switch_interval_;
  32. };
  33. class ResourceManager {
  34. public:
  35. ResourceManager(Win &win);
  36. void tick(float dt);
  37. ImageResource &getImage(const std::string &name) const;
  38. void addImage(std::unique_ptr<ImageResource> img) { images_[img->name_] = std::move(img); }
  39. private:
  40. std::unordered_map<std::string, std::unique_ptr<ImageResource>> images_;
  41. };
  42. }