Loading...
Searching...
No Matches
Entity.inl
Go to the documentation of this file.
1//
2// Created by denzel on 21/08/2025.
3//
4
5#pragma once
6
7 template<ComponentType T, typename... Args>
8 T *Entity::add_component(Args &&... args) {
9 auto component = std::make_unique<T>(std::forward<Args>(args)...);
10 T *component_ptr = component.get();
11 components_[std::type_index(typeid(T))] = std::move(component);
12
13 // Call lifecycle hook if Component base class has it
14 if constexpr (std::is_base_of_v<Component, T>) {
15 component_ptr->on_added(this);
16 }
17
18 if constexpr (std::is_base_of_v<ScriptComponent, T>) {
19 script_components_.push_back(component_ptr);
20 component_ptr->init();
21 }
22
23 return component_ptr;
24 }
25
26 template<ComponentType T>
27 T *Entity::get_component() const {
28 if (const auto it = components_.find(std::type_index(typeid(T))); it != components_.end()) {
29 return static_cast<T *>(it->second.get());
30 }
31 return nullptr;
32 }
33
34 template<ComponentType T>
35 bool Entity::remove_component() {
36 const auto it = components_.find(std::type_index(typeid(T)));
37 if (it != components_.end()) {
38 T *component_ptr = static_cast<T *>(it->second.get());
39
40 // Special handling for ScriptComponents
41 if constexpr (std::is_base_of_v<ScriptComponent, T>) {
42 component_ptr->remove(); // Call script cleanup
43 // Remove from script components list
44 auto script_it = std::find(script_components_.begin(), script_components_.end(), component_ptr);
45 if (script_it != script_components_.end()) {
46 script_components_.erase(script_it);
47 }
48 }
49
50 if constexpr (std::is_base_of_v<Component, T>) {
51 component_ptr->on_removed();
52 }
53 components_.erase(it);
54 return true;
55 }
56 return false;
57 }
58
59 template<ScriptComponentType T>
60 void Entity::send_event_to_script(const std::string &event_name, void *data) {
61 static_assert(std::is_base_of_v<ScriptComponent, T>, "T must derive from ScriptComponent");
62 if (auto *script = get_component<T>()) {
63 script->trigger_event(event_name, data);
64 }
65 }