Connection.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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 "File.h"
  27. #include "FileSystem.h"
  28. #include "Log.h"
  29. #include "MemoryBuffer.h"
  30. #include "NetworkEvents.h"
  31. #include "Profiler.h"
  32. #include "Protocol.h"
  33. #include "Scene.h"
  34. #include "SceneEvents.h"
  35. #include <kNet.h>
  36. #include "DebugNew.h"
  37. OBJECTTYPESTATIC(Connection);
  38. Connection::Connection(Context* context, bool isClient, kNet::SharedPtr<kNet::MessageConnection> connection) :
  39. Object(context),
  40. connection_(connection),
  41. frameNumber_(0),
  42. isClient_(isClient),
  43. connectPending_(false),
  44. sceneLoaded_(false)
  45. {
  46. }
  47. Connection::~Connection()
  48. {
  49. // Reset owner from the scene, as this connection is about to be destroyed
  50. if (scene_)
  51. scene_->ResetOwner(this);
  52. }
  53. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  54. {
  55. // Make sure not to use kNet internal message ID's
  56. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  57. {
  58. LOGERROR("Can not send message with reserved ID");
  59. return;
  60. }
  61. connection_->SendMessage(msgID, reliable, inOrder, 0, 0, (const char*)data, numBytes);
  62. }
  63. void Connection::SendMessage(int msgID, bool reliable, bool inOrder, const VectorBuffer& msg)
  64. {
  65. SendMessage(msgID, reliable, inOrder, msg.GetData(), msg.GetSize());
  66. }
  67. void Connection::SendMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const unsigned char* data, unsigned numBytes)
  68. {
  69. // Make sure not to use kNet internal message ID's
  70. if (msgID <= 0x4 || msgID >= 0x3ffffffe)
  71. {
  72. LOGERROR("Can not send message with reserved ID");
  73. return;
  74. }
  75. connection_->SendMessage(msgID, reliable, inOrder, 0, contentID, (const char*)data, numBytes);
  76. }
  77. void Connection::SendMessage(int msgID, unsigned contentID, bool reliable, bool inOrder, const VectorBuffer& msg)
  78. {
  79. SendMessage(msgID, contentID, reliable, inOrder, msg.GetData(), msg.GetSize());
  80. }
  81. void Connection::SendRemoteEvent(StringHash eventType, bool inOrder, const VariantMap& eventData)
  82. {
  83. msg_.Clear();
  84. msg_.WriteStringHash(eventType);
  85. msg_.WriteVariantMap(eventData);
  86. SendMessage(MSG_REMOTEEVENT, true, inOrder, msg_);
  87. }
  88. void Connection::SendRemoteEvent(Node* receiver, StringHash eventType, bool inOrder, const VariantMap& eventData)
  89. {
  90. if (!receiver)
  91. {
  92. LOGERROR("Null node for remote node event");
  93. return;
  94. }
  95. if (receiver->GetScene() != scene_)
  96. {
  97. LOGERROR("Node is not in the connection's scene, can not send remote node event");
  98. return;
  99. }
  100. if (receiver->GetID() >= FIRST_LOCAL_ID)
  101. {
  102. LOGERROR("Node has a local ID, can not send remote node event");
  103. return;
  104. }
  105. msg_.Clear();
  106. msg_.WriteVLE(receiver->GetID());
  107. msg_.WriteStringHash(eventType);
  108. msg_.WriteVariantMap(eventData);
  109. SendMessage(MSG_REMOTENODEEVENT, true, inOrder, msg_);
  110. }
  111. void Connection::SetScene(Scene* newScene)
  112. {
  113. if (scene_ == newScene)
  114. return;
  115. // Reset the owner reference from the previous scene's nodes
  116. if (scene_)
  117. scene_->ResetOwner(this);
  118. scene_ = newScene;
  119. sceneLoaded_ = false;
  120. UnsubscribeFromEvent(E_ASYNCLOADFINISHED);
  121. if (!scene_)
  122. return;
  123. if (isClient_)
  124. {
  125. sceneState_.Clear();
  126. // When scene is assigned on the server, instruct the client to load it
  127. /// \todo Download package(s) needed for the scene, if they do not exist already on the client
  128. msg_.Clear();
  129. msg_.WriteString(scene_->GetFileName());
  130. SendMessage(MSG_LOADSCENE, true, true, msg_);
  131. }
  132. else
  133. {
  134. // Make sure there is no existing async loading
  135. scene_->StopAsyncLoading();
  136. SubscribeToEvent(scene_, E_ASYNCLOADFINISHED, HANDLER(Connection, HandleAsyncLoadFinished));
  137. }
  138. }
  139. void Connection::SetIdentity(const VariantMap& identity)
  140. {
  141. identity_ = identity;
  142. }
  143. void Connection::SetControls(const Controls& newControls)
  144. {
  145. previousControls_ = controls_;
  146. controls_ = newControls;
  147. }
  148. void Connection::SetConnectPending(bool connectPending)
  149. {
  150. connectPending_ = connectPending;
  151. }
  152. void Connection::Disconnect(int waitMSec)
  153. {
  154. connection_->Disconnect(waitMSec);
  155. }
  156. void Connection::SendServerUpdate()
  157. {
  158. if (!isClient_ || !scene_ || !sceneLoaded_)
  159. return;
  160. PROFILE(SendServerUpdate);
  161. const Map<unsigned, Node*>& nodes = scene_->GetAllNodes();
  162. // Check for new or changed nodes
  163. // Start from the root node (scene) so that the scene-wide components get sent first
  164. processedNodes_.Clear();
  165. ProcessNode(scene_);
  166. // Then go through the rest of the nodes
  167. for (Map<unsigned, Node*>::ConstIterator i = nodes.Begin(); i != nodes.End() && i->first_ < FIRST_LOCAL_ID; ++i)
  168. ProcessNode(i->second_);
  169. // Check for removed nodes
  170. for (Map<unsigned, NodeReplicationState>::Iterator i = sceneState_.Begin(); i != sceneState_.End();)
  171. {
  172. Map<unsigned, NodeReplicationState>::Iterator current = i++;
  173. if (current->second_.frameNumber_ != frameNumber_)
  174. {
  175. msg_.Clear();
  176. msg_.WriteVLE(current->first_);
  177. SendMessage(MSG_REMOVENODE, true, true, msg_);
  178. sceneState_.Erase(current);
  179. }
  180. }
  181. ++frameNumber_;
  182. }
  183. void Connection::SendClientUpdate()
  184. {
  185. if (isClient_ || !scene_ || !sceneLoaded_)
  186. return;
  187. PROFILE(SendClientUpdate);
  188. msg_.Clear();
  189. msg_.WriteUInt(controls_.buttons_);
  190. msg_.WriteFloat(controls_.yaw_);
  191. msg_.WriteFloat(controls_.pitch_);
  192. msg_.WriteVariantMap(controls_.extraData_);
  193. SendMessage(MSG_CONTROLS, CONTROLS_CONTENT_ID, false, false, msg_);
  194. }
  195. void Connection::ProcessPendingLatestData()
  196. {
  197. if (!scene_)
  198. return;
  199. // Iterate through pending node data and see if we can find the nodes now
  200. for (Map<unsigned, PODVector<unsigned char> >::Iterator i = nodeLatestData_.Begin(); i != nodeLatestData_.End();)
  201. {
  202. Map<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  203. Node* node = scene_->GetNodeByID(current->first_);
  204. if (node)
  205. {
  206. MemoryBuffer msg(current->second_);
  207. msg.ReadVLE(); // Skip the node ID
  208. node->ReadLatestDataUpdate(msg);
  209. nodeLatestData_.Erase(current);
  210. }
  211. }
  212. // Iterate through pending component data and see if we can find the components now
  213. for (Map<unsigned, PODVector<unsigned char> >::Iterator i = componentLatestData_.Begin(); i != componentLatestData_.End();)
  214. {
  215. Map<unsigned, PODVector<unsigned char> >::Iterator current = i++;
  216. Component* component = scene_->GetComponentByID(current->first_);
  217. if (component)
  218. {
  219. MemoryBuffer msg(current->second_);
  220. msg.ReadVLE(); // Skip the component ID
  221. component->ReadLatestDataUpdate(msg);
  222. component->FinishUpdate();
  223. componentLatestData_.Erase(current);
  224. }
  225. }
  226. }
  227. void Connection::ProcessLoadScene(int msgID, MemoryBuffer& msg)
  228. {
  229. if (IsClient())
  230. {
  231. LOGWARNING("Received unexpected LoadScene message from client " + ToString());
  232. return;
  233. }
  234. if (!scene_)
  235. {
  236. LOGERROR("Can not handle LoadScene message without an assigned scene");
  237. return;
  238. }
  239. String fileName = msg.ReadString();
  240. // Make sure there is no existing async loading, and clear previous pending latest data if any
  241. scene_->StopAsyncLoading();
  242. nodeLatestData_.Clear();
  243. componentLatestData_.Clear();
  244. if (fileName.Empty())
  245. {
  246. scene_->Clear();
  247. // If filename is empty, can send the scene loaded reply immediately
  248. VectorBuffer replyMsg;
  249. replyMsg.WriteUInt(scene_->GetChecksum());
  250. SendMessage(MSG_SCENELOADED, true, true, replyMsg);
  251. }
  252. else
  253. {
  254. // Otherwise start the async loading process
  255. String extension = GetExtension(fileName);
  256. SharedPtr<File> file(new File(context_, fileName));
  257. bool success;
  258. if (extension == ".xml")
  259. success = scene_->LoadAsyncXML(file);
  260. else
  261. success = scene_->LoadAsync(file);
  262. if (!success)
  263. {
  264. using namespace NetworkSceneLoadFailed;
  265. VariantMap eventData;
  266. eventData[P_CONNECTION] = (void*)this;
  267. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  268. }
  269. }
  270. }
  271. void Connection::ProcessSceneChecksumError(int msgID, MemoryBuffer& msg)
  272. {
  273. if (IsClient())
  274. {
  275. LOGWARNING("Received unexpected SceneChecksumError message from client " + ToString());
  276. return;
  277. }
  278. using namespace NetworkSceneLoadFailed;
  279. VariantMap eventData;
  280. eventData[P_CONNECTION] = (void*)this;
  281. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  282. }
  283. void Connection::ProcessSceneUpdate(int msgID, MemoryBuffer& msg)
  284. {
  285. if (IsClient())
  286. {
  287. LOGWARNING("Received unexpected SceneUpdate message from client " + ToString());
  288. return;
  289. }
  290. if (!scene_)
  291. return;
  292. switch (msgID)
  293. {
  294. case MSG_CREATENODE:
  295. {
  296. unsigned nodeID = msg.ReadVLE();
  297. // In case of the root node (scene), it may already exist. Do not create in that case
  298. Node* node = scene_->GetNodeByID(nodeID);
  299. if (!node)
  300. {
  301. // Add initially to the root level. May be moved later
  302. node = scene_->CreateChild(nodeID, false);
  303. }
  304. // Read initial attributes
  305. node->ReadDeltaUpdate(msg, deltaUpdateBits_);
  306. // Read initial user variables
  307. unsigned numVars = msg.ReadVLE();
  308. VariantMap& vars = node->GetVars();
  309. while (numVars)
  310. {
  311. --numVars;
  312. ShortStringHash key = msg.ReadShortStringHash();
  313. vars[key] = msg.ReadVariant();
  314. }
  315. // Read components
  316. unsigned numComponents = msg.ReadVLE();
  317. while (numComponents)
  318. {
  319. --numComponents;
  320. ShortStringHash type = msg.ReadShortStringHash();
  321. unsigned componentID = msg.ReadVLE();
  322. // Check if the component by this ID and type already exists in this node
  323. Component* component = scene_->GetComponentByID(componentID);
  324. if (!component || component->GetType() != type || component->GetNode() != node)
  325. {
  326. if (component)
  327. component->Remove();
  328. component = node->CreateComponent(type, componentID, false);
  329. }
  330. // If was unable to create the component, would desync the message and therefore have to abort
  331. if (!component)
  332. {
  333. LOGERROR("CreateNode message parsing aborted due to unknown component");
  334. return;
  335. }
  336. // Read initial attributes, then perform finalization
  337. component->ReadDeltaUpdate(msg, deltaUpdateBits_);
  338. component->FinishUpdate();
  339. }
  340. }
  341. break;
  342. case MSG_NODEDELTAUPDATE:
  343. {
  344. unsigned nodeID = msg.ReadVLE();
  345. Node* node = scene_->GetNodeByID(nodeID);
  346. if (node)
  347. {
  348. node->ReadDeltaUpdate(msg, deltaUpdateBits_);
  349. unsigned changedVars = msg.ReadVLE();
  350. VariantMap& vars = node->GetVars();
  351. while (changedVars)
  352. {
  353. --changedVars;
  354. ShortStringHash key = msg.ReadShortStringHash();
  355. vars[key] = msg.ReadVariant();
  356. }
  357. }
  358. else
  359. LOGWARNING("NodeDeltaUpdate message received for missing node " + String(nodeID));
  360. }
  361. break;
  362. case MSG_NODELATESTDATA:
  363. {
  364. unsigned nodeID = msg.ReadVLE();
  365. Node* node = scene_->GetNodeByID(nodeID);
  366. if (node)
  367. node->ReadLatestDataUpdate(msg);
  368. else
  369. {
  370. // Latest data messages may be received out-of-order relative to node creation, so cache if necessary
  371. PODVector<unsigned char>& data = nodeLatestData_[nodeID];
  372. data.Resize(msg.GetSize());
  373. memcpy(&data[0], msg.GetData(), msg.GetSize());
  374. }
  375. }
  376. break;
  377. case MSG_REMOVENODE:
  378. {
  379. unsigned nodeID = msg.ReadVLE();
  380. Node* node = scene_->GetNodeByID(nodeID);
  381. if (node)
  382. node->Remove();
  383. else
  384. LOGWARNING("RemoveNode message received for missing node " + String(nodeID));
  385. nodeLatestData_.Erase(nodeID);
  386. }
  387. break;
  388. case MSG_CREATECOMPONENT:
  389. {
  390. unsigned nodeID = msg.ReadVLE();
  391. Node* node = scene_->GetNodeByID(nodeID);
  392. if (node)
  393. {
  394. ShortStringHash type = msg.ReadShortStringHash();
  395. unsigned componentID = msg.ReadVLE();
  396. // Check if the component by this ID and type already exists in this node
  397. Component* component = scene_->GetComponentByID(componentID);
  398. if (!component || component->GetType() != type || component->GetNode() != node)
  399. {
  400. if (component)
  401. component->Remove();
  402. component = node->CreateComponent(type, componentID, false);
  403. }
  404. // If was unable to create the component, would desync the message and therefore have to abort
  405. if (!component)
  406. {
  407. LOGERROR("CreateComponent message parsing aborted due to unknown component");
  408. return;
  409. }
  410. // Read initial attributes, then perform finalization
  411. component->ReadDeltaUpdate(msg, deltaUpdateBits_);
  412. component->FinishUpdate();
  413. }
  414. else
  415. LOGWARNING("CreateComponent message received for missing node " + String(nodeID));
  416. }
  417. break;
  418. case MSG_COMPONENTDELTAUPDATE:
  419. {
  420. unsigned componentID = msg.ReadVLE();
  421. Component* component = scene_->GetComponentByID(componentID);
  422. if (component)
  423. {
  424. component->ReadDeltaUpdate(msg, deltaUpdateBits_);
  425. component->FinishUpdate();
  426. }
  427. else
  428. LOGWARNING("ComponentDeltaUpdate message received for missing component " + String(componentID));
  429. }
  430. break;
  431. case MSG_COMPONENTLATESTDATA:
  432. {
  433. unsigned componentID = msg.ReadVLE();
  434. Component* component = scene_->GetComponentByID(componentID);
  435. if (component)
  436. {
  437. component->ReadLatestDataUpdate(msg);
  438. component->FinishUpdate();
  439. }
  440. else
  441. {
  442. // Latest data messages may be received out-of-order relative to component creation, so cache if necessary
  443. PODVector<unsigned char>& data = componentLatestData_[componentID];
  444. data.Resize(msg.GetSize());
  445. memcpy(&data[0], msg.GetData(), msg.GetSize());
  446. }
  447. }
  448. break;
  449. case MSG_REMOVECOMPONENT:
  450. {
  451. unsigned componentID = msg.ReadVLE();
  452. Component* component = scene_->GetComponentByID(componentID);
  453. if (component)
  454. component->Remove();
  455. else
  456. LOGWARNING("RemoveComponent message received for missing component " + String(componentID));
  457. componentLatestData_.Erase(componentID);
  458. }
  459. break;
  460. }
  461. }
  462. void Connection::ProcessIdentity(int msgID, MemoryBuffer& msg)
  463. {
  464. if (!IsClient())
  465. {
  466. LOGWARNING("Received unexpected Identity message from server");
  467. return;
  468. }
  469. identity_ = msg.ReadVariantMap();
  470. using namespace ClientIdentity;
  471. VariantMap eventData = identity_;
  472. eventData[P_CONNECTION] = (void*)this;
  473. eventData[P_ALLOW] = true;
  474. SendEvent(E_CLIENTIDENTITY, eventData);
  475. // If connection was denied as a response to the identity event, disconnect now
  476. if (!eventData[P_ALLOW].GetBool())
  477. Disconnect();
  478. }
  479. void Connection::ProcessControls(int msgID, MemoryBuffer& msg)
  480. {
  481. if (!IsClient())
  482. {
  483. LOGWARNING("Received unexpected Controls message from server");
  484. return;
  485. }
  486. Controls newControls;
  487. newControls.buttons_ = msg.ReadUInt();
  488. newControls.yaw_ = msg.ReadFloat();
  489. newControls.pitch_ = msg.ReadFloat();
  490. newControls.extraData_ = msg.ReadVariantMap();
  491. SetControls(newControls);
  492. }
  493. void Connection::ProcessSceneLoaded(int msgID, MemoryBuffer& msg)
  494. {
  495. if (!IsClient())
  496. {
  497. LOGWARNING("Received unexpected SceneLoaded message from server");
  498. return;
  499. }
  500. if (!scene_)
  501. {
  502. LOGWARNING("Received a SceneLoaded message without an assigned scene from client " + ToString());
  503. return;
  504. }
  505. unsigned checksum = msg.ReadUInt();
  506. if (checksum != scene_->GetChecksum())
  507. {
  508. VectorBuffer replyMsg;
  509. SendMessage(MSG_SCENECHECKSUMERROR, true, true, replyMsg);
  510. using namespace NetworkSceneLoadFailed;
  511. VariantMap eventData;
  512. eventData[P_CONNECTION] = (void*)this;
  513. SendEvent(E_NETWORKSCENELOADFAILED, eventData);
  514. }
  515. else
  516. {
  517. sceneLoaded_ = true;
  518. using namespace ClientSceneLoaded;
  519. VariantMap eventData;
  520. eventData[P_CONNECTION] = (void*)this;
  521. SendEvent(E_CLIENTSCENELOADED, eventData);
  522. }
  523. }
  524. void Connection::ProcessRemoteEvent(int msgID, MemoryBuffer& msg)
  525. {
  526. /// \todo Check whether the remote event is allowed based on a black- or whitelist
  527. if (msgID == MSG_REMOTEEVENT)
  528. {
  529. StringHash eventType = msg.ReadStringHash();
  530. VariantMap eventData = msg.ReadVariantMap();
  531. SendEvent(eventType, eventData);
  532. }
  533. else
  534. {
  535. if (!scene_)
  536. {
  537. LOGERROR("Can not receive remote node event without an assigned scene");
  538. return;
  539. }
  540. unsigned nodeID = msg.ReadVLE();
  541. StringHash eventType = msg.ReadStringHash();
  542. VariantMap eventData = msg.ReadVariantMap();
  543. Node* receiver = scene_->GetNodeByID(nodeID);
  544. if (!receiver)
  545. {
  546. LOGWARNING("Missing receiver for remote node event, discarding");
  547. return;
  548. }
  549. SendEvent(receiver, eventType, eventData);
  550. }
  551. }
  552. kNet::MessageConnection* Connection::GetMessageConnection() const
  553. {
  554. return const_cast<kNet::MessageConnection*>(connection_.ptr());
  555. }
  556. Scene* Connection::GetScene() const
  557. {
  558. return scene_;
  559. }
  560. bool Connection::IsConnected() const
  561. {
  562. return connection_->GetConnectionState() == kNet::ConnectionOK;
  563. }
  564. String Connection::GetAddress() const
  565. {
  566. const unsigned char* ip = connection_->RemoteEndPoint().ip;
  567. char str[256];
  568. sprintf(str, "%d.%d.%d.%d", (unsigned)ip[0], (unsigned)ip[1], (unsigned)ip[2], (unsigned)ip[3]);
  569. return String(str);
  570. }
  571. unsigned short Connection::GetPort() const
  572. {
  573. return connection_->RemoteEndPoint().port;
  574. }
  575. String Connection::ToString() const
  576. {
  577. return GetAddress() + ":" + String(GetPort());
  578. }
  579. void Connection::ProcessNode(Node* node)
  580. {
  581. if (!node || processedNodes_.Contains(node))
  582. return;
  583. processedNodes_.Insert(node);
  584. // Process depended upon nodes first
  585. PODVector<Node*> depends;
  586. node->GetDependencyNodes(depends);
  587. for (PODVector<Node*>::ConstIterator i = depends.Begin(); i != depends.End(); ++i)
  588. ProcessNode(*i);
  589. // Check if the client's scene state already has this node
  590. if (sceneState_.Find(node->GetID()) != sceneState_.End())
  591. ProcessExistingNode(node);
  592. else
  593. ProcessNewNode(node);
  594. }
  595. void Connection::ProcessNewNode(Node* node)
  596. {
  597. msg_.Clear();
  598. msg_.WriteVLE(node->GetID());
  599. NodeReplicationState newNodeState;
  600. newNodeState.frameNumber_ = frameNumber_;
  601. // Write node's attributes
  602. node->WriteInitialDeltaUpdate(msg_, deltaUpdateBits_, newNodeState.attributes_);
  603. // Write node's user variables
  604. const VariantMap& vars = node->GetVars();
  605. msg_.WriteVLE(vars.Size());
  606. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  607. {
  608. msg_.WriteShortStringHash(i->first_);
  609. msg_.WriteVariant(i->second_);
  610. newNodeState.vars_[i->first_] = i->second_;
  611. }
  612. // Write node's components
  613. msg_.WriteVLE(node->GetNumNetworkComponents());
  614. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  615. for (unsigned i = 0; i < components.Size(); ++i)
  616. {
  617. Component* component = components[i];
  618. if (component->GetID() >= FIRST_LOCAL_ID)
  619. continue;
  620. msg_.WriteShortStringHash(component->GetType());
  621. msg_.WriteVLE(component->GetID());
  622. ComponentReplicationState newComponentState;
  623. newComponentState.frameNumber_ = frameNumber_;
  624. newComponentState.type_ = component->GetType();
  625. // Write component's attributes
  626. component->WriteInitialDeltaUpdate(msg_, deltaUpdateBits_, newComponentState.attributes_);
  627. newNodeState.components_[component->GetID()] = newComponentState;
  628. }
  629. SendMessage(MSG_CREATENODE, true, true, msg_);
  630. sceneState_[node->GetID()] = newNodeState;
  631. }
  632. void Connection::ProcessExistingNode(Node* node)
  633. {
  634. NodeReplicationState& nodeState = sceneState_[node->GetID()];
  635. nodeState.frameNumber_ = frameNumber_;
  636. // Check if attributes have changed
  637. bool deltaUpdate, latestData;
  638. node->PrepareUpdates(deltaUpdateBits_, classCurrentState_[node->GetType()], nodeState.attributes_, deltaUpdate, latestData);
  639. // Check if user variables have changed. Note: variable removal is not supported
  640. changedVars_.Clear();
  641. const VariantMap& vars = node->GetVars();
  642. for (VariantMap::ConstIterator i = vars.Begin(); i != vars.End(); ++i)
  643. {
  644. VariantMap::Iterator j = nodeState.vars_.Find(i->first_);
  645. if (j == nodeState.vars_.End() || i->second_ != j->second_)
  646. {
  647. j->second_ = i->second_;
  648. changedVars_.Insert(i->first_);
  649. deltaUpdate = true;
  650. }
  651. }
  652. // Send deltaupdate message if necessary
  653. if (deltaUpdate)
  654. {
  655. msg_.Clear();
  656. msg_.WriteVLE(node->GetID());
  657. node->WriteDeltaUpdate(msg_, deltaUpdateBits_, nodeState.attributes_);
  658. // Write changed variables
  659. msg_.WriteVLE(changedVars_.Size());
  660. for (HashSet<ShortStringHash>::ConstIterator i = changedVars_.Begin(); i != changedVars_.End(); ++i)
  661. {
  662. VariantMap::ConstIterator j = vars.Find(*i);
  663. msg_.WriteShortStringHash(j->first_);
  664. msg_.WriteVariant(j->second_);
  665. }
  666. SendMessage(MSG_NODEDELTAUPDATE, true, true, msg_);
  667. }
  668. // Send latestdata message if necessary
  669. if (latestData)
  670. {
  671. // If at least one latest data attribute changes, send all of them
  672. msg_.Clear();
  673. msg_.WriteVLE(node->GetID());
  674. node->WriteLatestDataUpdate(msg_, nodeState.attributes_);
  675. SendMessage(MSG_NODELATESTDATA, node->GetID(), true, false, msg_);
  676. }
  677. // Check for new or changed components
  678. const Vector<SharedPtr<Component> >& components = node->GetComponents();
  679. for (unsigned i = 0; i < components.Size(); ++i)
  680. {
  681. Component* component = components[i];
  682. if (component->GetID() >= FIRST_LOCAL_ID)
  683. continue;
  684. Map<unsigned, ComponentReplicationState>::Iterator j = nodeState.components_.Find(component->GetID());
  685. if (j == nodeState.components_.End())
  686. {
  687. // New component
  688. msg_.Clear();
  689. msg_.WriteVLE(node->GetID());
  690. msg_.WriteShortStringHash(component->GetType());
  691. msg_.WriteVLE(component->GetID());
  692. ComponentReplicationState newComponentState;
  693. newComponentState.frameNumber_ = frameNumber_;
  694. newComponentState.type_ = component->GetType();
  695. // Write component's attributes
  696. component->WriteInitialDeltaUpdate(msg_, deltaUpdateBits_, newComponentState.attributes_);
  697. SendMessage(MSG_CREATECOMPONENT, true, true, msg_);
  698. nodeState.components_[component->GetID()] = newComponentState;
  699. }
  700. else
  701. {
  702. // Existing component
  703. ComponentReplicationState& componentState = j->second_;
  704. componentState.frameNumber_ = frameNumber_;
  705. component->PrepareUpdates(deltaUpdateBits_, classCurrentState_[component->GetType()], componentState.attributes_,
  706. deltaUpdate, latestData);
  707. // Send deltaupdate message if necessary
  708. if (deltaUpdate)
  709. {
  710. msg_.Clear();
  711. msg_.WriteVLE(component->GetID());
  712. component->WriteDeltaUpdate(msg_, deltaUpdateBits_, componentState.attributes_);
  713. SendMessage(MSG_COMPONENTDELTAUPDATE, true, true, msg_);
  714. }
  715. // Send latestdata message if necessary
  716. if (latestData)
  717. {
  718. // If at least one latest data attribute changes, send all of them
  719. msg_.Clear();
  720. msg_.WriteVLE(component->GetID());
  721. component->WriteLatestDataUpdate(msg_, componentState.attributes_);
  722. SendMessage(MSG_COMPONENTLATESTDATA, component->GetID(), true, false, msg_);
  723. }
  724. }
  725. }
  726. // Check for removed components
  727. for (Map<unsigned, ComponentReplicationState>::Iterator i = nodeState.components_.Begin(); i != nodeState.components_.End();)
  728. {
  729. Map<unsigned, ComponentReplicationState>::Iterator current = i++;
  730. if (current->second_.frameNumber_ != frameNumber_)
  731. {
  732. msg_.Clear();
  733. msg_.WriteVLE(current->first_);
  734. SendMessage(MSG_REMOVECOMPONENT, true, true, msg_);
  735. nodeState.components_.Erase(current);
  736. }
  737. }
  738. }
  739. void Connection::HandleAsyncLoadFinished(StringHash eventType, VariantMap& eventData)
  740. {
  741. VectorBuffer msg;
  742. msg.WriteUInt(scene_->GetChecksum());
  743. SendMessage(MSG_SCENELOADED, true, true, msg);
  744. }