Event system for cpp
- User
Event system for cpp
- Assistant
An event system for C++ allows communication between objects, enabling them to send (publish, emit) and receive (subscribe, listen) messages or notifications about certain events or actions that occur during the program's runtime.
Here's a simple example of an event system in C++. This implementation uses the Observer pattern to handle event subscriptions and notifications:
- Define the base EventListener class:
class EventListener { public: virtual ~EventListener() {} virtual void OnEvent() = 0; }; - User
- Assistant
- User
It says '=' cannot convert from 'EventBus *' to 'EventBus<Position, Velocity> *'class ECS; template<class... Cs> class System : public SystemBase { public:
friend class ECS; typedef std::function<void(const std::uint32_t, const std::vector<uint32_t>&, Cs*...)> Func; System(ECS& ecs, const std::uint8_t& layer); //template <typename EventT, typename... Args> //void CreateEvent(const std::vector<uint32_t>& entityIds, Args&&... args); virtual ComponentMask GetComponentMask() const override; void Action(Func func); template <typename... EventTypes> void RegisterEventBus(EventBus<EventTypes...>& eventBus) { eventBus_ = &eventBus; } - Assistant
Apologies for the confusion in my previous response. I did not include the
EventTypestemplate parameter inside the System class itself, which is causing the error. Let me correct that for you:- Add
EventTypes...as a template parameter to the System class:
template <class... Cs, class... EventTypes> class System : public SystemBase { public: //... template <typename... Ets> void RegisterEventBus(EventBus<Ets...>& eventBus) { eventBus_ = &eventBus; } protected: EventBus<EventTypes...>* eventBus_; //... };- Adjust the implementation of the System's constructor to include
EventTypes...:
template<class... Cs, class... EventTypes> System<Cs..., EventTypes...>::System(ECS& ecs, const std::uint8_t& layer) : ecs_(ecs), funcStatus_(false), eventBus_(nullptr) { // Original implementation } - Add
- User
But can you have two variadic template parameters for system?
- Assistant
You're correct that I made a mistake in my previous response. The initial implementation used a single variadic template in the
Systemclass; however, I introduced another variadic template parameter, which is incorrect. For this corrected implementation, let's use theEventBusinside theECSclass instead of integrating it into theSystemclass.- Modify the
ECSclass to include theEventBus:
template <typename... EventTypes> class ECS { public: // ... EventBus<EventTypes...>& GetEventBus() { return eventBus_; } private: // ... EventBus<EventTypes...> eventBus_; };- Modify the
Systemclass to only take one variadic template parameter as originally designed (remove the extra parameter that I previously added):
- Modify the
- User
Can you integrate it into the system class?
- Assistant
- User
- Assistant
Yes, this implementation should work as expected now that the callback registration and event dispatching are fully integrated into the
Systemclass. Just to clarify, I've updated your code to fix a small compilation error you might face:- Inside , change to .
- User
It says the '(' and ')' was unexpected using EventTypePointer = void()(const EventType&);
- Assistant
My apologies, I made an error in the code I provided. The
using EventTypePointerline is unnecessary and should be removed. Please update theRegisterCallbackmethod like this:template <typename EventType> void RegisterCallback(std::function<void(const EventType&)> callback) { auto wrapper = [callback](const Event* eventPtr) { callback(static_cast<const EventType&>(*eventPtr)); }; callbacks_[&typeid(EventType)] = wrapper; }Now the code should work without any errors. The
using EventTypePointerline was a typo and should not have been included in the method. The fixed version of theRegisterCallbackmethod simply stores a lambda function that wraps the given callback and casts the baseEventpointer to the specific event type. - User
- Assistant
Your implementation in your
Systemclass code looks correct in registering and dispatching events. However, there is a small mistake in how you dispatch the event. When dispatching the event, thewrapperfunction is being called with a type not matching the expected type. The wrapper function is expecting anconst Event*instead ofconst EventType&. We can fix this by updating theDispatchEventmethod:template <typename EventType> void DispatchEvent(const EventType& event) { auto it = callbacks_.find(typeid(EventType)); if (it != callbacks_.end()) { it->second(&event); } }With this change, the method should work correctly.
- User
Can you give an example of a movementsystem that sends out an event when an entity's x-position is greater than 500, to be received by a collisionsystem, adapted from my implementation of system.
- Assistant
- User
std::function Movement([&syst](const std::uint32_t elapsedMilliseconds, const std::vector<uint32_t>& entities, Position* p, Velocity* v ) { for (std::size_t i = 0, j = 1; i < entities.size(); ++i, ++j) { std::cout << i << " Entity-----------------\n" << "p: (" << p[i].x << ", " << p[i].y << ")\n" << std::endl; p[i].x += v[i].vel; p[i].y += v[i].vel; std::cout << i << " Entity-----------------\n" << "p: (" << p[i].x << ", " << p[i].y << ")\n" << std::endl;
if (p[i].x > 500) { EntityOutOfBoundsEvent event{ entities[i], p[i].x }; DispatchEvent(event); } } }); How can you make this work when the scene::init function calls it and sets the action to a created system? - Assistant
Instead of defining the movement logic inside the
Scene::initfunction, we can move this functionality into ourMovementSystemclass that was previously created. This way, the system holds its own update logic, improving the organization of the code. You can instantiate this system in theScene::initfunction and register it with the ECS.Here's how to define the
MovementSystemusing the provided logic:class MovementSystem : public System<Position, Velocity> { public: MovementSystem(ECS& ecs, uint8_t layer) : System<Position, Velocity>(ecs, layer) { Action([this](const std::uint32