IUnityEventQueue.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. // Unity Native Plugin API copyright © 2015 Unity Technologies ApS
  2. //
  3. // Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
  4. //
  5. // Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
  6. #ifndef __cplusplus
  7. #error "This file cannot be compiled in a C environment"
  8. #endif
  9. #pragma once
  10. #include "IUnityInterface.h"
  11. // 5.2 patch 1 + of Unity will support this.
  12. // The lack or presence of this feature can cause the EventQueue
  13. // to crash if used against the wrong version of Unity.
  14. //
  15. // Before we had the IUnityInterfaces system this interface changed
  16. // to support a cleanup handler on events. This broke our plugins
  17. // in older versions of Unity. The registry should help us with
  18. // this sort of thing in the future.
  19. #ifndef EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  20. #define EVENTQUEUE_SUPPORTS_EVENT_CLEANUP 1
  21. #endif
  22. ////////////////////////////////////////////////////////////////////////////////////////
  23. // NOTE: Do not include any additional headers here. This is an external facing header
  24. // so avoid any internal dependencies.
  25. ////////////////////////////////////////////////////////////////////////////////////////
  26. // The Unity EventQueue is a standard way of passing information between plugins or parts
  27. // of the engine without any reliance on managed systems, game objects or
  28. // other pieces of Unity.
  29. //
  30. // Events are simply a structure and GUID pair. GUIDs were chosen rather
  31. // than hashes as it allows plugins to define their own event
  32. // payloads and use the EventQueue.
  33. //
  34. // While the EventQueue itself is self contained and can be used for
  35. // many different applications within Unity the global event
  36. // queue that is passed to plugins is always serviced on the main
  37. // simulation thread and thus serves as a convenient means of
  38. // pushing asynchronous operations back to the main game thread
  39. //
  40. // Payloads should strive to be small. The EventQueue is a 0 allocation
  41. // system which ensures that the use of events does not fragment
  42. // or add undue pressure on resource limited systems.
  43. //
  44. // This header defines ALL that is required to listen, define
  45. // and send events from both within Unity and from plugins.
  46. ////////////////////////////////////////////////////////////////////////////////////////
  47. // USAGE:
  48. //
  49. // SENDING
  50. // ========
  51. //
  52. // To Define new Event:
  53. // --------------------
  54. // // Structure and GUID
  55. // struct MyEvent {};
  56. // REGISTER_EVENT_ID(0x19D736400584B24BULL,0x98B9EFBE26D3F3C9ULL,MyEvent)
  57. // // hash above is a GUID split into 2 64 bit integers for convenience.
  58. // // DO NOT DUPLICATE GUIDS!
  59. //
  60. // To Send an Event:
  61. // -----------------
  62. // // Create Payload and send
  63. // MyEvent evt;
  64. // GlobalEventQueue::GetInstance ().SendEvent (evt);
  65. //
  66. // LISTENING
  67. // ==========
  68. //
  69. // STATIC FUNCTION: To Listen For An Event:
  70. // ----------------------------------------
  71. //
  72. // void MyListenFunction (const MyEvent & payload)
  73. // { /* do something useful */ }
  74. //
  75. // // No register that function, create delegate, register delegate with EventQueue
  76. // // Lifetime of delegate is important.
  77. // StaticFunctionEventHandler<MyEvent> myEventDelegate (&MyListenFunction);
  78. // GlobalEventQueue::GetInstance ()->AddHandler (&myEventDelegate);
  79. //
  80. //
  81. // CLASS LISTENER: To Listen on an instance of a class:
  82. // ----------------------------------------------------
  83. // class MyClass
  84. // {
  85. // // This method will get called, always called HandleEvent
  86. // void HandleEvent(const MyEvent & payload);
  87. //
  88. // MyClass()
  89. // {
  90. // // Hookup to listen can be anywhere but here it's in the ctor.
  91. // GlobalEventQueue::GetInstance ()->AddHandler (m_myDelegate.SetObject (this));
  92. // }
  93. //
  94. // ~MyClass()
  95. // {
  96. // // Stop listening.
  97. // GlobalEventQueue::GetInstance ()->RemoveHandler (m_myDelegate);
  98. // }
  99. //
  100. // // Delegate is a member of the class.
  101. // ClassBasedEventHandler<MyEvent,MyClass> m_myDelegate;
  102. // };
  103. // GUID definition for a new event.
  104. //
  105. // There is a tool to compute these, run the tool on the name of your
  106. // message and insert the hash/type combination in your header file.
  107. // This defines the EventId for your event payload (struct)
  108. // Use this for events that do not require a destructor.
  109. #define REGISTER_EVENT_ID(HASHH, HASHL , TYPE) \
  110. namespace UnityEventQueue \
  111. { \
  112. template<> \
  113. inline const EventId GetEventId< TYPE > () \
  114. { \
  115. return EventId(HASHH,HASHL) ; \
  116. } \
  117. }
  118. #if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  119. // GUID definition for a new event with a destructor.
  120. //
  121. // If your event payload requires a destructor. Define:
  122. //
  123. // void Destroy()
  124. //
  125. // Which should be a method on your payload and then use this macro.
  126. // If your event
  127. // can guarantee that someone is listening before you fire
  128. // your first event this is all you have to do.
  129. //
  130. // However if you do not know if someone is listening when you
  131. // fire your first event you will need to call RegisterCleanup
  132. // somewhere to ensure your events get cleaned up properly.
  133. //
  134. // There is a tool to compute these, run the tool on the name of your
  135. // payload and insert the hash/type combination in your header file.
  136. #define REGISTER_EVENT_ID_WITH_CLEANUP(HASHH, HASHL, TYPE) \
  137. namespace UnityEventQueue \
  138. { \
  139. typedef StaticFunctionEventHandler< TYPE > DestructorMethod_##HASHH##HASHL; \
  140. \
  141. template<> \
  142. inline void GenericDestructorMethodForType< TYPE > ( const TYPE & eventPayload ) \
  143. { const_cast<TYPE&>(eventPayload).Destroy(); } \
  144. \
  145. template<> \
  146. inline EventHandler * GetEventDestructor< TYPE >() \
  147. { \
  148. static DestructorMethod_##HASHH##HASHL g_Destructor(&GenericDestructorMethodForType< TYPE >); \
  149. return &g_Destructor; \
  150. } \
  151. } \
  152. REGISTER_EVENT_ID(HASHH,HASHL,TYPE)
  153. #endif
  154. namespace UnityEventQueue
  155. {
  156. // EventId - GUID
  157. //
  158. // To facilitate custom events the EventId object must be a full fledged GUID
  159. // to ensure cross plugin uniqueness constraints.
  160. //
  161. // Template specialization is used to produce a means of looking up an
  162. // EventId from it's payload type at compile time. The net result should compile
  163. // down to passing around the GUID.
  164. //
  165. // REGISTER_EVENT_ID should be placed in
  166. // the header file of any payload definition OUTSIDE of all namespaces (all EventIds live
  167. // in the UnityEventQueue namespace by default) The payload structure and the registration ID are all that
  168. // is required to expose the event to other systems.
  169. //
  170. // There is a tool to generate registration macros for EventIds.
  171. struct EventId
  172. {
  173. public:
  174. EventId(unsigned long long high, unsigned long long low)
  175. : mGUIDHigh(high)
  176. , mGUIDLow(low)
  177. {}
  178. EventId(const EventId & other)
  179. {
  180. mGUIDHigh = other.mGUIDHigh;
  181. mGUIDLow = other.mGUIDLow;
  182. }
  183. EventId & operator=(const EventId & other)
  184. {
  185. mGUIDHigh = other.mGUIDHigh;
  186. mGUIDLow = other.mGUIDLow;
  187. return *this;
  188. }
  189. bool Equals(const EventId & other) const { return mGUIDHigh == other.mGUIDHigh && mGUIDLow == other.mGUIDLow; }
  190. bool LessThan(const EventId & other) const { return mGUIDHigh < other.mGUIDHigh || (mGUIDHigh == other.mGUIDHigh && mGUIDLow < other.mGUIDLow); }
  191. unsigned long long mGUIDHigh;
  192. unsigned long long mGUIDLow;
  193. };
  194. inline bool operator==(const EventId & left, const EventId & right) { return left.Equals(right); }
  195. inline bool operator!=(const EventId & left, const EventId & right) { return !left.Equals(right); }
  196. inline bool operator<(const EventId & left, const EventId & right) { return left.LessThan(right); }
  197. inline bool operator>(const EventId & left, const EventId & right) { return right.LessThan(left); }
  198. inline bool operator>=(const EventId & left, const EventId & right) { return !operator<(left, right); }
  199. inline bool operator<=(const EventId & left, const EventId & right) { return !operator>(left, right); }
  200. // Generic Version of GetEventId to allow for specialization
  201. //
  202. // If you get errors about return values related to this method
  203. // then you have forgotten to include REGISTER_EVENT_ID() for your
  204. // payload / event. This method should never be compiled, ever.
  205. template<typename T> const EventId GetEventId();
  206. class EventQueue;
  207. class EventHandler;
  208. #if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  209. // Generic version retrieving a classes destructor.
  210. // Any class that does not specialize this will not define a destructor.
  211. template<typename T> EventHandler * GetEventDestructor() { return (EventHandler*)NULL; }
  212. // This is a static method that helps us call a meaningful method on the event
  213. // itself improving the cleanliness of the EQ design.
  214. template<typename T> void GenericDestructorMethodForType(const T & /*eventPayload*/) {}
  215. #endif
  216. // ====================================================================
  217. // ADAPTER / DELEGATE - This is the base interface that the EventQueue
  218. // uses to know about listeners for events.
  219. //
  220. // DO NOT USE DIRECTLY!
  221. //
  222. // Use the StaticFunction of ClassBased EventHandlers to build
  223. // adapters to your systems and empower them to receive events.
  224. class EventHandler
  225. {
  226. public:
  227. EventHandler() : m_Next(0) {}
  228. virtual ~EventHandler() {}
  229. // This actually kicks the event to the handler function or object.
  230. virtual void HandleEvent(EventId & id, void * data) = 0;
  231. // This is required when registering this handler
  232. virtual EventId HandlerEventId() = 0;
  233. #if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  234. // This is required when registering this handler
  235. virtual EventHandler * GetMyEventDestructor() = 0;
  236. #endif
  237. // Internal, do not use, required for walking and calling handlers
  238. EventHandler * GetNext() { return m_Next; }
  239. private:
  240. // Intrusive list holding a linked list of handlers for this EventId
  241. // Exists to avoid allocations - Do Not Touch.
  242. friend class EventHandlerList;
  243. EventHandler * m_Next;
  244. };
  245. // ====================================================================
  246. // CLASS DELEGATE - Classes can be the target of events.
  247. //
  248. // Event handlers are the endpoints of the system. To Unity all
  249. // event endpoints look like a single virtual function call.
  250. //
  251. // This adapter will call the HandleEvent( EVENTTYPE & ) method
  252. // on the object specified when an event is triggered.
  253. template<typename EVENTTYPE, typename OBJECTTYPE>
  254. class ClassBasedEventHandler : public EventHandler
  255. {
  256. public:
  257. ClassBasedEventHandler(OBJECTTYPE * handler = NULL) : m_Handler(handler) {}
  258. // The actual adapter method, calls into the registered object.
  259. virtual void HandleEvent(EventId & id, void * data)
  260. { (void)id; m_Handler->HandleEvent(*static_cast<EVENTTYPE*>(data)); }
  261. // Boilerplate required when registering this handler.
  262. virtual EventId HandlerEventId()
  263. { return GetEventId<EVENTTYPE>(); }
  264. #if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  265. // Required boilerplate. Used during registration of this object.
  266. virtual EventHandler * GetMyEventDestructor()
  267. { return GetEventDestructor<EVENTTYPE>(); }
  268. #endif
  269. ClassBasedEventHandler<EVENTTYPE, OBJECTTYPE> *
  270. SetObject(OBJECTTYPE * handler)
  271. { m_Handler = handler; return this; }
  272. #if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  273. OBJECTTYPE * GetHandler()
  274. { return m_Handler; }
  275. #endif
  276. protected:
  277. OBJECTTYPE * m_Handler;
  278. };
  279. // ====================================================================
  280. // FUNCTION DELEGATE - Static functions can be event handlers.
  281. //
  282. // Event handlers are the endpoints of the system. To Unity all
  283. // event endpoints look like a single virtual function call.
  284. //
  285. // This object wraps a static function turning it into an event endpoint
  286. // much like a C# delegate does.
  287. // The wrapped function will be called when the event is triggered
  288. template<typename EVENTTYPE>
  289. class StaticFunctionEventHandler : public EventHandler
  290. {
  291. public:
  292. typedef void (*HandlerFunction)(const EVENTTYPE & payload);
  293. StaticFunctionEventHandler(HandlerFunction handlerCallback) : m_Handler(handlerCallback) {}
  294. virtual void HandleEvent(EventId & id, void * data)
  295. { (void)id; m_Handler(*static_cast<EVENTTYPE*>(data)); }
  296. // Required boilerplate. Used during registration of this object.
  297. virtual EventId HandlerEventId()
  298. { return GetEventId<EVENTTYPE>(); }
  299. #if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  300. // Required boilerplate. Used during registration of this object.
  301. virtual EventHandler * GetMyEventDestructor()
  302. { return GetEventDestructor<EVENTTYPE>(); }
  303. #endif
  304. protected:
  305. HandlerFunction m_Handler;
  306. };
  307. // ============================================================
  308. // Some built in event types for adding removing event handlers
  309. // from secondary threads. Use these instead of calling AddHandler
  310. // from a secondary thread.
  311. struct AddEventHandler
  312. {
  313. AddEventHandler(EventHandler * handler) : m_Handler(handler) {}
  314. EventHandler * m_Handler;
  315. };
  316. struct RemoveEventHandler
  317. {
  318. RemoveEventHandler(EventHandler * handler) : m_Handler(handler) {}
  319. EventHandler * m_Handler;
  320. };
  321. // ============================================================
  322. // The Event Queue is a lock free multiple write single read
  323. // deferred event system. It uses GUIDs to map payloads to
  324. // event handler delegates. The system has some
  325. // templates to make registering for events fairly painless
  326. // but takes care to try to keep template cost very low.
  327. //
  328. // NOTE: payloads should be very very small and never allocate
  329. // or free memory since they can and will be passed across
  330. // dll boundaries.
  331. //
  332. // There is a hard limit of kMaxEventQueueEventSize bytes for any
  333. // payload being passed through this system but payloads that are
  334. // this big are probably being handled improperly.
  335. UNITY_DECLARE_INTERFACE(IUnityEventQueue)
  336. {
  337. public:
  338. // size of 8196 required for PS4 system events
  339. #define kMaxEventQueueEventSize 8196+sizeof(EventId)
  340. virtual ~IUnityEventQueue() {
  341. }
  342. // The primary entry point for firing any
  343. // event through the system. The templated
  344. // version is simply syntatic sugar for extracting
  345. // the EventId from the event object.
  346. //
  347. // This can be called from any thread.
  348. template<typename T>
  349. void SendEvent(T & payload)
  350. {
  351. // Ensure we never fire an event that we can't handle size wise.
  352. Assert(sizeof(T) <= (kMaxEventQueueEventSize - sizeof(EventId)));
  353. // NOTE: Keep this small to avoid code bloat.
  354. // every line of code in here should be scrutinized
  355. // as this and GetEventId could easily be sources
  356. // of bloat if allowed to grow.
  357. SendEventImpl(UnityEventQueue::GetEventId<T>(), (unsigned char*)(&payload), sizeof(T));
  358. }
  359. #if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  360. // Some events want to have a destructor.
  361. //
  362. // You do this by creating a public Destroy()
  363. // method on your Event payload. You then
  364. // register the event with REGISTER_EVENT_ID_WITH_CLEANUP
  365. //
  366. // If your event will have someone listening to it right away
  367. // then you do not need to do anything else.
  368. //
  369. // However, if there is a danger that your event will be fired
  370. // before someone starts listening for it then you must
  371. // call this method somewhere. This will manually register your
  372. // class for cleanup. There is no harm in calling this even
  373. // if it is not required. If in doubt and your event payload
  374. // requires some form of destruction, call this method!
  375. template<typename T>
  376. void RegisterCleanup(T & payload)
  377. {
  378. EventHandler * eh = UnityEventQueue::GetEventDestructor<T>();
  379. if (eh != NULL)
  380. SetCleanupImpl(eh);
  381. }
  382. #endif
  383. // These are not thread safe and must be done on the same thread
  384. // as the dispatch thread. Doing otherwise risks race conditions.
  385. // Fire the add handler / remove handler event if you need to
  386. // schedule this from a different thread.
  387. virtual void AddHandler(EventHandler * handler) = 0;
  388. virtual void RemoveHandler(EventHandler * handler) = 0;
  389. protected:
  390. virtual void SendEventImpl(EventId id, unsigned char * data, int size) = 0;
  391. #if EVENTQUEUE_SUPPORTS_EVENT_CLEANUP
  392. // This is an event destructor. You can register one of these
  393. // per event type. This allows events to manage resource if
  394. // they absolutely must. In general you should avoid handling
  395. // resources in events as events usually imply cross thread activity.
  396. virtual void SetCleanupImpl(EventHandler * handler) = 0;
  397. #endif
  398. };
  399. }
  400. REGISTER_EVENT_ID(0x19D736400584B24BULL, 0x98B9EFBE26D3F3C9ULL, AddEventHandler)
  401. REGISTER_EVENT_ID(0x8D4A317C4F577F4AULL, 0x851D6E457566A905ULL, RemoveEventHandler)
  402. UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(0x9959C347F5AE374DULL, 0x9BADE6FC8EF49E7FULL, IUnityEventQueue, UnityEventQueue)