Object.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/LinkedList.h"
  24. #include "../Core/Variant.h"
  25. #include <functional>
  26. namespace Urho3D
  27. {
  28. class Context;
  29. class EventHandler;
  30. /// Type info.
  31. class URHO3D_API TypeInfo
  32. {
  33. public:
  34. /// Construct.
  35. TypeInfo(const char* typeName, const TypeInfo* baseTypeInfo);
  36. /// Destruct.
  37. ~TypeInfo();
  38. /// Check current type is type of specified type.
  39. bool IsTypeOf(StringHash type) const;
  40. /// Check current type is type of specified type.
  41. bool IsTypeOf(const TypeInfo* typeInfo) const;
  42. /// Check current type is type of specified class type.
  43. template<typename T> bool IsTypeOf() const { return IsTypeOf(T::GetTypeInfoStatic()); }
  44. /// Return type.
  45. StringHash GetType() const { return type_; }
  46. /// Return type name.
  47. const String& GetTypeName() const { return typeName_;}
  48. /// Return base type info.
  49. const TypeInfo* GetBaseTypeInfo() const { return baseTypeInfo_; }
  50. private:
  51. /// Type.
  52. StringHash type_;
  53. /// Type name.
  54. String typeName_;
  55. /// Base class type info.
  56. const TypeInfo* baseTypeInfo_;
  57. };
  58. #define URHO3D_OBJECT(typeName, baseTypeName) \
  59. public: \
  60. using ClassName = typeName; \
  61. using BaseClassName = baseTypeName; \
  62. virtual Urho3D::StringHash GetType() const override { return GetTypeInfoStatic()->GetType(); } \
  63. virtual const Urho3D::String& GetTypeName() const override { return GetTypeInfoStatic()->GetTypeName(); } \
  64. virtual const Urho3D::TypeInfo* GetTypeInfo() const override { return GetTypeInfoStatic(); } \
  65. static Urho3D::StringHash GetTypeStatic() { return GetTypeInfoStatic()->GetType(); } \
  66. static const Urho3D::String& GetTypeNameStatic() { return GetTypeInfoStatic()->GetTypeName(); } \
  67. static const Urho3D::TypeInfo* GetTypeInfoStatic() { static const Urho3D::TypeInfo typeInfoStatic(#typeName, BaseClassName::GetTypeInfoStatic()); return &typeInfoStatic; } \
  68. /// Base class for objects with type identification, subsystem access and event sending/receiving capability.
  69. class URHO3D_API Object : public RefCounted
  70. {
  71. friend class Context;
  72. public:
  73. /// Construct.
  74. Object(Context* context);
  75. /// Destruct. Clean up self from event sender & receiver structures.
  76. virtual ~Object() override;
  77. /// Return type hash.
  78. virtual StringHash GetType() const = 0;
  79. /// Return type name.
  80. virtual const String& GetTypeName() const = 0;
  81. /// Return type info.
  82. virtual const TypeInfo* GetTypeInfo() const = 0;
  83. /// Handle event.
  84. virtual void OnEvent(Object* sender, StringHash eventType, VariantMap& eventData);
  85. /// Return type info static.
  86. static const TypeInfo* GetTypeInfoStatic() { return nullptr; }
  87. /// Check current instance is type of specified type.
  88. bool IsInstanceOf(StringHash type) const;
  89. /// Check current instance is type of specified type.
  90. bool IsInstanceOf(const TypeInfo* typeInfo) const;
  91. /// Check current instance is type of specified class.
  92. template<typename T> bool IsInstanceOf() const { return IsInstanceOf(T::GetTypeInfoStatic()); }
  93. /// Subscribe to an event that can be sent by any sender.
  94. void SubscribeToEvent(StringHash eventType, EventHandler* handler);
  95. /// Subscribe to a specific sender's event.
  96. void SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler);
  97. /// Subscribe to an event that can be sent by any sender.
  98. void SubscribeToEvent(StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData = nullptr);
  99. /// Subscribe to a specific sender's event.
  100. void SubscribeToEvent(Object* sender, StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData = nullptr);
  101. /// Unsubscribe from an event.
  102. void UnsubscribeFromEvent(StringHash eventType);
  103. /// Unsubscribe from a specific sender's event.
  104. void UnsubscribeFromEvent(Object* sender, StringHash eventType);
  105. /// Unsubscribe from a specific sender's events.
  106. void UnsubscribeFromEvents(Object* sender);
  107. /// Unsubscribe from all events.
  108. void UnsubscribeFromAllEvents();
  109. /// Unsubscribe from all events except those listed, and optionally only those with userdata (script registered events.)
  110. void UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData);
  111. /// Send event to all subscribers.
  112. void SendEvent(StringHash eventType);
  113. /// Send event with parameters to all subscribers.
  114. void SendEvent(StringHash eventType, VariantMap& eventData);
  115. /// Return a preallocated map for event data. Used for optimization to avoid constant re-allocation of event data maps.
  116. VariantMap& GetEventDataMap() const;
  117. /// Send event with variadic parameter pairs to all subscribers. The parameter pairs is a list of paramID and paramValue separated by comma, one pair after another.
  118. template <typename... Args> void SendEvent(StringHash eventType, Args... args)
  119. {
  120. SendEvent(eventType, GetEventDataMap().Populate(args...));
  121. }
  122. /// Return execution context.
  123. Context* GetContext() const { return context_; }
  124. /// Return global variable based on key
  125. const Variant& GetGlobalVar(StringHash key) const;
  126. /// Return all global variables
  127. const VariantMap& GetGlobalVars() const;
  128. /// Set global variable with the respective key and value
  129. void SetGlobalVar(StringHash key, const Variant& value);
  130. /// Return subsystem by type.
  131. Object* GetSubsystem(StringHash type) const;
  132. /// Return active event sender. Null outside event handling.
  133. Object* GetEventSender() const;
  134. /// Return active event handler. Null outside event handling.
  135. EventHandler* GetEventHandler() const;
  136. /// Return whether has subscribed to an event without specific sender.
  137. bool HasSubscribedToEvent(StringHash eventType) const;
  138. /// Return whether has subscribed to a specific sender's event.
  139. bool HasSubscribedToEvent(Object* sender, StringHash eventType) const;
  140. /// Return whether has subscribed to any event.
  141. bool HasEventHandlers() const { return !eventHandlers_.Empty(); }
  142. /// Template version of returning a subsystem.
  143. template <class T> T* GetSubsystem() const;
  144. /// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
  145. const String& GetCategory() const;
  146. protected:
  147. /// Execution context.
  148. Context* context_;
  149. private:
  150. /// Find the first event handler with no specific sender.
  151. EventHandler* FindEventHandler(StringHash eventType, EventHandler** previous = nullptr) const;
  152. /// Find the first event handler with specific sender.
  153. EventHandler* FindSpecificEventHandler(Object* sender, EventHandler** previous = nullptr) const;
  154. /// Find the first event handler with specific sender and event type.
  155. EventHandler* FindSpecificEventHandler(Object* sender, StringHash eventType, EventHandler** previous = nullptr) const;
  156. /// Remove event handlers related to a specific sender.
  157. void RemoveEventSender(Object* sender);
  158. /// Event handlers. Sender is null for non-specific handlers.
  159. LinkedList<EventHandler> eventHandlers_;
  160. };
  161. template <class T> T* Object::GetSubsystem() const { return static_cast<T*>(GetSubsystem(T::GetTypeStatic())); }
  162. /// Base class for object factories.
  163. class URHO3D_API ObjectFactory : public RefCounted
  164. {
  165. public:
  166. /// Construct.
  167. ObjectFactory(Context* context) :
  168. context_(context)
  169. {
  170. assert(context_);
  171. }
  172. /// Create an object. Implemented in templated subclasses.
  173. virtual SharedPtr<Object> CreateObject() = 0;
  174. /// Return execution context.
  175. Context* GetContext() const { return context_; }
  176. /// Return type info of objects created by this factory.
  177. const TypeInfo* GetTypeInfo() const { return typeInfo_; }
  178. /// Return type hash of objects created by this factory.
  179. StringHash GetType() const { return typeInfo_->GetType(); }
  180. /// Return type name of objects created by this factory.
  181. const String& GetTypeName() const { return typeInfo_->GetTypeName(); }
  182. protected:
  183. /// Execution context.
  184. Context* context_;
  185. /// Type info.
  186. const TypeInfo* typeInfo_;
  187. };
  188. /// Template implementation of the object factory.
  189. template <class T> class ObjectFactoryImpl : public ObjectFactory
  190. {
  191. public:
  192. /// Construct.
  193. ObjectFactoryImpl(Context* context) :
  194. ObjectFactory(context)
  195. {
  196. typeInfo_ = T::GetTypeInfoStatic();
  197. }
  198. /// Create an object of the specific type.
  199. virtual SharedPtr<Object> CreateObject() override { return SharedPtr<Object>(new T(context_)); }
  200. };
  201. /// Internal helper class for invoking event handler functions.
  202. class URHO3D_API EventHandler : public LinkedListNode
  203. {
  204. public:
  205. /// Construct with specified receiver and userdata.
  206. EventHandler(Object* receiver, void* userData = nullptr) :
  207. receiver_(receiver),
  208. sender_(nullptr),
  209. userData_(userData)
  210. {
  211. }
  212. /// Destruct.
  213. virtual ~EventHandler() { }
  214. /// Set sender and event type.
  215. void SetSenderAndEventType(Object* sender, StringHash eventType)
  216. {
  217. sender_ = sender;
  218. eventType_ = eventType;
  219. }
  220. /// Invoke event handler function.
  221. virtual void Invoke(VariantMap& eventData) = 0;
  222. /// Return a unique copy of the event handler.
  223. virtual EventHandler* Clone() const = 0;
  224. /// Return event receiver.
  225. Object* GetReceiver() const { return receiver_; }
  226. /// Return event sender. Null if the handler is non-specific.
  227. Object* GetSender() const { return sender_; }
  228. /// Return event type.
  229. const StringHash& GetEventType() const { return eventType_; }
  230. /// Return userdata.
  231. void* GetUserData() const { return userData_; }
  232. protected:
  233. /// Event receiver.
  234. Object* receiver_;
  235. /// Event sender.
  236. Object* sender_;
  237. /// Event type.
  238. StringHash eventType_;
  239. /// Userdata.
  240. void* userData_;
  241. };
  242. /// Template implementation of the event handler invoke helper (stores a function pointer of specific class.)
  243. template <class T> class EventHandlerImpl : public EventHandler
  244. {
  245. public:
  246. using HandlerFunctionPtr = void (T::*)(StringHash, VariantMap&);
  247. /// Construct with receiver and function pointers and userdata.
  248. EventHandlerImpl(T* receiver, HandlerFunctionPtr function, void* userData = nullptr) :
  249. EventHandler(receiver, userData),
  250. function_(function)
  251. {
  252. assert(receiver_);
  253. assert(function_);
  254. }
  255. /// Invoke event handler function.
  256. virtual void Invoke(VariantMap& eventData) override
  257. {
  258. T* receiver = static_cast<T*>(receiver_);
  259. (receiver->*function_)(eventType_, eventData);
  260. }
  261. /// Return a unique copy of the event handler.
  262. virtual EventHandler* Clone() const override
  263. {
  264. return new EventHandlerImpl(static_cast<T*>(receiver_), function_, userData_);
  265. }
  266. private:
  267. /// Class-specific pointer to handler function.
  268. HandlerFunctionPtr function_;
  269. };
  270. /// Template implementation of the event handler invoke helper (std::function instance).
  271. class EventHandler11Impl : public EventHandler
  272. {
  273. public:
  274. /// Construct with receiver and function pointers and userdata.
  275. EventHandler11Impl(std::function<void(StringHash, VariantMap&)> function, void* userData = nullptr) :
  276. EventHandler(nullptr, userData),
  277. function_(function)
  278. {
  279. assert(function_);
  280. }
  281. /// Invoke event handler function.
  282. virtual void Invoke(VariantMap& eventData) override
  283. {
  284. function_(eventType_, eventData);
  285. }
  286. /// Return a unique copy of the event handler.
  287. virtual EventHandler* Clone() const override
  288. {
  289. return new EventHandler11Impl(function_, userData_);
  290. }
  291. private:
  292. /// Class-specific pointer to handler function.
  293. std::function<void(StringHash, VariantMap&)> function_;
  294. };
  295. /// Register event names.
  296. struct URHO3D_API EventNameRegistrar
  297. {
  298. /// Register an event name for hash reverse mapping.
  299. static StringHash RegisterEventName(const char* eventName);
  300. /// Return Event name or empty string if not found.
  301. static const String& GetEventName(StringHash eventID);
  302. /// Return Event name map.
  303. static HashMap<StringHash, String>& GetEventNameMap();
  304. };
  305. /// Describe an event's hash ID and begin a namespace in which to define its parameters.
  306. #define URHO3D_EVENT(eventID, eventName) static const Urho3D::StringHash eventID(Urho3D::EventNameRegistrar::RegisterEventName(#eventName)); namespace eventName
  307. /// Describe an event's parameter hash ID. Should be used inside an event namespace.
  308. #define URHO3D_PARAM(paramID, paramName) static const Urho3D::StringHash paramID(#paramName)
  309. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function.
  310. #define URHO3D_HANDLER(className, function) (new Urho3D::EventHandlerImpl<className>(this, &className::function))
  311. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function, and also defines a userdata pointer.
  312. #define URHO3D_HANDLER_USERDATA(className, function, userData) (new Urho3D::EventHandlerImpl<className>(this, &className::function, userData))
  313. }