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 this->ptr = pool.create(parent, std::forward<Args>(args)...);
57 if constexpr(std::is_base_of_v<Component, T>)
59 parent->add_component(*this);
60 stage.get_event_source().emit<Events::ComponentCreated>(*this);
64 parent->add_child(*this);
65 stage.get_event_source().emit<Events::EntityCreated>(*this);
70 Owned<T> &Owned<T>::operator=(Owned &&other)
74 this->ptr = other.ptr;
82 Stage &Owned<T>::get_stage(O &obj)
84 if constexpr(std::is_base_of_v<Component, O>)
85 return get_stage(*obj.get_entity());
87 return obj.get_stage();
91 void Owned<T>::destroy()
98 AccessGuard::get_instance().check<AccessGuard::Destroy>();
101 Stage &stage = get_stage(*obj);
103 if constexpr(std::is_base_of_v<Component, T>)
105 stage.get_event_source().emit<Events::ComponentDestroyed>(*this);
106 obj->get_entity()->remove_component(*this);
108 else if(auto parent = obj->get_parent().get())
110 stage.get_event_source().emit<Events::EntityDestroyed>(*this);
111 parent->remove_child(*this);
114 Pool<T> &pool = stage.get_pools().get_pool<T>();
115 pool.destroy(this->ptr);
118 } // namespace Msp::Game