NLS Engine  v0.1
The Next Logical Step in game engine design.
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Defines
MessageRouter.h
Go to the documentation of this file.
00001 #pragma once
00002 
00013 // Standard Includes
00014 #include <map>
00015 #include <queue>
00016 #include <set>
00017 
00018 // Library Includes
00019 #include <boost/bind.hpp>
00020 #include <boost/function.hpp>
00021 #include <threading.h>
00022 
00023 // Local Includes
00024 #include "Envelope_fwd.h"
00025 
00026 // Forward Declarations
00027 
00028 // Typedefs
00029 typedef boost::function<void (EnvelopeSPTR)> Subscriber;
00030 typedef boost::function<EnvelopeSPTR (EnvelopeSPTR)> DirectedSubscriber;
00031 typedef std::shared_ptr<Subscriber> SubscriberSPTR;
00032 typedef std::set<SubscriberSPTR> SubscriberCollectionType;
00033 typedef std::map<int, SubscriberCollectionType> SubscriptionsType;
00034 typedef std::map<int, std::shared_ptr<DirectedSubscriber>> DirectedSubscriptionsType;
00035 
00036 enum CORE_MESSAGE : unsigned int {STARTUP = 0x0000, QUIT = 0x0099, SHUTDOWN = 0x0100, CREATE = 0x0001, LOADLIBRARY = 0x0002, MODULESTARTED = 0x0003};
00037 
00038 class MessageRouter {
00039 public:
00040   MessageRouter(void);
00041   ~MessageRouter(void);
00042   
00043   void Subscribe(int id, SubscriberSPTR& s); // Subscribe to message id, with subscriber function s
00044   void Subscribe(std::vector<int>& ids, SubscriberSPTR& s); // Subscribe to all messages ids, with subscriber function s
00045   void SubscribeDirected(int id, std::shared_ptr<DirectedSubscriber>& s); // Subscribe to a Directed Subscription with subscription id
00046   void Unsubscribe(int id, SubscriberSPTR& s);
00047   void Unsubscribe(std::vector<int>& ids, SubscriberSPTR& s);
00048   void SendSP(EnvelopeSPTR, bool async = true); // Add a new envelope to the backlog, Envelopes must be dynamic memory to allow the dtor to free all unrouted messages safely. If sync is set to true the message is sent synchronously
00049   EnvelopeSPTR SendDirected(EnvelopeSPTR e, int id) const; // Sends a message to the specified id, and returns another Envelope
00050   void Route(void); // Thread to handle the backlog
00051   void Shutdown(EnvelopeSPTR e); // Used to shutdown this module after quit has been initiated
00052   void Quit(EnvelopeSPTR e); // Used when the application is quiting.
00053   
00054 private:
00055   mutable Threading::ReadWriteMutex subscriptionsMutex;
00056   SubscriptionsType subscriptions; // a mapping of message ids to subscribers
00057   
00058   mutable Threading::ReadWriteMutex directedSubscriptionMutex;
00059   DirectedSubscriptionsType directedSubscription; // a mapping of message ids to subscribers
00060   
00061   mutable Threading::ReadWriteMutex backlogMutex;
00062   std::queue<EnvelopeSPTR> backlog;
00063   
00064   bool routing;
00065 };