Connection.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Component.h"
  25. #include "Connection.h"
  26. #include "Log.h"
  27. #include "Protocol.h"
  28. #include "Scene.h"
  29. #include <kNet.h>
  30. #include "DebugNew.h"
  31. OBJECTTYPESTATIC(Connection);
  32. Connection::Connection(Context* context, bool isClient, kNet::SharedPtr<kNet::MessageConnection> connection) :
  33. Object(context),
  34. connection_(connection),
  35. frameNumber_(0),
  36. isClient_(isClient),
  37. connectPending_(false),
  38. sceneLoaded_(false)
  39. {
  40. }
  41. Connection::~Connection()
  42. {
  43. // Reset owner from the scene, as this connection is about to be destroyed
  44. if (scene_)
  45. scene_->ResetOwner(this);
  46. }
  47. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  48. {
  49. // Make sure not to use kNet internal message ID's
  50. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  51. {
  52. LOGERROR("Can not send message with reserved ID");
  53. return;
  54. }
  55. connection_->SendMessage(msgID, reliable, inOrder, 0, 0, (const char*)data, numBytes);
  56. }
  57. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg)
  58. {
  59. SendMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize());
  60. }
  61. void Connection::SendMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  62. {
  63. // Make sure not to use kNet internal message ID's
  64. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  65. {
  66. LOGERROR("Can not send message with reserved ID");
  67. return;
  68. }
  69. connection_->SendMessage(msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);
  70. }
  71. void Connection::SendMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const VectorBuffer& msg)
  72. {
  73. SendMessage(msgID, contentID, reliable, inOrder, msg.GetData(), msg.GetSize());
  74. }
  75. void Connection::SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  76. {
  77. msg_.Clear();
  78. msg_.WriteStringHash(eventType);
  79. msg_.WriteVariantMap(eventData);
  80. SendMessage(MSG_REMOTEEVENT, true, inOrder, msg_);
  81. }
  82. void Connection::SendRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  83. {
  84. if (!receiver)
  85. {
  86. LOGERROR("Null node for remote node event");
  87. return;
  88. }
  89. if (receiver->GetScene() != scene_)
  90. {
  91. LOGERROR("Node is not in the connection's scene, can not send remote node event");
  92. return;
  93. }
  94. if (receiver->GetID() >= FIRST_LOCAL_ID)
  95. {
  96. LOGERROR("Node has a local ID, can not send remote node event");
  97. return;
  98. }
  99. msg_.Clear();
  100. msg_.WriteVLE(receiver->GetID());
  101. msg_.WriteStringHash(eventType);
  102. msg_.WriteVariantMap(eventData);
  103. SendMessage(MSG_REMOTENODEEVENT, true, inOrder, msg_);
  104. }
  105. void Connection::SetScene(Scene* newScene)
  106. {
  107. if (scene_ == newScene)
  108. return;
  109. // Reset the owner reference from the previous scene's nodes
  110. if (scene_)
  111. scene_->ResetOwner(this);
  112. scene_ = newScene;
  113. sceneLoaded_ = false;
  114. if (isClient_ && scene_)
  115. {
  116. sceneState_.Clear();
  117. // When scene is assigned on the server, instruct the client to load it
  118. /// \todo Download package(s) needed for the scene, if they do not exist already on the client
  119. msg_.Clear();
  120. msg_.WriteString(scene_->GetFileName());
  121. SendMessage(MSG_LOADSCENE, true, true, msg_);
  122. }
  123. }
  124. void Connection::SetIdentity(const VariantMap& identity)
  125. {
  126. identity_ = identity;
  127. }
  128. void Connection::SetControls(const Controls& newControls)
  129. {
  130. previousControls_ = controls_;
  131. controls_ = newControls;
  132. }
  133. void Connection::SetConnectPending(bool connectPending)
  134. {
  135. connectPending_ = connectPending;
  136. }
  137. void Connection::Disconnect(int waitMSec)
  138. {
  139. connection_->Disconnect(waitMSec);
  140. }
  141. void Connection::ProcessReplication()
  142. {
  143. if (!isClient_ || !scene_ || !sceneLoaded_)
  144. return;
  145. const Map<unsigned, Node*>& nodes = scene_->GetAllNodes();
  146. // Check for new or modified nodes
  147. /// \todo Send in correct order that takes node parenting into account
  148. for (Map<unsigned, Node*>::ConstIterator i = nodes.Begin(); i != nodes.End(); ++i)
  149. {
  150. // Break when we reach local node IDs
  151. if (i->first_ >= FIRST_LOCAL_ID)
  152. break;
  153. if (sceneState_.Find(i->first_) == sceneState_.End())
  154. ProcessNewNode(i->second_);
  155. else
  156. ProcessExistingNode(i->second_);
  157. }
  158. // Check for removed nodes
  159. for (Map<unsigned, NodeReplicationState>::Iterator i = sceneState_.Begin(); i != sceneState_.End();)
  160. {
  161. Map<unsigned, NodeReplicationState>::Iterator current = i++;
  162. if (current->second_.frameNumber_ != frameNumber_)
  163. {
  164. msg_.Clear();
  165. msg_.WriteVLE(current->first_);
  166. SendMessage(MSG_REMOVENODE, true, true, msg_);
  167. sceneState_.Erase(current);
  168. }
  169. }
  170. ++frameNumber_;
  171. }
  172. kNet::MessageConnection* Connection::GetMessageConnection() const
  173. {
  174. return const_cast<kNet::MessageConnection*>(connection_.ptr());
  175. }
  176. Scene* Connection::GetScene() const
  177. {
  178. return scene_;
  179. }
  180. bool Connection::IsConnected() const
  181. {
  182. return connection_->GetConnectionState() == kNet::ConnectionOK;
  183. }
  184. String Connection::GetAddress() const
  185. {
  186. const unsigned char* ip = connection_->RemoteEndPoint().ip;
  187. char str[256];
  188. sprintf(str, "%d.%d.%d.%d", (unsigned)ip[0], (unsigned)ip[1], (unsigned)ip[2], (unsigned)ip[3]);
  189. return String(str);
  190. }
  191. unsigned short Connection::GetPort() const
  192. {
  193. return connection_->RemoteEndPoint().port;
  194. }
  195. String Connection::ToString() const
  196. {
  197. return GetAddress() + ":" + String(GetPort());
  198. }
  199. void Connection::ProcessNewNode(Node* node)
  200. {
  201. msg_.Clear();
  202. msg_.WriteVLE(node->GetID());
  203. NodeReplicationState newNodeState;
  204. newNodeState.frameNumber_ = frameNumber_;
  205. // Write node's attributes
  206. msg_.WriteVLE(node->GetNumNetworkAttributes());
  207. const Vector<AttributeInfo>* attributes = node->GetAttributes();
  208. for (unsigned i = 0; i < attributes->Size(); ++i)
  209. {
  210. const AttributeInfo& attr = attributes->At(i);
  211. if (!(attr.mode_ & AM_NETWORK))
  212. continue;
  213. Variant value = node->GetAttribute(i);
  214. msg_.WriteVariantData(value);
  215. newNodeState.attributes_.Push(value);
  216. }
  217. // Write node's variable map
  218. const VariantMap& vars = node->GetVars();
  219. msg_.WriteVLE(vars.Size());
  220. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  221. {
  222. msg_.WriteShortStringHash(i->first_);
  223. msg_.WriteVariant(i->second_);
  224. newNodeState.vars_[i->first_] = i->second_;
  225. }
  226. // Write node's components
  227. msg_.WriteVLE(node->GetNumNetworkComponents());
  228. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  229. for (unsigned i = 0; i < components.Size(); ++i)
  230. {
  231. Component* component = components[i];
  232. if (component->GetID() >= FIRST_LOCAL_ID)
  233. continue;
  234. msg_.WriteShortStringHash(component->GetType());
  235. msg_.WriteVLE(component->GetID());
  236. ComponentReplicationState newComponentState;
  237. newComponentState.frameNumber_ = frameNumber_;
  238. newComponentState.type_ = component->GetType();
  239. // Write component's attributes
  240. msg_.WriteVLE(component->GetNumNetworkAttributes());
  241. const Vector<AttributeInfo>* attributes = component->GetAttributes();
  242. if (attributes)
  243. {
  244. for (unsigned j = 0; j < attributes->Size(); ++j)
  245. {
  246. const AttributeInfo& attr = attributes->At(j);
  247. if (!(attr.mode_ & AM_NETWORK))
  248. continue;
  249. Variant value = component->GetAttribute(j);
  250. msg_.WriteVariantData(value);
  251. newComponentState.attributes_.Push(value);
  252. }
  253. }
  254. newNodeState.components_[component->GetID()] = newComponentState;
  255. }
  256. SendMessage(MSG_CREATENODE, true, true, msg_);
  257. sceneState_[node->GetID()] = newNodeState;
  258. }
  259. void Connection::ProcessExistingNode(Node* node)
  260. {
  261. NodeReplicationState& nodeState = sceneState_[node->GetID()];
  262. nodeState.frameNumber_ = frameNumber_;
  263. // Check if attributes have changed
  264. bool deltaUpdate = false;
  265. bool latestData = false;
  266. const Vector<AttributeInfo>* attributes = node->GetAttributes();
  267. deltaUpdateBits_.Resize((node->GetNumNetworkAttributes() + 7) >> 3);
  268. for (unsigned i = 0; i < deltaUpdateBits_.Size(); ++i)
  269. deltaUpdateBits_[i] = 0;
  270. unsigned index = 0;
  271. // Make sure the current attributes vector is large enough
  272. if (currentAttributes_.Size() < nodeState.attributes_.Size())
  273. currentAttributes_.Resize(nodeState.attributes_.Size());
  274. for (unsigned i = 0; i < attributes->Size(); ++i)
  275. {
  276. const AttributeInfo& attr = attributes->At(i);
  277. if (!(attr.mode_ & AM_NETWORK))
  278. continue;
  279. // Check for attribute change
  280. currentAttributes_[index] = node->GetAttribute(i);
  281. if (currentAttributes_[index] != nodeState.attributes_[index])
  282. {
  283. if (attr.mode_ & AM_LATESTDATA)
  284. latestData = true;
  285. else
  286. {
  287. deltaUpdate = true;
  288. deltaUpdateBits_[index >> 3] |= 1 << (index & 7);
  289. }
  290. }
  291. ++index;
  292. }
  293. // Check if variable map has changed. Note: variable removal is not supported
  294. changedVars_.Clear();
  295. const VariantMap& vars = node->GetVars();
  296. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  297. {
  298. VariantMap::ConstIterator j = nodeState.vars_.Find(i->first_);
  299. if (j == nodeState.vars_.End() || i->second_ != j->second_)
  300. {
  301. changedVars_.Insert(i->first_);
  302. deltaUpdate = true;
  303. }
  304. }
  305. // Send deltaupdate message if necessary
  306. if (deltaUpdate)
  307. {
  308. msg_.Clear();
  309. msg_.WriteVLE(node->GetID());
  310. // Write changed attributes
  311. msg_.Write(&deltaUpdateBits_[0], deltaUpdateBits_.Size());
  312. index = 0;
  313. for (unsigned i = 0; i < attributes->Size(); ++i)
  314. {
  315. const AttributeInfo& attr = attributes->At(i);
  316. if (!(attr.mode_ & AM_NETWORK))
  317. continue;
  318. if (deltaUpdateBits_[index << 3] & (1 << (index & 7)))
  319. {
  320. msg_.WriteVariantData(currentAttributes_[index]);
  321. nodeState.attributes_[index] = currentAttributes_[index];
  322. }
  323. ++index;
  324. }
  325. // Write changed variables
  326. msg_.WriteVLE(changedVars_.Size());
  327. for (HashSet<ShortStringHash>::ConstIterator i = changedVars_.Begin(); i != changedVars_.End(); ++i)
  328. {
  329. VariantMap::ConstIterator j = vars.Find(*i);
  330. msg_.WriteShortStringHash(j->first_);
  331. msg_.WriteVariant(j->second_);
  332. nodeState.vars_[j->first_] = j->second_;
  333. }
  334. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  335. }
  336. // Send latestdata message if necessary
  337. if (latestData)
  338. {
  339. // If at least one latest data attribute changes, send all of them
  340. msg_.Clear();
  341. msg_.WriteVLE(node->GetID());
  342. index = 0;
  343. for (unsigned i = 0; i < attributes->Size(); ++i)
  344. {
  345. const AttributeInfo& attr = attributes->At(i);
  346. if ((attr.mode_ & (AM_NETWORK | AM_LATESTDATA)) != (AM_NETWORK | AM_LATESTDATA))
  347. continue;
  348. msg_.WriteVariantData(currentAttributes_[index]);
  349. nodeState.attributes_[index] = currentAttributes_[index];
  350. ++index;
  351. }
  352. SendMessage(MSG_NODELATESTDATA, node->GetID(), true, false, msg_);
  353. }
  354. // Check for new/updated components
  355. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  356. for (unsigned i = 0; i < components.Size(); ++i)
  357. {
  358. Component* component = components[i];
  359. if (component->GetID() >= FIRST_LOCAL_ID)
  360. continue;
  361. Map<unsigned, ComponentReplicationState>::Iterator j = nodeState.components_.Find(component->GetID());
  362. if (j == nodeState.components_.End())
  363. {
  364. // New component
  365. msg_.Clear();
  366. msg_.WriteVLE(node->GetID());
  367. msg_.WriteShortStringHash(component->GetType());
  368. msg_.WriteVLE(component->GetID());
  369. ComponentReplicationState newComponentState;
  370. newComponentState.frameNumber_ = frameNumber_;
  371. newComponentState.type_ = component->GetType();
  372. // Write component's attributes
  373. msg_.WriteVLE(component->GetNumNetworkAttributes());
  374. const Vector<AttributeInfo>* attributes = component->GetAttributes();
  375. if (attributes)
  376. {
  377. for (unsigned k = 0; k < attributes->Size(); ++k)
  378. {
  379. const AttributeInfo& attr = attributes->At(k);
  380. if (!(attr.mode_ & AM_NETWORK))
  381. continue;
  382. Variant value = component->GetAttribute(k);
  383. msg_.WriteVariantData(value);
  384. newComponentState.attributes_.Push(value);
  385. }
  386. }
  387. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  388. nodeState.components_[component->GetID()] = newComponentState;
  389. }
  390. else
  391. {
  392. // Existing component
  393. ComponentReplicationState& componentState = j->second_;
  394. componentState.frameNumber_ = frameNumber_;
  395. deltaUpdate = false;
  396. latestData = false;
  397. const Vector<AttributeInfo>* attributes = component->GetAttributes();
  398. deltaUpdateBits_.Resize((component->GetNumNetworkAttributes() + 7) >> 3);
  399. for (unsigned k = 0; k < deltaUpdateBits_.Size(); ++k)
  400. deltaUpdateBits_[k] = 0;
  401. index = 0;
  402. // Make sure the current attributes vector is large enough
  403. if (currentAttributes_.Size() < componentState.attributes_.Size())
  404. currentAttributes_.Resize(componentState.attributes_.Size());
  405. for (unsigned k = 0; k < attributes->Size(); ++k)
  406. {
  407. const AttributeInfo& attr = attributes->At(k);
  408. if (!(attr.mode_ & AM_NETWORK))
  409. continue;
  410. // Check for attribute change
  411. currentAttributes_[index] = component->GetAttribute(k);
  412. if (currentAttributes_[index] != nodeState.attributes_[index])
  413. {
  414. if (attr.mode_ & AM_LATESTDATA)
  415. latestData = true;
  416. else
  417. {
  418. deltaUpdate = true;
  419. deltaUpdateBits_[index >> 3] |= 1 << (index & 7);
  420. }
  421. }
  422. ++index;
  423. }
  424. // Send deltaupdate message if necessary
  425. if (deltaUpdate)
  426. {
  427. msg_.Clear();
  428. msg_.WriteVLE(component->GetID());
  429. // Write changed attributes
  430. msg_.Write(&deltaUpdateBits_[0], deltaUpdateBits_.Size());
  431. index = 0;
  432. for (unsigned k = 0; k < attributes->Size(); ++k)
  433. {
  434. const AttributeInfo& attr = attributes->At(k);
  435. if (!(attr.mode_ & AM_NETWORK))
  436. continue;
  437. if (deltaUpdateBits_[index << 3] & (1 << (index & 7)))
  438. {
  439. msg_.WriteVariantData(currentAttributes_[index]);
  440. componentState.attributes_[index] = currentAttributes_[index];
  441. }
  442. ++index;
  443. }
  444. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  445. }
  446. // Send latestdata message if necessary
  447. if (latestData)
  448. {
  449. // If at least one latest data attribute changes, send all of them
  450. msg_.Clear();
  451. msg_.WriteVLE(component->GetID());
  452. index = 0;
  453. for (unsigned k = 0; k < attributes->Size(); ++k)
  454. {
  455. const AttributeInfo& attr = attributes->At(k);
  456. if ((attr.mode_ & (AM_NETWORK | AM_LATESTDATA)) != (AM_NETWORK | AM_LATESTDATA))
  457. continue;
  458. msg_.WriteVariantData(currentAttributes_[index]);
  459. componentState.attributes_[index] = currentAttributes_[index];
  460. ++index;
  461. }
  462. SendMessage(MSG_COMPONENTLATESTDATA, component->GetID(), true, false, msg_);
  463. }
  464. }
  465. }
  466. // Check for removed components
  467. for (Map<unsigned, ComponentReplicationState>::Iterator i = nodeState.components_.Begin(); i != nodeState.components_.End();)
  468. {
  469. Map<unsigned, ComponentReplicationState>::Iterator current = i++;
  470. if (current->second_.frameNumber_ != frameNumber_)
  471. {
  472. msg_.Clear();
  473. msg_.WriteVLE(node->GetID());
  474. msg_.WriteVLE(current->first_);
  475. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  476. nodeState.components_.Erase(current);
  477. }
  478. }
  479. }