1 | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************// |
2 | //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// |
3 | #pragma once |
4 | |
5 | #include "Prerequisites/BsPrerequisitesUtil.h" |
6 | #include "Utility/BsModule.h" |
7 | |
8 | namespace bs |
9 | { |
10 | /** @addtogroup General |
11 | * @{ |
12 | */ |
13 | |
14 | /** |
15 | * Allows you to transparently pass messages between different systems. |
16 | * |
17 | * @note Sim thread only. |
18 | */ |
19 | class BS_UTILITY_EXPORT MessageHandler : public Module<MessageHandler> |
20 | { |
21 | struct MessageHandlerData |
22 | { |
23 | UINT32 id; |
24 | std::function<void()> callback; |
25 | }; |
26 | |
27 | public: |
28 | MessageHandler() = default; |
29 | |
30 | /** Sends a message to all subscribed listeners. */ |
31 | void send(MessageId message); |
32 | |
33 | /** |
34 | * Subscribes a message listener for the specified message. Provided callback will be triggered whenever that |
35 | * message gets sent. |
36 | * |
37 | * @return A handle to the message subscription that you can use to unsubscribe from listening. |
38 | */ |
39 | HMessage listen(MessageId message, std::function<void()> callback); |
40 | |
41 | private: |
42 | friend class HMessage; |
43 | void unsubscribe(UINT32 handleId); |
44 | |
45 | Map<UINT32, Vector<MessageHandlerData>> mMessageHandlers; |
46 | Map<UINT32, UINT32> mHandlerIdToMessageMap; |
47 | |
48 | UINT32 mNextCallbackId = 1; |
49 | }; |
50 | |
51 | /** @} */ |
52 | } |
53 | |