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.

Mod.h 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #pragma once
  2. #include <stdint.h>
  3. #include <string>
  4. #include <vector>
  5. #include <memory>
  6. #include <type_traits>
  7. #include <SDL.h>
  8. #include "Tile.h"
  9. #include "Item.h"
  10. #include "WorldGen.h"
  11. #include "Entity.h"
  12. #include "Collection.h"
  13. #include "Resource.h"
  14. #include "OS.h"
  15. #include "util.h"
  16. namespace Swan {
  17. class Mod {
  18. public:
  19. Mod(std::string name): name_(std::move(name)) {}
  20. virtual ~Mod() = default;
  21. void registerTile(Tile::Builder tile);
  22. void registerItem(Item::Builder item);
  23. void registerWorldGen(std::string name, std::unique_ptr<WorldGen::Factory> gen);
  24. void registerSprite(std::string sprite);
  25. template<typename WG>
  26. void registerWorldGen(std::string name) {
  27. worldGens_.push_back(WorldGen::Factory{
  28. .name = name_ + "::" + name,
  29. .create = [](World &world) -> std::unique_ptr<WorldGen> {
  30. return std::make_unique<WG>(world);
  31. }
  32. });
  33. }
  34. template<typename Ent>
  35. void registerEntity(const std::string &name) {
  36. static_assert(
  37. std::is_move_constructible_v<Ent>,
  38. "Entities must be movable");
  39. entities_.push_back(EntityCollection::Factory{
  40. .name = name_ + "::" + name,
  41. .create = [](std::string name) -> std::unique_ptr<EntityCollection> {
  42. return std::make_unique<EntityCollectionImpl<Ent>>(std::move(name));
  43. }
  44. });
  45. }
  46. const std::string name_;
  47. std::vector<std::string> images_;
  48. std::vector<Tile::Builder> tiles_;
  49. std::vector<Item::Builder> items_;
  50. std::vector<std::string> sprites_;
  51. std::vector<WorldGen::Factory> worldGens_;
  52. std::vector<EntityCollection::Factory> entities_;
  53. };
  54. class ModWrapper {
  55. public:
  56. ModWrapper(std::unique_ptr<Mod> mod, std::string path, OS::Dynlib lib):
  57. mod_(std::move(mod)), path_(std::move(path)), dynlib_(std::move(lib)) {}
  58. ModWrapper(ModWrapper &&other) noexcept = default;
  59. ~ModWrapper() {
  60. // Mod::~Mod will destroy stuff allocated by the dynlib,
  61. // so we must run its destructor before deleting the dynlib
  62. mod_.reset();
  63. }
  64. std::unique_ptr<Mod> mod_;
  65. std::string path_;
  66. OS::Dynlib dynlib_;
  67. };
  68. }