1 #ifndef MSP_GAME_OWNED_H_
2 #define MSP_GAME_OWNED_H_
5 #include "accessguard.h"
16 class Owned: public Handle<T>
21 template<typename P, typename... Args>
22 Owned(Handle<P>, Args &&...);
24 template<typename P, typename... Args>
25 Owned(Owned<P> &p, Args &&... a): Owned(static_cast<Handle<P> &>(p), std::forward<Args>(a)...) { }
27 template<typename P, typename... Args>
28 requires(!std::is_const_v<P>)
29 Owned(P &parent, Args &&... args): Owned(Handle<P>::from_object(&parent), std::forward<Args>(args)...) { }
31 Owned(Owned &&other): Handle<T>(other) { other.ptr = nullptr; }
32 Owned &operator=(Owned &&other);
33 ~Owned() { destroy(); }
37 static Stage &get_stage(O &);
44 template<typename P, typename... Args>
45 Owned<T>::Owned(Handle<P> parent, Args &&... args)
48 AccessGuard::get_instance().check<AccessGuard::Create>();
52 throw std::invalid_argument("Owned::Owned");
54 Stage &stage = get_stage(*parent);
55 Pool<T> &pool = stage.get_pools().get_pool<T>();
56 bool first_created = !pool.get_capacity();
57 this->ptr = pool.create(parent, std::forward<Args>(args)...);
58 if constexpr(std::is_base_of_v<Component, T>)
61 stage.get_reflector().get_or_create_class<T>().template set_polymorphic_base<Component>(**this);
62 parent->add_component(*this);
63 stage.get_event_source().emit<Events::ComponentCreated>(*this);
68 stage.get_reflector().get_or_create_class<T>().template set_polymorphic_base<Entity>(**this);
69 parent->add_child(*this);
70 stage.get_event_source().emit<Events::EntityCreated>(*this);
75 Owned<T> &Owned<T>::operator=(Owned &&other)
79 this->ptr = other.ptr;
87 Stage &Owned<T>::get_stage(O &obj)
89 if constexpr(std::is_base_of_v<Component, O>)
90 return get_stage(*obj.get_entity());
92 return obj.get_stage();
96 void Owned<T>::destroy()
103 AccessGuard::get_instance().check<AccessGuard::Destroy>();
106 Stage &stage = get_stage(*obj);
108 if constexpr(std::is_base_of_v<Component, T>)
110 stage.get_event_source().emit<Events::ComponentDestroyed>(*this);
111 obj->get_entity()->remove_component(*this);
113 else if(auto parent = obj->get_parent().get())
115 stage.get_event_source().emit<Events::EntityDestroyed>(*this);
116 parent->remove_child(*this);
119 Pool<T> &pool = stage.get_pools().get_pool<T>();
120 pool.destroy(this->ptr);
123 } // namespace Msp::Game