]> git.tdb.fi Git - libs/game.git/blob - source/game/entity.h
Make it possible to retrieve components and systems of a particular type
[libs/game.git] / source / game / entity.h
1 #ifndef MSP_GAME_ENTITY_H_
2 #define MSP_GAME_ENTITY_H_
3
4 #include "handle.h"
5 #include "owned.h"
6
7 namespace Msp::Game {
8
9 class Component;
10 class Stage;
11 class Transform;
12 struct TransformValues;
13
14 class hierarchy_error: public std::logic_error
15 {
16 public:
17         hierarchy_error(): std::logic_error("hierarchy error") { }
18 };
19
20 class Entity
21 {
22 public:
23         enum TransformTag { NO_TRANSFORM };
24
25 private:
26         Handle<Entity> parent;
27         std::vector<Handle<Component>> components;
28         std::vector<Handle<Entity>> children;
29         Owned<Transform> transform;
30
31 public:
32         Entity(Handle<Entity>, TransformTag);
33         Entity(Handle<Entity>, const TransformValues &);
34         virtual ~Entity();
35
36         void add_component(Handle<Component>);
37         void remove_component(Handle<Component>);
38
39         template<typename T>
40         Handle<T> get_component();
41
42         Handle<Transform> get_transform() const { return transform; }
43
44         void add_child(Handle<Entity>);
45         void remove_child(Handle<Entity>);
46
47         Handle<Entity> get_parent() const { return parent; }
48         Handle<Entity> get_root();
49         const std::vector<Handle<Entity>> &get_children() const { return children; }
50         Stage &get_stage();
51 };
52
53
54 template<typename T>
55 inline Handle<T> Entity::get_component()
56 {
57         for(Handle<Component> c: components)
58                 if(Handle<T> tc = dynamic_handle_cast<T>(c))
59                         return tc;
60         return nullptr;
61 }
62
63 inline Handle<Entity> Entity::get_root()
64 {
65         Handle<Entity> e = Handle<Entity>::from_object(this);
66         while(Handle<Entity> p = e->get_parent())
67                 e = p;
68         return e;
69 }
70
71 } // namespace Msp::Game
72
73 #endif