EntityOutOfBoundsEvent event{ entities[i], p[i].x }; Says no instance of constructor…
- User
EntityOutOfBoundsEvent event{ entities[i], p[i].x }; Says no instance of constructor matches argument list struct Event { virtual ~Event() {} };struct EntityOutOfBoundsEvent : public Event { std::uint32_t entityId; float xPosition; };
- Assistant
The code provided has an issue in the construction of an
EntityOutOfBoundsEvent. The structEntityOutOfBoundsEventhas two member data:entityId(of typestd::uint32_t) andxPosition(of typefloat). When constructing an object of this type, you need to match the data types of the member data in the struct definition. It seems that you're trying to construct an object ofEntityOutOfBoundsEvent, so you need to provide values forentityIdandxPosition.Here's the corrected version of the object construction:
EntityOutOfBoundsEvent event{entities[i].id, p[i].x};Please modify the line that constructs the event object, as shown above. Don't forget to update the
entitiesstruct or class with anidmember if it doesn't have one. - User
Can you finish up this? I want the systCol to have a function that receives a EntityOutOfBounds Event 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); virtual ComponentMask GetComponentMask() const override; void Action(Func func); 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; } template <typename EventType> void DispatchEvent(const EventType& event) { auto it = callbacks_.find(typeid(EventType)); if (it != callbacks_.end()) { it->second(&event); } }protected:
template<std::size_t Index1, typename T, typename... Ts> std::enable_if_t<Index1 == sizeof...(Cs)> Update(const std::uint32_t elapsedMilliseconds, const ComponentMask& componentMask, const std::vector<uint32_t>& entityIds, T& t, Ts... ts); template<std::size_t Index1, typename T, typename... Ts> std::enable_if_t<Index1 != sizeof...(Cs)> Update(const std::uint32_t elapsedMilliseconds, const ComponentMask& componentMask, const std::vector<uint32_t>& entityIds, T& t, Ts... ts); virtual void Update(const std::uint32_t elapsedMilliseconds, Archetype* archetype) override; ECS& ecs_; ComponentMask componentMask_; Func func_; bool funcStatus_; std::unordered_map<std::type_index, std::function<void(const Event*)>> callbacks_;}; void Scene::init() { entityComponentSystem.RegisterComponent(); entityComponentSystem.RegisterComponent(); entityComponentSystem.RegisterComponent(); entityComponentSystem.RegisterComponent();
Entity entity1(entityComponentSystem); entity1.AddComponent<Size>({ 50,50 }); entity1.AddComponent<Position>({25, 25}); entity1.AddComponent<Name>({"fakw"}); entity1.AddComponent<Velocity>({ 25 }); Entity entity2(entityComponentSystem); entity2.AddComponent<Size>({ 29,20 }); entity2.AddComponent<Position>({ 25, 25 }); entity2.AddComponent<Name>({"Test"}); entity2.AddComponent<Velocity>({ 25555 }); CreateSystem<Position, Velocity>(entityComponentSystem, 0); CreateSystem<Position, Velocity>(entityComponentSystem, 1); auto syst = FindSystem<Position, Velocity>(0); auto systCol = FindSystem<Position, Velocity>(1); std::function Collision([&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) { } }); SetAction<Position, Velocity>(&Movement, 0);}
- Assistant
Here's the modified code with a new
Collisionfunction that receives anEntityOutOfBoundsEvent. TheCollisionfunction now checks for out-of-bounds entities and dispatches the events accordingly:void Scene::init() { entityComponentSystem.RegisterComponent<Position>(); entityComponentSystem.RegisterComponent<Name>(); entityComponentSystem.RegisterComponent<Size>(); entityComponentSystem.RegisterComponent<Velocity>(); Entity entity1(entityComponentSystem); entity1.AddComponent<Size>({50, 50}); entity1.AddComponent<Position>({25, 25}); entity1.AddComponent<Name>({"fakw"}); entity1.AddComponent<Velocity>({25}); Entity entity2(entityComponentSystem); entity2.AddComponent<Size>({29, 20}); entity2.AddComponent<Position>({25, 25}); entity2.AddComponent<Name>({"Test"}); entity2.AddComponent<Velocity>({25555}); CreateSystem<Position, Velocity>(entityComponentSystem, 0); CreateSystem<Position, Velocity>(entityComponentSystem, 1); auto syst = FindSystem<Position, Velocity>(0); auto systCol = FindSystem<Position, Velocity>(1); std::function Collision([&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) { if (p[i].x < 0 || p[i].y < 0) { EntityOutOfBoundsEvent event{entities[i], p[i].x}; systCol->DispatchEvent(event); } } }); SetAction<Position, Velocity>(&Movement, 0); systCol->RegisterCallback<EntityOutOfBoundsEvent>([](const EntityOutOfBoundsEvent &event) { std::cout << "Entity " << event.entityId << " is out of bounds at x position " << event.xPosition << std::endl; }); systCol->Action(Collision); }Ensure that you have included the
<iostream>header for thestd::coutfunctionality. In this example, I assume that the providedstd::vector<uint32_t> &entitiescontains the entity ids instead ofEntityobjects. If it containsEntityobjects, you need to change the construction of theEntityOutOfBoundsEventaccordingly.Please review the modified code and let me know if it meets your requirements.
- User
Can you implement a data-driven event bus for this implementation? Assume the declared functions are already defined. #pragma once
class SystemBase; class ECS { private:
typedef std::unordered_map<std::uint8_t, std::vector<SystemBase*>> SystemsArrayMap; typedef std::unordered_map<size_t, ComponentBase*> ComponentTypeIdBaseMap; struct Record { Archetype* archetype; size_t index; }; typedef std::unordered_map<size_t, Record> EntityArchetypeMap; typedef std::vector<Archetype*> ArchetypesArray; typedef std::unordered_map<size_t, ComponentMask> ComponentMasks;public: explicit ECS();
~ECS(); void Update(const std::uint8_t layer, const std::uint32_t delta); void RegisterEntity(const uint32_t entityId); void DestroyEntity(const std::uint32_t entityId); template <class C> void RegisterComponent(); template<class C, typename... Args> C* AddComponent(const uint32_t entityId, Args&&... args); template<class C> void RemoveComponent(const uint32_t entityId); template<class C> C* GetComponent(const uint32_t entityId); void RegisterSystem(const std::uint8_t& layer, SystemBase* system); void UnregisterSystem(const std::uint8_t& layer, SystemBase* system);private: std::uint32_t entityIdCounter;
SystemsArrayMap systems; EntityArchetypeMap entityArchetypeMap; EventBus eventBus_; ArchetypesArray archetypes; ComponentMasks componentMasks; ComponentTypeIdBaseMap componentMap;};
class SystemBase { public: virtual ~SystemBase() {}
virtual ComponentMask GetComponentMask() const = 0; virtual void Update(const std::uint32_t elapsedTime, Archetype* archetype) = 0;};
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); virtual ComponentMask GetComponentMask() const override; void Action(Func func);protected:
template<std::size_t Index1, typename T, typename... Ts> std::enable_if_t<Index1 == sizeof...(Cs)> Update(const std::uint32_t elapsedMilliseconds, const ComponentMask& componentMask, const std::vector<uint32_t>& entityIds, T& t, Ts... ts); template<std::size_t Index1, typename T, typename... Ts> std::enable_if_t<Index1 != sizeof...(Cs)> Update(const std::uint32_t elapsedMilliseconds, const ComponentMask& componentMask, const std::vector<uint32_t>& entityIds, T& t, Ts... ts); virtual void Update(const std::uint32_t elapsedMilliseconds, Archetype* archetype) override; ECS& ecs_; ComponentMask componentMask_; Func func_; bool funcStatus_;};
template<class... Cs> System<Cs...>::System(ECS& ecs, const std::uint8_t& layer) : ecs_(ecs), funcStatus_(false) { ecs_.RegisterSystem(layer, this); ecs_.GetEventBus().Subscribe(std::bind(&this::OnEntitySpawn, this, std::placeholders::1)); ((componentMask.AddComponent(GetTypeID())), ...); //callbacks_ = std::unordered_map<std::type_index, std::function<void(const Event*)>>(); }
template<class... Cs> ComponentMask System<Cs...>::GetComponentMask() const { return componentMask_; }
template<class... Cs> void System<Cs...>::Action(Func func) { func_ = func; funcStatus_ = true; }
template<class... Cs> void System<Cs...>::Update(const std::uint32_t elapsedMilliseconds, Archetype* archetype) { if (funcStatus_) Update<0>(elapsedMilliseconds, archetype->componentMask, archetype->entityIds, archetype->componentData); }
template<class... Cs> template<std::size_t Index, typename T, typename... Ts> std::enable_if_t<Index != sizeof...(Cs)> System<Cs...>::Update(const std::uint32_t elapsedMilliseconds, const ComponentMask& componentMask, const std::vector<uint32_t>& entityIds, T& t, Ts... ts) { using ComponentType = typename std::tuple_element<Index, std::tuple<Cs...>>::type; std::size_t thisTypeCS = Component::GetTypeID();
std::size_t index2 = 0; for (int i = 0; i < thisTypeCS; i++) { if (componentMask.HasComponent(i)) { index2++; } } Update<Index + 1>(elapsedMilliseconds, componentMask, entityIds, t, ts..., reinterpret_cast<ComponentType*>(&t[index2][0]));}
template<class... Cs> template<std::size_t Index, typename T, typename... Ts> std::enable_if_t<Index == sizeof...(Cs)> System<Cs...>::Update(const std::uint32_t elapsedMilliseconds, const ComponentMask& componentMask, const std::vector<uint32_t>& entityIds, T& t, Ts... ts) { func_(elapsedMilliseconds, entityIds, ts...); }
- Assistant
To implement a data-driven event bus, we need an
EventBusclass that can handle events and store subscribers' callbacks. I've added theEventBusclass to the provided code, along with the necessary methods for subscribing, unsubscribing, and dispatching events in theECSclass.Here's the modified code with the
EventBusimplementation:#pragma once #include <unordered_map> #include <vector> #include <cstdint> #include <typeindex> #include <functional> #include <array> class Event { public: virtual ~Event() {} }; class EventBus { public: template <typename EventType> void Subscribe(std::function<void(const EventType &)> callback) { auto wrapper = [callback](const Event *eventPtr) { callback(static_cast<const EventType &>(*eventPtr)); }; callbacks_[typeid(EventType)].push_back(wrapper); } template <typename EventType> void Unsubscribe() { callbacks_.erase(typeid(EventType)); } template <typename EventType> void Dispatch(const EventType &event) { auto it = callbacks_.find(typeid(EventType)); if (it != callbacks_.end()) { for (auto &callback : it->second) { callback(&event); } } } private: std::unordered_map<std::type_index, std::vector<std::function<void(const Event *)>>> callbacks_; }; class ECS { // ... (rest of ECS implementation, unchanged) public: EventBus &GetEventBus() { return eventBus_; } private: EventBus eventBus_; }; // ... (rest of the code, unchanged)Now you can add and remove component event handlers in systems as follows:
class ExampleEvent : public Event { public: // Event data and methods }; // In System's init() or constructor, subscribe to events: ecs_.GetEventBus().Subscribe<ExampleEvent>([this](const ExampleEvent &event) { // Event handling code }); // Unsubscribe from an event: ecs_.GetEventBus().Unsubscribe<ExampleEvent>();You can also dispatch events from the ECS class or any system that has access to the event bus:
ExampleEvent event; ecs_.GetEventBus().Dispatch(event);The new
EventBusimplementation should satisfy the requirement for a data-driven event bus in your original implementation. - User
#pragma once
#include #include <unordered_map> #include <unordered_set> #include #include #include
#include "System.h" #include "Archetype.h" #include "EventBus.h" #include "ComponentMask.h"
typedef std::vector ArchetypeId;
class SystemBase; class ECS { private:
typedef std::unordered_map<std::uint8_t, std::vector<SystemBase*>> SystemsArrayMap; typedef std::unordered_map<size_t, ComponentBase*> ComponentTypeIdBaseMap; struct Record { Archetype* archetype; size_t index; }; typedef std::unordered_map<size_t, Record> EntityArchetypeMap; typedef std::vector<Archetype*> ArchetypesArray; typedef std::unordered_map<size_t, ComponentMask> ComponentMasks;public: explicit ECS();
~ECS(); template<typename EventType> void Subscribe(std::function<void(const EventType&)> callback) { eventBus_.Subscribe<EventType>(callback); } template <typename EventType> void Unsubscribe(const EventBus::Callback<EventType>& callback) { eventBus_.Unsubscribe<EventType>(callback); } // Publish events template <typename EventType> void Publish(const EventType& event) { eventBus_.Dispatch<EventType>(event); } void Update(const std::uint8_t layer, const std::uint32_t delta); void RegisterEntity(const uint32_t entityId); void DestroyEntity(const std::uint32_t entityId); template <class C> void RegisterComponent(); template <class C> const bool IsComponentRegistered() const; template<class C, typename... Args> C* AddComponent(const uint32_t entityId, Args&&... args); template<class C> void RemoveComponent(const uint32_t entityId); template<class C> C* GetComponent(const uint32_t entityId); const bool HasComponent(const uint32_t entityId, size_t compTypeId) const; template<class C> size_t GetComponentTypeId(); template<class C> const bool HasComponent(const uint32_t entityId); void RegisterSystem(const std::uint8_t& layer, SystemBase* system); void UnregisterSystem(const std::uint8_t& layer, SystemBase* system); template<class... Cs> std::vector<size_t> GetEntitiesWithComponents(); Archetype* GetArchetype(const ComponentMask& componentMask); std::uint32_t GetNewId(); EventBus& GetEventBus() { return eventBus_; }private: EventBus eventBus_;
std::uint32_t entityIdCounter; SystemsArrayMap systems; EntityArchetypeMap entityArchetypeMap; ArchetypesArray archetypes; ComponentMasks componentMasks; ComponentTypeIdBaseMap componentMap; template<class C, typename... Args> C* TransferComponentsAndAdd(const uint32_t entityId, Archetype* newArchetype, Archetype* oldArchetype, Args&&... args); template<class C> void TransferComponentsAndRemove(size_t entityIndex, Archetype* oldArchetype, Archetype* newArchetype); size_t GetEntityIndex(const Archetype* archetype, uint32_t entityId); void UpdateRecord(uint32_t entityId, Archetype* archetype, Record& record); void UpdateEntitiesInArchetypes(Archetype* oldArchetype, Archetype* newArchetype, uint32_t entityId); size_t FindCurrentSize(Archetype* archetype, size_t ComponentTypeIndex, size_t index); void Reallocate(const size_t newComponentDataSize, Archetype* archetype, size_t index); void MoveComponentData(const ComponentBase* componentBase, Archetype* fromArch, Archetype* toArch, size_t fromIndex, size_t toIndex, size_t fromEntityIndex, size_t toEntityIndex); void TransferComponentData(const size_t compTypeIndex, Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex); void SwapComponentData(const size_t compTypeIndex, Archetype* arch, size_t index, size_t entityIndex); void RemoveAndAllocateComponentData(const size_t compTypeIndex, Archetype* fromArchetype, Archetype* toArchetype, size_t i, size_t j, size_t entityIndex);};
template void ECS::RegisterComponent() { size_t componentTypeId = Component::GetTypeID();
if (componentMap.contains(componentTypeId)) return; // can't re-register a type componentMap.emplace(componentTypeId, new Component<C>);};
template const bool ECS::IsComponentRegistered() const { size_t componentTypeId = Component::GetTypeID(); return (componentMap.contains(componentTypeId)); }
template<class C, typename... Args> C* ECS::AddComponent(const uint32_t entityId, Args&&... args) { // 1. Get the component type ID and check if the component already exists for the entity auto newComponentID = GetTypeID();
if (HasComponent(entityId, newComponentID)) { return nullptr; } // 2. Update the component mask for the entity and get the new archetype componentMasks[entityId].AddComponent(newComponentID); Archetype* newArchetype = GetArchetype(componentMasks[entityId]); // 3. Get and store the record of the entity Record& record = entityArchetypeMap[entityId]; Archetype* oldArchetype = record.archetype; C* newComponent = nullptr; // 4. If the entity has existing components, transfer or add the new component if (oldArchetype) { newComponent = TransferComponentsAndAdd<C>(entityId, newArchetype, oldArchetype, C(std::forward<Args>(args)...)); } // 5. If the entity has no existing components, allocate and add the new component else { size_t currentSize = FindCurrentSize(newArchetype, newComponentID, 0); newComponent = new (&newArchetype->componentData[0][currentSize]) C(std::forward<Args>(args)...); //newComponent = AllocateAndAddComponent<C>(newArchetype, std::forward<Args>(args)...); } // 6. Update the record and return the new component UpdateRecord(entityId, newArchetype, record); return newComponent;}
template void ECS::RemoveComponent(const uint32_t entityId) { auto componentID = GetTypeID();
if (!IsComponentRegistered<C>() || !HasComponent(entityId, componentID)) { return; } componentMasks[entityId].RemoveComponent(componentID); Record& record = entityArchetypeMap[entityId]; Archetype* oldArchetype = record.archetype; if (!oldArchetype) { return; } Archetype* newArchetype = GetArchetype(componentMasks[entityId]); size_t entityIndex = GetEntityIndex(oldArchetype, entityId); TransferComponentsAndRemove<C>(entityIndex, oldArchetype, newArchetype); UpdateRecord(entityId, newArchetype, record);}
template C* ECS::GetComponent(const uint32_t entityId) { size_t componentTypeId = Component::GetTypeID();
if (!HasComponent(entityId, componentTypeId)) { return nullptr; // Component doesn't exist for the entity } const Archetype* archetype = entityArchetypeMap[entityId].archetype; if (!archetype) { return nullptr; // Archetype doesn't exist for the entity } size_t componentIndex = archetype->componentMask.ReturnArchetypeIndex(componentTypeId); auto entityIterator = std::find( archetype->entityIds.begin(), archetype->entityIds.end(), entityId ); if (entityIterator == archetype->entityIds.end()) { return nullptr; } size_t entityIndex = entityIterator - archetype->entityIds.begin(); size_t componentSize = componentMap[componentTypeId]->GetSize(); C* component = reinterpret_cast<C*>(&archetype->componentData[componentIndex][entityIndex * componentSize]); return component;}
template size_t ECS::GetComponentTypeId() { auto newComponentId = Component::GetTypeID(); return newComponentId; }
template const bool ECS::HasComponent(const uint32_t entityId) { return (componentMasks[entityId]).HasComponent(Component::GetTypeID()); }
template<class... Cs> std::vector<size_t> ECS::GetEntitiesWithComponents() { std::vector<size_t> entities;
ComponentMask mask; ((mask.AddComponent(Component<Cs>::GetTypeID())), ...); for (const auto& [entityId, record] : entityArchetypeMap) { const Archetype* archetype = record.archetype; if (!archetype) { continue; } const ComponentMask& entityMask = componentMasks[entityId]; if (mask.IsSubsetOf(entityMask)) { entities.push_back(entityId); } } return entities;}
template<class C, typename... Args> C* ECS::TransferComponentsAndAdd(const uint32_t entityId, Archetype* newArchetype, Archetype* oldArchetype, Args&&... args) { auto newComponentMask = newArchetype->componentMask; auto oldComponentMask = oldArchetype->componentMask; C* newComponent = nullptr;
size_t entityIndex = GetEntityIndex(oldArchetype, entityId); for (size_t i = 0, fromIndex = 0, toIndex = 0; i < newComponentMask.Size() - 1; ++i) { if (newComponentMask.HasComponent(i)) { size_t currentSize = FindCurrentSize(newArchetype, i, toIndex); if (oldComponentMask.HasComponent(i)) { TransferComponentData(i, oldArchetype, newArchetype, fromIndex, toIndex, entityIndex); ++fromIndex; } else { newComponent = new (&newArchetype->componentData[toIndex][currentSize]) C(std::forward<Args>(args)...); } toIndex++; } } UpdateEntitiesInArchetypes(oldArchetype, newArchetype, entityId); return newComponent;}
template void ECS::TransferComponentsAndRemove(size_t entityIndex, Archetype* oldArchetype, Archetype* newArchetype) { auto oldComponentMask = oldArchetype->componentMask; auto newComponentMask = newArchetype->componentMask;
for (size_t i = 0, fromIndex = 0, toIndex = 0; i < oldComponentMask.Size(); ++i) { if (oldComponentMask.HasComponent(i)) { if (newComponentMask.HasComponent(i)) { RemoveAndAllocateComponentData(i, oldArchetype, newArchetype, fromIndex, toIndex, entityIndex); toIndex++; } else { SwapComponentData(i, oldArchetype, toIndex, entityIndex); } fromIndex++; } } std::iter_swap(oldArchetype->entityIds.begin() + entityIndex, oldArchetype->entityIds.end() - 1); oldArchetype->entityIds.pop_back();} How would you change this so that individual systems will be able to subscribe to events?
- Assistant
To have individual systems to subscribe to events, simply add methods to subscribe, unsubscribe, and dispatch events to the
Systemclass rather than theECSclass. The methods added to theSystemclass will use the event bus in theECSclass, ensuring seamless communication between the systems and event bus.Here's the modified code with the required changes:
class SystemBase { public: // ... (rest of SystemBase) template <typename EventType> void Subscribe(std::function<void(const EventType&)> callback) { ecs_.GetEventBus().Subscribe<EventType>(callback); } template <typename EventType> void Unsubscribe() { ecs_.GetEventBus().Unsubscribe<EventType>(); } template <typename EventType> void Publish(const EventType& event) { ecs_.GetEventBus().Dispatch<EventType>(event); } protected: ECS& ecs_; }; class ECS { // ... (rest of ECS) template<typename EventType> friend class System; // Add this line private: //... (rest of the code) };Now, you can call subscribe, unsubscribe, and publish methods directly from the systems:
class ExampleSystem : public System<ExampleComponent> { public: ExampleSystem(ECS& ecs, const std::uint8_t layer) : System<ExampleComponent>(ecs, layer) { // Subscribe to an event Subscribe<ExampleEvent>([](const ExampleEvent& event) { // Event handling code }); } ~ExampleSystem() { // Unsubscribe from the event Unsubscribe<ExampleEvent>(); } void SomeFunction() { ExampleEvent event; // Publish the event Publish(event); } };With this approach, each system can subscribe to events and publish events independently. This provides a more flexible and modular pattern for systems.