diff --git a/MiniEngine_Event.cpp b/MiniEngine_Event.cpp index 16b8e29..4e874c5 100644 --- a/MiniEngine_Event.cpp +++ b/MiniEngine_Event.cpp @@ -19,3 +19,67 @@ int PushEvent(const Event& refEvent) { return SDL_PushEvent(const_cast(&refEvent)); } + + +Looper::Looper() +{ + _update=_running=true; +} +void Looper::add(decltype(Event::type) event_type,const std::function& event_callback) +{ + _evmap[event_type].push_back(event_callback); +} +void Looper::add(decltype(Event::type) event_type,const std::function& event_callback) +{ + _evmap[event_type].push_back([&](Looper& lp,Event& ev)->int{return event_callback(ev);}); +} +void Looper::add(decltype(Event::type) event_type,const std::function& event_callback) +{ + _evmap[event_type].push_back([&](Looper& lp,Event& ev)->int{event_callback(lp,ev); return 0;}); +} +void Looper::add(decltype(Event::type) event_type,const std::function& event_callback) +{ + _evmap[event_type].push_back([&](Looper& lp,Event& ev)->int{event_callback(ev); return 0;}); +} +void Looper::dispatch() +{ + for(auto callback:_evmap[_e.type]) + { + if(callback(*this,_e)) break; + } +} +void Looper::run() +{ + while(_running) + { + while(!_update&&WaitEvent(_e)) + { + dispatch(); + } + + _update=false; + } +} +Event Looper::GetLastEvent() +{ + return _e; +} +void Looper::needupdate() +{ + _update=true; +} +void Looper::needstop() +{ + _running=false; +} +void Looper::stop() +{ + needstop(); + needupdate(); +} +void Looper::reset() +{ + _running=true; + _update=true; + _evmap.clear(); +} diff --git a/MiniEngine_Event.h b/MiniEngine_Event.h index 8c92434..aa3a4f6 100644 --- a/MiniEngine_Event.h +++ b/MiniEngine_Event.h @@ -1,5 +1,7 @@ #pragma once #include "MiniEngine.h" +#include +#include typedef SDL_Event Event; @@ -7,3 +9,28 @@ int PollEvent(Event& refEvent); int WaitEvent(Event& refEvent); int WaitEventTimeout(Event& refEvent,int ms); int PushEvent(const Event& refEvent); + +class Looper +{ +public: + Looper(); + /// If Callback does not return 0, then stop transferring this event. + void add(decltype(Event::type) event_type,const std::function& event_callback); + /// If Callback does not return 0, then stop transferring this event. (Discards Looper) + void add(decltype(Event::type) event_type,const std::function& event_callback); + /// If Callback has no return (void), then we assume it return 0. + void add(decltype(Event::type) event_type,const std::function& event_callback); + /// If Callback has no return (void), then we assume it return 0. (Discards Looper) + void add(decltype(Event::type) event_type,const std::function& event_callback); + void dispatch(); + void run(); + Event GetLastEvent(); + void needupdate(); + void needstop(); + void stop(); + void reset(); +private: + Event _e; + bool _running,_update; + std::map>> _evmap; +};