spacebox/src/Delegate.hpp

83 lines
2.4 KiB
C++

/* +------------------------------------------------------+
____/ \____ /| - Open source game framework licensed to freely use, |
\ / / | copy, modify and sell without restriction |
+--\ ^__^ /--+ | |
| ~/ \~ | | - created for <https://foam.shampoo.ooo> |
| ~~~~~~~~~~~~ | +------------------------------------------------------+
| SPACE ~~~~~ | /
| ~~~~~~~ BOX |/
+-------------*/
#pragma once
#include <string>
#include <map>
#include <list>
#include <functional>
#include <typeinfo>
#include <typeindex>
#include "SDL.h"
#include "Node.hpp"
namespace sb
{
struct Subscriber
{
std::function<void(SDL_Event&)> f;
Node* o;
};
class Delegate : public Node
{
private:
std::map<std::uint32_t, std::vector<Subscriber>> subscribers;
bool cancelling_propagation = false;
public:
inline static std::uint32_t command_event_type = SDL_RegisterEvents(1);
Delegate(Node*);
void add_subscriber(Subscriber, std::uint32_t);
void dispatch();
static bool compare(SDL_Event&, const std::vector<std::string>&, bool = false, bool = false);
static bool compare(SDL_Event&, const std::string& = "", bool = false, bool = false);
static bool compare_cancel(SDL_Event&, const std::string& = "");
static bool compare_neutral(SDL_Event&, const std::string& = "");
void cancel_propagation();
static const std::string& get_event_command(SDL_Event&);
static bool get_event_cancel_state(SDL_Event&);
template<typename T>
void subscribe(void(T::*f)(SDL_Event&), T* o, std::uint32_t type = command_event_type)
{
add_subscriber({std::bind(f, o, std::placeholders::_1), static_cast<Node*>(o)}, type);
}
template<typename T>
void unsubscribe(T* p)
{
for (auto t = subscribers.begin(); t != subscribers.end(); t++)
{
for (auto s = t->second.begin(); s != t->second.end();)
{
if (p == s->o)
{
s = t->second.erase(s);
}
else
{
s++;
}
}
}
}
};
}
#include "Input.hpp"
#include "Game.hpp"