Magic World game server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.2 KiB

5 years ago
  1. #include <MWMap.h>
  2. using namespace std;
  3. MWMap::MWMap(bool trace, const shared_ptr<Ice::Logger>& logger) :
  4. _trace(trace),
  5. _logger(logger)
  6. {
  7. }
  8. void
  9. MWMap::reserve(const string& name)
  10. {
  11. lock_guard<mutex> sync(_mutex);
  12. if(_reserved.find(name) != _reserved.end() || _members.find(name) != _members.end())
  13. {
  14. throw runtime_error("The name " + name + " is already in use.");
  15. }
  16. _reserved.insert(name);
  17. }
  18. void
  19. MWMap::unreserve(const string& name)
  20. {
  21. lock_guard<mutex> sync(_mutex);
  22. _reserved.erase(name);
  23. }
  24. void
  25. MWMap::join(const string& name, const shared_ptr<MWMapCallbackAdapter>& callback)
  26. {
  27. lock_guard<mutex> sync(_mutex);
  28. long long timestamp = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count();
  29. _reserved.erase(name);
  30. Ice::StringSeq names;
  31. for(const auto& q : _members)
  32. {
  33. names.push_back(q.first);
  34. }
  35. callback->init(move(names));
  36. _members[name] = callback;
  37. auto e = make_shared<MW::UserJoinedEvent>(timestamp, name);
  38. for(const auto& q: _members)
  39. {
  40. q.second->join(e);
  41. }
  42. if(_trace)
  43. {
  44. Ice::Trace out(_logger, "info");
  45. out << "User '" << name << "' joined the MW Map.";
  46. }
  47. }
  48. void
  49. MWMap::leave(const string& name)
  50. {
  51. lock_guard<mutex> sync(_mutex);
  52. long long timestamp = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count();
  53. _members.erase(name);
  54. auto e = make_shared<MW::UserLeftEvent>(timestamp, name);
  55. for(const auto& q: _members)
  56. {
  57. q.second->leave(e);
  58. }
  59. if(_trace)
  60. {
  61. Ice::Trace out(_logger, "info");
  62. out << "User '" << name << "' left the MWMap.";
  63. }
  64. }
  65. Ice::Long
  66. MWMap::send(const string& name, string message)
  67. {
  68. lock_guard<mutex> sync(_mutex);
  69. long long timestamp = chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now().time_since_epoch()).count();
  70. auto e = make_shared<MW::PositionEvent>(timestamp, name, message);
  71. for(const auto& q: _members)
  72. {
  73. q.second->send(e);
  74. }
  75. if(_trace)
  76. {
  77. Ice::Trace out(_logger, "info");
  78. out << name << ": " << message;
  79. }
  80. return timestamp;
  81. }