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

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