Object.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. #if URHO3D_CXX11
  26. #include <functional>
  27. #endif
  28. namespace Urho3D
  29. {
  30. class Context;
  31. class EventHandler;
  32. /// Type info.
  33. class URHO3D_API TypeInfo
  34. {
  35. public:
  36. /// Construct.
  37. TypeInfo(const char* typeName, const TypeInfo* baseTypeInfo);
  38. /// Destruct.
  39. ~TypeInfo();
  40. /// Check current type is type of specified type.
  41. bool IsTypeOf(StringHash type) const;
  42. /// Check current type is type of specified type.
  43. bool IsTypeOf(const TypeInfo* typeInfo) const;
  44. /// Check current type is type of specified class type.
  45. template<typename T> bool IsTypeOf() const { return IsTypeOf(T::GetTypeInfoStatic()); }
  46. /// Return type.
  47. StringHash GetType() const { return type_; }
  48. /// Return type name.
  49. const String& GetTypeName() const { return typeName_;}
  50. /// Return base type info.
  51. const TypeInfo* GetBaseTypeInfo() const { return baseTypeInfo_; }
  52. private:
  53. /// Type.
  54. StringHash type_;
  55. /// Type name.
  56. String typeName_;
  57. /// Base class type info.
  58. const TypeInfo* baseTypeInfo_;
  59. };
  60. #define URHO3D_OBJECT(typeName, baseTypeName) \
  61. public: \
  62. typedef typeName ClassName; \
  63. typedef baseTypeName BaseClassName; \
  64. virtual Urho3D::StringHash GetType() const { return GetTypeInfoStatic()->GetType(); } \
  65. virtual const Urho3D::String& GetTypeName() const { return GetTypeInfoStatic()->GetTypeName(); } \
  66. virtual const Urho3D::TypeInfo* GetTypeInfo() const { return GetTypeInfoStatic(); } \
  67. static Urho3D::StringHash GetTypeStatic() { return GetTypeInfoStatic()->GetType(); } \
  68. static const Urho3D::String& GetTypeNameStatic() { return GetTypeInfoStatic()->GetTypeName(); } \
  69. static const Urho3D::TypeInfo* GetTypeInfoStatic() { static const Urho3D::TypeInfo typeInfoStatic(#typeName, BaseClassName::GetTypeInfoStatic()); return &typeInfoStatic; } \
  70. /// Base class for objects with type identification, subsystem access and event sending/receiving capability.
  71. class URHO3D_API Object : public RefCounted
  72. {
  73. friend class Context;
  74. public:
  75. /// Construct.
  76. Object(Context* context);
  77. /// Destruct. Clean up self from event sender & receiver structures.
  78. virtual ~Object();
  79. /// Return type hash.
  80. virtual StringHash GetType() const = 0;
  81. /// Return type name.
  82. virtual const String& GetTypeName() const = 0;
  83. /// Return type info.
  84. virtual const TypeInfo* GetTypeInfo() const = 0;
  85. /// Handle event.
  86. virtual void OnEvent(Object* sender, StringHash eventType, VariantMap& eventData);
  87. /// Return type info static.
  88. static const TypeInfo* GetTypeInfoStatic() { return 0; }
  89. /// Check current instance is type of specified type.
  90. bool IsInstanceOf(StringHash type) const;
  91. /// Check current instance is type of specified type.
  92. bool IsInstanceOf(const TypeInfo* typeInfo) const;
  93. /// Check current instance is type of specified class.
  94. template<typename T> bool IsInstanceOf() const { return IsInstanceOf(T::GetTypeInfoStatic()); }
  95. /// Subscribe to an event that can be sent by any sender.
  96. void SubscribeToEvent(StringHash eventType, EventHandler* handler);
  97. /// Subscribe to a specific sender's event.
  98. void SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler);
  99. #ifdef URHO3D_CXX11
  100. /// Subscribe to an event that can be sent by any sender.
  101. void SubscribeToEvent(StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=0);
  102. /// Subscribe to a specific sender's event.
  103. void SubscribeToEvent(Object* sender, StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=0);
  104. #endif
  105. /// Unsubscribe from an event.
  106. void UnsubscribeFromEvent(StringHash eventType);
  107. /// Unsubscribe from a specific sender's event.
  108. void UnsubscribeFromEvent(Object* sender, StringHash eventType);
  109. /// Unsubscribe from a specific sender's events.
  110. void UnsubscribeFromEvents(Object* sender);
  111. /// Unsubscribe from all events.
  112. void UnsubscribeFromAllEvents();
  113. /// Unsubscribe from all events except those listed, and optionally only those with userdata (script registered events.)
  114. void UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData);
  115. /// Send event to all subscribers.
  116. void SendEvent(StringHash eventType);
  117. /// Send event with parameters to all subscribers.
  118. void SendEvent(StringHash eventType, VariantMap& eventData);
  119. /// Return a preallocated map for event data. Used for optimization to avoid constant re-allocation of event data maps.
  120. VariantMap& GetEventDataMap() const;
  121. #if URHO3D_CXX11
  122. /// 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.
  123. template <typename... Args> void SendEvent(StringHash eventType, Args... args)
  124. {
  125. SendEvent(eventType, GetEventDataMap().Populate(args...));
  126. }
  127. #endif
  128. /// Return execution context.
  129. Context* GetContext() const { return context_; }
  130. /// Return global variable based on key
  131. const Variant& GetGlobalVar(StringHash key) const;
  132. /// Return all global variables
  133. const VariantMap& GetGlobalVars() const;
  134. /// Set global variable with the respective key and value
  135. void SetGlobalVar(StringHash key, const Variant& value);
  136. /// Return subsystem by type.
  137. Object* GetSubsystem(StringHash type) const;
  138. /// Return active event sender. Null outside event handling.
  139. Object* GetEventSender() const;
  140. /// Return active event handler. Null outside event handling.
  141. EventHandler* GetEventHandler() const;
  142. /// Return whether has subscribed to an event without specific sender.
  143. bool HasSubscribedToEvent(StringHash eventType) const;
  144. /// Return whether has subscribed to a specific sender's event.
  145. bool HasSubscribedToEvent(Object* sender, StringHash eventType) const;
  146. /// Return whether has subscribed to any event.
  147. bool HasEventHandlers() const { return !eventHandlers_.Empty(); }
  148. /// Template version of returning a subsystem.
  149. template <class T> T* GetSubsystem() const;
  150. /// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
  151. const String& GetCategory() const;
  152. protected:
  153. /// Execution context.
  154. Context* context_;
  155. private:
  156. /// Find the first event handler with no specific sender.
  157. EventHandler* FindEventHandler(StringHash eventType, EventHandler** previous = 0) const;
  158. /// Find the first event handler with specific sender.
  159. EventHandler* FindSpecificEventHandler(Object* sender, EventHandler** previous = 0) const;
  160. /// Find the first event handler with specific sender and event type.
  161. EventHandler* FindSpecificEventHandler(Object* sender, StringHash eventType, EventHandler** previous = 0) const;
  162. /// Remove event handlers related to a specific sender.
  163. void RemoveEventSender(Object* sender);
  164. /// Event handlers. Sender is null for non-specific handlers.
  165. LinkedList<EventHandler> eventHandlers_;
  166. };
  167. template <class T> T* Object::GetSubsystem() const { return static_cast<T*>(GetSubsystem(T::GetTypeStatic())); }
  168. /// Base class for object factories.
  169. class URHO3D_API ObjectFactory : public RefCounted
  170. {
  171. public:
  172. /// Construct.
  173. ObjectFactory(Context* context) :
  174. context_(context)
  175. {
  176. assert(context_);
  177. }
  178. /// Create an object. Implemented in templated subclasses.
  179. virtual SharedPtr<Object> CreateObject() = 0;
  180. /// Return execution context.
  181. Context* GetContext() const { return context_; }
  182. /// Return type info of objects created by this factory.
  183. const TypeInfo* GetTypeInfo() const { return typeInfo_; }
  184. /// Return type hash of objects created by this factory.
  185. StringHash GetType() const { return typeInfo_->GetType(); }
  186. /// Return type name of objects created by this factory.
  187. const String& GetTypeName() const { return typeInfo_->GetTypeName(); }
  188. protected:
  189. /// Execution context.
  190. Context* context_;
  191. /// Type info.
  192. const TypeInfo* typeInfo_;
  193. };
  194. /// Template implementation of the object factory.
  195. template <class T> class ObjectFactoryImpl : public ObjectFactory
  196. {
  197. public:
  198. /// Construct.
  199. ObjectFactoryImpl(Context* context) :
  200. ObjectFactory(context)
  201. {
  202. typeInfo_ = T::GetTypeInfoStatic();
  203. }
  204. /// Create an object of the specific type.
  205. virtual SharedPtr<Object> CreateObject() { return SharedPtr<Object>(new T(context_)); }
  206. };
  207. /// Internal helper class for invoking event handler functions.
  208. class URHO3D_API EventHandler : public LinkedListNode
  209. {
  210. public:
  211. /// Construct with specified receiver and userdata.
  212. EventHandler(Object* receiver, void* userData = 0) :
  213. receiver_(receiver),
  214. sender_(0),
  215. userData_(userData)
  216. {
  217. }
  218. /// Destruct.
  219. virtual ~EventHandler() { }
  220. /// Set sender and event type.
  221. void SetSenderAndEventType(Object* sender, StringHash eventType)
  222. {
  223. sender_ = sender;
  224. eventType_ = eventType;
  225. }
  226. /// Invoke event handler function.
  227. virtual void Invoke(VariantMap& eventData) = 0;
  228. /// Return a unique copy of the event handler.
  229. virtual EventHandler* Clone() const = 0;
  230. /// Return event receiver.
  231. Object* GetReceiver() const { return receiver_; }
  232. /// Return event sender. Null if the handler is non-specific.
  233. Object* GetSender() const { return sender_; }
  234. /// Return event type.
  235. const StringHash& GetEventType() const { return eventType_; }
  236. /// Return userdata.
  237. void* GetUserData() const { return userData_; }
  238. protected:
  239. /// Event receiver.
  240. Object* receiver_;
  241. /// Event sender.
  242. Object* sender_;
  243. /// Event type.
  244. StringHash eventType_;
  245. /// Userdata.
  246. void* userData_;
  247. };
  248. /// Template implementation of the event handler invoke helper (stores a function pointer of specific class.)
  249. template <class T> class EventHandlerImpl : public EventHandler
  250. {
  251. public:
  252. typedef void (T::*HandlerFunctionPtr)(StringHash, VariantMap&);
  253. /// Construct with receiver and function pointers and userdata.
  254. EventHandlerImpl(T* receiver, HandlerFunctionPtr function, void* userData = 0) :
  255. EventHandler(receiver, userData),
  256. function_(function)
  257. {
  258. assert(receiver_);
  259. assert(function_);
  260. }
  261. /// Invoke event handler function.
  262. virtual void Invoke(VariantMap& eventData)
  263. {
  264. T* receiver = static_cast<T*>(receiver_);
  265. (receiver->*function_)(eventType_, eventData);
  266. }
  267. /// Return a unique copy of the event handler.
  268. virtual EventHandler* Clone() const
  269. {
  270. return new EventHandlerImpl(static_cast<T*>(receiver_), function_, userData_);
  271. }
  272. private:
  273. /// Class-specific pointer to handler function.
  274. HandlerFunctionPtr function_;
  275. };
  276. #if URHO3D_CXX11
  277. /// Template implementation of the event handler invoke helper (std::function instance).
  278. class EventHandler11Impl : public EventHandler
  279. {
  280. public:
  281. /// Construct with receiver and function pointers and userdata.
  282. EventHandler11Impl(std::function<void(StringHash, VariantMap&)> function, void* userData = 0) :
  283. EventHandler(0, userData),
  284. function_(function)
  285. {
  286. assert(function_);
  287. }
  288. /// Invoke event handler function.
  289. virtual void Invoke(VariantMap& eventData)
  290. {
  291. function_(eventType_, eventData);
  292. }
  293. /// Return a unique copy of the event handler.
  294. virtual EventHandler* Clone() const
  295. {
  296. return new EventHandler11Impl(function_, userData_);
  297. }
  298. private:
  299. /// Class-specific pointer to handler function.
  300. std::function<void(StringHash, VariantMap&)> function_;
  301. };
  302. #endif
  303. /// Register event names.
  304. struct URHO3D_API EventNameRegistrar
  305. {
  306. /// Register an event name for hash reverse mapping.
  307. static StringHash RegisterEventName(const char* eventName);
  308. /// Return Event name or empty string if not found.
  309. static const String& GetEventName(StringHash eventID);
  310. /// Return Event name map.
  311. static HashMap<StringHash, String>& GetEventNameMap();
  312. };
  313. /// Describe an event's hash ID and begin a namespace in which to define its parameters.
  314. #define URHO3D_EVENT(eventID, eventName) static const Urho3D::StringHash eventID(Urho3D::EventNameRegistrar::RegisterEventName(#eventName)); namespace eventName
  315. /// Describe an event's parameter hash ID. Should be used inside an event namespace.
  316. #define URHO3D_PARAM(paramID, paramName) static const Urho3D::StringHash paramID(#paramName)
  317. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function.
  318. #define URHO3D_HANDLER(className, function) (new Urho3D::EventHandlerImpl<className>(this, &className::function))
  319. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function, and also defines a userdata pointer.
  320. #define URHO3D_HANDLER_USERDATA(className, function, userData) (new Urho3D::EventHandlerImpl<className>(this, &className::function, userData))
  321. }