GameKit  0.0.1a
C++ gamedev tools
SceneObject.hpp
Go to the documentation of this file.
1 /*
2  * =====================================================================================
3  *
4  * Filename: SceneObject.hpp
5  *
6  * Description:
7  *
8  * Created: 17/01/2018 19:34:42
9  *
10  * Author: Quentin Bazin, <quent42340@gmail.com>
11  *
12  * =====================================================================================
13  */
14 #ifndef GK_SCENEOBJECT_HPP_
15 #define GK_SCENEOBJECT_HPP_
16 
17 #include <memory>
18 #include <typeindex>
19 #include <unordered_map>
20 
21 #include "gk/core/Exception.hpp"
22 
23 namespace gk {
24 
25 class SceneObject {
26  public:
27  SceneObject(const std::string &name = "null", const std::string &type = "null")
28  : m_name(name), m_type(type) {}
29 
30  template<typename T, typename... Args>
31  T &set(Args &&...args) {
32  m_components[typeid(T).hash_code()] = std::make_shared<T>(std::forward<Args>(args)...);
33  return get<T>();
34  }
35 
36  template<typename T>
37  bool has() const {
38  return m_components.count(typeid(T).hash_code()) == 1;
39  }
40 
41  template<typename T>
42  T &get() const {
43  auto it = m_components.find(typeid(T).hash_code());
44  if(it == m_components.end()) {
45  throw EXCEPTION("SceneObject", (void*)this, "(\"" + m_name + "\", \"" + m_type + "\") doesn't have a component of type:", typeid(T).name());
46  }
47 
48  return *std::static_pointer_cast<T>(it->second);
49  }
50 
51  template<typename T>
52  void remove() {
53  m_components.erase(typeid(T).hash_code());
54  }
55 
56  void debug() const {
57 #ifdef DEBUG_ENABLED
58  DEBUG("=== Component list of object:", (void*)this, "===");
59  DEBUG("=== List address:", (void*)&m_components);
60 
61  for(auto &it : m_components) {
62  DEBUG(it.first, ":", (void*)it.second.get());
63  }
64 
65  DEBUG("=== End of list. ===");
66 #endif
67  }
68 
69  const std::string &name() const { return m_name; }
70  const std::string &type() const { return m_type; }
71 
72  private:
73  std::string m_name;
74  std::string m_type;
75 
76  std::unordered_map<size_t, std::shared_ptr<void>> m_components;
77 };
78 
79 } // namespace gk
80 
81 #endif // GK_SCENEOBJECT_HPP_
#define DEBUG(args...)
Definition: Debug.hpp:31
std::string m_name
Definition: SceneObject.hpp:73
const std::string & name() const
Definition: SceneObject.hpp:69
std::unordered_map< size_t, std::shared_ptr< void > > m_components
Definition: SceneObject.hpp:76
#define EXCEPTION(args...)
Definition: Exception.hpp:22
bool has() const
Definition: SceneObject.hpp:37
const std::string & type() const
Definition: SceneObject.hpp:70
SceneObject(const std::string &name="null", const std::string &type="null")
Definition: SceneObject.hpp:27
void debug() const
Definition: SceneObject.hpp:56
std::string m_type
Definition: SceneObject.hpp:74